<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Hack a Day &#187; code</title>
	<atom:link href="http://hackaday.com/tag/code/feed/" rel="self" type="application/rss+xml" />
	<link>http://hackaday.com</link>
	<description>Fresh hacks every day</description>
	<lastBuildDate>Fri, 10 Feb 2012 06:18:04 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='hackaday.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/5560f98f805877b0e332f191cb9e0af3?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Hack a Day &#187; code</title>
		<link>http://hackaday.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://hackaday.com/osd.xml" title="Hack a Day" />
	<atom:link rel='hub' href='http://hackaday.com/?pushpress=hub'/>
		<item>
		<title>Ultrasonic combo lock</title>
		<link>http://hackaday.com/2011/12/14/ultrasonic-combo-lock/</link>
		<comments>http://hackaday.com/2011/12/14/ultrasonic-combo-lock/#comments</comments>
		<pubDate>Wed, 14 Dec 2011 20:01:13 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[arduino hacks]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[ultrasonic]]></category>
		<category><![CDATA[combination]]></category>
		<category><![CDATA[ping]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=63371</guid>
		<description><![CDATA[[John Boxall] took a different route for a single-input combination lock. This unit uses a Ping ultrasonic range finder to input a four digit code. It&#8217;s a hardware upgrade, but uses the same basic concept as his button-based combo lock. That design used an Arduino to measure how long you hold down a single button, [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=63371&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-63372" title="ultrasonic-combo-lock" src="http://hackadaycom.files.wordpress.com/2011/12/ultrasonic-combo-lock-e1323882187192.jpg" alt="" width="470" height="353" /></p>
<p>[John Boxall] took a different route for a single-input combination lock. This unit uses a Ping <a href="http://tronixstuff.wordpress.com/2011/12/13/project-ultrasonic-combination-switch/">ultrasonic range finder to input a four digit code</a>. It&#8217;s a hardware upgrade, but uses the same basic concept as <a href="http://hackaday.com/2011/07/14/building-a-single-button-combination-lock/">his button-based combo lock</a>. That design used an Arduino to measure how long you hold down a single button, with a one second pause between inputs, to enter the code. This one also uses timing to establish when each digit is read, but that digit is grabbed as the distance between your hand and the sensor.</p>
<p>There are things we like and dislike about the redesign. This is obviously much more expensive than other button-based locks like <a href="http://hackaday.com/2010/08/02/doorbell-combo-lock-can-open-your-garage-door/">this garage door opener we built</a>. If we were to run with [John's] design, we might spring for the Ping sensor (because it&#8217;s a pretty cool input) and replace he character LCD with an LED or two. The other drawback that we see here is that it may be easy for someone to steal your code by watching from afar. Still, we love the project and think you will too after seeing the demo clip below.</p>
<p><span id="more-63371"></span></p>
<span style="text-align:center; display: block;"><a href="http://hackaday.com/2011/12/14/ultrasonic-combo-lock/"><img src="http://img.youtube.com/vi/gEh48itDV8E/2.jpg" alt="" /></a></span>
<br />Filed under: <a href='http://hackaday.com/category/arduino-hacks/'>arduino hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/63371/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/63371/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/63371/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=63371&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2011/12/14/ultrasonic-combo-lock/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2011/12/ultrasonic-combo-lock-e1323882187192.jpg" medium="image">
			<media:title type="html">ultrasonic-combo-lock</media:title>
		</media:content>
	</item>
		<item>
		<title>Optimizing code for PWM efficiency</title>
		<link>http://hackaday.com/2011/05/14/optimizing-code-for-pwm-efficiency/</link>
		<comments>http://hackaday.com/2011/05/14/optimizing-code-for-pwm-efficiency/#comments</comments>
		<pubDate>Sat, 14 May 2011 19:52:50 +0000</pubDate>
		<dc:creator>Brian Benchoff</dc:creator>
				<category><![CDATA[Microcontrollers]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[microcontroller]]></category>
		<category><![CDATA[pwm]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=42872</guid>
		<description><![CDATA[For some projects, it&#8217;s okay to have a microcontroller twiddling it&#8217;s thumbs most of the time. When a project requires the cpu to do just one thing over and over, there&#8217;s no loss with inefficient code &#8211; it either works or it doesn&#8217;t. However, if a project requires a microcontroller to do several things at [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=42872&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-large wp-image-42873" title="Code" src="http://hackadaycom.files.wordpress.com/2011/05/code.png?w=450&#038;h=169" alt="" width="450" height="169" /></p>
<p>For some projects, it&#8217;s okay to have a microcontroller twiddling it&#8217;s thumbs most of the time. When a project requires the cpu to do just one thing over and over, there&#8217;s no loss with inefficient code &#8211; it either works or it doesn&#8217;t. However, if a project requires a microcontroller to do several things at once, like reading sensors, dimming LEDs, and writing serial data out, cpu utilization can become an issue. [Robert] wasn&#8217;t happy with the code he used to control a string of LEDs, so he <a href="http://blog.spitzenpfeil.org/wordpress/2011/02/20/pwm-again/">rewrote his code</a>. With the old implementation, [Robert]&#8216;s code used 60% of the cpu time. With the new and improved code, the cpu was only busy 8% of the time.</p>
<p>The code works by using a hardware timer to trigger an interrupt. After calculating the next time it should run again, and changing the state of the data line, the code just sits quietly until it&#8217;s needed again.</p>
<p>It&#8217;s not a pretty hack, or even one you can hold in your hands, but [Robert]&#8216;s determination in getting a μC to do what he wants is admirable.</p>
<br />Filed under: <a href='http://hackaday.com/category/microcontrollers/'>Microcontrollers</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/42872/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/42872/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/42872/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=42872&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2011/05/14/optimizing-code-for-pwm-efficiency/feed/</wfw:commentRss>
		<slash:comments>36</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">brianbenchoff</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2011/05/code.png?w=450" medium="image">
			<media:title type="html">Code</media:title>
		</media:content>
	</item>
		<item>
		<title>Drag and drop programming gets kids started early</title>
		<link>http://hackaday.com/2011/04/15/drag-and-drop-programming-gets-kids-started-early/</link>
		<comments>http://hackaday.com/2011/04/15/drag-and-drop-programming-gets-kids-started-early/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 21:01:27 +0000</pubDate>
		<dc:creator>Mike Nathan</dc:creator>
				<category><![CDATA[arduino hacks]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[fun]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[kids]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=40550</guid>
		<description><![CDATA[While programming an Arduino is a piece of cake for EEs who have been around the block a few times, there are some groups who would still find it difficult to get started with the IDE. It is touted for its ease of use, but there is a steep learning curve if say, you are [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=40550&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-40552" title="minibloq" src="http://hackadaycom.files.wordpress.com/2011/04/minibloq.jpg" alt="minibloq" width="470" height="280" /></p>
<p>While programming an Arduino is a piece of cake for EEs who have been around the block a few times, there are some groups who would still find it difficult to get started with the IDE. It is touted for its ease of use, but there is a steep learning curve if say, you are 5 or 6 years old. [Julián da Silva] has been hard at work for a while now, to <a href="http://blog.minibloq.org/2011/03/what-is-minibloq.html" target="_blank">make the Arduino more accessible than ever</a>.</p>
<p>Earlier today, we posted a story about <a href="http://hackaday.com/2011/04/15/squishy-circuits-for-tiny-tinkerers/" target="_blank">moldable putty which can be used by children</a> to build rudimentary circuits, enabling them to enter the fun world of hobby electronics at a young age. [Julián's] project &#8220;Minibloq&#8221; aims to do the same thing with the Arduino. A work in progress, Minibloq uses a graphical interface to &#8220;build&#8221; Arduino code a block at a time. The code components are dragged and dropped into place on one side of the screen, while the source code is generated on the other half. This helps gently introduce those people new to the Arduino how to write actual code, a little bit at a time.</p>
<p>[Julián] is working hard to ensure that his application works well on OLPC and other classroom-oriented computers to ensure it can reach as wide an audience as possible. We think this would be a great introduction to the world of micro controllers for children as well as those who have never tinkered with electronics at any point in their lives.</p>
<p>Keep reading to see a quick demo of the software in action.</p>
<p><span id="more-40550"></span><span style="text-align:center; display: block;"><a href="http://hackaday.com/2011/04/15/drag-and-drop-programming-gets-kids-started-early/"><img src="http://img.youtube.com/vi/sc61WI4DXU0/2.jpg" alt="" /></a></span></p>
<span style="text-align:center; display: block;"><a href="http://hackaday.com/2011/04/15/drag-and-drop-programming-gets-kids-started-early/"><img src="http://img.youtube.com/vi/fpWi_fZCRv0/2.jpg" alt="" /></a></span>
<br />Filed under: <a href='http://hackaday.com/category/arduino-hacks/'>arduino hacks</a>, <a href='http://hackaday.com/category/software-development/'>Software Development</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/40550/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/40550/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/40550/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=40550&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2011/04/15/drag-and-drop-programming-gets-kids-started-early/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">mikenathanathackaday</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2011/04/minibloq.jpg" medium="image">
			<media:title type="html">minibloq</media:title>
		</media:content>
	</item>
		<item>
		<title>Jeep-uter adds push button control to your vehicle</title>
		<link>http://hackaday.com/2011/01/25/jeep-uter-adds-push-button-control-to-your-vehicle/</link>
		<comments>http://hackaday.com/2011/01/25/jeep-uter-adds-push-button-control-to-your-vehicle/#comments</comments>
		<pubDate>Tue, 25 Jan 2011 16:00:40 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[transportation hacks]]></category>
		<category><![CDATA[arduino]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[computer]]></category>
		<category><![CDATA[dash]]></category>
		<category><![CDATA[ignition]]></category>
		<category><![CDATA[Jeep]]></category>
		<category><![CDATA[wrangler]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=33432</guid>
		<description><![CDATA[[Ed Zarick] built a module to control his vehicle which he calls the Jeeputer. The name&#8217;s a mash-up of Jeep and Computer; the device itself is a combination of Arduino, character LCD, and a collection of shift registers and relays for interfacing. Watch the video after the break to see what this can do. We were surprised [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=33432&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-33433" title="Back Camera" src="http://hackadaycom.files.wordpress.com/2011/01/jeep-uter-e1295967408408.jpg" alt="" width="470" height="351" /></p>
<p>[Ed Zarick] built <a href="http://www.edsjunk.net/Blog/Entries/2011/1/24_arduino_powered_jeep_WRANGLER.html">a module to control his vehicle</a> which he calls the Jeeputer. The name&#8217;s a mash-up of Jeep and Computer; the device itself is a combination of Arduino, character LCD, and a collection of shift registers and relays for interfacing. Watch the video after the break to see what this can do. We were surprised in the beginning when he says that all he has left to do is remove the steering wheel lock and he&#8217;ll be able to drive using the interface, but we think he means <a href="http://hackaday.com/2010/09/02/car-computer-requires-pin-for-ignition/">type in a code to unlock the ignition</a>, not <a href="http://hackaday.com/2009/11/10/remotely-control-your-crappy-car-dangerously/">remote control for his car</a>. He then goes on to demonstrate garage door control, power cycling for CB radio, GPS, 110V power inverter, vehicle light control, and much more. This must be the most feature packed car computer we&#8217;ve seen so far.</p>
<p><span id="more-33432"></span><span style="text-align:center; display: block;"><a href="http://hackaday.com/2011/01/25/jeep-uter-adds-push-button-control-to-your-vehicle/"><img src="http://img.youtube.com/vi/DrF22zAU8s4/2.jpg" alt="" /></a></span></p>
<br />Filed under: <a href='http://hackaday.com/category/transportation-hacks/'>transportation hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/33432/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/33432/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/33432/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=33432&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2011/01/25/jeep-uter-adds-push-button-control-to-your-vehicle/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2011/01/jeep-uter-e1295967408408.jpg" medium="image">
			<media:title type="html">Back Camera</media:title>
		</media:content>
	</item>
		<item>
		<title>C# Portable Settings Provider</title>
		<link>http://hackaday.com/2010/11/15/c-portable-settings-provider/</link>
		<comments>http://hackaday.com/2010/11/15/c-portable-settings-provider/#comments</comments>
		<pubDate>Mon, 15 Nov 2010 14:47:58 +0000</pubDate>
		<dc:creator>Greg R. Jacobs</dc:creator>
				<category><![CDATA[software hacks]]></category>
		<category><![CDATA[c sharp]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[content]]></category>
		<category><![CDATA[portable]]></category>
		<category><![CDATA[provider]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=30742</guid>
		<description><![CDATA[We live in a world where everything must be portable, ranging from mobile applications to making an application able to run on Linux, Windows and OS X.  Making a C# application to be completely portable across all windows computers is a problem that Microsoft knows about and willingly admits they will not fix. [Mike] from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=30742&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="aligncenter" src="https://lh6.googleusercontent.com/HDho6CKOelkdDSNmxrXLDAR_kpMJB5KYTKp8ketKo4mhtiOvFi9hAm8Ss_jj-XkzMpaY_TirKYGDIaXz-6LKhBEAtZu5A6fcDJLJSxRYtMZfRTiHmw" alt="" width="419px;" height="67px;" /></p>
<p>We live in a world where everything must be portable, ranging from mobile applications to making an application able to run on Linux, Windows and OS X.  Making a C# application to be completely portable across all windows computers is a problem that Microsoft knows about and willingly admits they will not fix. [Mike] from Geek Republic has taken it upon himself to show us how to <a href="http://www.geek-republic.com/2010/11/08/c-portable-settings-provider/">hack up some code to make your programs portable</a>.  This code is a good push forward for people loving the portability of modern applications. He will admit that bugs may exist so be on the lookout and he would probably appreciate the feedback.  Looking forward to a fully working provider so that .NET applications can be carried wherever people go!</p>
<br />Filed under: <a href='http://hackaday.com/category/software-hacks/'>software hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/30742/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/30742/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/30742/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=30742&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/11/15/c-portable-settings-provider/feed/</wfw:commentRss>
		<slash:comments>19</slash:comments>
		<georss:point>43.002684 -81.214990</georss:point>
		<geo:lat>43.002684</geo:lat>
		<geo:long>-81.214990</geo:long>
		<media:content url="" medium="image">
			<media:title type="html">greggers120588</media:title>
		</media:content>

		<media:content url="https://lh6.googleusercontent.com/HDho6CKOelkdDSNmxrXLDAR_kpMJB5KYTKp8ketKo4mhtiOvFi9hAm8Ss_jj-XkzMpaY_TirKYGDIaXz-6LKhBEAtZu5A6fcDJLJSxRYtMZfRTiHmw" medium="image" />
	</item>
		<item>
		<title>Debounce Code &#8211; one post to rule them all</title>
		<link>http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/</link>
		<comments>http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/#comments</comments>
		<pubDate>Tue, 09 Nov 2010 19:29:34 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[Microcontrollers]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[debounce]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=29916</guid>
		<description><![CDATA[Last month we asked you to send in your debounce code. You didn&#8217;t disappoint and it&#8217;s time to share the code received. There were some guideline for sending in code so if you don&#8217;t see yours here, it probably didn&#8217;t follow the rules, sorry. We also tried to weed out code that using delay loops [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29916&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-29272" title="debounce-waveform" src="http://hackadaycom.files.wordpress.com/2010/10/debounce-waveform.jpg" alt="" width="470" height="244" /></p>
<p>Last month <a href="http://hackaday.com/2010/10/13/open-call-send-us-your-debounce-code/">we asked you to send in your debounce code</a>. You didn&#8217;t disappoint and it&#8217;s time to share the code received. There were some guideline for sending in code so if you don&#8217;t see yours here, it probably didn&#8217;t follow the rules, sorry. We also tried to weed out code that using delay loops for debounce. These tend to be a poor way to handle inputs because they monopolize the processor.</p>
<p>We wanted to add upvote/downvote buttons to each set of code to give some idea of a group consensus on code quality but there&#8217;s no good system available for multiple up/down vote widgets on one wordpress page. This results in a huge code dump for any one person to go through. If you&#8217;ve got any ideas on how to better organize this let us know: <a href="mailto:debounce@hackaday.com">debounce@hackaday.com</a>.</p>
<p>We make no guarantees that this code is safe to use, or that it even works. Test it carefully before using for important tasks.</p>
<p>Join us after the break for a whirlwind of code examples.</p>
<h2><span id="more-29916"></span>Ned&#8217;s Debounce Code</h2>
<p>Ned sent in a package of debounce code that monitors multiple buttons, debounces them, and detects button hold and release.</p>
<p>Main.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/*****************************************************************************************
 * Project:			Button Code
 * Version:			V1.0
 * Client:			ProTechNZ
 * Date Created:	22/07/2010
 * Date Modified:	23/07/2010
 * Author:			Neil van Geffen
 * Company:			ProTech NZ

 * Micro:			ATMega128
 * Speed:			8MHz
 * Clock Source:	Internal
 *****************************************************************************************/

/************************* Defines *******************************************************/
#include &lt;io.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;
#include &lt;delay.h&gt;
#include &quot;NedsStandardHeader.h&quot;
#include &quot;C Files\buttons.h&quot;

#define BTN_UP			0x01
#define BTN_DOWN		0x02
#define BTN_ENTER		0x04
#define BTN_CLEAR		0x08

/************************* Structs and Enums *********************************************/

/************************* Function Prototypes *******************************************/
unsigned char TimeYet(unsigned int time);
unsigned int TimeDiff(unsigned int past, unsigned int future);
void USART0SendByte(unsigned char byteToSend);
void USART1SendByte(unsigned char byteToSend);
void USART0SendArray(unsigned char *array, unsigned char noOfBytes);
void USART0SendString(unsigned char *string);
void USART0SendStringF(flash unsigned char *string);

/************************* Global Variables***********************************************/
unsigned char tempByte;
unsigned int tempWord;

unsigned char pA, pB, pC, pD;

unsigned char releaseCounter;

volatile unsigned int isrTime;
unsigned int currentTime;
unsigned int timeButtons;
unsigned int clearPressed;

/************************* Setup Code ****************************************************/
void SetupPorts (void) {
    PORTA = 0x00;
    PORTB = 0x00;
    PORTC = 0x00;
    PORTD = 0x04;    // RXD1 (2)
    PORTE = 0x01;    // RXD0 (0)
    PORTF = 0x00;

    DDRA = 0xF0;
    DDRB = 0xFF;
    DDRC = 0xFF;
    DDRD = 0xFF;    // TXD1 (3)
    DDRE = 0x02;    // TXD0 (1)
    DDRF = 0xFF;
}

// 1mS timer
void SetupTimers (void) {
	TCCR0 = (0 &lt;&lt; FOC0) | (0 &lt;&lt; WGM00) | (0 &lt;&lt; COM01) | (0 &lt;&lt; COM00) | (1 &lt;&lt; WGM01) | (1 &lt;&lt; CS02) | (0 &lt;&lt; CS01) | (0 &lt;&lt; CS00);	// CTC 8e6/64/125 = 1KHz
	OCR0 = 124;
	TIMSK |= (1 &lt;&lt; OCIE0);
}

/************************* Main Code *****************************************************/
void main(void) {
	SetupPorts();
	SetupTimers();

	SREG.7 = 1;

	while (1)
	{
		SREG.7 = 0;											// Atomic Time Keeping
		currentTime = isrTime;
		SREG.7 = 1;

		pC &amp;= 0x07;											// keep pC to a max of 7
		pD &amp;= 0x07;											// keep pD to a max of 7
		PORTB = btnStatus.lastCount;						// output number of buttons pressed to LEDs on PortB
		PORTC = (0x80 &gt;&gt; pC);								// output a counter to PortC
		PORTD = (0x80 &gt;&gt; pD);								// output a counter to PortD

		if (TimeYet(timeButtons)) {							// Time to run this bit of code yet
			timeButtons += 5;								// Set the next time to 5mS away (can be any value really)

			UpdateButtons(currentTime);                     // Update the buttons
		}

		if (buttons.held) {									// If any button is held
			PORTF &amp;= 0x0F;									// clear the high nibble off PortF
			PORTF |= (buttons.held &lt;&lt; 4);					// and output the buttons held to PortF high nibble
			clearPressed = currentTime + 20;				// set the clearPressed time to 20ms (used to clear the LEDs after 20ms)

			switch (buttons.held) {							// do something depending on what buttons are held (can do a &quot;case BTN_UP | BTN_DOWN:&quot; if you wanted to as well)
				case BTN_UP:	pD++;		break;
				case BTN_DOWN:	pD--;		break;
				case BTN_ENTER:	pC++;		break;
				case BTN_CLEAR:	pC--;		break;
				default: pB++;
			}

			buttons.held = 0;								// Clear the buttons held flags
		}

		if (buttons.pressed) {								// if a button is pressed
			PORTF &amp;= 0xF0;									// clear the low nibble
			PORTF |= buttons.pressed;						// and set the current puttons held to the low nibble
			clearPressed = currentTime + 200;				// set the clearPressed time to 200ms to get it to clear the LEDs after 200ms

			switch (buttons.pressed) {						// do something depending on what buttons are pressed
				case BTN_UP:	pD++;		break;
				case BTN_DOWN:	pD--;		break;
				case BTN_ENTER:	pC++;		break;
				case BTN_CLEAR:	pC--;		break;
				default: pB++;
			}

			buttons.pressed = 0;							// clear the buttons pressed flags
		}

		if (buttons.released) {								// if any buttons are released
			releaseCounter++;								// increment the release counter
			PORTF = 0x00;									// clear PortF LEDs
			PORTA &amp;= 0x0F;									// clear the PortA high nibble
			PORTA |= (releaseCounter &lt;&lt; 4);					// and set what buttons were released to tht PortA LEDs

			switch (buttons.released) {						// do something on a button release
				case BTN_UP:	pD = 0;		break;
				case BTN_DOWN:	pD = 7;		break;
				case BTN_ENTER:	pC = 0;		break;
				case BTN_CLEAR:	pC = 7;		break;
				default: pB++;
			}

			buttons.released = 0;							// clear the button released flags
		}

		if (TimeYet(clearPressed)) {						// if we should clear the LEDs
			clearPressed = currentTime;						// stop the time from wrapping-over
			PORTF = 0x00;									// clear the LEDs
		}
	}
}

/************************* Functions *****************************************************/
unsigned char TimeYet(unsigned int time) {
 	if (((time - 1) - currentTime) &gt; 0xF000) {				// if the time has passed (will roll around when not serviced for 4095 counts)
    	return 1;											// the time has passed
    }
	else return 0;											// or else it has not yet passed
}

/************************* Interrupts ****************************************************/
interrupt [TIM0_COMP] void TimerZeroCompare (void) {
	isrTime++;												// Keep Time
}</pre></p>
<p>Buttons.h:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/************************************* START OF LIBRARY COMMENTS *******************************
* Library Name:		Neds Button Code
* Version:			V1.0
* Created:      	22/07/10
* Last Mod:			23/07/10
* CV Version:		2.04.8a
* Author:       	Neil van Geffen
* Company:      	ProTechNZ
* Purpose:      	Read 4 buttons and return button presses, helds and releases.
************************************************************************************************/

/************************************* KNOWN BUGS **********************************************
*
************************************************************************************************/

/************************************* NOTES ***************************************************
* The code will decode the button presses into presses, holds and releases.
* A press is a press AND release before a hold is registered
* A hold is a press held long enough to register as a hold.
* A hold will automatically repeat itself at an increasing rate
************************************************************************************************/

#define BUTTONS			(PINA &amp; 0x0F)		// Make the buttons the lower nibble active high (use ~ to get active low buttons to appear as active high)

#define REPEAT_MAX		250					// The start value of repeat debouncing when first pressing a button
#define REPEAT_MIN		25					// The lowest value of repeat debouncing when first holding a button
#define SPEED_SHIFT		3					// The repeat value decreases by the current repeat value &gt;&gt; by this value (aka 4 means it decreases by 1/16th every time)
#define DEBOUNCE_PRESS	25					// The debounce for a single press
#define DEBOUNCE_HOLD	600					// The debounce for a button hold

struct {
	unsigned int pressed:4;			// holds which buttons have been pressed and released
	unsigned int held:4;			// holds which buttons have been held for more than DEBOUNCE_HOLD
	unsigned int released:4;		// holds which buttons have been released after a button was held
} buttons;

#pragma used+
/***** UpdateButtons
 * Read 4 buttons (defined as BUTTONS above)
 * and save them to the buttons struct.
 * Best if called on a regulat basis like every 10mS.
 * Calling more often will give better resolution on button presses.
 ----------
 * @param - curretTime, the current time to compare the last press too to calculate debounce and press held length
 *****/
void UpdateButtons(unsigned int currentTime);
#pragma used-

#include &quot;buttons.c&quot;</pre></p>
<p>Buttons.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/************************************* START OF LIBRARY COMMENTS *******************************
* Library Name:		Neds Button Code
* Version:			V1.0
* Created:      	22/07/10
* Last Mod:			23/07/10
* CV Version:		2.04.8a
* Author:       	Neil van Geffen
* Company:      	ProTechNZ
* Purpose:      	Read 4 buttons and return button presses, helds and releases.
************************************************************************************************/

/************************************* KNOWN BUGS **********************************************
*
************************************************************************************************/

/************************************* NOTES ***************************************************
*
************************************************************************************************/

#define BUTTON_COUNT	((BUTTONS &amp;&amp; (BUTTONS &amp; (1 &lt;&lt; 0))) + (BUTTONS &amp;&amp; (BUTTONS &amp; (1 &lt;&lt; 1))) + (BUTTONS &amp;&amp; (BUTTONS &amp; (1 &lt;&lt; 2))) + (BUTTONS &amp;&amp; (BUTTONS &amp; (1 &lt;&lt; 3))))

#warning By compiling Neds button code, you acknowledge he is the man!

struct {
	unsigned char heldFlag:1;		// used by neds code, never change
	unsigned char decreaseFlag:1;	// used by neds code, never change

	unsigned char lastStatus:4;		// used by neds code, never change. The last valid combination of buttons pressed
	unsigned char lastCount:4;		// used by neds code, never change. The number of buttons held at one time

	unsigned int time;				// used by neds code, never change. The time the button press was changed

	unsigned int repeat;			// used by neds code, never change. The time between button held repeats
} btnStatus;

unsigned int TimeDiff(unsigned int past, unsigned int future) {
	if (((future - 1) - past) &gt; 0xF000) return 0;
	else return future - past;
}

void UpdateButtons(unsigned int currentTime) {
	if (TimeDiff(btnStatus.time, currentTime) &gt;= DEBOUNCE_HOLD) {									// If a button has been held
		if (btnStatus.decreaseFlag) {																// if the button count was lowered earlier but they have remained the same for the length of a hold time
			btnStatus.decreaseFlag = FALSE;														// clear the flag that states it was lowered
			btnStatus.lastStatus = BUTTONS;														// and set the button status to the currently pressed buttons
		}

		buttons.held = btnStatus.lastStatus;																// Set what buttons were held
		btnStatus.time += btnStatus.repeat;																// and set the time to repeat the next press
		btnStatus.repeat = MAX(REPEAT_MIN, btnStatus.repeat - MAX(1,(btnStatus.repeat &gt;&gt; SPEED_SHIFT)));		// and lower the repeat value to increase the button held repeat rate
		btnStatus.heldFlag = TRUE;																			// and set the flag that states a button was held
	}

	if (!BUTTONS) {
		if (btnStatus.heldFlag) {																	// If the buttons were previously held
			btnStatus.heldFlag = FALSE;															// Clear the flag so it doesnt set buttons pressed continously
			buttons.released = btnStatus.lastStatus;												// Set what buttons were pressed previously
		}
		else if (TimeDiff(btnStatus.time, currentTime) &gt;= DEBOUNCE_PRESS) {						// but if the buttons werent held, but pressed for long enough to pass as a debounce
			buttons.pressed = btnStatus.lastStatus;												// Set what buttons were pressed
		}

		btnStatus.lastCount = 0;																	// Clear the last count
		btnStatus.lastStatus = 0;																	// Clear the last Status
		btnStatus.time = currentTime;																// clear the last press time
	}
	else if (BUTTON_COUNT &gt; btnStatus.lastCount) {												// if the number of buttons pressed has changed
		btnStatus.lastCount = BUTTON_COUNT;														// save it for next time.
		btnStatus.lastStatus = BUTTONS;															// and save what buttons were pressed.
		btnStatus.decreaseFlag = FALSE;															// clear the flag that says the button presses just decreased.

		btnStatus.time = currentTime;																// reset the time of last button presses.
		btnStatus.repeat = REPEAT_MAX;															// and reset the time between held repeats.

	}
	else if (BUTTON_COUNT &amp;&amp; (BUTTON_COUNT &lt; btnStatus.lastCount)) {								// Or if the button count deceased but a button is still pressed
		btnStatus.lastCount = BUTTON_COUNT;														// save the count for next time
		btnStatus.decreaseFlag = TRUE;															// set the flag to say this happened

		btnStatus.time = currentTime;																// reset the time of last button presses.
		btnStatus.repeat = REPEAT_MAX;															// and reset the time between held repeats.
	}
	else if (!btnStatus.decreaseFlag &amp;&amp; (BUTTONS != btnStatus.lastStatus)) {						// If someone changed button presses but not the count
		btnStatus.lastCount = 0;																	// Force the count to change next time around so the code to set times etc isnt in 2 places.
	}                                                                   						// This is a fairly useless bit of code if the service time is less than 10mS and even if its more, it won't be all that usefull.
}</pre></p>
<h2>S1axter&#8217;s Debounce Code</h2>
<p>Developed for PIC24 chips, this code repeatedly calls a function to check a pin state.</p>
<p>pin_io.h:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">//////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Pin I/O control module - Header
//
// Language: Microchip C30
//
// File:     pin_io.h
// Author:   MyBitBox.com/Geeksinside.com
// Created:  08/23/09
//
//////////////////////////////////////////////////////////////////////////////////////////////////////

#ifndef __PIN_IO_H__
#define __PIN_IO_H__

void pin_io_init(void);
void pin_input_check(void);

#endif

</pre></p>
<p>pin_io.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">//////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Pin I/O control module
//
// Language: Microchip C30
//
// File:     pin_io.c
// Author:   MyBitBox.com/Geeksinside.com
// Created:  08/23/09
//
//////////////////////////////////////////////////////////////////////////////////////////////////////

typedef struct{
	uint16 mask;
	uint16 last_state;
	uint8 changed;
}pin_check_struct;

pin_check_struct inputA, inputB;

//====================================================================================
// Set up the pins
//====================================================================================
void pin_io_init(void)
{

	inputA.changed = FALSE;
	inputA.last_state = FALSE;
	inputA.mask = BMASK(2);       // look at PORTB2

	inputB.changed = FALSE;
	inputB.last_state = FALSE;
	inputB.mask = BMASK(4);        // look at PORTB4

	return;
}

//====================================================================================
// This is the debounce routine. When this is called it checks for consistant pin states
//====================================================================================
void pin_input_check(void)
{

	uint16 portb_snapshot = PORTB;

	// This is for the XXXXX input
	// ------------------------------------------------------
	if(inputA.changed == TRUE)
	{

		if(!((portb_snapshot ^ inputA.last_state)&amp;inputA.mask))
		{
			// If the line was changed last time, and it is the same state as last
			// time, then we need to lock it in here (If the bits are not the same then this routine
			// will be called again and the correct value will be locked in)
			if(portb_snapshot &amp; inputA.mask)
			{
				// Do this when the line goes high
				SYS_STATUS.FLAG_XXXXX_LINE = TRUE;
			}else{
				// Do this when the line goes low
				SYS_STATUS.FLAG_XXXXX_LINE = FALSE;
			}
			// Clear the changed flag
			inputA.changed = FALSE;
		}
	}
	// Mask out any changed input pins
	inputA.changed = ((inputA.last_state ^ (portb_snapshot &amp; inputA.mask))&gt;0);		// XOR with last last_state to find changed pins
	inputA.last_state = portb_snapshot &amp; inputA.mask;

	// This is for the YYYYY input
	// ------------------------------------------------------
	if(inputB.changed == TRUE)
	{

		if(!((portb_snapshot ^ inputB.last_state)&amp;inputB.mask))
		{
			// If the line was changed last time, and it is the same state as last
			// time, then we need to lock it in here (If the bits are not the same then this routine
			// will be called again and the correct value will be locked in)
			if(portb_snapshot &amp; inputB.mask)
			{
				// Do this when the line goes high
				SYS_STATUS.FLAG_YYYYY_LINE = TRUE;
			}else{
				// Do this when the line goes low
				SYS_STATUS.FLAG_YYYYY_LINE = FALSE;
			}
			// Clear the changed flag
			inputB.changed = FALSE;
		}
	}
	// Mask out any changed input pins
	inputB.changed = ((inputB.last_state ^ (portb_snapshot &amp; inputB.mask))&gt;0);		// XOR with last last_state to find changed pins
	inputB.last_state = portb_snapshot &amp; inputB.mask;

	return;
}

//end</pre></p>
<h2>Aaron Keith&#8217;s Debounce Code</h2>
<p>This code is tailored for an 8051 processor.</p>
<p>Button_debounce_8051.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/*--------------------------------------------------------------------------
10/14/2010: Button debounce code by Aaron Keith

This code detects and debounces button presses. It is tailored for use with
8051 micro controllers.  Complied on the RIDE 51 Complier

The interrupt service routine (ISR) runs 3600 times per second.  If the
button is pressed (the pin is connected to GND) Key_Hit is incremented to the
maximum 255.  When the button is released Key_Hit will decremented to 0.
Long_Key_Hit will increment more slowly and is used to detect the button
being help down.
--------------------------------------------------------------------------*/

#include&lt;reg51.h&gt;

#define TRUE 1
#define FALSE 0

//define pins used by buttons
at 0x97 sbit P1_7 ;
#define BUTTON P1_7   //Button on Port 1.7

//De bounce variables
unsigned char Key_Hit;
unsigned char Long_Key_Hit;

/*--------------------------------------------------------------------------
  Prototypes
--------------------------------------------------------------------------*/
void init_timers(void);

/*--------------------------------------------------------------------------
  FUNC: - Sets and starts a system timer
  PARAMS: NONE
  RETURNS: NONE
--------------------------------------------------------------------------*/
void init_timers(void)          // using a 11.0592 Mhz Clock
{
  TMOD = 0x02; //T0 mode 2 8 bit reload
  // Timer 0 is system tick

  TH0 = 0x00; // Reload = 256, giving 921600/256=3600
  TL0 = 0x00;

  ET0 = TRUE; // Enable interrupt on timer 0
  TR0 = TRUE; // Start timer 0;

  EA = TRUE;
}

/*--------------------------------------------------------------------------
  FUNC:  - Main
--------------------------------------------------------------------------*/
void main(void)
{

  init_timers(); //start the timer

  for (;;) //loop forever
    {

      if (Key_Hit == 0xff)
        {
          //Key press detected. Do something here
        }

      if (Key_Hit == 0x00)
        {
          //Key release detected. Do something here
        }

      if (Long_Key_Hit == 0xff)
        {
          //Key press and help down. Do something here
        }

    }

}

/*--------------------------------------------------------------------------
  INTERRUPT:  // The procedure runs 3600 times per second
--------------------------------------------------------------------------*/
void Timer0_interrupt(void) interrupt 1
{

  static unsigned char Div18Counter = 0;

  if (BUTTON)
    { // Button up (Pin is connected to VCC)
      if (Key_Hit != 0)  // Will never go below zero
        {
        Key_Hit--;
        }
    }
  else
    { // Button down (Pin is connected to GND)
      if (Key_Hit != 0xff)  // Will never go above 255
        {
        Key_Hit++;
        }
    }

  if (++Div18Counter &gt;= 18)   // run ever 5 mSec
    {
      Div18Counter = 0;

      if (Key_Hit == 0xff)
        {
          if (Long_Key_Hit != 0xff)
            Long_Key_Hit++;
        }
      else if (Key_Hit == 0x00)    // No delay when detecting key release.
        Long_Key_Hit = 0x00;
    }

}</pre></p>
<h2>Thomas Flayols&#8217; Debounce Code</h2>
<p>This code creates a software-based low-pass filter by taking a moving average of the pin value.</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">// Hi, to prevent contact bounce, my solution is to create software low pass filter by using a moving average...(no delay solution) see the jpg to see what's happen
// INPUT is the button input pin(0if not pressed, 1 if pressed)

main(void)
{
    unsigned char button = 0;
    while(1)
    {
         // your code here...

         button=(button * 9+INPUT * 10)/10; // do a moving average of the digital input... result button between 0 and 10

         if (button &gt; 5)
         {
                //the button is ON
         }
         else
         {
                //the button is OFF
         }

    }
}</pre></p>
<h2>Ganesh Krishna&#8217;s Debounce Code</h2>
<p>Can be scaled to any number of buttons, sample rate is configurable, and this aims to use as little RAM as possible</p>
<p>dbounce.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">#include &lt;htc.h&gt;

/* Scalable software debounce for buttons
 *
 * This is quick implementation of software debounce with as little RAM as possible.
 * stress is given to scalability of number of buttons
 * and scalability of number of samples per debounce cycle.
 *
 * While this file is written for PIC Microcontroller and Hi-tech compiler,
 * the debounce function itself is just C, and not hardware dependant.
 *
 * Use the functions at your own risk
 * Author: ganesh.ksm@gmail.com
 *
 * Assume BSD like license.
 * Acknowledge with an email if it works for you.
 *
*/

/*Number of buttons in the system*/
#define MAX_BUTTONS 4

/* MAJORITY_VOTE Number of samples for which the button must remain in pressed state
 * to consider that the button is pressed.
 * */
#define MAJORITY_VOTE 5

/* STABILITY_BITS is the number of final samples (last few samples at the end of debounce)
 * after which we consider the input stable
 * */
#define STABILITY_BITS 2

/* Convert Stability bits to a bit mask, i.e STABILITY_MASK has STABILITY_BITS bits set in its LSB
 * */
#define STABILITY_MASK ((1&lt;&lt;STABILITY_BITS) - 1)

/*This variable contains the debounced status of all buttons
   at any point of time
   */
volatile unsigned int debounced_buttons;

/* Reads port pins and returns 1 if button is active (assumed active low)
 * returns 0 if inactive. Microchip PIC18 specific.
 * */
unsigned char Read_Portbit(int button)
{
	switch(button)
	{
		case 0: return !RA0;
		case 1: return !RA1;
		case 2: return !RA2;
		case 3: return !RA3;
	}
}

/* Function: button_is_pressed()
 * Argument: Takes the button number as argument, an index into the array of buttons.
 * Returns:  non zero if the button of interest is pressed for majority time of polling
 *           returns zero if not pressed, debouncing not complete,
 *           button bouced back to unpressed state
 *
 * Calling rate: This function will return positive only after MAJORITY_VOTE is achieved
 *  times with same button argument for debounce of one button.
 * 		 where X is the number of samples per debounce,
 *
 * Depends on: Read_Portbit(button) which returns 1 if the pin of button of interest is active and 0 if not.
 */
char button_is_pressed( unsigned char button)
{
	unsigned int bit_count=0, temp;

	/* button_bits[] is an array to hold the previous states of the port pin value
	 * Each element holds the previous samples of teh button read.
	 * We need as many elements as there are buttons.
	 * Make this an integer array if more than 8 samples are needed for debounce determination.
	 * if less samples are needed adjust the MAJORITY_VOTE and STABILITY_BITS to a smaller number
	 * */

volatile static unsigned char button_bits[MAX_BUTTONS];

	/* Shift the latest read button status into the que
	 * we should have the latest sample in LSB and older samples
	 * higher up.*/

	button_bits[button]=button_bits[button]&lt;&lt;1 | (Read_Portbit(button) &amp; 0x01);
	temp = button_bits[button];

	/*Check if the input is stable in the last STABILITY_BITS samples*/
	if ((temp &amp; STABILITY_MASK) == STABILITY_MASK)
	{
		/* Count the number of bits set in temp, we need more than the majority
		 * straight out of the book of K&amp;R, check it :-)*/
		while(temp = temp&amp;(temp-1))
			bit_count++;
		bit_count++; // we are off by one

		/*Check if the required number of samples were favourable */
		if (bit_count&gt;=MAJORITY_VOTE)
		{
			button_bits[button] = 0;
			return 1;
		}
		else
			return 0;
	}
	else
	{
		return 0;
	}
}

/* Call at a rate about 8 times higher than the rate at which input detection is required
 * actual frequency depends on the number of samples required per debounce.
  */

void Service_user_Input(void)
{
	int i;
	for (i=0;i&lt;MAX_BUTTONS;i++)
	{
		if (button_is_pressed(i))
			debounced_buttons = debounced_buttons | 0x01&lt;&lt;i;
	}
}

void main (void)
{
	/*PIC18 specific intialization of timer interrupt*/
	GIE=1;
	PEIE=1;
	TMR0IE=1;

	T0CON= 0X48;    //16 bit timer without Prescaler for interrupts
	TMR0L=0xFA;
	TMR0H=0xFF;
	TMR0ON=1;
	TRISA = 0xFF; // PORTA is input.
	/*Application code starts here*/
	while(1)
	{
		/*Do something usefull with debounced_buttons*/
	}

}

void interrupt User_Input()
{
	TMR0L=0x00; /*Not really needed, but lets be explicit*/
	TMR0H=0x00;
	TMR0ON=1;

	Service_user_Input(); /*you may choose to call this in an timed function in the main thread too*/
}</pre></p>
<h2>Kenneth Kuhn&#8217;s Debounce Code</h2>
<p>[Chad] has been using a modified version of <a href="http://www.kennethkuhn.com/electronics/debounce.c">[Kenneth Kuhn's] debounce code</a> for some time now. Small, fast, and well commented, it uses an integrator algorithm.</p>
<p>debounce.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/******************************************************************************

debounce.c
written by Kenneth A. Kuhn
version 1.00

This is an algorithm that debounces or removes random or spurious
transistions of a digital signal read as an input by a computer.  This is
particularly applicable when the input is from a mechanical contact.  An

integrator is used to perform a time hysterisis so that the signal must
persistantly be in a logical state (0 or 1) in order for the output to change
to that state.  Random transitions of the input will not affect the output

except in the rare case where statistical clustering is longer than the
specified integration time.

The following example illustrates how this algorithm works.  The sequence
labeled, real signal, represents the real intended signal with no noise.  The

sequence labeled, corrupted, has significant random transitions added to the
real signal.  The sequence labled, integrator, represents the algorithm
integrator which is constrained to be between 0 and 3.  The sequence labeled,

output, only makes a transition when the integrator reaches either 0 or 3.
Note that the output signal lags the input signal by the integration time but
is free of spurious transitions.

real signal 0000111111110000000111111100000000011111111110000000000111111100000

corrupted   0100111011011001000011011010001001011100101111000100010111011100010
integrator  0100123233233212100012123232101001012321212333210100010123233321010
output      0000001111111111100000001111100000000111111111110000000001111111000

I have been using this algorithm for years and I show it here as a code
fragment in C.  The algorithm has been around for many years but does not seem
to be widely known.  Once in a rare while it is published in a tech note.  It

is notable that the algorithm uses integration as opposed to edge logic
(differentiation).  It is the integration that makes this algorithm so robust
in the presence of noise.
******************************************************************************/

/* The following parameters tune the algorithm to fit the particular
application.  The example numbers are for a case where a computer samples a
mechanical contact 10 times a second and a half-second integration time is

used to remove bounce.  Note: DEBOUNCE_TIME is in seconds and SAMPLE_FREQUENCY
is in Hertz */

#define DEBOUNCE_TIME		0.3
#define SAMPLE_FREQUENCY	10
#define MAXIMUM			(DEBOUNCE_TIME * SAMPLE_FREQUENCY)

/* These are the variables used */
unsigned int input;       /* 0 or 1 depending on the input signal */
unsigned int integrator;  /* Will range from 0 to the specified MAXIMUM */
unsigned int output;      /* Cleaned-up version of the input signal */

/* Step 1: Update the integrator based on the input signal.  Note that the
integrator follows the input, decreasing or increasing towards the limits as
determined by the input state (0 or 1). */

  if (input == 0)

    {
    if (integrator &gt; 0)
      integrator--;
    }
  else if (integrator &lt; MAXIMUM)
    integrator++;

/* Step 2: Update the output state based on the integrator.  Note that the
output will only change states if the integrator has reached a limit, either

0 or MAXIMUM. */

  if (integrator == 0)
    output = 0;
  else if (integrator &gt;= MAXIMUM)
    {
    output = 1;
    integrator = MAXIMUM;  /* defensive code if integrator got corrupted */
    }

/********************************************************* End of debounce.c */</pre></p>
<h2>Ubi de Feo&#8217;s Debounce Code</h2>
<p>Arduino sketch to debounce pins from an array.</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">#define ARRAY_SIZE 8
// array of pins to be debounced
short pinsToDebounce[]={
  2,3,4,5,6,7,8,9
};
// array of pin state
int swStates[]={
  0,0,0,0,0,0,0,0};
// array of previous pin state
int swPrevStates[]={
  0,0,0,0,0,0,0,0};
// array to store the actual state during debounce
int swDebouncedStates[]={
  0,0,0,0,0,0,0,0};
// array to store the previous state during debounce
int swPrevDebounceStates[]={0,0,0,0,0,0,0,0};
// time to debounce
int debounceDelay=100;
// array of previous times the pin has been checked
long prevTimes[]={
  0,0,0,0,0,0,0,0};

void setup(){
  Serial.begin(9600);

 initSwitches();
}
void loop(){
 readSwitches();
}

void initSwitches(){
  for(int i=0;i&lt;ARRAY_SIZE;i++){
    pinMode(pinsToDebounce[i],INPUT);
  }
}
void readSwitches(){

  // Serial.print(&quot;active switch set &quot;);
  // Serial.println((int)activeSwitchSet);

  for(short sw=0;sw&lt;ARRAY_SIZE;sw++){
    volatile int pin=pinsToDebounce[sw];
    volatile int mpPin=pin;
    volatile int pinPosition=sw;

    swStates[pinPosition]=digitalRead(pin);
  }

  debouncePins();
   checkStateChange();
}
void debouncePins(){

  volatile long _millis=millis();

  for(short sw=0;sw&lt;ARRAY_SIZE;sw++){
    if(swStates[sw]!=swPrevStates[sw]){
      prevTimes[sw]=_millis;
    }
    if(_millis-prevTimes[sw]&gt;debounceDelay){
      prevTimes[sw]=_millis;
      swDebouncedStates[sw]=swStates[sw];
      /*
      Serial.print(&quot;button &quot;);
       Serial.print(sw);
       Serial.print(&quot; is &quot;);
       Serial.println(swDebouncedStates[sw]);
       */
    }
    swPrevStates[sw]=swStates[sw];
  }

}

void checkStateChange(){
  for(short sw=0;sw&lt;5;sw++){
    if(swPrevDebounceStates[sw]!=swDebouncedStates[sw]){
      /*
      Serial.println(&quot;&quot;);
      Serial.print(&quot;button &quot;);
      Serial.print(sw);
      Serial.print(&quot; &quot;);
      Serial.println(swDebouncedStates[sw]);
      */
      if(swDebouncedStates[sw]==1){
        pinActive(sw);
      }
      if(swDebouncedStates[sw]==0){
        pinInactive(sw);
      }
    }
    swPrevDebounceStates[sw]=swDebouncedStates[sw];
  }
}

void printDebStates(){
  Serial.println(&quot;%%%%%%%%%%%%%%%%%%%%%%%%&quot;);
  for(int i=0;i&lt;ARRAY_SIZE;i++){
    Serial.print(swDebouncedStates[i]);
    Serial.print('*');

  }

  Serial.println(&quot;&quot;);
}
void pinActive(int _id){

  Serial.print(&quot;active pin &quot;);
  Serial.println(pinsToDebounce[_id]);
}
void pinInactive(int _id){
   Serial.print(&quot;inactive pin &quot;);
 Serial.println(pinsToDebounce[_id]);
}</pre></p>
<h2>Christoph Gommel&#8217;s Debounce Code</h2>
<p>Debouncing and scanning a keyboard matrix with an STM32 ARM processor.</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/*
  keyboard.c
  Used on an STM32F103 in a wireless remote control
  (C) 2010 Christoph Gommel &lt;chg@contronix.de&gt;
  Contronix GmbH, Nizzastr. 6, 01445 Radebeul, Germany
  Tags: matrix, keyboard, stm32, stm32f103, debounce, hackaday
 */
#include &quot;stm32f10x.h&quot;
#include &quot;keyboard.h&quot;
#include &quot;fifo.h&quot;

#define KEYBOARD_GPIO (GPIOA)

// Cols and rows are intentionally placed in the right order enabling the bit shifting trick used.

#define COL1 (GPIO_Pin_1)
#define COL2 (GPIO_Pin_2)
#define COL3 (GPIO_Pin_3)
#define COLS (COL1|COL2|COL3)

#define ROW1 (GPIO_Pin_4)
#define ROW2 (GPIO_Pin_5)
#define ROW3 (GPIO_Pin_6)
#define ROW4 (GPIO_Pin_7)
#define ROW5 (GPIO_Pin_8)
#define ROWS (ROW1|ROW2|ROW3|ROW4|ROW5)
//#define ROWS_B (ROW5)

#define ColNum (3)
#define RowNum (5)

#define ColStart (1)
#define RowStart (4)

//Very useful macro to increment and modulo in one instruction
#define incmod(n,m); n=((n+1)%m);

// Yes, we have a shift key too
#define SHIFT (GPIO_Pin_0)

GPIO_InitTypeDef GPIO_InitStructure;

#define KeyBufferSize (20)

//volatile unsigned char keypad_queue_buffer[KeyBufferSize];

static char keypad_queue_buffer[KeyBufferSize];
fifo_t keyfifo;

void keyboard_init(void)
{
  //Initialize a self made fifo system
  fifo_init(&amp;keyfifo, keypad_queue_buffer, KeyBufferSize);

  //Give clock to the GPIO
  RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);

  //Initialize the rows as push-pull-output
  GPIO_InitStructure.GPIO_Pin = ROWS;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
  GPIO_Init(KEYBOARD_GPIO, &amp;GPIO_InitStructure);

  //The cols ar input with pull-up
  GPIO_InitStructure.GPIO_Pin = COLS | SHIFT;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IPU;
  GPIO_Init(KEYBOARD_GPIO, &amp;GPIO_InitStructure);

  GPIO_SetBits(KEYBOARD_GPIO, ROWS);

}

volatile unsigned int CurrentRow = 0;
volatile unsigned int lastScan = 0;
volatile unsigned int thisScan = 0;
volatile unsigned int debounceCnt;
volatile unsigned int numberOfKeys;
volatile unsigned int thisScancode;
volatile unsigned int lastScancode;

//Adapt this to you wishes
#define debounceMax (10)

//The following piece of code will be called every 10 ms from a systick interrupt
void keyboard_scan(void)
{
  unsigned int scan;
  scan = ((~GPIO_ReadInputData(KEYBOARD_GPIO)) &amp; COLS) &gt;&gt; ColStart;

  //this is the really interesting core of my matrix scanning algorithm.
  //each key of the matrix is represented in one bit of a 16 bit unsigned short ;)
  thisScan = (thisScan | (scan &lt;&lt; (ColNum * RowNum))) &gt;&gt; ColNum;
  //Release Current Row
  GPIO_SetBits(KEYBOARD_GPIO, 1 &lt;&lt; (CurrentRow + RowStart));

  incmod(CurrentRow,RowNum);
  //prepare next Row

  GPIO_ResetBits(KEYBOARD_GPIO, 1 &lt;&lt; (CurrentRow + RowStart));

  if (0 == CurrentRow)
  {
    //Something changed, let's reset the debounce counter
    if (thisScan != lastScan)
    {
      debounceCnt = 0;
    }
    //...or increase if nothing changed
    else if (debounceCnt &lt; debounceMax)
    {
      debounceCnt++;
    }
    //... if the threshold is reached
    if (debounceCnt == debounceMax)
    {
      numberOfKeys = 0;
      int i;
      //count the number of keys pressed and mark the position of the set bit in &quot;thisScancode&quot;
      for (i = 0; i &lt; (ColNum * RowNum); i++)
        if (thisScan &amp; (1 &lt;&lt; i))
        {
          numberOfKeys++;
          thisScancode = i + 1;
        }
      //ignore multiple key presses...
      if (1 != numberOfKeys)
        thisScancode = 0;
      else
      {
       //.. except the shift key which is NOT part of the matrix
        if (keyboard_getshift())
          thisScancode |= KEYBOARD_SHIFT;
        if (thisScancode != lastScancode)
        {
          //printf(&quot;Scan: %d\r\n&quot;,thisScancode);
          fifo_put(&amp;keyfifo, thisScancode);
        //this is typematic. to generate multiple keystrokes on one single looooooooooong press
#ifdef ENABLE_TYPEMATIC
          typematicCnt=0;
#endif
        }
#ifdef ENABLE_TYPEMATIC
        else
        {
          typematicCnt++;
          if ((typematicThreshold+typematicSpeed)&lt;=typematicCnt)
          typematicCnt=typematicThreshold;

          if (typematicThreshold==typematicCnt)
          {
            fifo_put(&amp;keyfifo, thisScancode);
          }
        }
#endif
      }
      lastScancode = thisScancode;
      //Now we have to do the processing because we get some freshly debounced situation, baby!
      //currentKey=((thisScan^oldScan)&amp;thisScan);
      //oldScan=thisScan;
    }
    lastScan = thisScan;
    thisScan = 0;
  }
}

//that's it, folks ;)</pre></p>
<h2>Dean Hall&#8217;s Debounce Code</h2>
<p>Debouncing a pin interrupt on AVR microcontrollers</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/*
 * Sample debouncing code
 *
 * Copyright 2010 Dean Hall.
 * This code snippet is offered under the MIT license:
 * http://www.opensource.org/licenses/mit-license.html
 */

/*
 * The hardware is an AVR with a switch connected to the INT0 input.
 * The firmware uses:
 *
 * - AVR Libc: http://www.nongnu.org/avr-libc/
 * - The AvrX microkernel: http://www.barello.net/avrx/
 *
 * This sample code performs debouncing on the INT0 input.
 * Here is the expected sequence of actions:
 *
 * - The AVR can be doing anything (awake or asleep) when the button is pressed
 * - The button press produces a low-going signal and bounces for a time
 * - The low-going signal activates the INT0 interrupt
 * - The INT0 service routine:
 *     - Disables the INT0 interrupt so bouncing doesn't cause multiple IRQs
 *     - Puts an AvrX message in the event queue of the inputs task
 * - The event in the queue causes the inputs_task to be scheduled, which:
 *     - Performs the action that the INT0 button is supposed to invoke
 *     - Starts an AvrX delay timer to allow for the button to stop bouncing
 *       During this delay, other AvrX tasks may run.
 *     - After the delay, the INT0 interrupt is re-enabled for the next input.
 *
 * In this design, the delay is especially long (1s) due to a very cheap button
 * and no need to respond to fast button presses.
 *
 * The downside of this software design is that no other input events are
 * processed while a button is debounced, although their press-messages are
 * queued up and handled after the debounce period.  This behavior was
 * acceptable for this immediate design, but may not be for all situations.
 */

#include &lt;avr/interrupt.h&gt;
#include &quot;avrx.h&quot;

#define DEBOUNCE_DELAY (uint16_t)(1000 / MILLISECONDS_PER_TIC)

static MessageControlBlock remote_ctrl_pressed_msg;

/* Remote Control button press interrupt service routine */
AVRX_SIGINT(INT0_vect)
{
   IntProlog();

   /* Disable INT0/RemoteCtrl interrupt */
   GICR &amp;= ~_BV(INT0);

   AvrXIntSendMessage(&amp;inputs_msg_queue, &amp;remote_ctrl_pressed_msg);
   Epilog();
}

AVRX_GCC_TASKDEF(inputs_task, TASK_STACK_SIZE, 3)
{
   TimerControlBlock debounce_timer;
   MessageControlBlock *pmsg;

   /* Set INT0/RemoteCtrl and INT1/OpTest to trigger on falling edge */
   GICR &amp;= ~(_BV(INT0) | _BV(INT1));
   MCUCR &amp;= ~(_BV(ISC00) | _BV(ISC10));
   MCUCR |= (_BV(ISC01) | _BV(ISC11));
   GICR |= (_BV(INT0) | _BV(INT1));

   /* ... other initialization stuff removed */

   for (;;)
   {
       /* Wait for a message that an input was pressed or timer expired */
       pmsg = AvrXWaitMessage(&amp;inputs_msg_queue);

       /* ... removed if-cases for other unrelated input messages */

       else if (pmsg == &amp;remote_ctrl_pressed_msg)
       {
           DEBUG_PRINT(VERBOSITY_LOW, &quot;RmtCtrl pressed.\n&quot;);

           /* ... removed code that performs the action the button invokes */

           /* Debounce delay for RemoteCtrl button; lets other threads run */
           AvrXDelay(&amp;debounce_timer, DEBOUNCE_DELAY);

           /* Clear flag and enable interrupt */
           GIFR |= _BV(INTF0);
           GICR |= _BV(INT0);
       }
   }
}
</pre></p>
<h2>Brad Basler&#8217;s Debounce Code</h2>
<p>Debounce synchronously or asynchronously using an ISR. Usage is discussed in <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;index&amp;t=89686">this thread</a>.</p>
<p>debounce.h:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">#ifndef __DEBOUNCE_H__
#define __DEBOUNCE_H__

#include &lt;avr/interrupt.h&gt;

//Optimized for 20 millisecond period on a 1Mhz clock
#define DBNC_TIMR0_PRESCALER 	_BV(CS02)
#define DBNC_TIMR0_BASEVAL	 	178

//Defines the size of the debouncer handler arrays (i.e. 4 for a maximum of four)
#define DBNC_NUM_DEBOUNCERS		8

//Defines the number of timer ticks before a value is considered legitimate
//This will define a maximum debounce time of approx 100 milliseconds @ 5
//The minimum debounce time will be approx 80 milliseconds
#define DBNC_COUNTER_TOP 3

#define _BITSHIFTBY(bit,num) ((bit)&lt;&lt;(num))

typedef void(*debounceHandler)(uint8_t,uint8_t);

typedef struct
{
	//A pointer to a volatile port (I/O or otherwise)
	volatile uint8_t *port;

	//A pointer to a debounceHandler function
	debounceHandler handler;

	//This is the decremental counter which determines
	//if the button has been debounced
	uint8_t counter;

	/*

		Bits 0-3: bit index to check against (0-7)
		Bits 4-5: unused
		Bit    5: Last known sate
		Bit    6: Signaled
		Bit    7: Asynchronous

	*/
	uint8_t bitmap;
} DBNC_ITEM;

typedef struct
{

	//An array of debouncer units
	DBNC_ITEM dbUnits[DBNC_NUM_DEBOUNCERS];

	//This is set to 1 when any signal in the dbncSignaled array has been set
	uint8_t signalReady;

} DBNC_GLOBAL;

/*
	Forward Declarations
*/

//ISR for timer0 overflow interrupt
ISR(TIMER0_OVF_vect);
void callSignaledHandlers(void);
void registerDebouncer(volatile uint8_t *port,uint8_t bit,uint8_t index,uint8_t Asynchronous,debounceHandler handler);
void signalChangedState(uint8_t index,uint8_t counterTop);
void initializeDebouncerTimer();

#endif
</pre></p>
<p>debounce.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">#include &lt;avr/io.h&gt;
#include &lt;avr/interrupt.h&gt;
#include &lt;util/delay.h&gt;
#include &quot;debounce.h&quot;

volatile DBNC_GLOBAL db;

//ISR for timer0 overflow interrupt
ISR(TIMER0_OVF_vect)
{
	uint8_t i;
	uint8_t temp;
	uint8_t workDone = 0;

	//Cycle through all debounced items
	for (i=0;i&lt;DBNC_NUM_DEBOUNCERS;i++)
	{
		//Skip items that have been idle
		if (db.dbUnits[i].counter == 0)
			continue;

		workDone = 1;

		//If debounce period has elapsed
		if (--db.dbUnits[i].counter == 0)
		{

			//Grab current logical bit state of the port (1 or 0)
			temp = (((*(db.dbUnits[i].port)) &amp; _BV((db.dbUnits[i].bitmap &amp; 0b111))) != 0);

			//If current state != last state
			//store change
			if (temp != ((db.dbUnits[i].bitmap &amp; _BV(5)) &gt;&gt; 5))
			{
				//Flip last state bit
				db.dbUnits[i].bitmap ^= _BV(5);

				//If this debouncer item is synchronous
				//Then signal it
				if (!(db.dbUnits[i].bitmap &amp; _BV(7))) {

					//Signal this debouncer item
					db.dbUnits[i].bitmap |= _BV(6);

					//Signaling options
					db.signalReady = 1;
				}

				//Otherwise it's asynchronous,
				//call immediately
				else
					//Call Handler
					(*db.dbUnits[i].handler)(i,temp);
			}
		}
	}

	//If all counters were already 0, disable the timer
	if (!workDone)
		TCCR0B = 0;

	TCNT0  = DBNC_TIMR0_BASEVAL;
}

//Call any signaled handlers (to be executed in main program loop)
void callSignaledHandlers(void)
{
	int i;

	if (!db.signalReady) return;

	for (i=0;i&lt;DBNC_NUM_DEBOUNCERS;i++)
	{
		//Check if this item is signaled
		if (db.dbUnits[i].bitmap &amp; _BV(6)) {

			//If so, reset its signal
			db.dbUnits[i].bitmap &amp;= ~_BV(6);

			//Call item and pass on last known state
			(*db.dbUnits[i].handler)(i,(db.dbUnits[i].bitmap &amp; _BV(5))&gt;&gt;5);
		}
	}

	//Reset signal
	db.signalReady = 0;

}

void registerDebouncer(volatile uint8_t *port,uint8_t bit,uint8_t index,uint8_t Asynchronous,debounceHandler handler)
{
	//Store port pointer
	//Store handler pointer
	//Reset counter to 0
	//Store bitmap of bit offset/asynchronous state
	//Set signaled to 0
	db.dbUnits[index].port 		= port;
	db.dbUnits[index].handler 	= handler;
	db.dbUnits[index].counter  	= 0;

	db.dbUnits[index].bitmap	= _BITSHIFTBY((Asynchronous != 0),7)|
						 		  _BITSHIFTBY((((*port) &amp; _BV(bit)) != 0),5)|
						 		  bit;
}

void signalChangedState(uint8_t index,uint8_t counterTop)
{
	if (!counterTop)
		db.dbUnits[index].counter = DBNC_COUNTER_TOP;
	else
		db.dbUnits[index].counter = counterTop;

	if (!TCCR0B)
		TCCR0B = DBNC_TIMR0_PRESCALER;
}

void initializeDebouncerTimer()
{
	//Note: doesn't start timer
	TCCR0A = 0x00;
	TCCR0B = 0x00;
	TCNT0  = DBNC_TIMR0_BASEVAL;
	TIMSK0 = _BV(TOIE0);
}

</pre></p>
<p>test.c:</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">#include &lt;avr/io.h&gt;
#include &lt;util/delay.h&gt;
#include &quot;debounce.h&quot;

volatile uint8_t lastState;

void ButtonClicker(uint8_t index,uint8_t state);

/*

Pin-change interrupt 0

	Detects pin changes on PCINT0-7 (all masked on), i.e. PB0-7 on Atmega2560

	It compares these values to the last known state and signals a change
	on any pins that have changed state.

*/
ISR(PCINT0_vect)
{
	uint8_t temp = lastState^PINB;
	lastState = PINB;

	if ((temp &amp; _BV(0)))
		signalChangedState(0,2);
	if ((temp &amp; _BV(1)))
		signalChangedState(1,3);
	if ((temp &amp; _BV(2)))
		signalChangedState(2,4);
	if ((temp &amp; _BV(3)))
		signalChangedState(3,5);
	if ((temp &amp; _BV(4)))
		signalChangedState(4,20);
	if ((temp &amp; _BV(5)))
		signalChangedState(5,50);
	if ((temp &amp; _BV(6)))
		signalChangedState(6,200);
	if ((temp &amp; _BV(7)))
		signalChangedState(7,200);
}

int main(void)
{
	//Initialize PORTB as all inputs, no internal pull-ups
	DDRB  = 0x00;
	PORTB = 0x00;

	//Initialize PORTD as all outputs, all HIGH (LEDs off)
	DDRD  = 0xFF;
	PORTD = 0xFF;

	//Initial timer setup (does not start timer)
	initializeDebouncerTimer();

	lastState = PINB;

	//Fills in details regarding
	registerDebouncer(&amp;PINB,PB0,0,1,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB1,1,1,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB2,2,1,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB3,3,1,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB4,4,0,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB5,5,0,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB6,6,0,&amp;ButtonClicker);
	registerDebouncer(&amp;PINB,PB7,7,0,&amp;ButtonClicker);

	//Enable pin-change interrupt &amp; mask
	PCICR  = _BV(PCIE0);
	PCMSK0 = 0xFF;

	//Enable interrupts
	sei();

	while(1)
	{
		//This will loop through any signaled debouncer items and
		//call their handlers (doesn't apply to asynchronous)
		callSignaledHandlers();

		_delay_ms(5);
	}

	return 0;
}

void ButtonClicker(uint8_t index,uint8_t state)
{
	if (state == 0)
	{

		PORTD ^= _BV(index);
	}
}
</pre></p>
<h2>William Dillon&#8217;s Debounce Code</h2>
<p>Uses rising and falling edge detection in software to create a digital filter.</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/* uint8_t doDebounce(uint8_t *state, volatile uint8_t *port, uint8_t pin)
 *
 * This function implements the logic for detecting button transitions for
 * arbitrary ports and bits.  The return value is the debounced value the the
 * given pin.
 *
 * The implementation of this function is inspired by the digital filter
 * presented in ECE573 at Oregon State University.  It is different because
 * I'm using the single 8-bit variable to store all of the state, rather than a
 * 8 bit accumulator and 8 bit flag.  We're using the range from 0x00 -&gt; 0x7F
 * and bit 7 (0x80) as the flag.
 *
 * The user of this function must provide a static state variable.  This
 * value encodes the state and history of the pin  Failure to maintain the state
 * would cause erratic behavior.  The port can be any of the PINn
 * memory-mapped input buffers.  Pin must be between 0 and 7.
 *
 * Because these buttons pull to ground, we'll invert the meaning of the edges
 * in software, 1 = yes is much more natural.
 */
uint8_t doDebounce(uint8_t *state, volatile uint8_t *port, uint8_t pin) {
       uint8_t old  =  *state &amp; 0x7F;
       uint8_t flag = (*state &amp; 0x80)? 1 : 0;

       // Digital filter part, value = (old * .75) + (new * .25)
       old -= (old &gt;&gt; 2);                                                              // 1 - (1/4) = .75
       old += ((*port) &amp; (1 &lt;&lt; pin))? 0x1F : 0x00;             // if bit set, add .25

       // Software schmitt trigger
       // Newly detected rising edge
       if ( (flag == 1) &amp;&amp; (old &gt; 0x70) ) {
               flag = 0;
       }

       // Newly detected falling edge
       else if ( (flag == 0) &amp;&amp; (old &lt; 0x07) ){
               flag = 1;
       }

       // Update the state variable
       *state = (old &amp; 0x7F) | ((flag &amp; 0x01) &lt;&lt; 7);

       // Return only the pin state
       return flag;
}</pre></p>
<h2>Mike Szczys&#8217; Debounce Code</h2>
<p>I fell in love with the Danni Debounce code early on. Here&#8217;s my retouched version of it.</p>
<p><pre class="brush: cpp; collapse: true; light: false; toolbar: true; wrap-lines: false;">/*--------------------------------------------------------------------------
10/13/2010: Button debounce code by Mike Szczys

based on &quot;danni debounce&quot; code by Peter Dannegger:

http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=189356#189356

This code detects and debounces button presses. It is tailored for use with
AVR microcontrollers but I've adapted it for other architectures easily and
successfully. It can be modified to use all eight bits on the same port
for up to eight buttons.

The interrupt service routine (ISR) at the bottom uses binary counter
variables (ct0 and ct1) to check the buttons once every 10ms until 40ms has
passed. If the button registeres the first and last times it reads it as
a keypress. There is no functionality in this code for detecting a held
button.
--------------------------------------------------------------------------*/

// F_CPU used by debounce to calculate 10ms interrupts
#define F_CPU 1200000

#include &lt;avr/io.h&gt;
#include &lt;avr/interrupt.h&gt;

//define pins used by buttons
#define KEY_DDR		DDRB
#define KEY_PORT	PORTB
#define KEY_PIN		PINB
#define KEY0		1	//Button on PB1
#define KEY1		2	//Button on PB2

//Debounce variables
unsigned char debounce_cnt = 0;
volatile unsigned char key_press;
unsigned char key_state;

/*--------------------------------------------------------------------------
  Prototypes
--------------------------------------------------------------------------*/
unsigned char get_key_press( unsigned char key_mask );
void init_timers(void);
void init_io(void);

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Used to read debounced button presses
  PARAMS: A keymask corresponding to the pin for the button you with to poll
  RETURNS: A keymask where any high bits represent a button press
--------------------------------------------------------------------------*/
unsigned char get_key_press( unsigned char key_mask )
{
  cli();			// read and clear atomic !
  key_mask &amp;= key_press;	// read key(s)
  key_press ^= key_mask;	// clear key(s)
  sei();			// enable interrupts
  return key_mask;
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Sets and starts a system timer
  PARAMS: NONE
  RETURNS: NONE
--------------------------------------------------------------------------*/
void init_timers(void)
{
  cli();			// read and clear atomic !
  //Timer0 for buttons
  TCCR0B |= 1&lt;&lt;CS02 | 1&lt;&lt;CS00;	//Divide by 1024
  TIMSK0 |= 1&lt;&lt;TOIE0;		//enable timer overflow interrupt
  sei();			// enable interrupts
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Initialize input and output registers
  PARAMS: NONE
  RETURNS: NONE
--------------------------------------------------------------------------*/
void init_io(void)
{
  //Setup Buttons
  KEY_DDR &amp;= ~((1&lt;&lt;KEY0) | (1&lt;&lt;KEY1));	//Set pins as input
  KEY_PORT |= (1&lt;&lt;KEY0) | (1&lt;&lt;KEY1);	//enable pull-up resistors
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Main
--------------------------------------------------------------------------*/
int main(void)
{
  init_timers();	//start the timer
  init_io();		//setup the buttons

  for (;;) //loop forever
  {
    if( get_key_press( 1&lt;&lt;KEY0 ))
    {
      //KEY0 press detected. Do something here
    }

    if (get_key_press( 1&lt;&lt;KEY1 ))
    {
      //KEY1 press detected. Do something here
    }
  }
}

//--------------------------------------------------------------------------
ISR(TIM0_OVF_vect)           // interrupt every 10ms
{
  static unsigned char ct0, ct1;
  unsigned char i;

  //TCNT0 is where TIMER0 starts counting. This calculates a value based on
  //the system clock speed that will cause the timer to reach an overflow
  //after exactly 10ms
  TCNT0 = (unsigned char)(signed short)-(((F_CPU / 1024) * .01) + 0.5);   // preload for 10ms interrupts

  i = key_state ^ ~KEY_PIN;    // key changed ?
  ct0 = ~( ct0 &amp; i );          // reset or count ct0
  ct1 = ct0 ^ (ct1 &amp; i);       // reset or count ct1
  i &amp;= ct0 &amp; ct1;              // count until roll over ?
  key_state ^= i;              // then toggle debounced state
  key_press |= key_state &amp; i;  // 0-&gt;1: key press detect
}</pre></p>
<p><span style="font-size:20px;font-weight:bold;">Links to other code</span></p>
<p>Some folks just sent us links to code. Here they are:</p>
<p>[Pieter Conradie's] <a href="http://www.piconomic.co.za/fwlib/group___k_b_d___m_a_t_r_i_x.html">matrix scanning code</a>.</p>
<p>[Hernandi F. Krammes'] <a href="http://formfeed.blogspot.com/2010/10/debounce-machine-i-state-approach.html">debounce code for PIC</a>.</p>
<p>[Dave] uses [Jack Ganssle's] debounce code; Listing 2 of <a href="http://www.ganssle.com/debouncing-pt2.htm">this page</a>.</p>
<p>&nbsp;</p>
<p>[Photo credit: <a href="http://www.ganssle.com/debouncing.htm">Jack Ganssle</a>]</p>
<br />Filed under: <a href='http://hackaday.com/category/microcontrollers/'>Microcontrollers</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/29916/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/29916/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/29916/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29916&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/feed/</wfw:commentRss>
		<slash:comments>31</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/10/debounce-waveform.jpg" medium="image">
			<media:title type="html">debounce-waveform</media:title>
		</media:content>
	</item>
		<item>
		<title>AVR Programming 03: Reading and compiling code</title>
		<link>http://hackaday.com/2010/11/05/avr-programming-03-reading-and-compiling-code/</link>
		<comments>http://hackaday.com/2010/11/05/avr-programming-03-reading-and-compiling-code/#comments</comments>
		<pubDate>Fri, 05 Nov 2010 22:00:09 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[how-to]]></category>
		<category><![CDATA[Microcontrollers]]></category>
		<category><![CDATA[AVR]]></category>
		<category><![CDATA[bitwise]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[datasheet]]></category>
		<category><![CDATA[programmer]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=29460</guid>
		<description><![CDATA[In the last installment of our tutorial series we built a simple circuit on a breadboard and programmed an ATmega168 to make it run. That proves that you know how to follow directions, but the eureka moments of doing everything yourself are on the way. This time around you will get down and dirty with [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29460&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-29579" title="avr-programming-for-everyone" src="http://hackadaycom.files.wordpress.com/2010/10/avr-programming-for-everyone.jpg" alt="" width="470" height="150" /></p>
<p>In <a href="http://hackaday.com/2010/10/25/avr-programming-02-the-hardware/">the last installment</a> of our tutorial series we built a simple circuit on a breadboard and programmed an ATmega168 to make it run. That proves that you know how to follow directions, but the eureka moments of doing everything yourself are on the way. This time around you will get down and dirty with the datasheet, learning where each line of the sample code came from, and give your recently installed compiler a test drive. We will:</p>
<ul>
<li>Talk about bitwise operators and how they work when coding for microcontrollers</li>
<li>Discuss C code shorthand</li>
<li>Review the sample code from Part 2 and talk about what each line of code does</li>
<li>Learn to compile code</li>
</ul>
<p>If this is the first you&#8217;ve heard about our AVR Programming series, head back to <a href="http://hackaday.com/2010/10/23/avr-programming-introduction/">Part 1</a> and start from the beginning. Otherwise, take a deep breath and we&#8217;ll being after the break.</p>
<p><strong>Series roadmap:</strong></p>
<ul>
<li><a title="Permanent Link to AVR Programming 01: Introduction" rel="bookmark" href="http://hackaday.com/2010/10/23/avr-programming-introduction/">AVR Programming 01: Introduction</a></li>
<li><a title="Permanent Link to AVR Programming 01: Introduction" rel="bookmark" href="http://hackaday.com/2010/10/23/avr-programming-introduction/"></a><a title="Permanent Link to AVR Programming 02: The Hardware" rel="bookmark" href="http://hackaday.com/2010/10/25/avr-programming-02-the-hardware/">AVR Programming 02: The Hardware</a></li>
<li><a title="Permanent Link to AVR Programming 02: The Hardware" rel="bookmark" href="http://hackaday.com/2010/10/25/avr-programming-02-the-hardware/"></a><a title="Permanent Link to AVR Programming 03: Reading and compiling code" rel="bookmark" href="http://hackaday.com/2010/11/05/avr-programming-03-reading-and-compiling-code/">AVR Programming 03: Reading and compiling code</a></li>
<li><a href="http://hackaday.com/2010/11/19/avr-programming-04-writing-code-etc/">AVR Programming 04: Writing code</a></li>
</ul>
<p><span id="more-29460"></span></p>
<h2>Prerequisites</h2>
<ul>
<li>You must know something about C code. The ability to read it is probably good enough, Google can help you with the rest as you learn.</li>
<li>It helps if you have a text editor that includes syntax highlighting. I&#8217;m purely a Linux user and I like to use both Kate and Gedit depending on my mood. But I also use nano from the shell quite frequently. This is a tool and your choice is purely personal preference.</li>
<li>Grab <a href="https://github.com/szczys/had_AVRtut_2/archives/master">the sample code from part 2</a> of the series. I&#8217;ve embedded it below but you may want it in a separate windows for reference.</li>
<li>Datasheets; the instruction manual for hardware. Grab <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf">the datasheet for the ATmega168</a> as I&#8217;ll be referencing specific pages as examples. Knowing how to look up information in the datasheet and turn it into code will make it easy for you to use any chip in the AVR family.</li>
</ul>
<h2>Bitwise Operators</h2>
<p>Even though we&#8217;ll be writing code in the C language, we&#8217;re quite close to the hardware when programming microcontrollers. Because of this <strong>you must understand bitwise operators</strong>. Not just kind of, not intuitively, you should know them well enough to teach them to someone else without looking it up.</p>
<p>Hands down the best explanation I&#8217;ve ever come across is by [Eric Weddington], who also co-authored the makefile that came with my example code. It is also known as <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;t=37871">Programming 101.</a> Read it, know it, love it. But I&#8217;ll try to give a quick crash course for those to lazy to read his whole lesson.</p>
<div style="padding-left:30px;">
<table border="1">
<tbody>
<tr>
<th>Code Symbol</th>
<th>Logic Function</th>
</tr>
<tr>
<td align="center">|</td>
<td align="center">OR</td>
</tr>
<tr>
<td align="center">&amp;</td>
<td align="center">AND</td>
</tr>
<tr>
<td align="center">~</td>
<td align="center">NOT</td>
</tr>
<tr>
<td align="center">^</td>
<td align="center">XOR</td>
</tr>
<tr>
<td align="center">&lt;&lt;</td>
<td align="center">Shift Left</td>
</tr>
<tr>
<td align="center">&gt;&gt;</td>
<td align="center">Shift Right</td>
</tr>
</tbody>
</table>
</div>
<p>The list above shows all of the code symbols and their logic operation.</p>
<ul>
<li>OR &#8211; true if either or both bits being compared are 1</li>
<li>AND &#8211; true only if both bits being compared are 1</li>
<li>NOT &#8211; results in the opposite of a value (~1 = 0, ~0 = 1)</li>
<li>XOR &#8211; exclusive OR&#8230; true if one bit being compared is 1 but false if neither or both of them are</li>
<li>Shift Left &#8211; moves bits left within a binary number. (1&lt;&lt;0 = 0b0001, 1&lt;&lt;4 = 0b1000)</li>
<li>Shift Right &#8211; moves bits to the right a desired amount (0b1000&gt;&gt;2 = 0b0010)</li>
</ul>
<p>We&#8217;re going to use Shift Left all the time in our code because it&#8217;s a quick way to build a binary number. We&#8217;re <strong>always</strong> working in binary numbers made up of eight bits. Those bits are numbered 0-7 because counting always starts with 0 when it comes to microcontrollers. So if you want to set the fifth bit to a logic high (&#8217;1&#8242;) you would shift &#8217;1&#8242; left by 5:</p>
<pre>1&lt;&lt;5</pre>
<p>This will result in the binary number 0b00100000. If this is child&#8217;s play, move to the next section. If not, read [Eric's] tutorial.</p>
<h2>C Code Shorthand</h2>
<p>I tend to use shorthand in my code as my hands often hurt from too much typing (as they do now). This saves a bit on the old ibuprofen expenditure for the month by allowing me to type less characters to accomplish the same simple assignments. Here&#8217;s a quick table of examples:</p>
<div style="padding-left:30px;">
<table border="1">
<tbody>
<tr>
<th>Traditional Code</th>
<th>Shorthand Equivalent</th>
</tr>
<tr>
<td align="center">value = value + 1;</td>
<td align="center">value += 1;</td>
</tr>
<tr>
<td align="center">value = value &gt;&gt; 1;</td>
<td align="center">value &gt;&gt;= 1;</td>
</tr>
<tr>
<td align="center">value = value &amp; bitMask;</td>
<td align="center">value &amp;= bitMask;</td>
</tr>
<tr>
<td align="center">value = value | bitMask;</td>
<td align="center">value |= bitMask;</td>
</tr>
<tr>
<td align="center">PORTD = PORTD ^ (1&lt;&lt;0);</td>
<td align="center">PORTD ^= (1&lt;&lt;0);</td>
</tr>
</tbody>
</table>
</div>
<p>So basically, if I am setting a variable by using that same variable as the first <a href="http://en.wikipedia.org/wiki/Operand">operand</a> I can just place the <a href="http://en.wikipedia.org/wiki/Operator">operator</a> before the equals sign and put the second operand after the equals sign to accomplish the same task without typing the variable name twice. If you understood that sentence you&#8217;re doing quite well!</p>
<p><span style="font-size:20px;font-weight:bold;">Jump into the sample code</span></p>
<p><strong>Psuedocode</strong></p>
<p>A good practice when developing code is to write psuedocode. Something that clearly states what you want to do in plain language. This is an outline of the structure that your program will take and it shouldn&#8217;t include any specific code, but will be replaced by that code later:</p>
<p><pre class="brush: cpp;">//Setup the clock
  //prepare an interrupt every 1 second

//Setup the I/O for the LED

//toggle the LED during each interrupt</pre></p>
<p>This program is so simple that the psuedocode seems unnecessary, but it will keep you focused and help stave off errors on larger projects.</p>
<p><strong>The Actual Code</strong></p>
<p>The main.c from the <a href="https://github.com/szczys/had_AVRtut_2/archives/master">Part 2 sample code</a> is embedded below. Take a minute to match up the parts of the psuedocode above with actual code blocks below.</p>
<p><pre class="brush: cpp; wrap-lines: false;">/*
* Hackaday.com AVR Tutorial firmware
* written by: Mike Szczys (@szczys)
* 10/24/2010
*
* ATmega168
* Blinks one LED conneced to PD0
*
* http://hackaday.com/2010/10/25/avr-programming-02-the-hardware/
*/

#include &lt;avr/io.h&gt;
#include &lt;avr/interrupt.h&gt;

int main(void)
{

  //Setup the clock
  cli();			//Disable global interrupts
  TCCR1B |= 1&lt;&lt;CS11 | 1&lt;&lt;CS10;	//Divide by 64
  OCR1A = 15624;		//Count 15624 cycles for 1 second interrupt
  TCCR1B |= 1&lt;&lt;WGM12;		//Put Timer/Counter1 in CTC mode
  TIMSK1 |= 1&lt;&lt;OCIE1A;		//enable timer compare interrupt
  sei();			//Enable global interrupts

  //Setup the I/O for the LED

  DDRD |= (1&lt;&lt;0);		//Set PortD Pin0 as an output
  PORTD |= (1&lt;&lt;0);		//Set PortD Pin0 high to turn on LED

  while(1) { }			//Loop forever, interrupts do the rest
}

ISR(TIMER1_COMPA_vect)		//Interrupt Service Routine
{
  PORTD ^= (1&lt;&lt;0);		//Use xor to toggle the LED
}</pre></p>
<p>The first few lines are comments for the benefit of human eyes and will not be used by the microcontroller. Comments in C are prefaced by two slashes (//) for single line comments or encased in slash-star (/*) and star-slash (*/) pairs for multiline comments. It&#8217;s a good idea to write comments that detail the program, what it does, what hardware it runs on, and any other helpful information. I find that I often reuse code from past projects and a bit of information at the top of the file helps locate what I&#8217;m looking for quickly.</p>
<p><strong>The Includes</strong></p>
<p>The next thing you see are the includes:</p>
<p><pre class="brush: cpp; wrap-lines: false;">#include &lt;avr/io.h&gt;
#include &lt;avr/interrupt.h&gt;</pre></p>
<p>Includes tell the compiler that we&#8217;re going to be using things from other files. In this case, two files from <a href="http://www.nongnu.org/avr-libc/user-manual/">AVR Libc</a> that came with the cross-compiling toolchain we installed in <a href="http://hackaday.com/2010/10/23/avr-programming-introduction/">Part 1</a>. These are C files that allow us to use human-readable (and rememberable!) code when working with the hardware on the chip. The io.h file rolls header files for all of the supported AVR chips into one. We define what processor we&#8217;re using in our makefile, and the appropriate header file is automatically chosen from io.h when we compile our code later in this tutorial.</p>
<p>In our example code I&#8217;ve used names like DDRD, PORTD, TCCR1B, OCR1A, TIMSK1, etc. All of these have addresses that are pointed to using the io.h file. This allows us to call pins on the chip by the names like PORTD which are the same across all AVR variants instead of register addresses like 0x0B which has different functions on different chips. Most likely you&#8217;ll need to include io.h in every AVR program you use, and doing so makes your code more portable. The interrupt.h file is only needed if you are using interrupts, something we&#8217;ll talk about as we look at the next code block</p>
<p><strong>Setting up the clock for use with interrupts</strong></p>
<p>Processors need a clock signal in order to work. AVR chips can use external clocks like a crystal oscillator or a ceramic resonator, but they come from the factory configured to use the internal RC oscillator as the system clock (read more on page 28 of the datasheet). The internal RC oscillator of the ATmega168 runs at approximately 8.0 MHz depending on voltage stability and temperature. It also ships with the DIV8 fuse enabled which divides the clock signal down to 1.0 MHz. For the sample program I wanted an LED to blink between on and off, changing about once a second. Here&#8217;s the code block that sets that functionality up:</p>
<p><pre class="brush: cpp; wrap-lines: false;">  //Setup the clock
  cli();			//Disable global interrupts
  TCCR1B |= 1&lt;&lt;CS11 | 1&lt;&lt;CS10;	//Divide by 64
  OCR1A = 15624;		//Count 15624 cycles for 1 second interrupt
  TCCR1B |= 1&lt;&lt;WGM12;		//Put Timer/Counter1 in CTC mode
  TIMSK1 |= 1&lt;&lt;OCIE1A;		//enable timer compare interrupt
  sei();			//Enable global interrupts
</pre></p>
<p>The very first line has something to do with interrupts. An interrupt is a great feature of microprocessors. Basically you tell the chips to watch for a certain condition. When it matches that condition it will stop what it is doing no matter where it is, and run a different set of code called an Interrupt Service Routine (ISR). Because we are about to change some settings having to do with interrupts, we don&#8217;t want anything (like an interrupt) to stop us in the middle of this process. I&#8217;ve used a command that is available to us because we included interrupt.h at the beginning of our file. The command is <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html#ga68c330e94fe121eba993e5a5973c3162">cli();</a> which disables all interrupts. Once we are done with our settings we <span style="text-decoration:underline;">must</span> remember to enable them again, using the <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html#gaad5ebd34cb344c26ac87594f79b06b73">sei();</a> command. You can see I&#8217;ve done that at the bottom of this code block</p>
<p>Now we want to watch for the passage of 1 second worth of time. The four lines in between these two commands are used to setup a counter to do just that. Because the internal oscillator is running at 1 MHz, or 1 Million cycles per second, we must trigger an interrupt every 1 million cycles. The biggest timer this chip has is 16-bits which can only count from 0 to 65,535. In other words, we don&#8217;t have a timer that can count high enough to measure such a large number of cycles.</p>
<p>Fortunately, we have the option to use a divider with our timer, called a prescaler. To do so we look in the datasheet on page 134 to see a chart outlining the clock select. It shows prescaler options which divide the system clock by 1, 8, 64, 256, and 1024. Knowing that we want to count 1,000,000 cycles we can use a bit of math to choose the best prescaler:</p>
<pre style="padding-left:30px;">1,000,000 / 1 = 1,000,000
1,000,000 / 8 = 125,000
1,000,000 / 64 = 15,625
1,000,000 / 256 = 3,906.25
1,000,000 / 1024 = 976.5625</pre>
<p>The math only leaves us with one choice. That&#8217;s because using a prescaler of 1 or 8 results in a number of cycles that is larger than <a href="http://www.google.com/#hl=en&amp;expIds=17259,24416,26637,27060,27284,27357&amp;sugexp=ldymls&amp;xhr=t&amp;q=2%5E16&amp;cp=4&amp;pf=p&amp;sclient=psy&amp;aq=f&amp;aqi=h1g4&amp;aql=&amp;oq=2%5E16&amp;gs_rfai=&amp;pbx=1&amp;fp=2304850557947867">65,536</a> so our 16-bit timer can&#8217;t count high enough. Prescalers of 256 and 1024 give results that are not a whole number. If we don&#8217;t use a whole number we introduce an inaccuracy in our timing because we can&#8217;t measure a fraction of a cycle. A prescaler of 64 meets both our needs, being a whole number that is smaller than the limits of our 16-bit counter.</p>
<p>How can we set up this prescaler? The datasheet tells all. Looking at &#8220;Timer/Counter1 Control Register B&#8221; (TCCR1B) which spans pages 133 and 134 we can find the answer. Diagram 15-5 shows a clock settings table. In our case we need to set CS10 and CS11 to &#8217;1&#8242; on the TCCR1B register. To do this we use an OR operator and Left Shift a &#8217;1&#8242; to the location of the CS10 and CS11 bits:</p>
<p><pre class="brush: cpp; wrap-lines: false;">  TCCR1B |= 1&lt;&lt;CS11 | 1&lt;&lt;CS10;</pre></p>
<p>Because this is our first real bitwise math let&#8217;s look at it in depth. First off, we&#8217;re only setting two bits on the register so we do not want to use just an equals sign. If I had done that, this command would force all other bits to zero. Instead, I use shorthand code to use the OR operator to compare TCCR1B with a bitmask containing a &#8217;1&#8242; at the correct location for the CS10 and CS11 bits. Any other bits on the  TCCR1B register that are set to &#8217;1&#8242; will remain so.</p>
<p>I&#8217;ve created a bitmask to the right of the |= operator. As I talked about in the includes section, CS10 and CS11 are defined in io.h. But looking at the TCCR1B register we can see that CS10 is on bit 0 and CS11 is on bit 1. If you solved your math problem longhand it would look like this:</p>
<pre>1&lt;&lt;CS11 | 1&lt;&lt;CS10;
1&lt;&lt;1 | 1&lt;&lt;0;
0b00000010 | 0b00000001;
0b00000011;</pre>
<p>This is the method that you use for setting any bit for any purpose. It really is that simple. Build a bitmask and apply it to a register or variable. Just remember to be careful about preserving data that might already be stored on a register or in a value but using the OR operator during assignment.</p>
<p>Now that we have a divided clock source for the counter, and a target number of 15,625 cycles to watch for thanks to the math above. We can use one of the modes of Timer1, the Clear Timer on Compare Match (CTC), to trigger an interrupt at that exact cycle count. Take a look at page 121 of the datasheet and you will see we need to set OCR1A to our target value. We&#8217;ll set it to 15,624, one less than our cycle count because microcontroller timers start counting with the number zero, not one. This time we will use an equal sign because there are no other values stored in this register:</p>
<p><pre class="brush: cpp; wrap-lines: false;">  OCR1A = 15624;</pre></p>
<p>I also need to set the timer mode I want to use. Table 15-4 on page 133 has a lot of information on this. As discussed before, I want to use CTC mode so that narrows my choices on this table down to just two. I can choose between those because I know I&#8217;m using the value of OCR1A as the largest number the timer should count to, or TOP. The chart tells me to set the WGM12 bit on the TCCR1B register to 1.:</p>
<p><pre class="brush: cpp; wrap-lines: false;">  TCCR1B |= 1&lt;&lt;WGM12;</pre></p>
<p>This could have been done at the same time as the timer prescaler because they&#8217;re set on the same register. But it&#8217;s fine to do it in two steps because I&#8217;ve used the OR operator, making sure I&#8217;m not changing any of the other bits on this register.</p>
<p>The next step can be a &#8220;gotcha&#8221; for new developers. Everything is now setup correctly for our timer to trigger an interrupt at the appropriate interval. But if we don&#8217;t set the &#8220;interrupt enable&#8221; flag for that particular event, the interrupt will never happen. Page 136 of the datasheet cryptically discusses the use of the Timer/Counter Output Compare A Match Interrupt Enable. Setting this bit to 1 will enable the CTC interrupt we are planning to use:</p>
<p><pre class="brush: cpp; wrap-lines: false;">   TIMSK1 |= 1&lt;&lt;OCIE1A;</pre></p>
<p>Simple right? Do it a few times and it will be. There&#8217;s a lot of functionality with the timers on these chips and wading through the register settings is the price you pay for that power. But now we&#8217;re ready to go with 1-second interrupts.</p>
<p><strong>Initializing the Input/Output pins</strong></p>
<p>When an AVR chip resets, the pins are all placed in tri-state mode. At the beginning of the program any input and output pins need to be setup for their desired function. Starting on page 73 of the datasheet you can read about using pins as general input and output. There are three registers for each pin that we will generally be concerned with: Data Direction Register (DDR), Port register (PORT) and Pin register (PIN). Each of these will be suffixed with a letter corresponding to which set of pins we are working with. I&#8217;ve connected the LED to Port D so I need to work with DDRD, PORTD, and if I was using inputs, PIND.</p>
<p><pre class="brush: cpp; wrap-lines: false;">  //Setup the I/O for the LED

  DDRD |= (1&lt;&lt;0);		//Set PortD Pin0 as an output
  PORTD |= (1&lt;&lt;0);		//Set PortD Pin0 high to turn on LED</pre></p>
<p>The code above is used to set up an LED. Setting a bit on DDRD to 1 will make the corresponding pin an output. Setting it to zero would make it an input. Here I&#8217;ve set up an output because we are driving an LED. Outputs can be turned on or off by setting a 1 or a 0 to the PORT register respectively. So above I&#8217;ve used PORTD to turn on bit 0 which corresponds to pin connected to the LED.</p>
<p>If we were using a pin as an input the PORT register would be used to enable or disable an internal pull-up resistor and the PIN register would be used to measure the logic value currently present on that pin. Table 13-1 on page 74 shows the various states of I/O pins, but I&#8217;ll cover it more in part 4 of this series.</p>
<p><strong>The Loop</strong></p>
<p>Embedded programs must have an infinite loop that prevents the program from getting to the end and exiting. That&#8217;s because if our program exits the chip will just sit there and do nothing (after all, there&#8217;d be no program running). In this case I don&#8217;t need the loop to do anything since I&#8217;ve already set up the hardware and I&#8217;m using an interrupt to blink the LED:</p>
<p><pre class="brush: cpp; wrap-lines: false;">  while(1) { }			//Loop forever, interrupts do the rest</pre></p>
<p>I&#8217;ll add functionality to the loop in Part 4 or the series, but for now the &#8216;while(1)&#8217; loop just traps the program and does nothing else.</p>
<p><strong>Handling the interrupt</strong></p>
<p>Everything is now setup and ready to go, but nothing will happen unless we write code that does something after the interrupt happens. This is called an Interrupt Service Routine (ISR). The rest of the code is halted and this routine is run. It is best to keep this as short as possible, which is easy here because we just need to toggle the LED:</p>
<p><pre class="brush: cpp; wrap-lines: false;">ISR(TIMER1_COMPA_vect)		//Interrupt Service Routine
{
  PORTD ^= (1&lt;&lt;0);		//Use xor to toggle the LED
}</pre></p>
<p>If you look at page 62 of the datasheet you can see that the interrupt source for Timer/Counter1 Compare A match is called &#8220;TIMER1 COMPA&#8221;. We take this and use it as the input variable for the ISR, replacing spaces with underscores and adding a lower case &#8220;vect&#8221; at the end. This is how the compiler knows which ISR belongs to different interrupt sources. As for the LED itself, I&#8217;ve used the XOR operator and a bitmask. The bitmask ensures that only bit 0 will be changed.</p>
<h2>Compiling Code</h2>
<p>Before we leave this segment of the tutorial series you should give your compiler a test-drive.</p>
<p>The compiler takes our C code and turns it into a file that can be written to the microcontroller. The ins and outs of a compiler get a bit hairy and this isn&#8217;t the time to explain those details. But as you learn to write embedded code you should make an effort to also learn how this code will be interpreted by the compiler. Doing so will prevent a lot of headaches caused by optimization (the compiler trying to streamline your bloated C code) and it will allow you to make the most of your hardware both in terms of programming space, and functionality.</p>
<p>But for now there&#8217;s a make file included in <a href="https://github.com/szczys/had_AVRtut_2/archives/master">the example source from Part 2</a>. If you haven&#8217;t already, unzip that package and navigate to the &#8216;src&#8217; directory. There are two files in that directory, main.c and makefile. A makefile is a way to automate the compiling process. This one compiles, links, and programs a C code source file. If you look at the makefile you&#8217;ll notice that there are several user settings near the top. You need to setup the microprocessor for which you&#8217;ve written code, the name of the source file you&#8217;ve written (TARGET = main), the programmer you&#8217;re using (from the AVRdude list discussed in Part 2), and the port path for the programmer.</p>
<p>If you type &#8216;make&#8217; you should be able to compile the example program. Unless you have an AVR Dragon programmer and you&#8217;re running Linux you&#8217;ll get an error when it tries to program the chip, but it should compile the code and output several extra files:</p>
<p><pre class="brush: bash; wrap-lines: false;">$  ls -la
total 84
drwxr-xr-x 2 mike mike  4096 2010-11-04 14:20 .
drwxr-xr-x 3 mike mike  4096 2010-11-01 14:55 ..
-rw-r--r-- 1 mike mike   894 2010-10-24 12:34 main.c
-rw-r--r-- 1 mike mike    23 2010-11-04 14:20 main.d
-rw-r--r-- 1 mike mike    13 2010-11-04 14:20 main.eep
-rwxr-xr-x 1 mike mike  7121 2010-11-04 14:20 main.elf
-rw-r--r-- 1 mike mike   750 2010-11-04 14:20 main.hex
-rw-r--r-- 1 mike mike  5224 2010-11-04 14:20 main.lss
-rw-r--r-- 1 mike mike  5171 2010-11-04 14:20 main.lst
-rw-r--r-- 1 mike mike 14464 2010-11-04 14:20 main.map
-rw-r--r-- 1 mike mike  3972 2010-11-04 14:20 main.o
-rw-r--r-- 1 mike mike  1454 2010-11-04 14:20 main.sym
-rw-r--r-- 1 mike mike 10235 2010-10-24 10:44 makefile</pre></p>
<p>&#8216;main.hex&#8217; is the file that you can program onto the microcontroller. This makefile is extremely versatile. You can also see that it output &#8216;main.eep&#8217; which can be used to program the EEPROM on the chip if your code includes default data stored in the EEPROM. It can also be altered to output an assembler file, or binaries in different formats.</p>
<p>If you&#8217;re compiler didn&#8217;t spit out this information, there&#8217;s something wrong with your toolchain. Use your friend Google to search for any error messages and see if you can&#8217;t get things fixed up. Another great exercise would be to modify this file to work with your programmer. If you managed to get AVRdude working in Part 2 of this series, this alteration is as simple as changing the makefile to use those same settings.</p>
<h2>Conclusion</h2>
<p>That&#8217;s it for now. In the next installment of this series I&#8217;ll be talking about fuse bits, writing our own code, and I&#8217;ll try to touch on many of the different peripheral features of this chip. I&#8217;m plan to augment the original circuit with a few more LEDs (so make sure you have at least 8 of them and their matching resistors) along with adding a button for input. Thanks for reading!</p>
<h2><strong>Follow Me</strong></h2>
<p><a href="http://twitter.com/szczys">@szczys</a></p>
<h2>Resources</h2>
<p>Atmel AVR <a href="http://www.atmel.com/dyn/resources/prod_documents/doc2545.pdf">ATmega168 Datasheet</a> (PDF)</p>
<p><a href="http://www.nongnu.org/avr-libc/user-manual/">AVR Libc manual</a></p>
<br />Filed under: <a href='http://hackaday.com/category/how-to/'>how-to</a>, <a href='http://hackaday.com/category/microcontrollers/'>Microcontrollers</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/29460/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/29460/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/29460/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29460&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/11/05/avr-programming-03-reading-and-compiling-code/feed/</wfw:commentRss>
		<slash:comments>29</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/10/avr-programming-for-everyone.jpg" medium="image">
			<media:title type="html">avr-programming-for-everyone</media:title>
		</media:content>
	</item>
		<item>
		<title>Open Call: send us your Debounce code</title>
		<link>http://hackaday.com/2010/10/13/open-call-send-us-your-debounce-code/</link>
		<comments>http://hackaday.com/2010/10/13/open-call-send-us-your-debounce-code/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 20:11:32 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[HackIt]]></category>
		<category><![CDATA[assembly]]></category>
		<category><![CDATA[button]]></category>
		<category><![CDATA[c++]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[debounce]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[switch]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=29271</guid>
		<description><![CDATA[If you&#8217;ve ever designed an embedded system with at least one button you&#8217;ve had to deal with button debouncing. This is also know as contact bounce, a phenomenon where a button press can be registered as multiple button presses if not handled correctly. One way to take care of this is with a hardware filter built from [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29271&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-29272" title="debounce-waveform" src="http://hackadaycom.files.wordpress.com/2010/10/debounce-waveform.jpg" alt="" width="470" height="244" /></p>
<p>If you&#8217;ve ever designed an embedded system with at least one button you&#8217;ve had to deal with button debouncing. This is also know as <a href="http://en.wikipedia.org/wiki/Debounce#Contact_bounce">contact bounce</a>, a phenomenon where a button press can be registered as multiple button presses if not handled correctly. One way to take care of this is with a hardware filter built from a resistor-capacitor setup, or by using a couple of NAND gates. We find that [Jack Ganssle] put together the most comprehensive and <a href="http://www.ganssle.com/debouncing.htm">approachable look at contact bounce</a> which you should read through if you want to learn more.</p>
<p>We&#8217;re interested in software solutions for debouncing buttons. This seems to be <a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;t=33821">one of the most common forum questions</a> but it can be hard to find answers in the form of reliable code examples. Do you have debounce code that you depend on in every application? Are you willing to share it with the world? We&#8217;d like to gather as many examples as possible and publish them in one-post-to-rule-them-all.</p>
<h2>Send your debounce code to: <a href="mailto:debounce@hackaday.com">debounce@hackaday.com</a></h2>
<p>Here&#8217;s some guidelines to follow:</p>
<ul>
<li><strong>Please only include debounce code.</strong> Get rid of other unrelated functions/etc.</li>
<li><strong>You should send C code.</strong> If you want to also send an assembly code version that&#8217;s fine, but it must be supplementary to the C code.</li>
<li><strong>Please comment your code.</strong> This will help others understand and use it. You may be tempted to explain the code in your email but this info is best placed in the code comments</li>
<li><strong>Cite your sources.</strong> If you adapted this code from someone else&#8217;s please include a note about that in the code comments.</li>
</ul>
<p>As an example we&#8217;ve included one of our favorite sets of debounce code after the break. Please note how it follows the guidelines listed above.</p>
<p><span id="more-29271"></span></p>
<p><pre class="brush: cpp; wrap-lines: false;">/*--------------------------------------------------------------------------
10/13/2010: Button debounce code by Mike Szczys

based on &quot;danni debounce&quot; code by Peter Dannegger:
http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=189356#189356

This code detects and debounces button presses. It is tailored for use with
AVR microcontrollers but I've adapted it for other architectures easily and
successfully. It can be modified to use all eight bits on the same port
for up to eight buttons.

The interrupt service routine (ISR) at the bottom uses binary counter
variables (ct0 and ct1) to check the buttons once every 10ms until 40ms has
passed. If the button registeres the first and last times it reads it as
a keypress. There is no functionality in this code for detecting a held
button.
--------------------------------------------------------------------------*/

// F_CPU used by debounce to calculate 10ms interrupts
#define F_CPU 1200000

#include &lt;avr/io.h&gt;
#include &lt;avr/interrupt.h&gt;

//define pins used by buttons
#define KEY_DDR		DDRB
#define KEY_PORT	PORTB
#define KEY_PIN		PINB
#define KEY0		1	//Button on PB1
#define KEY1		2	//Button on PB2

//Debounce variables
unsigned char debounce_cnt = 0;
volatile unsigned char key_press;
unsigned char key_state;

/*--------------------------------------------------------------------------
  Prototypes
--------------------------------------------------------------------------*/
unsigned char get_key_press( unsigned char key_mask );
void init_timers(void);
void init_io(void);

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Used to read debounced button presses
  PARAMS: A keymask corresponding to the pin for the button you with to poll
  RETURNS: A keymask where any high bits represent a button press
--------------------------------------------------------------------------*/
unsigned char get_key_press( unsigned char key_mask )
{
  cli();			// read and clear atomic !
  key_mask &amp;= key_press;	// read key(s)
  key_press ^= key_mask;	// clear key(s)
  sei();			// enable interrupts
  return key_mask;
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Sets and starts a system timer
  PARAMS: NONE
  RETURNS: NONE
--------------------------------------------------------------------------*/
void init_timers(void)
{
  cli();			// read and clear atomic !
  //Timer0 for buttons
  TCCR0B |= 1&lt;&lt;CS02 | 1&lt;&lt;CS00;	//Divide by 1024
  TIMSK0 |= 1&lt;&lt;TOIE0;		//enable timer overflow interrupt
  sei();			// enable interrupts
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Initialize input and output registers
  PARAMS: NONE
  RETURNS: NONE
--------------------------------------------------------------------------*/
void init_io(void)
{
  //Setup Buttons
  KEY_DDR &amp;= ~((1&lt;&lt;KEY0) | (1&lt;&lt;KEY1));	//Set pins as input
  KEY_PORT |= (1&lt;&lt;KEY0) | (1&lt;&lt;KEY1);	//enable pull-up resistors
}

/*--------------------------------------------------------------------------
  FUNC: 10/13/10 - Main
--------------------------------------------------------------------------*/
int main(void)
{
  init_timers();	//start the timer
  init_io();		//setup the buttons

  for (;;) //loop forever
  {
    if( get_key_press( 1&lt;&lt;KEY0 ))
    {
      //KEY0 press detected. Do something here
    }

    if (get_key_press( 1&lt;&lt;KEY1 ))
    {
      //KEY1 press detected. Do something here
    }
  }
}

//--------------------------------------------------------------------------
ISR(TIM0_OVF_vect)           // interrupt every 10ms
{
  static unsigned char ct0, ct1;
  unsigned char i;

  //TCNT0 is where TIMER0 starts counting. This calculates a value based on
  //the system clock speed that will cause the timer to reach an overflow
  //after exactly 10ms
  TCNT0 = (unsigned char)(signed short)-(((F_CPU / 1024) * .01) + 0.5);   // preload for 10ms interrupts

  i = key_state ^ ~KEY_PIN;    // key changed ?
  ct0 = ~( ct0 &amp; i );          // reset or count ct0
  ct1 = ct0 ^ (ct1 &amp; i);       // reset or count ct1
  i &amp;= ct0 &amp; ct1;              // count until roll over ?
  key_state ^= i;              // then toggle debounced state
  key_press |= key_state &amp; i;  // 0-&gt;1: key press detect
}</pre></p>
<p>[Photo credit: <a href="http://www.ganssle.com/debouncing.htm">Jack Ganssle</a>]</p>
<br />Filed under: <a href='http://hackaday.com/category/hackit/'>HackIt</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/29271/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/29271/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/29271/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=29271&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/10/13/open-call-send-us-your-debounce-code/feed/</wfw:commentRss>
		<slash:comments>75</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/10/debounce-waveform.jpg" medium="image">
			<media:title type="html">debounce-waveform</media:title>
		</media:content>
	</item>
		<item>
		<title>As promised: more industrial robot goodness</title>
		<link>http://hackaday.com/2010/09/19/as-promised-more-industrial-robot-goodness/</link>
		<comments>http://hackaday.com/2010/09/19/as-promised-more-industrial-robot-goodness/#comments</comments>
		<pubDate>Sun, 19 Sep 2010 14:10:31 +0000</pubDate>
		<dc:creator>Jakob Griffith</dc:creator>
				<category><![CDATA[robots hacks]]></category>
		<category><![CDATA[arm]]></category>
		<category><![CDATA[bmw]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[industrial]]></category>
		<category><![CDATA[robot]]></category>
		<category><![CDATA[scribblybot]]></category>
		<category><![CDATA[twitter]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=28300</guid>
		<description><![CDATA[Remember [Mattythorne]? He took a BMW industrial arm and re-purposed it to write twitter messages on a white board. You can read a small excerpt here. Well [Matt] is back, and as promised includes an entire write up for how he got @scribblebot scribbling twitter messages.  It&#8217;s a little light on details and we wish [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=28300&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-28302" title="Anyone read the hilarious tweets people are sending? We would start flipping out if we saw the robot write &quot;Warning Error, aborting original objective. New Objective: Must. Destroy. Humans.&quot;" src="http://hackadaycom.files.wordpress.com/2010/09/4814802710_f63ed4ed1e_b.jpg" alt="" width="470" height="353" /></p>
<p>Remember [Mattythorne]? He took a BMW industrial arm and <a href="http://blog.mattythorne.com/2010/09/18/scribblybot-the-full-story/">re-purposed it to write twitter messages</a> on a white board. You can read a <a href="http://hackaday.com/2010/09/07/re-purpose-industrial-robotic-arms/">small excerpt here. </a></p>
<p>Well [Matt] is back, and as promised includes an entire write up for how he got <a href="http://twitter.com/scribblybot">@scribblebot</a> scribbling twitter messages.  It&#8217;s a little light on details and we wish there was some more in-depth how-to magic, but then we remembered with most of the population not having an industrial arm in the first place the extra time spent incorporating the extra info would be far from worth it. Regardless, it doesn&#8217;t surprise that the previous commentators were not far off the mark in how difficult programing one of these machines would be. While such arms do have a few built in libraries it looks like a very exhausting process to override the default axis of motion, incorporate a UI, build a pen holder, and more. And in the end, is it worth it? [Matt] tells us the arm is going to be going back to monotonous car building work soon, giving weeks of prep only a day in the limelight.</p>
<br />Filed under: <a href='http://hackaday.com/category/robots-hacks/'>robots hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/28300/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/28300/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/28300/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=28300&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/09/19/as-promised-more-industrial-robot-goodness/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Jakob Griffith</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/09/4814802710_f63ed4ed1e_b.jpg" medium="image">
			<media:title type="html">Anyone read the hilarious tweets people are sending? We would start flipping out if we saw the robot write &#34;Warning Error, aborting original objective. New Objective: Must. Destroy. Humans.&#34;</media:title>
		</media:content>
	</item>
		<item>
		<title>Automated entry for a garden gate</title>
		<link>http://hackaday.com/2010/09/14/automated-entry-for-a-garden-gate/</link>
		<comments>http://hackaday.com/2010/09/14/automated-entry-for-a-garden-gate/#comments</comments>
		<pubDate>Tue, 14 Sep 2010 16:00:44 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[home hacks]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[electronic strike]]></category>
		<category><![CDATA[garden]]></category>
		<category><![CDATA[gate]]></category>
		<category><![CDATA[iphone]]></category>
		<category><![CDATA[keypad]]></category>
		<category><![CDATA[lock]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=28201</guid>
		<description><![CDATA[[Dan McGrath] tipped us off about a solution for a problem that most people don&#8217;t have. He built a web-based entry system for his garden gate. This isn&#8217;t quite as original as that chain and sprocket dorm room system, but it does use a keypad for entry. [Dan's] already got a web server and home [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=28201&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-28202" title="side-gate-automated-entry" src="http://hackadaycom.files.wordpress.com/2010/09/side-gate-automated-entry.jpg" alt="" width="470" height="377" /></p>
<p>[Dan McGrath] tipped us off about a solution for a problem that most people don&#8217;t have. He built <a href="http://www.yourmissus.com/gate_automation/">a web-based entry system for his garden gate</a>. This isn&#8217;t quite as original as <a href="http://hackaday.com/2010/09/11/keypad-door-lock-better-than-last-years-keyfob/">that chain and sprocket dorm room system</a>, but it does use a keypad for entry. [Dan's] already got a web server and home automation box that is always running. He coded a webpage that presents a virtual keypad for code entry. If the right code is input the system unlocks the electronic strike on the other side of this gate. Since the interface is a web page you can load if from any web browser (an iPhone is used for demonstration purposes after the break). But if you don&#8217;t have internet access you&#8217;re in trouble; there&#8217;s no physical keypad. But we guess you could always just jump the fence. <span id="more-28201"></span><span style="text-align:center; display: block;"><a href="http://hackaday.com/2010/09/14/automated-entry-for-a-garden-gate/"><img src="http://img.youtube.com/vi/riJTvfJsTCI/2.jpg" alt="" /></a></span></p>
<br />Filed under: <a href='http://hackaday.com/category/home-hacks/'>home hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/28201/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/28201/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/28201/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=28201&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/09/14/automated-entry-for-a-garden-gate/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/09/side-gate-automated-entry.jpg" medium="image">
			<media:title type="html">side-gate-automated-entry</media:title>
		</media:content>
	</item>
		<item>
		<title>Android Development 101- Part 4:Advanced Database/GUI Code and DDMS</title>
		<link>http://hackaday.com/2010/08/02/android-development-101-part-4advanced-databasegui-code-and-ddms/</link>
		<comments>http://hackaday.com/2010/08/02/android-development-101-part-4advanced-databasegui-code-and-ddms/#comments</comments>
		<pubDate>Mon, 02 Aug 2010 17:00:29 +0000</pubDate>
		<dc:creator>Greg R. Jacobs</dc:creator>
				<category><![CDATA[android hacks]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[android sdk]]></category>
		<category><![CDATA[code]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=26664</guid>
		<description><![CDATA[In this tutorial we are going to cover some advanced database code as well as tie in to some more advanced GUI techniques. We left off on the last tutorial showing you how to insert and select data to/from the database as well as make a table. What we need now is to be able [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=26664&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/header.jpg"><img class="alignnone size-full wp-image-26680" title="Header" src="http://hackadaycom.files.wordpress.com/2010/08/header.jpg" alt="" width="400" height="301" /></a></p>
<p>In this tutorial we are going to cover some advanced database code as well as tie in to some more advanced GUI techniques.  We left off on the <a href="http://hackaday.com/2010/07/21/android-development-101-part-3introduction-to-databases/">last tutorial</a> showing you how to insert and select data to/from the database as well as make a table.  What we need now is to be able to delete data if it is not needed and update it if we entered it incorrectly.  We will tie these abilities in with some more advanced functionality utilizing a long press on the screen for delete and for updating we will just press the data we want to edit.</p>
<p><span id="more-26664"></span></p>
<p>The project we are about to dive into is from the Android Developers website called <a href="http://developer.android.com/resources/tutorials/notepad/index.html">Notepad v2</a> with modifications to make it geared more towards our <strong>RandomQuotes </strong>Project.  We are using an already made example then modifying it because it covers more advanced ground on the GUI and database sides which is excellent for beginners and great for more advanced users to push on with. Since the items will be displayed to us in a ListView we can no longer entitle this project RandomQuote but will instead use EnhancedQuotes as our project name.  Just to be clear, we will be creating a whole new project instead of copying another one over.  Here is the required information below to make the project</p>
<p><strong>Project Name:</strong> EnhancedQuotes<br />
<strong>Build Target:</strong> Android 1.5<br />
<strong>Application Name:</strong> EnhancedQuotes<br />
<strong>Package Name:</strong> com.gregjacobs.enhancedquotes<br />
<strong>Create Activity:</strong> QuotesMain<br />
<strong>Min SDK Version:</strong> 3</p>
<p>After your project is created we can start some more advanced GUI work and integrate that with some update and delete statements.  At this point, I’d like to start dividing our code into different files based on the need of the application.  This is important in modern programming because it allows us to stay organized and execute functions for different screens or layouts efficiently and effectively.  For this project we are going to split our code into 3 <em>.java</em> files and we are going to have 3 different layout files as well.  We will start off with the basics by creating a new class file in our package <strong>com.gregjacobs.enhancedquotes</strong> called <strong>QuotesDBAdapter</strong>.  This will contain our database code but instead of using the previous database file we created, we will start a new one. Lets look at how Google does it and see whats available other than Raw Queries from the previous tutorial.</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter1.png"><img class="alignnone size-thumbnail wp-image-26682" title="QuoteDBAdapter1" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter1.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter2.png"><img class="alignnone size-thumbnail wp-image-26683" title="QuoteDBAdapter2" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter2.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter3.png"><img class="alignnone size-thumbnail wp-image-26684" title="QuoteDBAdapter3" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter3.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter4.png"><img class="alignnone size-thumbnail wp-image-26685" title="QuoteDBAdapter4" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter4.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter5.png"><img class="alignnone size-thumbnail wp-image-26686" title="QuoteDBAdapter5" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter5.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter6.png"><img class="alignnone size-thumbnail wp-image-26687" title="QuoteDBAdapter6" src="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter6.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: java;">
package com.gregjacobs.enhancedquotes;

import java.util.Random;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class QuotesDBAdapter {

	static Random random = new Random();
    public static final String KEY_QUOTES = &quot;quotes&quot;;
    public static final String KEY_ROWID = &quot;_id&quot;;

    private static final String TAG = &quot;QuotesDbAdapter&quot;;
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    /**
     * Database creation sql statement
     */
    private static final String DATABASE_CREATE =
            &quot;create table tblRandomQuotes (_id integer primary key autoincrement, &quot;
                    + &quot;quotes text not null);&quot;;

    private static final String DATABASE_NAME = &quot;Random&quot;;
    private static final String DATABASE_TABLE = &quot;tblRandomQuotes&quot;;
    private static final int DATABASE_VERSION = 2;

    private final Context mCtx;

    private static class DatabaseHelper extends SQLiteOpenHelper {

        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {

            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, &quot;Upgrading database from version &quot; + oldVersion + &quot; to &quot;
                    + newVersion + &quot;, which will destroy all old data&quot;);
            db.execSQL(&quot;DROP TABLE IF EXISTS tblRandomQuotes&quot;);
            onCreate(db);
        }
    }

    /**
     * Constructor - takes the context to allow the database to be
     * opened/created
     *
     * @param ctx the Context within which to work
     */
    public QuotesDBAdapter(Context ctx) {
        this.mCtx = ctx;
    }

    public QuotesDBAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }

    public void close() {
        mDbHelper.close();
    }

</pre></p>
<p>Looking at the code above, all of the imports should look familiar as well as everything leading up to this point.  This is standard database code to implement in your Android applications. In the code below we start getting into separating our SQL statements into sections and using the functions that were stated in the previous post.</p>
<p><pre class="brush: java;">
    public long createQuote(String quotes) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_QUOTES, quotes);

        return mDb.insert(DATABASE_TABLE, null, initialValues);
    }
</pre></p>
<p>Looking at the insert statement the first variable would be the database table we are inserting into, the next variable is if we have a null set of values we would enter that here and the last is the values being inserted into the table.</p>
<p><pre class="brush: java;">
    public boolean deleteQuote(long rowId) {

        return mDb.delete(DATABASE_TABLE, KEY_ROWID + &quot;=&quot; + rowId, null) &gt; 0;
    }
</pre></p>
<p>The delete statement holds three values in its method.  The first variable to enter would be the database table, the second being the where statement if there was one.  In this case we will need it but for some instances you may not.  The last variable is the Where statement arguments but if you included them in the previous part, that will work too.  It is good to note that putting “?” in your where statement and defining them in the third variable can be done as well.</p>
<p><pre class="brush: java;">
    public Cursor fetchAllQuotes() {

        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_QUOTES}, null, null, null, null, null);
    }

    public Cursor fetchQuote(long rowId) throws SQLException {

        Cursor mCursor =

                mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                        KEY_QUOTES}, KEY_ROWID + &quot;=&quot; + rowId, null,
                        null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;

    }
 </pre></p>
<p><strong>FetchAllQuotes </strong>runs a query against the database and grabs the id and the quotes field and return all the results to a cursor.  The first variable is the database table, the second is the columns the statement should return, third being the rows from the columns to return if there are any,  fourth being the selection arguments, fifth is the group by SQL function, sixth is a having SQL statement, and seventh is the order by SQL function.  For this we are only filling the first two and the rest can be null.  The <strong>fetchQuote </strong>uses the same function but specifies what row its looking for.</p>
<p><pre class="brush: java;">

    public boolean updateQuote(long rowId, String title) {
        ContentValues args = new ContentValues();
        args.put(KEY_QUOTES, title);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + &quot;=&quot; + rowId, null) &gt; 0;
    }
    </pre></p>
<p>For the update statement we still need the database name, the new variables for any given row and finally the row number in which to update.</p>
<p><pre class="brush: java;">

    public int getAllEntries()
    {
        Cursor cursor = mDb.rawQuery(
                    &quot;SELECT COUNT(quotes) FROM tblRandomQuotes&quot;, null);
                if(cursor.moveToFirst()) {
                    return cursor.getInt(0);
                }
                return cursor.getInt(0);

    }

    public String getRandomEntry()
    {
    	int id = 1;
    	id = getAllEntries();

    	int rand = random.nextInt(id) + 1;
        Cursor cursor = mDb.rawQuery(
                    &quot;SELECT quotes FROM tblRandomQuotes WHERE _id = &quot; + rand, null);
                if(cursor.moveToFirst()) {
                    return cursor.getString(0);
                }
                return cursor.getString(0);

    }
}
</pre></p>
<p>These two functions above were mentioned last post and will be used to generate a random quote on the screen using a Toast.</p>
<p>Next we are going to cover all of the <em>.xml</em> files starting with the <em>strings.xml</em> file.  this will contain the strings for all three of our layout XML files.  The code should be pretty straight forward with already having done two or three examples.  The <em>strings.xml</em> is as follows:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/strings.png"><img class="alignnone size-thumbnail wp-image-26689" title="Strings" src="http://hackadaycom.files.wordpress.com/2010/08/strings.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    &lt;string name=&quot;app_name&quot;&gt;Quotes Tracker&lt;/string&gt;
    &lt;string name=&quot;no_quotes&quot;&gt;No Quotes Yet&lt;/string&gt;
    &lt;string name=&quot;menu_insert&quot;&gt;Add Quote&lt;/string&gt;
    &lt;string name=&quot;menu_delete&quot;&gt;Delete Quote&lt;/string&gt;
    &lt;string name=&quot;title&quot;&gt;Quote:&lt;/string&gt;
    &lt;string name=&quot;confirm&quot;&gt;Confirm&lt;/string&gt;
    &lt;string name=&quot;edit_quotes&quot;&gt;Edit Quote&lt;/string&gt;
    &lt;string name=&quot;genRan&quot;&gt;Generate Random Quote!&lt;/string&gt;
&lt;/resources&gt;
</pre></p>
<p>After the <em>strings.xml</em> file we are going to move onto <em>row.xml</em> in the layout folder.  It is not created yet so we are going to create a new XML file.  We do this by right clicking on the layout folder and navigating to <strong>New</strong> and then to <strong>Other&#8230;</strong>. After this we will scroll down until we find the <strong>XML</strong> folder.  Open it and double click on the file called <strong>XML</strong>.  Change the name of the XML file from <strong>NewFile.xml</strong> to <strong>row.xml</strong>.  The file will be created and the console may come up and present you with an error but we will fix that in a second.  Now we get to the code we are going to insert into the XML file:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/row.png"><img class="alignnone size-thumbnail wp-image-26692" title="row" src="http://hackadaycom.files.wordpress.com/2010/08/row.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;TextView android:id=&quot;@+id/text1&quot; xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:layout_width=&quot;wrap_content&quot;
    android:layout_height=&quot;wrap_content&quot;/&gt;
</pre></p>
<p>The source code for this layout is a label or TextView that will insert multiple times into the <em>main.xml</em> for every entry we have.  We will move onto the <em>main.xml</em> to show you how this is done.</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/main.png"><img class="alignnone size-thumbnail wp-image-26693" title="Main" src="http://hackadaycom.files.wordpress.com/2010/08/main.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
android:orientation=&quot;vertical&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
&gt;
&lt;ListView android:id=&quot;@+id/android:list&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;/&gt;
&lt;TextView android:id=&quot;@+id/android:empty&quot;
android:layout_width=&quot;wrap_content&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;No Quotes!&quot;/&gt;
&lt;Button
android:id=&quot;@+id/genRan&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/genRan&quot;
/&gt;
&lt;/LinearLayout&gt;
</pre></p>
<p>We are using a <strong>LinearLayout </strong>above and a <strong>ListView </strong>and a single Label that displays “No Quotes!” if the database is empty.  Even though the items in the database are shown we will want to generate one randomly and that is what the button is doing at the bottom of the ListView.  We can now move onto the <em>edit.xml</em> here which a new XML file (same spot as last time) will need to be created:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/edit.png"><img class="alignnone size-thumbnail wp-image-26694" title="Edit" src="http://hackadaycom.files.wordpress.com/2010/08/edit.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;

&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
	android:orientation=&quot;vertical&quot; android:layout_width=&quot;fill_parent&quot;
	android:layout_height=&quot;fill_parent&quot;&gt;

	&lt;LinearLayout android:orientation=&quot;horizontal&quot;
		android:layout_width=&quot;fill_parent&quot;
		android:layout_height=&quot;wrap_content&quot;&gt;

		&lt;TextView android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:text=&quot;@string/title&quot; /&gt;
		&lt;EditText android:id=&quot;@+id/title&quot;
		  android:layout_width=&quot;wrap_content&quot;
			android:layout_height=&quot;wrap_content&quot;
			android:layout_weight=&quot;1&quot;/&gt;
	&lt;/LinearLayout&gt;

	&lt;Button android:id=&quot;@+id/confirm&quot;
	  android:text=&quot;@string/confirm&quot;
		android:layout_width=&quot;wrap_content&quot;
		android:layout_height=&quot;wrap_content&quot; /&gt;

&lt;/LinearLayout&gt;
</pre></p>
<p>Above we have one linear layout after another and that is for a very specific reason.  To be able to present a neat and clean layout we must use the first linear layout to align everything vertically and fill the parent window.  After that, the second linear layout will align the textbox and label horizontally.  If the two linear layouts were not present the textbox would be the size of the current screen instead of the neat one line layout we have now.  Other than that, the layout is pretty is basic and there should be no trouble here.</p>
<p>Next we are going to create a new <em>.java</em> file in our package <strong>com.gregjacobs.enhancedquotes</strong> called <strong>QuoteEdit </strong>and it will contain code to accept any edits we may do on our items.  Below is the code and comments on the important stuff you may not know, although it should look pretty familiar because we have used almost all of these functions and methods in previous posts.  Here is the code for <em>QuoteEdit.java</em>:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/quoteedit1.png"><img class="alignnone size-thumbnail wp-image-26695" title="QuoteEdit1" src="http://hackadaycom.files.wordpress.com/2010/08/quoteedit1.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quoteedit2.png"><img class="alignnone size-thumbnail wp-image-26696" title="QuoteEdit2" src="http://hackadaycom.files.wordpress.com/2010/08/quoteedit2.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: java;">
package com.gregjacobs.enhancedquotes;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class QuoteEdit extends Activity {

	private EditText mQuoteText;
    private Long mRowId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit);

        mQuoteText = (EditText) findViewById(R.id.title);

        Button confirmButton = (Button) findViewById(R.id.confirm);

        mRowId = null;
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
            mRowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);

            if (title != null) {
            	mQuoteText.setText(title);
            }
        }
       </pre></p>
<p>All above is pretty standard until you get to the <strong>Bundle extras = getIntent().getExtras();</strong> part of the code.  This code is pulling from the <em>QuotesMain.java</em> using an <em>Intent</em>.  Now some beginners may be wondering what an Intent is.  An Intent is a passive object to hold data that can pass between applications.  In human-speak, its the glue that allows us to get information from the <em>QuotesMain.java</em> file to the <em>QuotesEdit.java</em> file efficiently and easily.  Another new term would be a <em>Bundle</em>.  A bundle allows use to map strings to objects such as the Intent we just talked about.  So with the Bundle entitled extras, we are able to pull the data from the main <em>.java</em> file over to <em>QuotesEdit.java</em> file and vice versa.</p>
<p><pre class="brush: java;">
        confirmButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Bundle bundle = new Bundle();

                bundle.putString(QuotesDBAdapter.KEY_QUOTES, mQuoteText.getText().toString());
                if (mRowId != null) {
                    bundle.putLong(QuotesDBAdapter.KEY_ROWID, mRowId);
                }

                Intent mIntent = new Intent();
                mIntent.putExtras(bundle);
                setResult(RESULT_OK, mIntent);
                finish();
            }

        });
    }
}
</pre></p>
<p style="text-align:left;">The Bundle above will package the current text in the textbox with the original ID of the object and send it back over the <em>QuotesEdit.java</em> to the <em>QuotesMain.java</em>.  We are now ready to move onto <em>QuotesMain.java</em> where we are going to pull everything we have done so far together.  This code will implement the long press on items as well as utilizing the menu button on any phone to bring up an add function.  Here is the code to utilize in <em>QuotesMain.java</em>:</p>
<pre style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain1.png"><img class="alignnone size-thumbnail wp-image-26697" title="QuotesMain1" src="http://hackadaycom.files.wordpress.com/2010/08/quotesmain1.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain2.png"><img class="alignnone size-thumbnail wp-image-26698" title="QuotesMain2" src="http://hackadaycom.files.wordpress.com/2010/08/quotesmain2.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain3.png"><img class="alignnone size-thumbnail wp-image-26699" title="QuotesMain3" src="http://hackadaycom.files.wordpress.com/2010/08/quotesmain3.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></pre>
<pre style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain3.png"></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain4.png"><img class="alignnone size-thumbnail wp-image-26700" title="QuotesMain4" src="http://hackadaycom.files.wordpress.com/2010/08/quotesmain4.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/quotesmain5.png"><img class="alignnone size-thumbnail wp-image-26701" title="QuotesMain5" src="http://hackadaycom.files.wordpress.com/2010/08/quotesmain5.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></pre>
<p><pre class="brush: java;">
package com.gregjacobs.enhancedquotes;

import android.app.ListActivity;
import android.view.View.OnClickListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.Button;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
</pre></p>
<p>Above we have a few new imports to be able to use the more advanced items in this project such as intents, menu’s and menuitem, listview and simplecursoradapters.  These will all be explained as they come up.</p>
<p><pre class="brush: java;">
public class QuotesMain extends ListActivity {
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_EDIT=1;

    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;

    private QuotesDBAdapter mDbHelper;
    private Cursor mNotesCursor;

    public Button button;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mDbHelper = new QuotesDBAdapter(this);
        mDbHelper.open();
        fillData();
        registerForContextMenu(getListView());
        button = (Button)findViewById(R.id.genRan);
        button.setOnClickListener(mAddListener);
    }
    </pre></p>
<p>We are making variables for creating, editing, inserting and deleting and making them static because they are not going to change.  In the onCreate function we utilize <strong>fillData()</strong> which will be defined below.  As well you will notice that we register the listview items in the context menu and set a listener for the button.  A context menu is best described as kind of a pop-up menu and this will be utilized when we want to delete a item within the listview.</p>
<p><pre class="brush: java;">
    private OnClickListener mAddListener = new OnClickListener()
    {
    	public void onClick(View v)
    	{
			//long id1 = 0;
			// do something when the button is clicked
			try
			{
				String quote = &quot;&quot;;
				quote = mDbHelper.getRandomEntry();
				Context context = getApplicationContext();
				CharSequence text = quote;
				int duration = Toast.LENGTH_LONG;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
			catch (Exception ex)
			{
				Context context = getApplicationContext();
				CharSequence text = ex.toString();
				int duration = Toast.LENGTH_LONG;

				Toast toast = Toast.makeText(context, text, duration);
				toast.show();
			}
    	}
    };

    private void fillData() {
        // Get all of the rows from the database and create the item list
        mNotesCursor = mDbHelper.fetchAllQuotes();
        startManagingCursor(mNotesCursor);

        // Create an array to specify the fields we want to display in the list (only TITLE)
        String[] from = new String[]{QuotesDBAdapter.KEY_QUOTES};

        // and an array of the fields we want to bind those fields to (in this case just text1)
        int[] to = new int[]{R.id.text1};

        // Now create a simple cursor adapter and set it to display
        SimpleCursorAdapter notes =
        	    new SimpleCursorAdapter(this, R.layout.row, mNotesCursor, from, to);
        setListAdapter(notes);
    }
    </pre></p>
<p>The button function above is exactly like the previous one that is used to generate a random quote from our list.  The new method<strong> fillData()</strong> as mentioned above is going to be used to get all of the quotes and bind the ID and the actual quote together and add them to the listview using the <strong>SimpleCursorAdapter</strong>.  The <strong>SimpleCursorAdapter </strong>is used to bind bind columns in a returned cursor to any text we place on the screen.</p>
<p><pre class="brush: java;">
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, INSERT_ID,0, R.string.menu_insert);
        return true;
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) {
        switch(item.getItemId()) {
        case INSERT_ID:
            createNote();
            return true;
	    }
        return super.onMenuItemSelected(featureId, item);
    }
</pre></p>
<p>In the first function above called <strong>onCreateOptionsMenu()</strong> we are adding the ability to add an item to the database using the menu press option that will bring up dialog asking if we would like to do this.  If this completes successfully then the statement will return true.  The one below it checks to see if an item has been pressed in the menu.  If it has it uses a switch statement to check the value that we defined above.  If it matches then we create a note which is defined below.</p>
<p><pre class="brush: java;">
    @Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
        menu.add(0, DELETE_ID, 0, R.string.menu_delete);
	}

    @Override
	public boolean onContextItemSelected(MenuItem item) {
		switch(item.getItemId()) {
    	case DELETE_ID:
    		AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
	        mDbHelper.deleteQuote(info.id);
	        fillData();
	        return true;
		}
		return super.onContextItemSelected(item);
	}

	private void createNote() {
    	Intent i = new Intent(this, QuoteEdit.class);
    	 startActivityForResult(i, ACTIVITY_CREATE);
   	 }
</pre></p>
<p>The function above is used to register the context menu and give the option to delete items using the menu.add function as seen above as well as here.  If the context menu item Delete is pressed then the database helper will delete the quote based on the ID.  The <strong>createNote()</strong> function uses an intent to pass the application over to the QuoteEdit file and load a new screen and when done a new intent will send the completed data back over here so we can add it to the listview.</p>
<p><pre class="brush: java;">

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
    	super.onListItemClick(l, v, position, id);
        Cursor c = mNotesCursor;
        c.moveToPosition(position);
        Intent i = new Intent(this, QuoteEdit.class);
        i.putExtra(QuotesDBAdapter.KEY_ROWID, id);
        i.putExtra(QuotesDBAdapter.KEY_QUOTES, c.getString(
                c.getColumnIndexOrThrow(QuotesDBAdapter.KEY_QUOTES)));
        startActivityForResult(i, ACTIVITY_EDIT);
    }
</pre></p>
<p>If an item from the listview is pressed the function above is loaded to initialize an intent and put the information into the intent and pull it over to the QuoteEdit class to be edited.  When completed the QuoteEdit class will send the completed data back over and we can continue to add, edit or delete more items.</p>
<p><pre class="brush: java;">
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Bundle extras = intent.getExtras();
        switch(requestCode) {
        case ACTIVITY_CREATE:
            String title = extras.getString(QuotesDBAdapter.KEY_QUOTES);
            mDbHelper.createQuote(title);
            fillData();
            break;
        case ACTIVITY_EDIT:
            Long rowId = extras.getLong(QuotesDBAdapter.KEY_ROWID);
            if (rowId != null) {
                String editTitle = extras.getString(QuotesDBAdapter.KEY_QUOTES);
                mDbHelper.updateQuote(rowId, editTitle);
            }
            fillData();
            break;
        }
    }
}
</pre></p>
<p>The method above takes the result of an activity and uses the result to utilize a specific method.  The result in this case would either be creating a new quote or editing an existing one.  The basis of this switch statement is to utilize the database helper and either insert data or update data within the database.</p>
<p>We now have one more file to go over before we could run our application on the emulator.  This would be the <em>AndroidManifest.XML</em> file and that will control what is registered and what runs, it is essentially the heart of the program and we need it to recognize that we have 2 parts to our application.  Here is the code for the AndroidManifest:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/androidmanifest.png"><img class="alignnone size-thumbnail wp-image-26709" title="AndroidManifest" src="http://hackadaycom.files.wordpress.com/2010/08/androidmanifest.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot; package=&quot;com.gregjacobs.enhancedquotes&quot;&gt;
    &lt;application android:icon=&quot;@drawable/icon&quot;&gt;
        &lt;activity android:name=&quot;.QuotesMain&quot; android:label=&quot;@string/app_name&quot;&gt;
            &lt;intent-filter&gt;
                &lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
                &lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
            &lt;/intent-filter&gt;
        &lt;/activity&gt;
    	&lt;activity android:name=&quot;.QuoteEdit&quot; android:label=&quot;@string/app_name&quot;&gt;&lt;/activity&gt;
    &lt;/application&gt;
&lt;/manifest&gt;
</pre></p>
<p>If your code doesnt look like this then you will have to do some modifications to your code to talor it to this.   You will notice that we have added another <strong>Activity</strong> to the manifest file and are giving it the same name as the one above, <strong>app_name</strong>.  This will denote that we have another activity that we would like to use and we register it here.  Also, you will notice that the <strong>uses-sdk android:minSdkVersion=&#8221;3&#8243;</strong> has been taken out.  This is because an application does not really need it but it is always good to have.  This just uses it as a reference and will use the specified build target when building your application.</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/demo1.png"><img class="alignnone size-thumbnail wp-image-26712" title="Demo1" src="http://hackadaycom.files.wordpress.com/2010/08/demo1.png?w=114&#038;h=96" alt="" width="114" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/demo2.png"><img class="alignnone size-thumbnail wp-image-26713" title="Demo2" src="http://hackadaycom.files.wordpress.com/2010/08/demo2.png?w=114&#038;h=96" alt="" width="114" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/demo3.png"><img class="alignnone size-thumbnail wp-image-26714" title="Demo3" src="http://hackadaycom.files.wordpress.com/2010/08/demo3.png?w=114&#038;h=96" alt="" width="114" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/demo4.png"><img class="alignnone size-thumbnail wp-image-26715" title="Demo4" src="http://hackadaycom.files.wordpress.com/2010/08/demo4.png?w=114&#038;h=96" alt="" width="114" height="96" /></a></p>
<p>The application should build and you will be able to try out the more advanced features of Android programming.  The possibilities are endless with the knowledge you learn but what if your database/database code is not working?</p>
<p>Thats what the <strong>Dalvick Debug Monitor Server (DDMS)</strong> is for.  When the emulator is running we are able to switch over to the DDMS by going to the top right of your screen and pressing the <strong>&gt;&gt;</strong> and then clicking on <strong>DDMS</strong>.  If you are new to Android Development this new screen will be very confusing for you.  What we are going to take out of going to the DDMS for right now is the ability to add and take from our emulator items which may be of interest.  For this particular tutorial we are going to grab a database from the running emulator.</p>
<p>Before we get started we will need to download some software I find very useful for SQLite developers.  This being <a href="http://sqlitebrowser.sourceforge.net/">SQLite Database Browser</a> (SDB).  This software will allow you to open SQLite databases and explore the contents, even modifying them through SQL statements.  Once the file is downloaded find the folder and click on the <em>.exe</em> to start it up.  Leave this program up and we will get back to it later.</p>
<p>To be able to put them into the SDB we need to pull them off the emulator. To do this we have to delve into the running emulator and find the database we want.  It is key to remember that databases are application specific so we will need to find the package name and the database will be under a Database Folder.  When in DDMS goto the devices tab and click on our emulator.  then in the middle of the program should be a tab called <strong>File Explorer</strong>.  Once File Explorer has been clicked we will now see three folders (maybe more depending on what you do with the device) called <strong>data</strong>,<strong>sdcard </strong>and <strong>system</strong>.  We will leave <strong>system </strong>and <strong>sdcard </strong>alone for right now as we are going to use the <strong>data </strong>folder so open it.  Once open, navigate to another folder called data and open it too.  We are now presented with the package names with everything installed on our emulator.  Navigate to <strong>com.gregjacobs.enhancedquotes</strong> and open it.  Once open the two folders that appear should be <strong>databases </strong>and <strong>lib</strong>.  Open databases folder and take the file called <strong>Random</strong>.  Now to be able to take this file we are going to click on it once then navigate to the top of the tab and press the button that looks like a <strong>floppy disc with an arrow pointing to the left</strong>.  Once this icon is clicked a dialog box will appear asking where you want to save the selected file.  Choose an easy to locate place and click save.</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/ddms1.png"><img class="alignnone size-thumbnail wp-image-26710" title="DDMS1" src="http://hackadaycom.files.wordpress.com/2010/08/ddms1.png?w=128&#038;h=77" alt="" width="128" height="77" /></a><a href="http://hackadaycom.files.wordpress.com/2010/08/ddms2.png"><img class="alignnone size-thumbnail wp-image-26711" title="DDMS2" src="http://hackadaycom.files.wordpress.com/2010/08/ddms2.png?w=128&#038;h=77" alt="" width="128" height="77" /></a></p>
<p>One the file has been taken from the emulator we are going to go back to SDB and click the big open button, find our file we saved and click open.  Once the file is open we are able to see the structure of the database and navigate to browse the data.  to do this we are going to click on the tab called<strong> Browse Data</strong> and in the dropdown that says table beside it, we are going to choose <strong>tblRandomQuotes</strong>.  The data in the table will now appear and now you know where to find your data if you ever need to modify something an put it back onto the emulator.  The SDB is also good for testing out SQL queries if you are unsure of what the data returned would be.  This will be an invaluable tool if you do database applications in Android.</p>
<p>Here are the files from my project for comparison:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/08/androidmanifest-xml.doc">AndroidManifest.xml</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/edit-xml.doc">edit.xml</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/main-xml.doc">main.xml</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/quoteedit-java.doc">QuoteEdit.java</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/quotemain-java.doc">QuoteMain.java</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/quotesdbadapter-java.doc">QuotesDBAdapter.java</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/row-xml.doc">row.xml</a> | <a href="http://hackadaycom.files.wordpress.com/2010/08/strings-xml.doc">strings.xml</a></p>
<p>Now that you have an advanced understanding of some of the GUI options available to you and Database code covered in more detail in this tutorial, you are ready to start making some applications that have a little more depth than just button clicks.  With the understanding you have of Intents and Bundles, you can make your programs well rounded and divide your code and layouts to match what your looking to make.  If anyone has an idea that they have implemented since following this tutorial feel free to send them to me us so we can check out what you have learned.  The next tutorial will cover designing the statistics tracker and using <a href="http://www.droiddraw.org/">DroidDraw </a>to develop some of the UI.  Until the next tutorial, Happy Hacking!</p>
<p>Articles Used For Reference:</p>
<p><a href="http://developer.android.com/resources/tutorials/notepad/index.html">Google Notepad Tutorial</a> &#8211; <a href="http://developer.android.com/resources/tutorials/notepad/notepad-ex2.html">NotepadV2</a></p>
<p>Continue on to Part 5: <a href="http://hackaday.com/2010/08/05/android-development-101-part-5droiddraw-information-tracker-completed/">DroidDraw &amp; Information Tracker Complete</a></p>
<br />Filed under: <a href='http://hackaday.com/category/android-hacks/'>android hacks</a>, <a href='http://hackaday.com/category/software-development/'>Software Development</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/26664/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/26664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/26664/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=26664&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/08/02/android-development-101-part-4advanced-databasegui-code-and-ddms/feed/</wfw:commentRss>
		<slash:comments>40</slash:comments>
		<georss:point>43.002684 -81.214990</georss:point>
		<geo:lat>43.002684</geo:lat>
		<geo:long>-81.214990</geo:long>
		<media:content url="" medium="image">
			<media:title type="html">greggers120588</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/header.jpg" medium="image">
			<media:title type="html">Header</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter1.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter1</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter2.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter2</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter3.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter3</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter4.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter4</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter5.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter5</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotedbadapter6.png?w=128" medium="image">
			<media:title type="html">QuoteDBAdapter6</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/strings.png?w=128" medium="image">
			<media:title type="html">Strings</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/row.png?w=128" medium="image">
			<media:title type="html">row</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/main.png?w=128" medium="image">
			<media:title type="html">Main</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/edit.png?w=128" medium="image">
			<media:title type="html">Edit</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quoteedit1.png?w=128" medium="image">
			<media:title type="html">QuoteEdit1</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quoteedit2.png?w=128" medium="image">
			<media:title type="html">QuoteEdit2</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotesmain1.png?w=128" medium="image">
			<media:title type="html">QuotesMain1</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotesmain2.png?w=128" medium="image">
			<media:title type="html">QuotesMain2</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotesmain3.png?w=128" medium="image">
			<media:title type="html">QuotesMain3</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotesmain4.png?w=128" medium="image">
			<media:title type="html">QuotesMain4</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/quotesmain5.png?w=128" medium="image">
			<media:title type="html">QuotesMain5</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/androidmanifest.png?w=128" medium="image">
			<media:title type="html">AndroidManifest</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/demo1.png?w=114" medium="image">
			<media:title type="html">Demo1</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/demo2.png?w=114" medium="image">
			<media:title type="html">Demo2</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/demo3.png?w=114" medium="image">
			<media:title type="html">Demo3</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/demo4.png?w=114" medium="image">
			<media:title type="html">Demo4</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/ddms1.png?w=128" medium="image">
			<media:title type="html">DDMS1</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/08/ddms2.png?w=128" medium="image">
			<media:title type="html">DDMS2</media:title>
		</media:content>
	</item>
		<item>
		<title>Android Development 101 &#8211; Part 3:Introduction to Databases</title>
		<link>http://hackaday.com/2010/07/21/android-development-101-part-3introduction-to-databases/</link>
		<comments>http://hackaday.com/2010/07/21/android-development-101-part-3introduction-to-databases/#comments</comments>
		<pubDate>Wed, 21 Jul 2010 18:00:07 +0000</pubDate>
		<dc:creator>Greg R. Jacobs</dc:creator>
				<category><![CDATA[android hacks]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[android]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[dev]]></category>
		<category><![CDATA[development]]></category>
		<category><![CDATA[google]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=26328</guid>
		<description><![CDATA[In this tutorial we will be pivoting from our last tutorial on Graphical Elements to start focusing on databases in Android development. The android platform uses SQLite databases in its applications and is one of five data storage options in android development. We will only be focusing on SQLite development in android because it is [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=26328&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p style="text-align:center;"><img class="aligncenter size-large wp-image-26335" title="Android Lab" src="http://hackadaycom.files.wordpress.com/2010/07/img_199912_android-lab.jpg?w=450&#038;h=337" alt="" width="450" height="337" /></p>
<p>In this tutorial we will be pivoting from our last tutorial on <a href="http://hackaday.com/2010/07/19/android-development-101-part-2improved-hello-world/">Graphical Elements</a> to start focusing on databases in Android development.  The android platform uses SQLite databases in its applications and is one of five data storage options in android development.  We will only be focusing on SQLite development in android because it is key to the construction of a workable/functional program.  After this tutorial you should be able to implement a SQLite database that you are then able to insert and select items from tables in the database.</p>
<p>For this project we will be creating a Random Quote generator that has you enter quotes or sayings in a textbox and press a button to insert them into the database.  We will issue a confirmation toast that allows us to see if the data was entered into the database successfully and the textbox will be blank. If a second button is pressed, the database will be accessed and told to select a random quote from the database to show in a toast on the screen.</p>
<p><span id="more-26328"></span></p>
<p>To start off we will make a new project called <strong>RandomQuotes</strong>.  In <a href="http://hackaday.com/2010/07/15/android-dev-101-%E2%80%93-part-1hello-world/">part one</a> of the series we stepped through making a new project so we wont walk through all of the steps again but instead I will just give you the information you need.  The information to get this project up and running bare bones is as follows:</p>
<ul>
<li><strong>Project Name:</strong> RandomQuotes</li>
<li><strong>Build Target:</strong> Android 1.5</li>
<li><strong>Application Name:</strong> RandomQuotes</li>
<li><strong>Package Name:</strong> com.gregjacobs.randomquotes</li>
<li><strong>Create Activity:</strong> QuotesMain</li>
<li><strong>Min SDK Version:</strong> 3</li>
</ul>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-databases001.png"><img class="size-thumbnail wp-image-26336  aligncenter" title="Part3-Databases001" src="http://hackadaycom.files.wordpress.com/2010/07/part3-databases001.png?w=56&#038;h=96" alt="" width="56" height="96" /></a></p>
<p>After inserting these values and you have pressed Finish we will start by making a class file in our <em>com.gregjacobs.randomquotes</em> package.  To do this we will right click on the package and navigate to <strong>New </strong>then to <strong>Class</strong>.  When the new window pops up the only data we will enter is the <strong>Name </strong>section filling it with <strong>DBAdapter</strong>. After this is done we press <strong>Finish </strong>and are presented with a bare bones class file that we will quickly start to modify.  This tutorial will be like the last in the sense that code will be posted and I will explain the important parts and what functions are doing.  The only difference from the previous tutorial code will be that I include text files as well as documenting the code here so you are able to download and compare.  We will start off with the <em>DBAdapter.java</em> file:</p>
<p style="text-align:center;">
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-005.png"><img class="size-thumbnail wp-image-26340   alignleft" title="Part3 - Final Product - 005" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-005.png?w=120&#038;h=96" alt="" width="120" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-006.png"><img class="size-thumbnail wp-image-26341 alignleft" title="Part3 - Final Product - 006" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-006.png?w=120&#038;h=96" alt="" width="120" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-007.png"><img class="size-thumbnail wp-image-26342   alignleft" title="Part3 - Final Product - 007" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-007.png?w=120&#038;h=96" alt="" width="120" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-008.png"><img class="size-thumbnail wp-image-26343   alignleft" title="Part3 - Final Product - 008" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-008.png?w=120&#038;h=96" alt="" width="120" height="96" /></a></p>
<p style="text-align:center;">
<p style="text-align:center;">
<p style="text-align:center;">
<p style="text-align:left;">
<p><pre class="brush: java;">
package com.gregjacobs.randomquotes;

import java.util.Random;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
</pre></p>
<p>We will start off by importing all of the tools required to get this SQLite Database up and running.  All of these might be straightforward for database programmers but we will discuss them anyways.  <strong>ContentValues </strong>allow us the ability to store a set of values for insert statements, <strong>Context </strong>as explained in the last post allows us access to the application environment.  <strong>Cursor </strong>is probably the most vital import we will need next to the SQLite imports.  Cursor allows us access to the data returned to the cursor from a database query.  <strong>SQLException </strong>allows us to throw SQL exceptions if there is ever an error, these messages provide more insight as to what the problem may be.  <strong>SQLiteDatabase </strong>gives us the ability to manage a SQLite database using methods.  <strong>SQLiteOpenHelper </strong>is basically a helper class that allows for creation and version management of a database.  <strong>Log </strong>will basically log output in case there is an error.</p>
<p><pre class="brush: java;">
public class DBAdapter
{
    int id = 0;
    public static final String KEY_ROWID = &quot;_id&quot;;
    public static final String KEY_QUOTE = &quot;Quote&quot;;
    private static final String TAG = &quot;DBAdapter&quot;;

    private static final String DATABASE_NAME = &quot;Random&quot;;
    private static final String DATABASE_TABLE = &quot;tblRandomQuotes&quot;;
    private static final int DATABASE_VERSION = 1;

    private static final String DATABASE_CREATE =
        &quot;create table tblRandomQuotes (_id integer primary key autoincrement, &quot;
        + &quot;Quote text not null );&quot;;

    private final Context context;

    private DatabaseHelper DBHelper;
    private SQLiteDatabase db;
</pre></p>
<p>Here we define all of our variables to be used in the database from the database name right down to the database create statement.  We are using final variables because they will never change values and making a variable for table names and the like will later on make our lives easier than hard-coding all of our values and commiting too much (remember the re-usability).</p>
<p><pre class="brush: java;">
    public DBAdapter(Context ctx)
    {
        this.context = ctx;
        DBHelper = new DatabaseHelper(context);
    }

	private static class DatabaseHelper extends SQLiteOpenHelper
    {
        DatabaseHelper(Context context)
        {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db)
        {
            db.execSQL(DATABASE_CREATE);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion,
                              int newVersion)
        {
            Log.w(TAG, &quot;Upgrading database from version &quot; + oldVersion
                  + &quot; to &quot;
                  + newVersion + &quot;, which will destroy all old data&quot;);
            db.execSQL(&quot;DROP TABLE IF EXISTS tblRandomQuotes&quot;);
            onCreate(db);
        }
    }
    </pre></p>
<p>Above we define a constructor to grab the context of the application and extend that to our <strong>DatabaseHelper </strong>just under the constructor.  The <strong>DatabaseHelper </strong>class extends our <strong>SQLiteOpenHelper</strong> which will add greater functionality to management of our SQLite database.  The key function that we will see used later on will be <strong>onCreate</strong> which will allow us to execute a SQL statement to create our database.</p>
<p><pre class="brush: java;">
    //---opens the database---
    public DBAdapter open() throws SQLException
    {
        db = DBHelper.getWritableDatabase();
        return this;
    }

    //---closes the database---
    public void close()
    {
        DBHelper.close();
    }
    </pre></p>
<p>Above we have two key functions that allow us to open and close the database that can be referenced when calling them in our main <em>.java</em> file.</p>
<p><pre class="brush: java;">
    //---insert a title into the database---
    public long insertQuote(String Quote)
    {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_QUOTE, Quote);
        return db.insert(DATABASE_TABLE, null, initialValues);
    }
</pre></p>
<p>The function above will be processing our quotes when we call them in the main <em>.java</em> file. It will also be getting them ready for entry into the database by putting the string <strong>Quote </strong>into a <strong>ContentValues </strong>called <strong>initialValues </strong>which is then inserted into the database table.</p>
<p><pre class="brush: java;">
    public int getAllEntries()
    {
        Cursor cursor = db.rawQuery(
                    &quot;SELECT COUNT(Quote) FROM tblRandomQuotes&quot;, null);
                if(cursor.moveToFirst()) {
                    return cursor.getInt(0);
                }
                return cursor.getInt(0);

    }
    </pre></p>
<p>This function will be querying the database table for the number of quotes entered so it can assist the random number generator in how high a number to choose so that we don&#8217;t throw an exception.  We are using a <strong>rawQuery </strong>for the most part because I am personally not a huge fan of the way Android handles their queries ( having you enter in different parts of the statement in segments and separate them with commas) but I am impressed that they allow you to have full functionality with a native SQL query.  The if statement will move the cursor to the first result (if there are many results) and grab the first integer it sees there.  If the if statement is not true it will grab the result from the starting position anyways.</p>
<p><pre class="brush: java;">
    public String getRandomEntry()
    {

    	id = getAllEntries();
    	Random random = new Random();
    	int rand = random.nextInt(getAllEntries());
    	if(rand == 0)
    		++rand;
        Cursor cursor = db.rawQuery(
                    &quot;SELECT Quote FROM tblRandomQuotes WHERE _id = &quot; + rand, null);
                if(cursor.moveToFirst()) {
                    return cursor.getString(0);
                }
                return cursor.getString(0);

    }

}
</pre></p>
<p>This function will be called by the main <em>.java</em> program to return a random result based on the number of entries into our database.  We use the function <strong>getAllEntries </strong>to get the number of quotes and we then tell our random variable that it can go no higher than<strong> id</strong>.  In our select statement we then tell it to look for quote <strong>WHERE _id = rand</strong> which is our random number.</p>
<p>After this class file is completed, we have a fully reusable database adapter that is ready to start inserting quotes into the database.  We now need to focus on both of the XML files which will be a quick trip down memory lane so code and pictures will be posted and we shouldn’t have to review as everything is basically from the <a href="http://hackaday.com/2010/07/19/android-development-101-part-2improved-hello-world/">last post</a>.  Here is the <em>main.xml</em>:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-010.png"><img class="aligncenter size-thumbnail wp-image-26346" title="Part3 - Final Product - 010" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-010.png?w=120&#038;h=96" alt="" width="120" height="96" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
    android:orientation=&quot;vertical&quot;
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;fill_parent&quot;
    &gt;
&lt;TextView
    android:layout_width=&quot;fill_parent&quot;
    android:layout_height=&quot;wrap_content&quot;
    android:text=&quot;@string/Quote&quot;
/&gt;
&lt;EditText
android:id=&quot;@+id/Quote&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
/&gt;
&lt;Button
android:id=&quot;@+id/go&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/press&quot;
/&gt;
&lt;Button
android:id=&quot;@+id/genRan&quot;
android:layout_width=&quot;fill_parent&quot;
android:layout_height=&quot;wrap_content&quot;
android:text=&quot;@string/genRan&quot;
/&gt;
&lt;/LinearLayout&gt;
</pre></p>
<p>Here is the <em>strings.xml</em> file:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-009.png"><img class="aligncenter size-thumbnail wp-image-26347" title="Part3 - Final Product - 009" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-009.png?w=120&#038;h=96" alt="" width="120" height="96" /></a></p>
<p><pre class="brush: xml;">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;resources&gt;
    &lt;string name=&quot;Quote&quot;&gt;Please Enter A Quote:&lt;/string&gt;
    &lt;string name=&quot;app_name&quot;&gt;Random Quotes&lt;/string&gt;
    &lt;string name=&quot;press&quot;&gt;Press Me!&lt;/string&gt;
    &lt;string name=&quot;genRan&quot;&gt;Generate Random Quote!&lt;/string&gt;
&lt;/resources&gt;
</pre></p>
<p>Both are pretty straight forward and the only difference from these files and the previous posts is the additional string node in <em>strings.xml</em> and the extra button in <em>main.xml</em>.  Now we have the layout in place with everything where we want it to be it is now our task to code the <em>QuotesMain.java</em> file.  This file will register our two buttons and attach them to one event handler using a switch statement.  Here is the code for our <em>QuotesMain.java</em> file:</p>
<p style="text-align:center;">
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-011.png"><img class="size-thumbnail wp-image-26348 alignleft" title="Part3 - Final Product - 011" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-011.png?w=120&#038;h=96" alt="" width="120" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-012.png"><img class="size-thumbnail wp-image-26349 alignleft" title="Part3 - Final Product - 012" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-012.png?w=120&#038;h=96" alt="" width="120" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-013.png"><img class="size-thumbnail wp-image-26350 alignleft" title="Part3 - Final Product - 013" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-013.png?w=120&#038;h=96" alt="" width="120" height="96" /></a></p>
<p style="text-align:center;">
<p style="text-align:center;">
<p style="text-align:center;">
<p><pre class="brush: java;">
package com.gregjacobs.randomquotes;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
</pre></p>
<p>Here we are importing all of the required items to be able to pull this project together.  All of these should be familiar to you from <a href="http://hackaday.com/2010/07/19/android-development-101-part-2improved-hello-world/">Graphical Elements</a> and if they aren’t it is a good post to start on and work your way here.</p>
<p><pre class="brush: java;">
public class QuotesMain extends Activity {
	DBAdapter db = new DBAdapter(this);
	EditText Quote;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // Capture our button from layout
        Button setButton = (Button)findViewById(R.id.go);
        Button getButton = (Button)findViewById(R.id.genRan);
        // Register the onClick listener with the implementation above
        setButton.setOnClickListener(mAddListener);
        getButton.setOnClickListener(mAddListener);
    }
</pre></p>
<p>We now have to buttons being referenced by id and they are <strong>getButton </strong>(which gets the information from the text box and inserts it into the database) and <strong>setButton </strong>(which retrieves a random quote from the database depending on the number of items in the database).  These both have the same event handler and decisions on what code to run are made below.</p>
<p><pre class="brush: java;">
    // Create an anonymous implementation of OnClickListener
    private OnClickListener mAddListener = new OnClickListener()
    {
    	public void onClick(View v)
    	{
    		switch(v.getId())
    		{
    		case R.id.go:
				db.open();
				long id = 0;
				// do something when the button is clicked
				try
				{
					Quote = (EditText)findViewById(R.id.Quote);
					db.insertQuote(Quote.getText().toString());

					id = db.getAllEntries();

					Context context = getApplicationContext();
					CharSequence text = &quot;The quote '&quot; + Quote.getText() + &quot;' was added successfully!\nQuotes Total = &quot; + id;
					int duration = Toast.LENGTH_LONG;

					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
					Quote.setText(&quot;&quot;);
				}
				catch (Exception ex)
				{
					Context context = getApplicationContext();
					CharSequence text = ex.toString() + &quot;ID = &quot; + id;
					int duration = Toast.LENGTH_LONG;

					Toast toast = Toast.makeText(context, text, duration);
					toast.show();
				}
				db.close();
				break;
</pre></p>
<p>In the above case statement we can see that we grab the text from the textbox and insert the data into the database using <strong>db.insertQuote</strong> from the <strong>DBAdapter </strong>java class.  After a successful insertion we will display a toast that allows us to see what quote was entered in successfully and what the number of quotes in the database are.</p>
<p><pre class="brush: java;">
    		case R.id.genRan:
    			db.open();
    			//long id1 = 0;
    			// do something when the button is clicked
    			try
    			{
    				String quote = &quot;&quot;;
    				quote = db.getRandomEntry();
    				Context context = getApplicationContext();
    				CharSequence text = quote;
    				int duration = Toast.LENGTH_LONG;

    				Toast toast = Toast.makeText(context, text, duration);
    				toast.show();
    			}
    			catch (Exception ex)
    			{
    				Context context = getApplicationContext();
    				CharSequence text = ex.toString();
    				int duration = Toast.LENGTH_LONG;

    				Toast toast = Toast.makeText(context, text, duration);
    				toast.show();
    			}
    			db.close();
    		}
		}
    };
}
</pre></p>
<p>This case uses a string variable to reference the random entry we are pulling out of the database using <strong>db.getRandomEntry</strong>.  We then display that data in a toast to show that the information was actually grabbed.  All of this code when pulled together and displayed on an android screen should look like this:</p>
<p>Entering Text:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-001.png"><img class="aligncenter size-thumbnail wp-image-26352" title="Part3 - Final Product - 001" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-001.png?w=114&#038;h=96" alt="" width="114" height="96" /></a></p>
<p>Displaying Random Entries:</p>
<p style="text-align:center;"><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-002.png"><img class="aligncenter size-thumbnail wp-image-26353" title="Part3 - Final Product - 002" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-002.png?w=114&#038;h=96" alt="" width="114" height="96" /></a><a href="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-003.png"><img class="aligncenter size-thumbnail wp-image-26354" title="Part3 - Final Product - 003" src="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-003.png?w=114&#038;h=96" alt="" width="114" height="96" /></a></p>
<p>With an introduction to databases for android covered you can start writing applications that require data storage such as the final product mentioned in the first post.  There are a plethora of other features to cover in SQLite databasing for android. More of those will be covered in the next tutorial.  Things such as updating your database, deleting entries and getting to know your way around the <strong>DDMS </strong>(Dalvik Debug Monitor Service) are all an essential part of android programming.  If you can’t wait till the next article to check these articles on <a href="http://developer.android.com/guide/developing/tools/ddms.html">DDMS </a>and <a href="http://www.devx.com/wireless/Article/40842/1954">Updating and Deleting</a>.  As always if anyone has problems, questions or issues don&#8217;t hesitate to ask and I will try my hardest to get back to you before the next post! Until the next time, Happy Hacking!</p>
<p>Text files of code for comparison:</p>
<p><a href="http://hackadaycom.files.wordpress.com/2010/07/dbadapter-java.doc">DBAdapter</a> | <a href="http://hackadaycom.files.wordpress.com/2010/07/strings.doc">strings</a> | <a href="http://hackadaycom.files.wordpress.com/2010/07/main.doc">main</a> | <a href="http://hackadaycom.files.wordpress.com/2010/07/quotesmain.doc">QuotesMain</a></p>
<p>Articles used for reference:</p>
<p>DevX &#8211; <a href="http://www.devx.com/wireless/Article/40842/1954">Creating and Using Databases in Android</a><br />
Android Developers &#8211; <a href="http://developer.android.com/guide/index.html">Reference Guide</a></p>
<p>Continue on to Part 4: <a href="http://hackaday.com/2010/08/02/android-development-101-part-4advanced-databasegui-code-and-ddms/">Advanced Database/GUI Code &amp; DDMS</a></p>
<br />Filed under: <a href='http://hackaday.com/category/android-hacks/'>android hacks</a>, <a href='http://hackaday.com/category/software-development/'>Software Development</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/26328/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/26328/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/26328/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=26328&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/07/21/android-development-101-part-3introduction-to-databases/feed/</wfw:commentRss>
		<slash:comments>61</slash:comments>
		<georss:point>43.002684 -81.214990</georss:point>
		<geo:lat>43.002684</geo:lat>
		<geo:long>-81.214990</geo:long>
		<media:content url="" medium="image">
			<media:title type="html">greggers120588</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/img_199912_android-lab.jpg?w=450" medium="image">
			<media:title type="html">Android Lab</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-databases001.png?w=56" medium="image">
			<media:title type="html">Part3-Databases001</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-005.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 005</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-006.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 006</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-007.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 007</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-008.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 008</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-010.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 010</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-009.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 009</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-011.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 011</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-012.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 012</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-013.png?w=120" medium="image">
			<media:title type="html">Part3 - Final Product - 013</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-001.png?w=114" medium="image">
			<media:title type="html">Part3 - Final Product - 001</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-002.png?w=114" medium="image">
			<media:title type="html">Part3 - Final Product - 002</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/07/part3-final-product-003.png?w=114" medium="image">
			<media:title type="html">Part3 - Final Product - 003</media:title>
		</media:content>
	</item>
		<item>
		<title>Coded safety for diy laser</title>
		<link>http://hackaday.com/2010/07/02/coded-safety-for-diy-laser/</link>
		<comments>http://hackaday.com/2010/07/02/coded-safety-for-diy-laser/#comments</comments>
		<pubDate>Fri, 02 Jul 2010 17:00:24 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[laser hacks]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[lock]]></category>
		<category><![CDATA[pic]]></category>
		<category><![CDATA[safety]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=25573</guid>
		<description><![CDATA[Finally we see a hack that is focuses on safety when it comes to high-power laser hacks. A safety switch has been added to the butt of the flashlight body which houses the laser diode. When the safety is flipped on an LED blinks to prompt the user for a security code. If you enter [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=25573&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<span style="text-align:center; display: block;"><a href="http://hackaday.com/2010/07/02/coded-safety-for-diy-laser/"><img src="http://img.youtube.com/vi/2yVtJia5UWY/2.jpg" alt="" /></a></span>
<p>Finally we see a hack that is focuses on <a href="http://laserpointerforums.com/f65/445nm-pointer-build-laser-lock-security-system-52416.html">safety when it comes to high-power laser hacks</a>. A safety switch has been added to the butt of the flashlight body which houses the laser diode. When the safety is flipped on an LED blinks to prompt the user for a security code. If you enter the correct code on a momentary push switch, electrical access to the laser is enabled. There are also a couple of nice features such as continuous on and auto shutoff.</p>
<p>This would be hard to implement if you&#8217;re working on <a href="http://hackaday.com/2009/10/12/underwater-laser-just-add-shark/">a watertight package</a> but we like the fact that an unsuspecting house guest won&#8217;t go blind if searching for a flashlight during a storm. One last thing, the code entry system is PIC based which reminds us of [Alan Parekh's] <a href="http://alan-parekh.com/projects/button-code-single-button-code-entry-system/">one-button system</a>.</p>
<br />Filed under: <a href='http://hackaday.com/category/laser-hacks/'>laser hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/25573/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/25573/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/25573/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=25573&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/07/02/coded-safety-for-diy-laser/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>
	</item>
		<item>
		<title>May the Phorse be with you</title>
		<link>http://hackaday.com/2010/05/31/may-the-phorse-be-with-you/</link>
		<comments>http://hackaday.com/2010/05/31/may-the-phorse-be-with-you/#comments</comments>
		<pubDate>Mon, 31 May 2010 20:00:29 +0000</pubDate>
		<dc:creator>Jakob Griffith</dc:creator>
				<category><![CDATA[led hacks]]></category>
		<category><![CDATA[ATtiny25]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[entry]]></category>
		<category><![CDATA[led]]></category>
		<category><![CDATA[light]]></category>
		<category><![CDATA[morse]]></category>
		<category><![CDATA[phorse]]></category>
		<category><![CDATA[POV]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=24615</guid>
		<description><![CDATA[The PhorsePOV by [Julian Skidmore] almost slipped by, but we thought it was a nice easy hack for your Memorial Monday. The gadget uses an ATTINY25 to drive 6 LEDs aren&#8217;t standard characters 7 units high? Which when waved in the air produces a readable message. What we were really interested in is the use [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=24615&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-24617" title="Worst, Title, Ever! Thank you comicbook guy." src="http://hackadaycom.files.wordpress.com/2010/05/phorsepovrealproto2.png" alt="" width="470" height="251" /></p>
<p>The <a href="http://sites.google.com/site/libby8dev/stripes/examples">PhorsePOV</a> by [Julian Skidmore] almost slipped by, but we thought it was a nice easy hack for your Memorial Monday. The gadget uses an ATTINY25 to drive 6 LEDs <span style="text-decoration:line-through;">aren&#8217;t standard characters 7 units high</span>? Which when <a href="http://hackaday.com/?s=pov">waved in the air</a> produces a readable message. What we were really interested in is the use of a single button for text entry, called Phorse code, or an &#8220;easier to learn and remember&#8221; version of <a href="http://en.wikipedia.org/wiki/Morse_code">Morse code</a>. While it seemed silly at first, most of us here could enter messages within a few minutes of trying.</p>
<br />Filed under: <a href='http://hackaday.com/category/led-hacks/'>led hacks</a>  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/24615/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/24615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/24615/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=24615&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/05/31/may-the-phorse-be-with-you/feed/</wfw:commentRss>
		<slash:comments>23</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Jakob Griffith</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/05/phorsepovrealproto2.png" medium="image">
			<media:title type="html">Worst, Title, Ever! Thank you comicbook guy.</media:title>
		</media:content>
	</item>
		<item>
		<title>NES lovers grew up and now they&#8217;re coding for Palm</title>
		<link>http://hackaday.com/2010/01/27/nes-lovers-grew-up-and-now-theyre-coding-for-palm/</link>
		<comments>http://hackaday.com/2010/01/27/nes-lovers-grew-up-and-now-theyre-coding-for-palm/#comments</comments>
		<pubDate>Wed, 27 Jan 2010 19:01:58 +0000</pubDate>
		<dc:creator>Mike Szczys</dc:creator>
				<category><![CDATA[pre hacks]]></category>
		<category><![CDATA[code]]></category>
		<category><![CDATA[contra]]></category>
		<category><![CDATA[konami]]></category>
		<category><![CDATA[palm]]></category>
		<category><![CDATA[pixi]]></category>
		<category><![CDATA[pre]]></category>
		<category><![CDATA[root]]></category>

		<guid isPermaLink="false">http://hackaday.com/?p=21137</guid>
		<description><![CDATA[In case you missed it back in June, the Palm Pre was rooted by extracting the Root ROM from a Palm tool used to reset a device with damaged software. A lot has been learned from examining the code inside that ROM but we&#8217;re most amused by one thing in particular. If you grew up [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=21137&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p><img class="alignnone size-full wp-image-21138" title="palm-pre-konami-code" src="http://hackadaycom.files.wordpress.com/2010/01/palm-pre-konami-code.jpg" alt="" width="470" height="327" /></p>
<p>In case you missed it back in June, <a href="http://www.engadget.com/2009/06/09/palms-webos-root-image-leaks-out-code-enthusiasts-reschedule-t/">the Palm Pre was rooted</a> by extracting the Root ROM from a Palm tool used to reset a device with damaged software. A lot has been learned from examining the code inside that ROM but we&#8217;re most amused by one thing in particular. If you grew up in the 80&#8242;s there&#8217;s a pretty good chance you know the <a href="http://en.wikipedia.org/wiki/Konami_Code">Konami Code</a> by heart. So did the developers of WebOS, the firmware running on the Palm Pre. By inputting the familiar (UpUpDownDownLeftRightLeftRightBA) set of gestures <a href="http://www.engadget.com/2009/06/10/the-secret-to-palm-pre-dev-mode-lies-in-the-konami-code/">the handset enters Developer mode</a> for connection to the SDK which was <a href="http://hackaday.com/2009/06/27/palm-pre-mojo-sdk-leaked/">leaked last summer</a> but is <a href="http://developer.palm.com/">now in open release</a>.</p>
<br />Posted in pre hacks  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/hackadaycom.wordpress.com/21137/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/hackadaycom.wordpress.com/21137/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/hackadaycom.wordpress.com/21137/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=hackaday.com&amp;blog=4779443&amp;post=21137&amp;subd=hackadaycom&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://hackaday.com/2010/01/27/nes-lovers-grew-up-and-now-theyre-coding-for-palm/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
	
		<media:content url="" medium="image">
			<media:title type="html">Mike Szczys</media:title>
		</media:content>

		<media:content url="http://hackadaycom.files.wordpress.com/2010/01/palm-pre-konami-code.jpg" medium="image">
			<media:title type="html">palm-pre-konami-code</media:title>
		</media:content>
	</item>
	</channel>
</rss>
