<?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/"
	>

<channel>
	<title>smileymicros.com</title>
	<atom:link href="http://smileymicros.com/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://smileymicros.com/blog</link>
	<description>Smiley&#039;s Workshop Blog</description>
	<lastBuildDate>Wed, 07 Mar 2012 21:33:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>LCD Navigator Tutorial</title>
		<link>http://smileymicros.com/blog/2012/03/07/lcd-navigator-tutorial/</link>
		<comments>http://smileymicros.com/blog/2012/03/07/lcd-navigator-tutorial/#comments</comments>
		<pubDate>Wed, 07 Mar 2012 20:58:52 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[arduino]]></category>
		<category><![CDATA[ATmega328]]></category>
		<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[Button]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[LCD]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/?p=1514</guid>
		<description><![CDATA[This material was abstracted from Smiley’s Workshop 42: Breadboard LCD Navigator – Part 1, the LCD January 2012 Nuts&#38;Volts and Smiley’s Workshop 43: February 2012 Nuts&#38;Volts. The Figure numbers are not sequential but start over where the Part 2 section &#8230; <a href="http://smileymicros.com/blog/2012/03/07/lcd-navigator-tutorial/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>This material was abstracted from Smiley’s Workshop 42: Breadboard LCD Navigator – Part 1, the LCD  January 2012 Nuts&amp;Volts and Smiley’s Workshop 43: February 2012 Nuts&amp;Volts. The Figure numbers are not sequential but start over where the Part 2 section begins</h3>
<p><strong>Source code links are at the at end of the article.</strong></p>
<p><strong>Assembly Instructions: </strong><a href="http://www.smileymicros.com/index.php?module=pagemaster&#038;PAGE_user_op=view_page&#038;PAGE_id=93&#038;MMN_position=145:145">LCDNAV Assembly</a></p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0023.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb3.jpg" border="0" alt="clip_image002" width="205" height="248" /></a></p>
<p>Figure 1: LCD Navigator</p>
<h3><a name="_Toc308183151"><span style="font-weight: bold;">Lab Section: The LCD Navigator</span></a></h3>
<h4><a name="_Toc308183152"><span style="font-weight: bold;">Assemble the LCD Navigator Projects Kit</span></a></h4>
<p>The LCD Navigator Projects Kit, shown if Figure 4, is available from the Nuts&amp;Volts magazine and webstore.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0083.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008_thumb3.jpg" border="0" alt="clip_image008" width="242" height="248" /></a></p>
<p>Figure 4: LCD Navigator Parts Kit</p>
<p>Instructions on assembling the board are available on www.smileymicros.com under the LCDNAV menu. The schematics for this board are shown in Figure 5: LCDNAV Schematics</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0103.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010_thumb3.jpg" border="0" alt="clip_image010" width="248" height="185" /></a></p>
<p>Figure 5: LCDNAV Schematics</p>
<h4><a name="_Toc308183153"><span style="font-weight: bold;">LCD Hardware: The HD44780 LCD</span></a></h4>
<p>I read a book (I think it was David Brin’s ‘Practice Effect’) where some primitive people found a digital watch with an LCD display. They were amazed that whoever made the thing was able to train all the little black bugs to run around and align themselves in such peculiar patterns. And that’s the extent of the detail I’ll give on the underlying technology of LCDs. We’ll concentrate instead on using C to train the little black bugs to do our tricks.</p>
<p>We are lucky since Hitachi developed a simple way to control the LCD that has now become an industry standard for low-cost character LCDs: the HD44780 driver/controller chip that you’ll find built into our display. They provide a parallel control interface that can send data in either 8-bit or 4-bit chunks and control the communication with enable and read strobe lines. Since we like to save pins in our AVR designs, we will use the 4-bit mode. And of course all that brain fatiguing stuff we learned about bitwise operators is going to come in handy</p>
<h5><a name="_Toc308183154"><span style="font-weight: bold;">Wiring LCDNAV to the Arduino</span></a></h5>
<p>Well, after all that preaching to get folks to drill down through the simpler library functions and use the underlying C, we are going to do our first demonstration of the LCD Navigator with the Arduino! But not really: we will only be using the board and do the code in C using AVRStudio, WinAVR, and avrdude. The Arduino is an easy to use development platform and you don’t have to use the Arduino IDE or libraries – you can use it with plain old C. You can see how to wire this up in Figure 6: LCDNAV wired to Arduino and Figure7: LCDNAV with Arduino.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0122.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image012_thumb2.jpg" border="0" alt="clip_image012" width="248" height="167" /></a></p>
<p>Figure 6: LCDNAV with Arduino</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0142.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image014_thumb2.jpg" border="0" alt="clip_image014" width="248" height="141" /></a></p>
<p>Figure 7: LCDNAV wired to Arduino</p>
<p><strong>LCDNAV wiring to the Arduino:</strong></p>
<ul>· DB7 Pin 2<br />
· DB6 Pin 3<br />
· DB5 Pin 4<br />
· DB4 Pin 5<br />
· E Pin 11<br />
· RW GND<br />
· RS Pin 12<br />
· LFT Pin 6<br />
· UP Pin 7<br />
· CTR Pin 8<br />
· DWN Pin 10<br />
· RGT Pin 9</ul>
<h4><a name="_Toc302659879"></a><a name="_Toc308183155"><span style="font-weight: bold;">LCD Software</span></a></h4>
<h5><a name="_Toc308183156"><span style="font-weight: bold;">Using the LCD</span></a></h5>
<p>We will use our avrtoolbox lcd elementary library which somewhat duplicates the function in the Arduino LiquidCrystal library, but in a more generalized fashion to use with the regular AVR C tools: AVRStudio, WinAVR, and avrdude. The source code is located in avrtoolbox\libavr\testers\source \lcd_hd44780. I owe a debt to Peter Dannenger for his LCD tutorial on AVRFreaks. His code provided a good starting point for porting the Arduino LiquidCrystal functions. [http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=828978]</p>
<p>You can find the source code for this library at: http://code.google.com/p/avrtoolbox/libavr/source/driver/external_hardware/lcd-hd44780</p>
<p><strong>The library has the following functions:</strong></p>
<ul>lcd_init()<br />
lcd_clear()<br />
lcd_home()<br />
lcd_set_cursor()<br />
lcd_putc()<br />
lcd_puts()<br />
lcd_puts_p()<br />
lcd_cursor_on()<br />
lcd_­cursor_off()<br />
lcd_blink_on()<br />
lcd_­­­blink_off()<br />
lcd_display_on()<br />
lcd_display_off()</ul>
<p>As shown in Figure 8: LCD documentation in avrtoolbox. You can access the avrtoolbox documentation at www.smileymicros.com\avrtoolbox_html.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0161.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image016_thumb1.jpg" border="0" alt="clip_image016" width="248" height="220" /></a></p>
<p>Figure 8: LCD documentation in avrtoolbox</p>
<p><strong><em>Yes, but can you use it with the Arduino?</em></strong></p>
<p>I’m really not trying to make folks lives more complex than necessary, but you can use the LCD with the Arduino LiquidCrystal library. It is wired up for it anyway. The only caveat is that their code is for a 16&#215;2 (16 characters 2 lines) LCD while our LCDNAV board uses a 8&#215;2 LCD (it is a lot cheaper). You need to change one line each example from: lcd.begin(16, 2); to: lcd.begin(8, 2); . But note that this doesn’t make a difference in some of the examples since they are hardwired to 16 characters. I suggest sticking with the avrtoolbox code for now.</p>
<p><strong>Part 2 &#8211; the navigator buttons:</strong><br />
<strong>Source code links at end of article</strong></p>
<h3>From Smiley’s Workshop 43 <a name="_Toc294708808">February Nuts&amp;Volts</a></h3>
<p><a name="_Toc296429605"></a><a name="_Toc300151295"></a></p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0022.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image002_thumb1.jpg" border="0" alt="clip_image002" width="205" height="248" /></a></p>
<p>Figure 1: LCD Navigator</p>
<h3><a name="_Toc302311129"></a><a name="_Toc302659872"></a><a name="_Toc308025262"></a><a name="_Toc309048121"></a><a name="_Toc309657841"></a><a name="_Toc311043818">Recap:</a></h3>
<p>Last month we looked at the LCD part of the LCD Navigator Project. This month we will look at the Navigator part – the five momentary push buttons arrayed as a cross in Figure 1. These buttons can be used to navigate a menu much like you would typically do with a TV Remote Control 5 button navigator as shown in Figure 2. These buttons don’t even typically have labels since most folks can intuit that they are up, down, left, right, and select after only a few moments of messing with them and watching what happens on a TV menu.</p>
<p><a name="_Toc308025263"></a><a name="_Toc309048122"></a><a name="_Toc309657842" href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0042.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image004_thumb1.jpg" border="0" alt="clip_image004" width="248" height="157" /></a></p>
<p>Figure 2: Typical Remote control menu navigator buttons</p>
<p>We will first look at the hardware considerations for using mechanical switches like these push buttons. Then we will learn to use the nav_button library that you can find in avrtoolbox &#8211; buried fairly deeply in the folder tree at: avrtoolbox\libavr\source\driver\external_hardware\nav_button. You can get this from the avrtoolbox repository at: http://code.google.com/p/avrtoolbox/. You will probably want to start with the tester library at: avrtoolbox\libavr\testers\nav_buttons.</p>
<h3><a name="_Toc308025266"></a><a name="_Toc309048125"></a><a name="_Toc309657848"></a><a name="_Toc311043819">The LCD Navigator</a></h3>
<p>We looked at the LCD part of the LCD Navigator in last month’s Workshop. The board schematic is shown in Figure 3 and a picture of it connected to an Arduino via a Breadboard as shown in Figure 4. Finally the breadboard wiring is shown in Figure 5. You may even already have wired this up to test last month’s LCD code.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0062.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image006_thumb1.jpg" border="0" alt="clip_image006" width="248" height="185" /></a></p>
<p>Figure 3: LCDNAV Schematics</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0082.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image008_thumb1.jpg" border="0" alt="clip_image008" width="248" height="167" /></a></p>
<p>Figure 4 – LCD Navigator with Arduino</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0102.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image010_thumb1.jpg" border="0" alt="clip_image010" width="248" height="141" /></a></p>
<p>Figure5: LCDNAV wired to Arduino</p>
<p>LCDNAV wiring to the Arduino:<br />
· DB7 Pin 2<br />
· DB6 Pin 3<br />
· DB5 Pin 4<br />
· DB4 Pin 5<br />
· E Pin 11<br />
· RW GND<br />
· RS Pin 12<br />
· LFT Pin 6<br />
· UP Pin 7<br />
· CTR Pin 8<br />
· DWN Pin 10<br />
· RGT Pin 9</p>
<h3><a name="_Toc308025267"></a><a name="_Toc309048126"></a><a name="_Toc309657849"></a><a name="_Toc311043820">Navigator Buttons: Hardware</a></h3>
<p>You can use this with the Arduino as shown in Figures 3, 4, and 5 or you can use the BreadboArduino that we used in Workshop 41 (Nuts&amp;Volts December 2011) [You can purchase the BreadboArdino Chaser Lights Project kit from Nuts&amp;Volts magazine and webshop]. Please keep in mind that even though we demonstrate the LCDNAV board using Arduino compatible hardware, we will use code that is regular C using the regular free AVR C tools: AVRStudio, WinAVR, and avrdude. (And please note that this was tested with AVRStudio 4, not the latest version 5 that according to the buzz on AVRFreaks is not ready for prime time.) To help wire this thing up, I’ve generated a label for the ATmega328p shown in both Figure 6 and 7 that you can print and put on the chip using double sided sticky tape. You can get this in avrtoolbox at: \testers\nav_buttons\atmega328_label.doc.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0122.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image012_thumb1.jpg" border="0" alt="clip_image012" width="248" height="188" /></a></p>
<p>Figure 6: LCDNAV with the BreadboArduino</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0142.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image014_thumb1.jpg" border="0" alt="clip_image014" width="51" height="248" /></a></p>
<p>Figure7: ATmega328 Port Pin Label</p>
<h5><a name="_Toc308025268"></a><a name="_Toc309048127"></a><a name="_Toc309657850"></a><a name="_Toc311043821">Wiring LCDNAV to the BreadboArduino</a></h5>
<p>Now get out the BreadboArduino Chaser Lights Project that you did last month and pull off all those parts that were specific to the Chaser Lights (Ouch! I know – but see the end of this Workshop for a PCB solution to your loss.) Figure 8 shows the BreadboArduino schematic and Figure 9 shows how you’ll wire up the LCDNAV connections to the ATmega328p on the breadboard. You saw how this should look in Figure 6. Good luck!</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0162.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image016_thumb1.jpg" border="0" alt="clip_image016" width="248" height="190" /></a></p>
<p>Figure 8: BreadboArduino Basic Wiring</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image0182.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image018" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image018_thumb1.jpg" border="0" alt="clip_image018" width="248" height="197" /></a></p>
<p>Figure 9: LCDNAV wired to BreadboArduino</p>
<p>LCDNAV wiring to the ATmega328 on the BreadboArduino:<br />
· DB7 Pin 4 (PD2)<br />
· DB6 Pin 5 (PD3)<br />
· DB5 Pin 6 (PD4)<br />
· DB4 Pin 11 (PD5)<br />
· E Pin 17 (PB3)<br />
· RW GND<br />
· RS Pin 18 (PB4)<br />
· LFT Pin 12 (PD6)<br />
· UP Pin 13 (PD7)<br />
· CTR Pin 14 (PB0)<br />
· DWN Pin 16 (PB2)<br />
· RGT Pin 15 (PB1)</p>
<h4><a name="_Toc308025269"></a><a name="_Toc309048128"></a><a name="_Toc309657851"></a><a name="_Toc311043822">Navigator Buttons: Software</a></h4>
<p><a name="_Toc302659878"></a><a name="_Toc308025270"></a><a name="_Toc309048129"></a><a name="_Toc309657852">Whether you choose to build this project for an Arduino board or the BreadboArduino or any other AVR development board, you’ll want to first test it with the nav_buttons tester software. When you run this code the first message output is “NavButt” (I wasn’t trying to be funny, it’s just that with only 8 characters and two lines we have to be parsimonious with our text.) This is followed shortly by the revision number then the screen blanks and waits for you to press a button. Figure 6 shows the message that is printed if you press the center button: CTR! </a></p>
<p>The program spins in a forever loop &#8211; for(;;) – checking the nav_available() function to see if &#8211; well can you guess? Right, it returns 0 if no button has been pressed and not 0 if a button has been pressed. The ‘not 0’ is a number that has a bit for each button press identified. We assume that there will generally only be one bit set, but you might get several pressed at the same time so the code process the bits sequentially setting each bit back to 0 when it has been handled until all the bits are set back to 0. As you will see shortly, this sequential processing gives you the opportunity to prioritize the key presses so that, for instance, the CTR key will always be processed before any other key.</p>
<h5><a name="_Toc311043823">The Navigator Library</a></h5>
<p>The navigator library consists of nav.c and nav.h which exposes a few simple functions.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
void nav_init(); // initialize the navigator buttons
uint8_t nav_available(); // true if a new button press is available
uint8_t nav_get_button(); // return the next available button
</span></code></pre>
<p>This makes for a very simple tester program:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
#include "c:\avrtoolbox\libavr\source\general\util\util.h"
#include "c:\avrtoolbox\libavr\source\driver\external_hardware\lcd_hd44780\lcd.h"
#include "c:\avrtoolbox\libavr\source\driver\external_hardware\nav_button\nav.h"

int main( void )
{
	uint8_t key = 0;

	lcd_init();
	nav_init();

	lcd_puts("NavButt");
	delay(500);
	lcd_clear();
	lcd_puts("REV028");
	delay(1000);
	lcd_clear();

  for(;;)
  {
	if(nav_available())
	{
		key = nav_get_key();

		if(key == CTR)
		{
			lcd_home();
			lcd_blank(16);
			lcd_puts("CTR!");
		}
		if(key == LFT)
		{
			lcd_home();
			lcd_blank(16);
			lcd_puts("LFT!");
		}
		if(key == RGT)
		{
			lcd_home();
			lcd_blank(16);
			lcd_puts("RGT!");
		}
		if(key == UP)
		{
			lcd_home();
			lcd_blank(16);
			lcd_puts("UP!");
		}
		if(key == DWN)
		{
			lcd_home();
			lcd_blank(16);
			lcd_puts("DWN!");
		}
		delay(100);
		lcd_home();
		lcd_blank(16);
	}
  }
}
</span></code></pre>
<p>When we press the down button the LCD shows ‘DWN!’ as shown in Figure 10: DWN!</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image020.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image020" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image020_thumb.jpg" border="0" alt="clip_image020" width="248" height="168" /></a></p>
<p>Figure 10: DWN!</p>
<p>And as usual this simplicity is hiding some complexity under the hood that we will look at in more detail. When you first look at this, especially if you are a novice you might correctly ask ‘where is all the code that notes when a button is pressed?’ Well, that is all set up by the nav_init() routine that ‘sets up’ an ISR (Interrupt Service Routine) that runs in the background out of sight of our main loop. A timer peripheral is set to interrupt the main code every 5 mS (milli-Seconds or 0.005 seconds) and check the state of the buttons. If a button is low for 5 consecutive 5mS intervals (25mS) then we are reasonable sure that the button has been pressed. We will get into a lot of detail about timers and ISRs in another Workshop, but for now I recommend that you look at the nav_init() function to get a feel for what is going on.</p>
<p>There are several other neat tricks hidden under the hood of this code, including the way the port pins are mapped to each of the five buttons. For example:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
#define NAV_LFT_PORTX PORTD
#define NAV_LFT_DDR DDRD
#define NAV_LFT_PINX PIND
#define NAV_LFT_PIN PD6
</span></code></pre>
<p>Here we see that we require four separate definitions just for setting up the LFT button in the initiation. If you want to wire the buttons to different ports and pins, you will need to change them in these definitions in nav.h.</p>
<p>If you look a little deeper at the code in nav.c you’ll see a rather bizarre seeming algorithm for accepting a button push as valid. Before looking at that code, we’ll need to take a moment to examine the topic of switch bounce and the debouncing thereof.</p>
<h4><a name="_Toc311043824">Switch Bounce</a></h4>
<p>Each of the navigator buttons is connected to a 10K ? pull-up resistor to VCC and a 100 ? current-limiting resistor to the breadboard pin as shown in Figure 3: LCDNAV Schematics. When the button is not pressed, the breadboard pin is pulled up to VCC and reads as a 1 if the associated AVR pin is set to digital input. When the button is pressed the breadboard pin is connected to ground (through the current limiting 100 ohm resistor) and the AVR digital input reads 0. Well this is going to be easy, we only have to look for a 0 or a 1 – right? Wrong – in the button the actual mechanical connection is not instantaneous and in fact the voltages bounces around and takes a bit of time from a computer perspective to settle on either VCC or GND which leads to the button being in output bouncing between 1 and 0 like crazy. Figure 11: Switch Bounce illustrates what happens to the voltage across a switch as it is pressed and released.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image022.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image022" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image022_thumb.jpg" border="0" alt="clip_image022" width="248" height="141" /></a></p>
<p>Figure 11: Switch Bounce</p>
<p>Jack Ganssle provides an excellent discussion of switch bounce at: http://www.ganssle.com/debouncing.htm</p>
<p>The algorithm I use in nav.c to deal with switch bounce is fairly clear and teachable, but not any where near the most efficient that can be used. As usual I came up with what I thought was a good algorithm for dealing with this only to find out on AVRFreaks.net (http://tinyurl.com/6hjz5yt) that other’s have been down this path before me and done a better job. I will admit that the ‘best’ way of doing this is very dense and not easy to understand, so for now let’s just use our less efficient technique and save the more efficient (and harder to understand) version for a later Workshop.</p>
<p>Some of the more perceptive readers will want to know why we have to use the 10K ohm resistor to pull up the switch when we can configure the pull-up resistors for the input pins. They may also want to know why we need the 100-ohm resistor at all. And the answer is that this design is for novices using a breadboard and neither resistor would be needed if we could be sure that all users would use this thing properly. The 100-ohm resistor is there for the person who accidentally configures the button pin to output and then sets it high thus providing a direct path from VCC to GND if the 100-ohm resistor wasn’t there to prevent it. The 10K ohm resistor is for the person who configures the pin to input and then sets it to 0, which would provide a direct path from VCC to GND.</p>
<h3><a name="_Toc311043825">Simple Menu Navigation Software</a></h3>
<p>Unlike many of the software projects we encounter, menu software doesn’t lend itself to a generic library. Instead it involves learning about and creating state machines that can vary in complexity from very complex to extremely complex. We’ll try to keep it as simple as we can and only use the C switch statement that we’ve seen before as our state machine in a simple demonstration application nav_menu.c that you can find under the avr_applications section of avrtoolbox. You can use it as a template if you want to write a menu system of your own. In this application we will also show how to enter text and numbers using the navigator keys.</p>
<p>The nav_menu.c application builds on the tester code shown above using a series of switch statements in functions to keep track of the system state. The program opens with the LCD showing the program name and revision as shown in Figure 12: nav_menu.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image024.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image024" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image024_thumb.jpg" border="0" alt="clip_image024" width="248" height="168" /></a></p>
<p>Figure 12: nav_menu.</p>
<p>First we define the number of states: #define MAX_TOP 5 – and don’t forget that since we are counting from 0, that the maximum of 5 means that we actually will have 6 functions named according to what they do as follows:</p>
<p>Enter text<br />
Enter number<br />
View text<br />
View number<br />
Erase text<br />
Erase number</p>
<p>When we run the code, the forever loop will either increment or decrement a variable ‘top’ depending on our presses of the UP or DWN key:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
if(key == UP)
{
    if (top &lt;= MAX_TOP) top++;
}

if(key == DWN)
{
    if (top &gt; 0) top--;
}
</span></code></pre>
<p>At the end of the loop we wait half a second to make sure the user has pressed and released a key, then we show the ‘top’ number on the second line of the LCD.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
delay(500);
lcd_set_cursor( 0, 1 );
lcd_puts(itoa(top,num,10) );
</span></code></pre>
<p>When the user pressed the center (CTR) button:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
if(key == CTR)
{
    get_top(top);
}
</span></code></pre>
<p>The get_top(top) function is called:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
void get_top(uint8_t get)
{
	switch (get)
	{
		case 0:
			entr_txt();
			break;
		case 1:
			entr_num();
			break;
		case 2:
			view_txt();
			break;
		case 3:
			view_num();
			break;
		case 4:
			erse_txt();
			break;
		case 5:
			erse_num();
			break;
		default:
			break;
	}
}
</span></code></pre>
<p>Suppose you press the up button 4 times to show the number 3, and then press CTR. This will switch to case 3 which calls the view_num() function:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
//View number
void view_num()
{
	lcd_clear();
	lcd_puts_p(view_num_txt);
}
</span></code></pre>
<p>The view_num_txt was defined as some text in PROGMEM space as follows:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
const char view_num_txt[] PROGMEM = "view_num";
</span></code></pre>
<p>And the LCD displays the called function name on line one along with the number for that state on line two as shown in Figure 13.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image026.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image026" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image026_thumb.jpg" border="0" alt="clip_image026" width="248" height="168" /></a></p>
<p>Figure 13: view_num</p>
<p>The functions that let you enter text and numbers are interesting, but a bit much for this month’s Workshop so we’ll just let you look at the source code if you are interested.</p>
<h3><a name="_Toc311043826">Preview: Simple Chaser Lights Board</a></h3>
<p>If purchased the BreadboArduino kit and constructed the Simple Chaser Lights project last month you are probably going to think that it is such a shame to tear up that project just to get at the BreadboArduino so that we can test our LCDNAV. If only there was something we could do to have all those blinking lights AND test the LCDNAV board… Well, Figure 14 shows that we now have an alternative to building the Chaser Lights on a breadboard, we can get a printed circuit board and parts kit from Nuts&amp;Volts that lets you build a permanent platform for you chaser lights experiments.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image028.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image028" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image028_thumb.jpg" border="0" alt="clip_image028" width="248" height="119" /></a></p>
<p>Figure 14: Chaser Lights Board</p>
<p>The main difference between this board and the circuit discussed in the Workshop 41 (Nuts&amp;Volts December 2011) is that this one does not have a communication channel for reprogramming. It comes preprogrammed with most of the light patterns discussed before and as a bonus it has some POV (Point Of View) Messages that allow you to write text in the air by waving the board like a wand as we’ll learn all about in next month’s Workshop. You will find the simple_chaser_lights and the pov_wand software in avrtoolbox under the avr_applications directory so you can get a head start on this visually arresting project before we look at the details in next month’s Workshop.</p>
<p>Questions? Nuts&amp;Volts is hosting forums for its writers and you can find mine at: http://forum.servomagazine.com/. But if you want a quick response, especially to a question not directly related to an article you could put on your biohazard suit and start a thread on www.avrfreaks.net. But first read my blog entry that will tell you why you need the biohazard suit: <a href="http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/">http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/</a>.</p>
<p>And if you just can’t wait and want to get a leg up on all this serial stuff and real C programming for the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit and the Virtual Serial Port Cookbook using the Nuts&amp;Volts magazine or their web shop.</p>
<p><strong>I&#8217;ve created a snapshot of the LCD Navigator source code that you can find at:</strong><br />
http://code.google.com/p/avrtoolbox/downloads/list under the title lcd_navigator_source.zip<br />
This code is abstracted from avrtoolbox and doesn&#8217;t require that directory structure &#8211; it has all the files in a single directory and the project is set up to use those files.</p>
<p><strong>Source code is located at:</strong></p>
<p>http://code.google.com/p/avrtoolbox/libavr/source/driver/external_hardware/lcd_hd44780</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/lcd_hd44780</p>
<p>http://code.google.com/p/avrtoolbox/libavr/source/driver\external_hardware/nav_button</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/nav_buttons</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/nav_buttons/atmega328_label.doc</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2012/03/07/lcd-navigator-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Simple Chaser Lights Kit Tutorial</title>
		<link>http://smileymicros.com/blog/2012/02/04/simple-chaser-lights-kit-tutorial-part-1/</link>
		<comments>http://smileymicros.com/blog/2012/02/04/simple-chaser-lights-kit-tutorial-part-1/#comments</comments>
		<pubDate>Sat, 04 Feb 2012 19:39:30 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[ATmega328]]></category>
		<category><![CDATA[LED]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2012/02/04/simple-chaser-lights-kit-tutorial-part-1/</guid>
		<description><![CDATA[Figure 1: ATTACK OF THE KILLER CHASER LIGHTS This material is cut from Smiley’s Workshop 44 from the January 2012 Nuts&#38;Volts Magazine. The theory section was removed, so there may appear to be some Figures missing. We will apply the &#8230; <a href="http://smileymicros.com/blog/2012/02/04/simple-chaser-lights-kit-tutorial-part-1/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3><a name="_Toc229816894"></a><a name="_Toc229817066"></a><a name="_Toc230075380"></a><a name="_Toc232072375"></a><a name="_Toc229816890"></a><a name="_Toc229817062"></a><a name="_Toc230075376"></a><a name="_Toc232072369"></a><a name="_Toc233616889"></a><a name="_Toc233969838"></a><a name="_Toc236301230"></a><a name="_Toc236727493"></a><a name="_Toc236727571"></a><a name="_Toc237255517"></a><a name="_Toc250218105"></a><a name="_Toc255485288"></a><a name="_Toc256436361"></a><a name="_Toc258146398"></a><a name="_Toc260057958"></a><a name="_Toc260663727"></a><a name="_Toc260842159"></a><a name="_Toc262990924"></a><a name="_Toc268098410"></a><a name="_Toc268789979"></a><a name="_Toc271204266"></a><a name="_Toc271720048"></a><a name="_Toc273452210"></a><a name="_Toc275186013"></a><a name="_Toc276390391"></a><a name="_Toc294273625"></a><a name="_Toc294708807"></a><a name="_Toc296429604"></a><a name="_Toc300151294"></a><a name="_Toc301355197"></a><a name="_Toc311817017"></a><a name="_Toc312160069"></a></h3>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image002.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image002_thumb.jpg" border="0" alt="clip_image002" width="248" height="137" /></a></p>
<p>Figure 1: ATTACK OF THE KILLER CHASER LIGHTS</p>
<p>This material is cut from Smiley’s Workshop 44 from the January 2012 Nuts&amp;Volts Magazine. The theory section was removed, so there may appear to be some Figures missing.</p>
<p>We will apply the hard stuff to storing data to be displayed on the Simple Chaser Lights Board (available from Nuts&amp;Volts). This board will let us build various sorts of chaser lights such as in a theater marquee like in Figure 1, or for Battlestar Glactica Cylons or Knight Rider Kitts as shown in Figures 4 and 5.</p>
<h3><a name="_Toc313889515">Introducing The Simple Chaser Lights Kit</a></h3>
<p>In the December Nuts&amp;Volts Smiley’s Workshop 41, we learned about C bitwise operations and we used that knowledge to make a simple chaser lights project using the BreadboArduino (available from Nuts&amp;Volts) as shown in Figure 2. This is a great project for learning bitwise digital input and output operations since it reads the bit states from an 8-bit DIP switch and outputs 8-bit patterns on 8 LEDs, thus providing tangible physical representations of bits and bytes used for input and output.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image004.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image004_thumb.jpg" border="0" alt="clip_image004" width="248" height="94" /></a></p>
<p>Figure 2: Chaser Lights on BreadboArduino</p>
<p>If you built the breadboard project shown in Figure 2, you probably had some problems getting it wired correctly &#8212; I sure did and it was my project! So I decided to put the design (minus the USB board) on a printed circuit board so we can build it easily and have something we can knock around a bit and not worry about parts and wires falling off. Figure 3 shows the results. This kit is very easy to assemble and you can find the details on my blog at www.smileymicros.com\blog and it is available from Nuts&amp;Volts. As usual this is a fully open source project so the source code and the Eagle schematics and layout are located at http://code.google.com/p/avrtoolbox/.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image006.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image006_thumb.jpg" border="0" alt="clip_image006" width="248" height="119" /></a></p>
<p>Figure 3: Chaser Lights Board</p>
<p>The main difference between this board and the circuit discussed in the Workshop 41 is that this one does not have a communication channel for reprogramming. It comes with a bunch of chaser patterns built in, but if you want to reprogram it, you will have to remove the IC and reprogram it on an STK500 or Dragon or some other socketed programmer with an ISP connection (this is also covered in the blog). You will find the simple_chaser_lights software in avrtoolbox under the avr_applications directory so you can get a head start on this visually arresting project before we look at the details in next month’s Workshop.</p>
<p><strong><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image008.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image008_thumb.jpg" border="0" alt="clip_image008" width="172" height="248" /></a></strong></p>
<p>Figure 4: Cylon Eyes</p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong> </strong></p>
<p><strong><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image010.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image010_thumb.jpg" border="0" alt="clip_image010" width="248" height="142" /></a></strong></p>
<p>Figure 5: Kitt from Knight Rider.</p>
<h3><a name="_Toc311817025"></a><a name="_Toc312160077"></a><a name="_Toc313889523">Lab:</a></h3>
<p>Figure 7 and Table 1 show the Simple Chaser Lights Kit parts and Bill of Materials available from Nuts&amp;Volts. Figures 8 and 9 show the schematic and layout. Most folks will be able to figure out how to build this thing from the picture and parts list. But since I just noticed that it is the 21<sup>st</sup> century and that for very little money I could start doing videos for of some of these concepts I am trying to get across, I decided to do a video demonstration on how to construct the Simple Chaser Lights Board Kit. You can find this by Googling ‘Simple Chaser Light Assembly’ or checking my blog at www.smileymicros.com\blog.</p>
<p>When you build this, one thing to remember is that the LED images on the PCB (and the LEDs themselves) have a flat side that faces the LED short leg that is the one you connect to ground. Don’t get them backwards since LEDs are diodes and current will on flow in one direction. Another thing to note is that the VCC and GND pads do not have any sort of connection hardware. You solder the connections to the battery box red and black connections (VCC and GND respectively). Unfortunately this economy comes at the cost of fragility. As you wiggle these wires around they quickly fatigue and will break off. So to prevent this add a glob of high temperature hot glue to the connection to seal the wires and their insulation to the PCB board. This will serve for strain relief and help lessen the likely hood that you’ll bread the power connection. Yeah, it’s ugly &#8211; but cheap &#8211; so like many a date I’ve had, I’ll just go with it.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image012.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image012_thumb.jpg" border="0" alt="clip_image012" width="244" height="154" /></a></p>
<p>Figure 7: Simple Chaser Lights Parts Kit</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="34" valign="top"><strong>#</strong></td>
<td width="34"><strong>Qty.</strong></td>
<td width="171"><strong>Description</strong></td>
</tr>
<tr>
<td width="34" valign="top">1</td>
<td width="34">1</td>
<td width="171">PCB</td>
</tr>
<tr>
<td width="34" valign="top">2</td>
<td width="34">1</td>
<td width="171">ATMEGA328p</td>
</tr>
<tr>
<td width="34" valign="top">3</td>
<td width="34">1</td>
<td width="171">28-pin socket</td>
</tr>
<tr>
<td width="34" valign="top">4</td>
<td width="34">1</td>
<td width="171">8-bit DIP Switch</td>
</tr>
<tr>
<td width="34" valign="top">5</td>
<td width="34">8</td>
<td width="171">5mm Red LED</td>
</tr>
<tr>
<td width="34" valign="top">6</td>
<td width="34">1</td>
<td width="171">220 Resistor Network</td>
</tr>
<tr>
<td width="34" valign="top">7</td>
<td width="34">1</td>
<td width="171">10K Resistor Network</td>
</tr>
<tr>
<td width="34" valign="top">8</td>
<td width="34">1</td>
<td width="171">10K Resistor</td>
</tr>
<tr>
<td width="34" valign="top">9</td>
<td width="34">1</td>
<td width="171">0.1uF Capacitor</td>
</tr>
<tr>
<td width="34" valign="top">10</td>
<td width="34">1</td>
<td width="171">Battery Box 2-AA</td>
</tr>
</tbody>
</table>
<p>Table 1: Simple Chaser Lights Bill of Materials.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image014.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image014_thumb.jpg" border="0" alt="clip_image014" width="248" height="244" /></a></p>
<p>Figure 8: Simple Chaser Lights Schematic</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image016.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image016_thumb.jpg" border="0" alt="clip_image016" width="244" height="70" /></a></p>
<p>Figure 9: Simple Chaser Lights Layout</p>
<h4><a name="_Toc311817026"></a><a name="_Toc312160078"></a><a name="_Toc313889524">How to use the Simple Chaser Lights</a></h4>
<p>Out of the box, the microcontroller is programmed to show 32 patterns (encoded on the leftmost 5-bits of the DIP) at 4 speeds (encoded on the next 2-bits) and you can invert all the patterns (encoded on the rightmost bit) as shown in Figure 10.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image018.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image018" src="http://smileymicros.com/blog/wp-content/uploads/2012/02/clip_image018_thumb.jpg" border="0" alt="clip_image018" width="248" height="124" /></a></p>
<p>Figure 10: DIP Switch</p>
<p>The following list shows the results of various bit patterns set on the DIP switch:</p>
<p><strong>DIP switch bit positions for patterns:<br />
</strong>00000xxx (0): right_sweep1<br />
00001xxx (1): right_sweep2<br />
00010xxx (2): right_sweep3<br />
00011xxx (3): right_sweep4<br />
00100xxx (4): left_sweep1<br />
00101xxx (5): left_sweep2<br />
00110xxx (6): left_sweep3<br />
00111xxx (7): left_sweep4<br />
01000xxx (8): right_stack<br />
01001xxx (9): left_stack<br />
01010xxx (10): right_ant<br />
01011xxx (11): left_ant<br />
01100xxx (12): inout<br />
01101xxx (13): blinkin<br />
01110xxx (14): brownian<br />
01111xxx (15): random<br />
10000xxx (16): cylon1<br />
10001xxx (17): cylon2<br />
10010xxx (18): cylon3<br />
10011xxx (19): cylon4<br />
10100xxx (20): cylon_all<br />
10101xxx (21): tick_tock_half<br />
10110xxx (22): tick_tock_all<br />
10111xxx (23): pov_smiley_micros<br />
11000xxx (24): pov_nutsvolts<br />
11001xxx (25): pov_help<br />
11010xxx (26): pov_stop<br />
11011xxx (27): pov_ I_love_you<br />
11100xxx (28): pov_ taxi<br />
11101xxx (29): pov_right_arrows<br />
11110xxx (30): pov_left_arrows<br />
11111xxx (31): show_all_chasers</p>
<p><strong>DIP switch bit positions for speeds:</strong><br />
xxxxx00x (0) lowest speed<br />
xxxxx01x (0) lower speed<br />
xxxxx10x (0) higher speed<br />
xxxxx11x (0) highest speed</p>
<p><strong>DIP switch bit positions for polarity:<br />
</strong>xxxxxxx0 (0) Normal<br />
xxxxxxx1 (1) Inverted</p>
<p>23 thru 30 start with ‘pov_’ which stands for persistence of vision, and when you set one of those patterns, the output will look pretty strange, unless you wave the board about, then they will look even stranger. But let’s reserve the details of that for another Workshop. Next month we are going to see how to extend the 8 LEDs into a full-fledged chaser marquee style frame.</p>
<p>Questions? Nuts&amp;Volts is hosting forums for its writers and you can find mine at: http://forum.servomagazine.com/. But if you want a quick response, especially to a question not directly related to an article you can put on your biohazard suit and start a thread on www.avrfreaks.net. First read my blog entry that will tell you why you need the biohazard suit: <a href="http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/">http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/</a>.</p>
<p>And if you just can’t wait and want to get a leg up on all this serial stuff and real C programming for the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit and the Virtual Serial Port Cookbook using the Nuts&amp;Volts magazine or their web shop.</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2012/02/04/simple-chaser-lights-kit-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Chaser Lights with the BreadboArduino</title>
		<link>http://smileymicros.com/blog/2011/11/20/chaser-lights-with-the-breadboarduino/</link>
		<comments>http://smileymicros.com/blog/2011/11/20/chaser-lights-with-the-breadboarduino/#comments</comments>
		<pubDate>Mon, 21 Nov 2011 03:47:26 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/11/20/chaser-lights-with-the-breadboarduino/</guid>
		<description><![CDATA[All that theory makes my head hurt, I want to make something bright and shiny! And what is brighter and shinier than LEDs? (Okay, the sun, but who has time to go outdoors when there is so much neat stuff &#8230; <a href="http://smileymicros.com/blog/2011/11/20/chaser-lights-with-the-breadboarduino/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h4>All that theory makes my head hurt, I want to make something bright and shiny! And what is brighter and shinier than LEDs? (Okay, the sun, but who has time to go outdoors when there is so much neat stuff to learn?). Let’s design some Chaser Lights with 8 LEDs that allows us to use an 8-pin DIP switch to select 16 sweep patterns, 8 speeds, and polarity (more on that later). You can see what this looks like in Figure 1, and I’m sorry for the rat’s nest of wires. The ATmega328 pins in Figure 2 and the schematic in Figure 3 will guide you to creating your own rat’s nest.</h4>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0024.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb4.jpg" border="0" alt="clip_image002" width="222" height="244" /></a></p>
<p>Figure 2: ATmega328 Port Pin Mapping</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0044.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004_thumb4.jpg" border="0" alt="clip_image004" width="248" height="131" /></a></p>
<p>Figure 3: ATmega328 Pins for DIP switch and LED</p>
<h5><a name="_Toc305680441">Getting Bit Fields from a DIP Switch</a></h5>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0064.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006_thumb4.jpg" border="0" alt="clip_image006" width="248" height="124" /></a></p>
<p>Figure4: DIP Switch Use</p>
<p>We will let the top 4-switches can encode 16 patterns, the next lower three can encode 8 speeds and the lowest switch encode the polarity. In order to look at each of these parameters individually while ignoring the others we use bit masks which are sets of bits set to one that we AND ‘&amp;’ with the byte so that we exclude the other bits. This is best explained with an example.</p>
<pre><code>
// DIP switch masks
#define POLARITYMASK 0x01 // 00000001
#define SPEEDMASK 0x0E // 00001110
#define PATTERNMASK 0xF0 // 11110000
</code></pre>
<p>We have eight patterns and we can encode them with four switches as follows:</p>
<p><strong><span style="text-decoration: underline;">Binary</span></strong><strong> <span style="text-decoration: underline;">Decimal</span> <span style="text-decoration: underline;">Pattern Select</span></strong></p>
<ul> 0000 0 right_sweep1<br />
0001 1 right_sweep2<br />
0010 2 right_sweep3<br />
0011 3 right_sweep4<br />
0100 4 left_sweep1<br />
0101 5 left_sweep2<br />
0110 6 left_sweep3<br />
0111 7 left_sweep4<br />
1000 8 right_stack<br />
1001 9 left_stack<br />
1010 10 right_ant<br />
1011 11 left_ant<br />
1100 12 inout<br />
1101 13 blinkin<br />
1110 14 brownian<br />
1111 15 random</ul>
<p>[NOTE: for sweep 5,6,and 7 just run sweep 1, 2, 3 with polarity reversed.]</p>
<p>If we AND each of these masks with the value we read on the DIP switch we convert all the bits we aren’t interested in to 0 and leave those we are interested in as they were in the port. Suppose, for instance, that set the pattern to left_stack (9), the speed select to 6, and the polarity to 1, we would see 10011011 (0x9B).</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
          PORTB = 10011011 (0x9B)

	        bit #    76543210
                 PORTB = 10011011 = 0x9B
	  POLARITYMASK = 00000001 = 0x01
		------------------------
	   	   AND = 00000001 = 0x01

	        bit #    76543210
                 PORTB = 10011011 = 0x9B
	     SPEEDMASK = 00001110 = 0x0E
		------------------------
	   	   AND = 00001010 = 0x0A

	      bit #    76543210
               PORTB = 10011011 = 0x9B
	 PATTERNMASK = 11110000 = 0xF0
		------------------------
	   	   AND = 10010000 = 0x90
</span></code></pre>
<p>To get the parameters using raw C we would write:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
uint8_t pattern = 0;
uint8_t speed = 0;
uint8_t polarity= 0;
uint8_t dip_value = 0;

dip_value = get_dip();

// Using raw C bitwise operators
pattern = ((dip_value &amp; PATTERNMASK) &gt;&gt; 4 );
speed = ((dip_value  &amp; SPEEDMASK) &gt;&gt; 1 );
polarity = dip_value &amp; POLARITYMASK;
</span></code></pre>
<p>With the only problem that we have to remember where the field was in the mask so that we can remember to shift it the correct number of times. Or we can give ourselves yet another bitwise crutch and write macros to get these parameters automatically so that we don’t need to remember so much. This crutch would let use retrieve the pattern, speed, and polarity without having to remember anything about the size and position of our bit fields.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
// Using a function as a crutch
pattern = get_mask_field8(dip_value,PATTERNMASK);
speed = get_mask_field8(dip_value,SPEEDMASK);
polarity = get_mask_field8(dip_value,POLARITYMASK);
</span></code></pre>
<p>As is often the case I owe a debt to the folks at www.avrfreaks.net for the macros we’ll use. I posted mine concept and immediately was given a better way: http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=877894#877894 (Michael Hennebry provided the algorithm, and I changed the macro names to conform to my process):</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
#define bit_to_shift8(mask) ( \
((mask) &amp; 0x01) ? 0 : ( \
((mask) &amp; 0x02) ? 1 : ( \
((mask) &amp; 0x04) ? 2 : ( \
((mask) &amp; 0x08) ? 3 : ( \
((mask) &amp; 0x10) ? 4 : ( \
((mask) &amp; 0x20) ? 5 : ( \
((mask) &amp; 0x40) ? 6 : 7 )))))))
#define get_mask_field8(byte, mask) \

(((byte) &amp; (mask))&gt;&gt;bit_to_shift8(mask))
</span></code></pre>
<p>This method allows the compiler to do some serious optimizing and according to another AVRFreak, Cliff Lawson, this wonder uses only four opcodes on an AVR!</p>
<p>If there is a down side it is that this may well be one of the most complicated looking things we have seen so far. But if you’ll take some time with it, you should be able to follow what it is doing. First, the bit_to_shift8 macro finds the number of 0 bits to the right of a mask. For instance for our PATTERNMASK 0xF0 // 0b11110000 we see that after we mask the DIP switch we need to shift the value four places to the right to get the numeric value of the pattern field. As you remember from algebra, when you work a problem with parenthesis you evaluate the innermost one first, then sequentially each next inner parenthesis until the final outer parenthesis. In the case of the bit_to_shif8 macro the system evaluates first the expression: ((mask) &amp; 0&#215;40) ? 6 : 7 ) this looks at the second highest bit position and if it is 1 then the lowest bit found <strong>– so far &#8211; </strong>is the 0&#215;40 bit, number 6, if not then it is 7. Next it looks at ((mask) &amp; 0&#215;20) ? 5 : ( X ) this looks at the third highest bit position and if it is 1 then the lowest bit found<strong> – so far -</strong> is the 0&#215;20 bit, number 5, if not then it is what we found in the previous evalutation (either bit 6 or 7). The next ((mask) &amp; 0&#215;10) ? 4 : ( \ does exactly the same as before and determines the lowest bit <strong>so far</strong>. And so on till each bit has been evaluated. For the PATTERNMASK the lowest bit is 0&#215;01 and the shift is 4, for the SPEEDMASK the lowest bit it 0&#215;02 and the shift is 1, and for the POLARITYMASK the lowest bit is the lowest bit 0 so the shift is also 0. So for our pattern mask, the bit_to_shift8 tells us how many bits to shift right we just AND ‘&amp;’ our DIP switch value with our PATTERNMASK and shift it the 4 bits to get the number for the pattern. I hope this is clear because if you understand this you are getting fairly sophisticated in your understanding of C programming and bitwise operations. I also recommend rereading this section each night at bedtime if you have trouble falling to sleep, with this you should find yourself nodding right off.</p>
<p>Okay, I’ve slipped off the rails again and run out of time and space (fortunately gravity is still working) so if you want to see how this is used in a real Chaser Light application, you can get the source code at http://code.google.com/p/avrtoolbox/ in the source under avr_applications\simple-chaser_lights.</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/11/20/chaser-lights-with-the-breadboarduino/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Breadboard LCD Navigator &#8211; Part 1, the LCD</title>
		<link>http://smileymicros.com/blog/2011/11/08/breadboard-lcd-navigator-part-1-the-lcd/</link>
		<comments>http://smileymicros.com/blog/2011/11/08/breadboard-lcd-navigator-part-1-the-lcd/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 21:26:12 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[arduino]]></category>
		<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[C Programming]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/11/08/breadboard-lcd-navigator-part-1-the-lcd/</guid>
		<description><![CDATA[Smiley’s Workshop 42: Breadboard LCD Navigator – Part 1, the LCD Source code links are at the at end of the article. Joe Pardue January 2012 Nuts&#38;Volts Figure 1: LCD Navigator Recap: Over the past several months we looked at &#8230; <a href="http://smileymicros.com/blog/2011/11/08/breadboard-lcd-navigator-part-1-the-lcd/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>Smiley’s Workshop 42: Breadboard LCD Navigator – Part 1, the LCD</h3>
<p><strong>Source code links are at the at end of the article.</strong></p>
<p>Joe Pardue January 2012 Nuts&amp;Volts</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0023.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb3.jpg" border="0" alt="clip_image002" width="205" height="248" /></a></p>
<p>Figure 1: LCD Navigator</p>
<h3><a name="_Toc302311129"></a><a name="_Toc302659872"></a><a name="_Toc307589154"></a><a name="_Toc308183144"><span style="font-weight: bold;">Recap:</span></a></h3>
<p>Over the past several months we looked at Digital I/O (DIO). In Part 1 (October 2011 Nuts&amp;Volts) we looked at the software side of DIO as it is done in the Arduino using sequentially numbered pins on the Arduino board and we wrote a library of functions similar to the Arduino DIO library functions but using regular C concepts and tools (AVRStudio, WinAVR, avrdude, avrlibc, etc).</p>
<p>In Part 2 (November 2011 Nuts&amp;Volts) we saw that the Arduino pins are simple abstractions of the deeper AVR microcontrollers concept of ports that are 8-bit arrays of pins and we wrote a library that specifically handles ports and their pins as they are used by raw AVRs.</p>
<p>In Part 3 (December 2011 Nuts&amp;Volts) we dropped the abstractions and looked at how DIO is really done in AVRs using the tools available in C without having to write special libraries to manipulate the ports and pins for DIO. We also went deep into bitwise operators, a painful but necessary bit of learning that is required if you really want to know what C programming is all about (and microcontrollers in general for that matter).</p>
<p>We applied all that to a Simple Chaser Light application that you can find at: http://code.google.com/p/avrtoolbox/. And you can test it in hardware with the BreadboArduino Projects kit available from the Nuts&amp;Volts webstore.</p>
<p>Now we are going to have some fun and apply what we’ve learned about DIO by building something really useful, an Open Source Project that has an LCD and 5 buttons used to navigate through menus shown on the LCD. You can think of this as a tiny computer terminal and keyboard: a very minimalist (read cheap) one for the AVR. And like other Smiley’s Workshop projects, you can get the parts kit from Nuts&amp;Volts magazine and their webstore.</p>
<h3><a name="_Toc302311138"></a><a name="_Toc302659873"></a><a name="_Toc308183145"><span style="font-weight: bold;">Theory Section: Digital I/O in C</span></a></h3>
<p>The C programming language knows nothing about AVR DIO. C is a hardware independent programming language and runs on any computer. The AVR is a specific computer that does the same sorts of things that are done by other microcontrollers (such as the 8051 or PIC) but it does those things using different hardware. C abstracts the sorts of things you can do with a computer into a higher-level concept that mimics a generic computer. C leaves it up to the compiler to convert the C code into the actual assembly language instructions that a particular computer uses.</p>
<p>C does such a good job of abstracting the way computers work that it is often called a generic assembly language. In early October 2011, Wired Magazine posted an eulogy to Dennis Ritchie, the father of C: <em>Ritchie’s running joke was that C had “the power of assembly language and the convenience of … assembly language.” In other words, he acknowledged that C was a less-than-gorgeous creation that still ran very close to the hardware. Today, it’s considered a low-level language, not high. But Ritchie’s joke didn’t quite do justice to the new language. In offering true data structures, it operated at a level that was just high enough.</em></p>
<p>Our job is to take the generic things that C can do and use them with the specific things that our AVR can do. And herein lies the rub. AVRs can do a LOT. And as I’ve said before, one of the biggest problems with these things is that they can do so many different things in so many different ways, that it is a chore to figure out which of these many is ‘best’ for a given application. The datasheets are the ultimate resource but unfortunately they tell you how to do everything and don’t give much of a hint as to which of the many things that are doable – which one you should choose, as is the best way to do the task at hand. If you haven’t already done so, I recommend that you get the datasheet for the ATmega328 from www.Atmel.com and skim around in it, especially the Digital I/O section. What you’ll notice is that the data sheet offers us so much bounty that it is nigh impossible to sort out what we really need to do to get these pins inputting and outputting. Let’s take the bitwise stuff we learned last month and see how that is used to set up the DIO registers.</p>
<h4><a name="_Toc308183146"><span style="font-weight: bold;">AVR Registers</span></a></h4>
<p>The AVR uses 8-bit memory locations called registers to set the functionality of each of its peripheral devices. We’ve sort of hit at AVR registers in other Workshops, but let’s take them on again, this time from the perspective of how we will use them with C and bitwise operators. Register space is located near the beginning of the AVR memory space. There are a total of 86 registers listed for the ATmega328. They sport names like SPCR, TCNT0, EEARH, EIFR, TIFR2, and so forth. And many of these registers have bits that you set or clear to activate or deactivate a specific AVR function. These bits also have names like TWAM6, COM2B1, ADIE, PCINT22, SP2, ACBG, and so forth. The point I’m making here is that there are hundreds of acronyms used to control the various AVR functions and neither you nor I have a chance in heck of remembering even a small fraction of them. Thus it is a painful necessity to get intimate with the data sheet. This pain can be somewhat alleviated by using the Atmel Application notes, forums like www.avrfreaks.net, and tutorials like this one, but ultimately if you are going to get proficient with microcontrollers you have to get real friendly with data sheets.</p>
<h4><a name="_Toc308183147"><span style="font-weight: bold;">AVR IO-Port Registers</span></a></h4>
<p>If you refer to the I/O-Ports section of the datasheet and look at the Register Description, you’ll see 10 registers listed. We are interested in 9 of these registers that are used to control Ports B, C, and D. Each port has a PORTx data register, a DDRx data direction register, and a PINx port input pin address register. The bits of each of these registers maps directly to the external I/O pin on the device as shown in Figure 2: ATmega328 Port mapping. The PORTx register is used primarily to write data to these pins, the PINx register to read the external state of the pin, and the DDRx to set the direction of the pin. [We discussed the electrical aspects of I/O pins in part 1 of the DIO series.] Figure 3: Port B Registers, show these registers in the datasheet, and you can see that the individual bits in the registers are logically named after the external pin they represent. And just a note of warning the PINx register is 8-bits just like the PORTx register and will confuse you thinking that it is somehow related to individual pins – this will be especially true if you are an Ardu-refugee and think in terms of individual pins. It isn’t about individual pins it is about inputting data from all the pins in a port. Hopefully this will get clear shortly.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0043.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004_thumb3.jpg" border="0" alt="clip_image004" width="226" height="248" /></a></p>
<p>Figure 2: ATmega328 Port Pin Mapping.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0063.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006_thumb3.jpg" border="0" alt="clip_image006" width="248" height="108" /></a></p>
<p>Figure 3: Port B Registers</p>
<p>Okay, now that you’ve figured out which registers and bits you need to modify and what state to set them, how do you do that in C?</p>
<h4><a name="_Toc308183148"><span style="font-weight: bold;">Using AVR Registers in C</span></a></h4>
<p>You might look at this and think something like, ‘Okay, I want to write a 1 to pin 0 of Port B so I write:</p>
<p>// WRONG!<br />
PORTB0 = 1;</p>
<p>But (you complain) the datasheet says the name of that pin is PORTB0 so how come this doesn’t work?’ and the answer is that because in the avrlibc io header the #define for PORTB0 is 0 so all you’ve written is: 0 = 1; which it isn’t. All the PORTB0 define does is provide an alias for the pin number which is 0. So how do you set PORTB0 to 1?</p>
<p>// Right<br />
PORTB |= (1&lt;&lt;PORTB0);</p>
<p>Well ‘Oh bother!’ and other exclamations. That requires those darn bitwise operators. And if you think setting the bit to 1 looks weird, how about clearing it to 0:</p>
<p>// Clear bit to 0<br />
PORTB &amp;= ~(1&lt;&lt;PORTB0);</p>
<p>Yeah, looks sort of like what we learned last month with the bit_set(p,m) and bit_clear(p,m) functions – only now we’ve taken the armor off. This real C folks, tighten your seat belts.</p>
<h4><a name="_Toc302311139"></a><a name="_Toc302659875"></a><a name="_Toc308183149"><span style="font-weight: bold;">Setting the pins for input or output</span></a></h4>
<p>Since we want to set the pins to output to control our LCD display we read in the datasheet:</p>
<p><em>The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin.</em></p>
<p>Set the DDRx bit for the pin of interest to 0 and it is an input. Set it to 1 and it is an output. Let’s replace the x with B and see how it is done in our very own port_pin_mode function [int8_t port_pin_mode(uint8_t portx, uint8_t pin, uint8_t mode)] from the elementary digitalio library we discussed in the November and December Workshops:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">if ( mode == INPUT ) // set DDRB bit to 0
{
    DDRB &amp;= ~(1&lt;&lt;pin);
}
else // ( mode == OUTPUT ) // set DDRB bit to 1
{
    DDRB |= (1&lt;&lt;pin);
}</span></code></pre>
<p>This would be a good time for you to open up port_pin_mode.c [it is in the avrtoolbox repository] in Programmers Notepad to see the actual implementation. So memorize this: <strong>In 0 out 1</strong>. Or <strong>I0O1</strong>.<strong> </strong>Or<strong> IzeroOone</strong>. Or <strong>Izzy struck out once</strong>. Or just keep the datasheet handy, which is what I do because I can never remember which does what.</p>
<p>Well, despite the data sheet we see that it really is simple to set up and use digital input and output, so why even bother with the elementary digitalio library functions? Yeah, my point exactly, but since the Arduino has it and one of my goals with the elementary library, as I say elsewhere, is to provide a C transition for Ardu-refugees I’ve included it in the avrtoolbox. Use it. Look at the source. Then move on.</p>
<h4><a name="_Toc308183150"><span style="font-weight: bold;">Moving On</span></a></h4>
<p>For those who want to use C as is was intended (okay, that’s an opinion), we initialize the LCD control pins by providing aliases for the relevant port, pin, and data direction registers, then we use bitwise operators to set them as shown below. To use the LCD we must set up four data pins and two control pins which we alias to the definitions in the avrlibc input output header file for the ATmega328 (iom328p.h located in your WinAVR directory ..\avr\include\avr\).</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// Define the specific ports and pins used for the LCD
#define LCD_D4_PORT PORTD
#define LCD_D4_DDR DDRD
#define LCD_D4_PIN PD5
#define LCD_D5_PORT PORTD
#define LCD_D5_DDR DDRD
#define LCD_D5_PIN PD4
#define LCD_D6_PORT PORTD
#define LCD_D6_DDR DDRD
#define LCD_D6_PIN PD3
#define LCD_D7_PORT PORTD
#define LCD_D7_DDR DDRD
#define LCD_D7_PIN PD2
#define LCD_E_PORT PORTB
#define LCD_E_DDR DDRB
#define LCD_E_PIN PB3
#define LCD_RS_PORT PORTB
#define LCD_RS_DDR DDRB
#define LCD_RS_PIN PB4</span></code></pre>
<p>To initialize these pins to outputs we use:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// set LCD DDR pins to 1 for output
LCD_D4_DDR |= (1&lt;&lt;LCD_D4_PIN);
LCD_D5_DDR |= (1&lt;&lt;LCD_D5_PIN);
LCD_D6_DDR |= (1&lt;&lt;LCD_D6_PIN);
LCD_D7_DDR |= LCD_D7_PIN);
LCD_E_DDR |= (1&lt;&lt;LCD_E_PIN);
LCD_RS_DDR |= (1&lt;&lt;LCD_RS_PIN);</span></code></pre>
<p>And now the registers are set up so that we can control the LCD. Of course controlling an LCD of the HD44780 variety is moderately complex, but will get to that later.</p>
<h3><a name="_Toc308183151"><span style="font-weight: bold;">Lab Section: The LCD Navigator</span></a></h3>
<h4><a name="_Toc308183152"><span style="font-weight: bold;">Assemble the LCD Navigator Projects Kit</span></a></h4>
<p>The LCD Navigator Projects Kit, shown if Figure 4, is available from the Nuts&amp;Volts magazine and webstore.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0083.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008_thumb3.jpg" border="0" alt="clip_image008" width="242" height="248" /></a></p>
<p>Figure 4: LCD Navigator Parts Kit</p>
<p>Instructions on assembling the board are available on www.smileymicros.com under the LCDNAV menu. The schematics for this board are shown in Figure 5: LCDNAV Schematics</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0103.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010_thumb3.jpg" border="0" alt="clip_image010" width="248" height="185" /></a></p>
<p>Figure 5: LCDNAV Schematics</p>
<h4><a name="_Toc308183153"><span style="font-weight: bold;">LCD Hardware: The HD44780 LCD</span></a></h4>
<p>I read a book (I think it was David Brin’s ‘Practice Effect’) where some primitive people found a digital watch with an LCD display. They were amazed that whoever made the thing was able to train all the little black bugs to run around and align themselves in such peculiar patterns. And that’s the extent of the detail I’ll give on the underlying technology of LCDs. We’ll concentrate instead on using C to train the little black bugs to do our tricks.</p>
<p>We are lucky since Hitachi developed a simple way to control the LCD that has now become an industry standard for low-cost character LCDs: the HD44780 driver/controller chip that you’ll find built into our display. They provide a parallel control interface that can send data in either 8-bit or 4-bit chunks and control the communication with enable and read strobe lines. Since we like to save pins in our AVR designs, we will use the 4-bit mode. And of course all that brain fatiguing stuff we learned about bitwise operators is going to come in handy</p>
<h5><a name="_Toc308183154"><span style="font-weight: bold;">Wiring LCDNAV to the Arduino</span></a></h5>
<p>Well, after all that preaching to get folks to drill down through the simpler library functions and use the underlying C, we are going to do our first demonstration of the LCD Navigator with the Arduino! But not really: we will only be using the board and do the code in C using AVRStudio, WinAVR, and avrdude. The Arduino is an easy to use development platform and you don’t have to use the Arduino IDE or libraries – you can use it with plain old C. You can see how to wire this up in Figure 6: LCDNAV wired to Arduino and Figure7: LCDNAV with Arduino.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0122.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image012_thumb2.jpg" border="0" alt="clip_image012" width="248" height="167" /></a></p>
<p>Figure 6: LCDNAV with Arduino</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0142.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image014_thumb2.jpg" border="0" alt="clip_image014" width="248" height="141" /></a></p>
<p>Figure 7: LCDNAV wired to Arduino</p>
<p><strong>LCDNAV wiring to the Arduino:</strong></p>
<ul>· DB7 Pin 2<br />
· DB6 Pin 3<br />
· DB5 Pin 4<br />
· DB4 Pin 5<br />
· E Pin 11<br />
· RW GND<br />
· RS Pin 12<br />
· LFT Pin 6<br />
· UP Pin 7<br />
· CTR Pin 8<br />
· DWN Pin 10<br />
· RGT Pin 9</ul>
<h4><a name="_Toc302659879"></a><a name="_Toc308183155"><span style="font-weight: bold;">LCD Software</span></a></h4>
<h5><a name="_Toc308183156"><span style="font-weight: bold;">Using the LCD</span></a></h5>
<p>We will use our avrtoolbox lcd elementary library which somewhat duplicates the function in the Arduino LiquidCrystal library, but in a more generalized fashion to use with the regular AVR C tools: AVRStudio, WinAVR, and avrdude. The source code is located in avrtoolbox\libavr\testers\source \lcd_hd44780. I owe a debt to Peter Dannenger for his LCD tutorial on AVRFreaks. His code provided a good starting point for porting the Arduino LiquidCrystal functions. [http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=828978]</p>
<p>You can find the source code for this library at: http://code.google.com/p/avrtoolbox/libavr/source/driver/external_hardware/lcd-hd44780</p>
<p><strong>The library has the following functions:</strong></p>
<ul>lcd_init()<br />
lcd_clear()<br />
lcd_home()<br />
lcd_set_cursor()<br />
lcd_putc()<br />
lcd_puts()<br />
lcd_puts_p()<br />
lcd_cursor_on()<br />
lcd_­cursor_off()<br />
lcd_blink_on()<br />
lcd_­­­blink_off()<br />
lcd_display_on()<br />
lcd_display_off()</ul>
<p>As shown in Figure 8: LCD documentation in avrtoolbox. You can access the avrtoolbox documentation at www.smileymicros.com\avrtoolbox_html.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0161.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image016_thumb1.jpg" border="0" alt="clip_image016" width="248" height="220" /></a></p>
<p>Figure 8: LCD documentation in avrtoolbox</p>
<p><strong><em>Yes, but can you use it with the Arduino?</em></strong></p>
<p>I’m really not trying to make folks lives more complex than necessary, but you can use the LCD with the Arduino LiquidCrystal library. It is wired up for it anyway. The only caveat is that their code is for a 16&#215;2 (16 characters 2 lines) LCD while our LCDNAV board uses a 8&#215;2 LCD (it is a lot cheaper). You need to change one line each example from: lcd.begin(16, 2); to: lcd.begin(8, 2); . But note that this doesn’t make a difference in some of the examples since they are hardwired to 16 characters. I suggest sticking with the avrtoolbox code for now.</p>
<p>Well, as usual we stop in middle of things. For now you can wire this up as shown and use it with several applications in http://code.google.com/p/avrtoolbox/. These include tester programs for the LCD and Nav button libraries and an LCDNAV_demo program in the avr_application directory. Have fun now playing with it and we’ll get more of the details later Workshops. Next month we’ll look at the Navigator buttons and a menu application for the LCD Navigator project.</p>
<p>Questions? Nuts&amp;Volts is hosting forums for its writers and you can find mine at: http://forum.servomagazine.com/. But if you want a quick response, especially to a question not directly related to an article you can put on your biohazard suit and start a thread on www.avrfreaks.net. But first read my blog entry that will tell you why you need the biohazard suit: <a href="http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/">http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/</a>.</p>
<p>And if you just can’t wait and want to get a leg up on all this serial stuff and real C programming for the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit and the Virtual Serial Port Cookbook using the Nuts&amp;Volts magazine or their web shop.</p>
<p><strong>I&#8217;ve created a snapshot of the LCD Navigator source code that you can find at:</strong></p>
<p>http://code.google.com/p/avrtoolbox/downloads/list</p>
<p>This code is abstracted from avrtoolbox and doesn&#8217;t require that directory structure &#8211; it has all the files in a single directory and the project is set up to use those files.</p>
<p><strong>Source code is located at:</strong></p>
<p>http://code.google.com/p/avrtoolbox/libavr/source/driver/external_hardware/lcd_hd44780</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/lcd_hd44780</p>
<p>http://code.google.com/p/avrtoolbox/libavr/source/driver\external_hardware/nav_button</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/nav_buttons</p>
<p>http://code.google.com/p/avrtoolbox/libavr/testers/nav_buttons/atmega328_label.doc</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/11/08/breadboard-lcd-navigator-part-1-the-lcd/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>avrtoolbox &#8211; USART</title>
		<link>http://smileymicros.com/blog/2011/11/08/avrtoolbox-usart/</link>
		<comments>http://smileymicros.com/blog/2011/11/08/avrtoolbox-usart/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 20:21:39 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[Serial]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/11/08/avrtoolbox-usart/</guid>
		<description><![CDATA[Smiley’s Workshop 37: avrtoolbox USART Joe Pardue June 8, 2011 Recap: We continue to build tools to go into our avrtoolbox. Last month we looked at buffering data. This month we’ll use those buffers for serial communications while learning about &#8230; <a href="http://smileymicros.com/blog/2011/11/08/avrtoolbox-usart/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>Smiley’s Workshop 37: avrtoolbox USART</h3>
<p>Joe Pardue June 8, 2011</p>
<h3><span style="font-weight: bold;">Recap:</span></h3>
<p>We continue to build tools to go into our avrtoolbox. Last month we looked at buffering data. This month we’ll use those buffers for serial communications while learning about the AVR USART. We will use the software engineering tools we’ve been discussing throughout the avrtoolbox series to design and build a USART library. If you ran the Serial Tester in Workshop 35 and the Ring Buffer Tester in Workshop 36, you’ve already used earlier versions of the USART library and didn’t even know it. AND folks, that is the main reason why libraries are such a powerful software engineering tools – you can use them and not even know it!</p>
<h3></a></a><span style="font-weight: bold;">Introduction</span></a></h3>
<p>Much of what we’ve done in these Workshops takes for granted that we have functioning serial communications as a tool for doing our development work. Whether we are blinking LEDs or developing a robotric coyote that will leap over our back fence and eat our neighbors yappy little poofy dogettes (okay that was unkind dream fulfillment on my part). Anyway, somewhere in the background we’ve got a serial link between our AVR embedded system and a Windows PC easing both development and use of our systems. Ultimately, for an embedded system to be ‘embedded’ we will cut that link, but for learning purposes, the serial port is our greatest friend. I personally consider the serial port to be the most powerful embedded systems development tool you can use. The communication channel between a PC and an embedded system can allow you to rapidly upload test programs via an AVR bootloader and you can sprinkle serial statements throughout your code with little messages like “Got to button_reader()” and “Leaving button_reader()” so if you are running your code with a terminal program you might see “Got to button_reader()” but not “Leaving button_reader()”, you‘ll know that your program crapped out in the button_reader() function between the first and second statements. I now do virtually all my debugging this way – bracketing suspicious blocks of code with messages until I’ve rooted out the guilty party. Debugging without the serial port working properly is a bit like doing surgery in the dark. Oh sure, you can spend money and use simulators or emulators or go really cheap and have the code blink LEDs, but if the design is going to have a serial port built into it anyway why not use it for development? The only real drawback is that the code to use the serial port has to work properly – so how do you debug serial code? Well, I used the serial port to debug itself giving me the classic chicken or egg problem. I can’t tell you the times I’ve sat cussing and looking at a blank terminal trying to get my serial code working properly. And I must admit that I had to occasionally resort to blinking an LED to get things going. But the advantage you have is that I’ve got things going for you so you don’t have to re-plow that field. So let’s learn some more about the USART that makes these serial tools available.</p>
<p>We looked at the PC side of the two-sided serial link way back in Workshops 18, 19, and 20 (you can see these at my blog at www.smileymicros.com\blog). In those articles/blog-entries, we learned how to write PC serial code in C# and Visual Basic .NET. And created the Simple Terminal shown in Figure 1 and we even learned how to write a GUI for an Arduino based Voltmeter with a read out on the PC, shown in Figure 2.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0022.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb2.jpg" border="0" alt="clip_image002" width="248" height="160" /></a></p>
<p>Figure 1: A Simple Terminal</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0042.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004_thumb2.jpg" border="0" alt="clip_image004" width="248" height="225" /></a></p>
<p>Figure 2: An Arduino Voltmeter</p>
<p>The PC at one time had a UART to do serial communications, but that is long gone in favor of USB so now we have to use a Virtual Serial Port on the PC side of things. In fact, those three articles were excerpts from my book <em>Virtual Serial Port Cookbook</em> where you can learn how to use the FTDI FT232R to ease your communications between a PC and a microcontroller. If you find this intriguing and want to help support your favorite technical magazine and writer, you can get the book and an educational parts kit from the Nuts&amp;Volts website.</p>
<h3><span style="font-weight: bold;">A VERY Brief History of Serial Communications</span></a></h3>
<p>There are some seriously oddball things about USARTS and serial ports, mostly due to accidents of the history and the evolution of serial communications, so lets first take a look at that history and get a feel for the origins of some of the weirdness.</p>
<p>Why do we call the communication speed ‘Baud rate’? Why does a serial connector have ring indicator pin? Why does a PC keyboard have a ‘Ctrl’ (control) key? Frankly a lot of the hardware and software terminology for serial communications seems weird when seen out of the context of how we arrived at today’s serial communication techniques. This section skims the surface of a large topic primarily to show how some of the terms we will be using came to pass.</p>
<h4><span style="font-weight: bold;">Samuel F.B. Morse</span></a></h4>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0062.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006_thumb2.jpg" border="0" alt="clip_image006" width="248" height="144" /></a></p>
<p>Figure 3: Morse Self Portrait (yes he was an artist) and his Telegraph Machine</p>
<p>Morse (Figure 3) patented the Telegraph in 1840. The name comes from the Greek tele = far away and graphos = writing, and true to its name, the original telegraph machine ‘wrote’ with dots and dashes on paper.</p>
<p>Morse’s real invention was not the transmitter or receiver, which were based on devices that were being played with in electric laboratories of the time. His contribution was a binary code (Figure 4) that allowed characters to be sent as a serial stream of electric signals. He made the most commonly used characters, such as A, E, and T into the simpler codes and the less commonly used, such as Q, X, and Z into the more complex code.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0082.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008_thumb2.jpg" border="0" alt="clip_image008" width="248" height="123" /></a></p>
<p>Figure 4: Morse’s Eponymous Code</p>
<h4><span style="font-weight: bold;">Emile Baudot</span></a></h4>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0102.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010_thumb2.jpg" border="0" alt="clip_image010" width="248" height="159" /></a></p>
<p>Figure 5: Emile Baudot picture on a French phone card.</p>
<p>In 1874 Emile Baudot (Figure 5) invented a 5-bit binary code that used a 5-key transmitter. By using mechanical clockworks the 5-bits were shifted out onto a single wire and used by the receiving station to print a character on paper. 5-bits can uniquely encode 32 characters. Later modifications to Baudot’s code changed the code to 26 character codes and 6 control codes. Two of the control codes were used to select either a 26-letter code or a 26-number/punctuation-code table. The remaining 4 control codes were used for mechanical instructions to control the remote printer. With this new code an operator could cause the remote printer to print 52 characters and could also control where on the paper the character was printed.</p>
<p>If you wonder why this matters, look at your computer’s keyboard and note the Ctrl key. That is the control key and is used to alter the meaning of the rest of the keyboard in much the same way as was done by Baudot’s apparatus which is a direct ancestor of your keyboard. Also, when we transmit something we will use the ASCII code and we will see that we have lots of atavistic printer control codes such as CR (Carriage Return), LF (Line Feed), and BEL (for bell, as in dingaling) and we might wonder why we need such ‘characters’ in our attempts to send data between a PC and a microcontroller since neither has a carriage, a roller, or a dingalinger. Now you know.</p>
<p>Baud rate refers to the number of unique symbols that can be transmitted per second –the physical ability of the system to change states each second. There is often some confusion in the use of Bd (Baud) and bps (bits-per-second). The bps refers to the amount of information that can be transmitted each second. If each physical state change represents a bit of information then Bd = bps. And while this often is not the case, in our use where one state change represents one bit of data then we will use them interchangeable.</p>
<h4><span style="font-weight: bold;">Teletype Machines</span></a></h4>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0121.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image012_thumb1.jpg" border="0" alt="clip_image012" width="248" height="247" /></a></p>
<p>Figure 6: WAC Teletype operators during World War II.</p>
<p>Baudot’s invention evolved into the Teletype machine, an electro-mechanical typewriter that could act as both a transmitter and receiver of text messages over long distances.</p>
<p>In early computers a Teletype machine (Figure 6) was used to enter characters that were punched into cards or paper tape for loading programs into computers. [During WWII the Colossus computer at Bletchley Park was used to crack encrypted German Teletype messages.] Eventually, direct connections were developed to allow the Teletype to function much like a PC keyboard.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0141.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image014_thumb1.jpg" border="0" alt="clip_image014" width="248" height="142" /></a></p>
<p>Figure 7: C being invented on a more recent Teletype machine.</p>
<p>Figure 7 shows Dennis Ritchie, inventor of the C programming language standing next to Ken Thompson, inventor of Unix, designing the original Unix operating system at Bell Labs on a PDP-11 using a Teletype machine to ‘talk’ to the computer.</p>
<h4><span style="font-weight: bold;">RS232 and Modems</span></a></h4>
<p>The Telegraph and Teletype machines used a binary (on or off) signal to transmit and receive data. However, the world was wired not for binary signals, but for telephones that send analog signal (voice &#8211; 300 to 3400 Hz). During the 1950’s folks figured out how to allow binary signals to be sent over these plain old telephone lines by acoustic frequency MOdulating and DEModulating the signal, thus the name modem.</p>
<p>The RS232 standard was written to allow Teletype machines, which were referred to as DTE (Data Terminal Equipment) to link to a modem, referred to as DCE (Data Communication Equipment) that could then transmit the binary data from a Teletype machine over a phone line to a distant computer. There were several iterations of this standard but by 1969 RS232C became ‘the’ standard that would eventually be adopted (sort of) by Microsoft for the PC serial port. The ‘sort of’ is necessary since the PC isn’t exactly 100% pure, but close enough that the PC serial port became often known as the RS232 port. The port has 9 pins. Data is transmitted on the TxD pin and received on the RxD pin. Six additional pins are used to control the communications between the PC and the modem. They are the DCD, DSR, DTR, RTS, CTS, and RI, which we’ll learn a lot more about later. The serial port was originally intended to be used with modems, but designers found that it could also be used to communicate with other peripheral devices such as mice, drawing pads, oscilloscopes, etc. thus leading to our more generic use for communicating with microcontrollers.</p>
<p>The section has provided a very brief introduction to some of the history that has lead to the arcane terminology we will be using later in the article.</p>
<p>Now you know that we call the communication speed ‘Baud rate’ after Emile Baudot; that a serial connector has ring indicator pin because the original connector was meant to attach to a modem and use a telephone line which ‘rings’ when a call comes in; that a PC keyboard has a ‘Ctrl’ (control) key because it evolved from Baudot’s original keyboard; and that any other weird term you come across probably has a historic reason for being used. And just as a fun-factoid of interest, the Arduino uses the DTR pin of the modem to reset the AVR so that you can use the bootloader to upload applications.</p>
<h4>So what does this have to do with USART?</a></h4>
<p>Early in the development of digital systems all the above arcania was put into a single IC peripheral that came to be known as a <strong>UART</strong> <strong><span style="text-decoration: underline;">U</span></strong>niversal <strong><span style="text-decoration: underline;">A</span></strong>synchronous <strong><span style="text-decoration: underline;">R</span></strong>eceiver <strong><span style="text-decoration: underline;">T</span></strong>ransimitter. Like many useful peripheral ICs (memory, ADC, timers, etc.) the UART was soon put on the same silicon as a microprocessor like the AVR core. The old-fashioned UART did only asynchronous (not occurring at predetermined or regular intervals – no clock) communication, but Atmel added some features that let theirs do some synchronous (does occur at predetermined regular intervals – clocked) things and added an S to the name that has confused folks mightily. We won’t be using the S other than in the name – so just get used to the fact that when we say USART we are actually dealing with the venerable UART, but since this is an Atmel peripheral, we’ll use their name for it (grudgingly). Clear? I didn’t think so.</p>
<h3><span style="font-weight: bold;">AVR USART Hardware</span></a></h3>
<p>I suggest that you get the Atmel ATmega328 datasheet and take a look at the section on the USART. Yup, this beast is like most peripherals, it can do so many different things that the real hard part is figuring out the limited subset of things that you really want it to do. We won’t be using 90% of what you see in the data sheet, but the trick, <strong><span style="text-decoration: underline;">as usual</span></strong>, is figuring out which 10% we want to use. There are things that it can do that I have never seen done in any system I’ve used. Like allowing 5,6,7,8 or 9 data bits. I’ve only ever used 8 bits and only seen 7 and 9 on other systems, never 5 or 6, but somebody somewhere in some historical context used these so they are there if you need them. To simplify things let’s keep this is as simple as possible by using only the most common modem parameters: 8 data bits, no parity, one stop bit, and no handshaking. Okay, so the datasheet is hard – let’s try to simplify it a bit.</p>
<h3><span style="font-weight: bold;">Set Up the USART</span></a></h3>
<h4><span style="font-weight: bold;">Using Aliases for Comprehension and Portability.</span></a></h4>
<p>We have already discussed a bit about using aliases for register and bit acronyms in earlier workshops, but let’s risk some repetition and revisit the concepts (anyway, repetition is supposed to help learning). We have two main problems with registers and the bits in them. First there are hundreds of them and second they are named using acronyms making for a double whammy of “wazzat!?” when you look at their names. Quick, what is UCSR0C or UPM01? You are likely to see both of these in some AVR source code so you might expect that you are supposed to know what they mean. The UCSR0C is the USART Control and Status Register C for USART0 and the UPM01 is USART Parity Mode bit 1 for USART0. Now don’t you feel like a real dummy for not knowing that? Well, I don’t and I personally think folks who use the raw acronyms in their code are foolish because they may remember what these things mean the day after they write the code, but they almost certainly won’t six-months later when they are trying to find a bug and the boss is standing over them with a gun to their sorry head. Sure, they can keep looking them up in the data sheet (some folks call this ‘job security’), but wouldn’t it be better if they had used an alias in the first place that spelled it out? If they used:</p>
<p>#define USART_CONTROL_STATUS_REG_C UCSR0C</p>
<p>#define USART_PARITY_MODE_BIT_1 UPM01</p>
<p>Then when they look at their code and see: USART_CONTROL_STATUS_REG_C or USART_PARITY_MODE_BIT_1 they will have a much better chance of knowing what is going on without having to dig out the datasheet and find the acronyms. The compiler doesn’t care because it doesn’t see the long name anyway since the preprocessor substitutes the acronym. Of course you do have the bother of all the extra typing and I do hate typing the ‘_’ character, but I’ve found in the long run doing things this way is just adding more documentation for your code and that is generally a good thing, especially for educational code, so that’s what we will do.</p>
<p>Another example of why this is useful is that not all the AVRs use the same acronyms for the same register and some have more than one USART. Using defines helps ease reusing code for multiple devices as shown here:</p>
<p>// Remove comment from only one device<br />
//#define USART_ATMEGA169<br />
#define USART0_ATMEGA328<br />
//#define USART1_ATMEGA328</p>
<p>…more devices…</p>
<p>#if defined(USART_ATMEGA169)<br />
#define USART_CONTROL_STATUS_REG_C UCSRC<br />
#define USART_PARITY_MODE_BIT_1 UPM1</p>
<p>…more aliases…</p>
<p>#elif defined(USART0_ATMEGA328)<br />
#define USART_CONTROL_STATUS_REG_C UCSR0C<br />
#define USART_PARITY_MODE_BIT_1 UPM01</p>
<p>…more aliases…</p>
<p>#elif defined(USART1_ATMEGA328)<br />
#define USART_CONTROL_STATUS_REG_C UCSR1C<br />
#define USART_PARITY_MODE_BIT_1 UPM11</p>
<p>…more aliases…</p>
<p>This allows you to use the same source code for each device only changing one line to select the device. So the code can have USART_CONTROL_STATUS_REG_C and the preprocessor gets to decide if that is UCSR0C or UCSR1C depending on the #define you selected. Do this and give your library an indicative name like: libavr_USART0_atmega328.a and away you go.</p>
<p>You’ll find something like this in the avrtoolbox USART directory where we have libraries for the AVR Butterfly (ATmega169), the Arduino board (ATmega328), and the BeAVR (ATmega644).</p>
<h4><span style="font-weight: bold;">Which Registers and Bits?</span></a></h4>
<p>While I promised that we would only use a small subset of what the USART can do, we still have to set a bunch of registers and bits. To further simplify our life, let’s just look at what we have aliased for the ATmega169 (AVR Butterfly) in USART.h:</p>
<p>// Registers<br />
#define UART_BAUD_RATE_HIGH UBRRH<br />
#define UART_BAUD_RATE_LOW UBRRL<br />
#define UART_CONTROL_STATUS_REG_A UCSRA<br />
#define UART_CONTROL_STATUS_REG_B UCSRB<br />
#define UART_CONTROL_STATUS_REG_C UCSRC</p>
<p>// Bits<br />
#define UART_ENABLE_TRANSMITTER TXEN<br />
#define UART_ENABLE_RECEIVER RXEN<br />
#define UART_READY_TO_TRANSMIT UDRE<br />
#define UART_TRANSMIT_COMPLETE TXC<br />
#define UART_RECEIVE_COMPLETE RXC<br />
#define UART_DATA_REG UDR<br />
#define UART_STOP_BIT_SELECT USBS<br />
#define UART_CHARACTER_SIZE_0 UCSZ0<br />
#define UART_CHARACTER_SIZE_1 UCSZ1<br />
#define UART_CHARACTER_SIZE_2 UCSZ2<br />
#define UART_MODE_SELECT UMSEL<br />
#define UART_DOUBLE_SPEED U2X<br />
#define UART_FRAME_ERROR FE<br />
#define UART_DATA_OVER_RUN DOR<br />
#define UART_PARITY_ERROR UPE<br />
#define UART_PARITY_MODE_0 UPM0<br />
#define UART_PARITY_MODE_1 UPM1<br />
#define UART_MULTI_PROCESSOR_COMMUNICATION_MODE MPCM<br />
#define UART_TX_COMPLETE_INTERRUPT_ENABLE TXCIE<br />
#define UART_RX_COMPLETE_INTERRUPT_ENABLE RXCIE<br />
#define UART_DATA_REGISTER_EMPTY_INTERRUPT_ENABLE UDRIE<br />
#define UART_RX_DATA_BIT_8 RXB8<br />
#define UART_TX_DATA_BIT_8 TXB8</p>
<p>That is five registers and 23 bits! The long form of the names are somewhat explanatory, but you may want to look at the data sheet to get the details if you are excessively curious or masochistic. You can see why we want to set this up one time, get it working, put it in a black-box with lots of duct-tape and never look at it again.</p>
<h4><span style="font-weight: bold;">And How Do We Set These Registers and Bits?</span></a></h4>
<p>We have two USART initialization functions, one initializes everything and the other relies on defaults for all but the baudrate. The comprehensive function has a list of parameters that it sets:
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void USART0_init(uint32_t baud,\
uint32_t freq_cpu,\
USART_mode_t mode,\
USART_databits_t databits,\
USART_stopbits_t stopbits,\
USART_parity_t parity)</span></code></pre>
<p>In the function we call various other functions or macros to set the parameters, such as:</p>
<p>USART0_mode(mode);</p>
<p>Which is a macro:</p>
<p>#define USART0_mode(x) bit_write(x, UART_CONTROL_STATUS_REG_C, BIT(UART_MODE_SELECT))</p>
<p>If you are interested in the details you can view the rest in the source code in the avrtoolbox project by clicking Source – Browse – Trunk – libavr – source – usart – usart0_init.c. This is complex and you can easily see why we want to set this up one time, get it working, put it in a black-box with lots of duct-tape and never look at it again.</p>
<h3><span style="font-weight: bold;">The rest is in avrtoolbox</span></a></h3>
<p>To conform to our avrtoolbox process we need a Functional Requirements Specification, an Application Programmer Interface, a tester program, the source code, libraries for the AVR Butterfly (ATmega169), Arduino board (ATmega328) and the BeAVR (ATmega328 on a breadboard). And you will find all that in various states of completion in the avrtoolbox open source project <a href="http://code.google.com/p/avrtoolbox/">http://code.google.com/p/avrtoolbox/</a>. Just click on Source then Browse | trunk | libavr. You will see four subdirectories: doc, librarian, source, testers and I’ll leave it up to you to figure out what is in each. And please be aware that this is a work in progress. Not everything is finished and none of it is perfect, in fact there are typos and bugs everywhere. If you expect perfection &#8211; stay away &#8211; if however you want to be helpful when you find a problem or have a question you’ll put on your biohazard suit and start a thread on www.avrfreaks.net with the word ‘avrtoolbox’ in the title and I probably will see it. But first read my blog entry that will tell you why you need the biohazard suit: <a href="http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/">http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/</a>. Next month we are going to take a look at the C Standard Library and apply what we’ve learned about ring buffers and USART libraries to getting the venerable C printf() function working along with some string manipulation functions and a command-line interpreter that we will soon become one of your favorite development tools.</p>
<p>And if you just can’t wait and want to get a leg up on all this serial stuff and real C programming for the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit and the Virtual Serial Port Cookbook using the Nuts&amp;Volts magazine or website.</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/11/08/avrtoolbox-usart/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>avrtoolbox &#8211; ring buffer.</title>
		<link>http://smileymicros.com/blog/2011/11/08/avrtoolbox-ring-buffer/</link>
		<comments>http://smileymicros.com/blog/2011/11/08/avrtoolbox-ring-buffer/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 19:28:34 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[C Programming]]></category>
		<category><![CDATA[Serial]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/11/08/avrtoolbox-ring-buffer/</guid>
		<description><![CDATA[Smiley’s Workshop 36: avrtoolbox ring buffer. Joe Pardue May 11, 2011 Recap: So far in our briefly interrupted series on avrtoolbox, we’ve looked at some software engineering principles and applied them to creating the avrtoolbox project on Google Code [http://code.google.com/p/avrtoolbox/]. &#8230; <a href="http://smileymicros.com/blog/2011/11/08/avrtoolbox-ring-buffer/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>Smiley’s Workshop 36: avrtoolbox ring buffer.</h3>
<p>Joe Pardue May 11, 2011</p>
<h3><strong>Recap:</strong></h3>
<p>So far in our briefly interrupted series on avrtoolbox, we’ve looked at some software engineering principles and applied them to creating the avrtoolbox project on Google Code [http://code.google.com/p/avrtoolbox/]. We’ve learned about creating an open source project using a consistent C programming style, documenting it with doxygen, putting our functions in libraries, and keeping track of the whole thing with a software versioning system. Last month we learned a bit about two more software engineering tools: the FRS (Functional Requirements Specification) and the API (Applications Programmer Interface) and applied all that to an elementary serial communications library meant to mimic the kinds of novice friendly functions we’d find in the Arduino or PBASIC.</p>
<p>The novice friendly serial library was built on top of two other libraries, one for storing the data (ring buffer) and another for sending and receiving the data (usart). These libraries are not particularly novice friendly and more like what you’d see in a professional software production environment. This month we are going to look at ring buffers and next month we will look at the AVR usart. Also this month we will look at another software engineering tool, the AVRStudio Simulator that we will use to test the ring buffer functions.</p>
<h3><strong>What is a ring buffer?</strong></h3>
<p>A ring buffer algorithm turns a linear array into a circular array, which as you will see in a moment, can be very useful for rapidly storing and retrieving data. A linear array is just a sequence of contiguous memory locations set aside to store data in such a way that you can access the data by using a number indicating its position in the array. For instance if you had a 64 byte linear array named linArray and wanted to get the 32<sup>nd</sup> byte you would use: myByte = linArray[31]. You use 31 instead of 32 because in arrays we start numbering a 0 rather than 1 meaning we have bytes number 0 to 63 stored for a total of 64 bytes. A ring buffer is a linear array, but we use a special algorithm to make it behave as if it was a ring having neither a beginning nor end.</p>
<p>Ring buffers are very useful in C programming where we often have a situation where we have two ‘things’ that are trying to deal with the same variable set of data, but doing so at different rates. For instance, we may want to evaluate a stream of bytes that are coming in over a UART to see if we are receiving a command. But we may be getting the bytes faster than it can analyze them; so incoming bytes begin to pile up. Another situation could be that we have some code generating data to be transmitted out over a UART but the data is being generated in short spurts faster than the UART can transmit them; so outgoing bytes begin to pile up.</p>
<p>In both cases we need something analogous to a kind of pipe with a balloon in the middle that expands or contracts as the pressure differs on either end of the pipe. This is actually not such a bad analogy since we immediately see that the balloon must have properties of size and stretchiness that accommodates what comes in and goes out the pipes without overstretching and bursting. Obviously if we connect a fire hose to one end and a soda straw to the other, that balloon better be large and the fire hose better not be left on too long.</p>
<p>Memory is linear, meaning it is addressed with an integer sequence beginning at 0 and ending at the largest address. We can create a subset of memory as an array that may be allocated anywhere in memory, but the array will keep track of the memory locations as if the first location is address 0. For example, we could allocate a 16-byte array that the compiler/linker would locate beginning at memory location 1000 and ending at memory location 1015. When we address the first element of the array, we use 0, but the underlying code substitutes the address of the first memory element: 1000. This abstraction from the real address means that we can reuse an array in other code on other processors and let the compiler/linker figure out where to put it, a detail that is of no interest to our application. Using our linArray[] example, the first byte at linArray[0] could be at 1000 or 2345 or 54321 but we never see that address since we are using the linArray[0] as an alias for that first address.</p>
<p>We can use this 16-byte array to act as our balloon and handle the overflow. Lets say the input function is based on an Interrupt Service Routine (ISR) and our function that processes the input data can be interrupted at anytime for more data to be added to the array. Suppose that we have added 10 bytes to our 16-byte array and we start processing them and are about to process the 6th of the 10 bytes when the ISR receives another 10 bytes to put in the array. Now we have a problem because we have received 20 bytes total and the array is only 16 bytes long. But notice that we have already processed 5 of the first 10 bytes so the first 5 spaces are now of no interest to us and can be considered ‘empty’. We thus have 5 empty spaces at the start of the array and 8 empty spaces at the end of the array, for a total of 13 available spaces, but they are not contiguous. We could go ahead and do this the hard way and use our array as a linear array where the ISR copies the five oldest unprocessed bytes from their locations to the beginning of the array, then follows them with the newly received 10 bytes, leaving the total of 15 unprocessed bytes in the array in the proper order beginning at the start of the array. Using this ‘hard way’ technique we will have to set some kind of message to inform any function using the array that the first unprocessed byte has been moved to 0. The user will have to read the message and, in the case above know that the next byte to examine is not the 6<sup>th</sup>, which it was about to work on, but the first. This shifting of byte and processing of flags is complex and time consuming, but thankfully the ring buffer concept provides a much easier way to accomplish the task without having to move the data. Instead of moving the data, we keep two indexes, one pointing to the next location to store data from (head index) and the other pointing to the next location to read data from (tail index). The ring algorithm is more difficult to understand, but it is much more efficient for the machine.</p>
<p>Let’s visualize a circular array like a necklace with pearls where each pearl representing a location to store a byte of data. Lets say we have 16 pearls and we want one process to be storing data for another process to remove, each at its own rate. The process that does the storing will have the address of the ‘first’ input pearl and store data sequentially around the necklace. The storing process needs to remember the location of the first pearl and the number of pearls used to store data. Then when we want to store a new byte, we can calculate the total number of already stored bytes (length) and get the next storage pearl by adding this length to the first location to get the location for the next empty pearl. To extend the analogy, lets say that the pearls are chosen in a clockwise direction, and that storing data turns a pearl black. We can see in Figures 0 through 6 that adding data causes pearls to turn black sequentially in the clockwise direction. For this analogy we name the location of the next byte memory location to be written (stored) as the Head and the location of the next byte to be read (removed) as the Tail. We add data to the Head and remove data from the Tail.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0021.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb1.jpg" border="0" alt="clip_image002" width="248" height="205" /></a> <a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0041.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004_thumb1.jpg" border="0" alt="clip_image004" width="248" height="199" /></a></p>
<p>Figure 0: Empty Figure 1: First byte stored</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0061.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006_thumb1.jpg" border="0" alt="clip_image006" width="248" height="197" /></a> <a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0081.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008_thumb1.jpg" border="0" alt="clip_image008" width="248" height="230" /></a></p>
<p>Figure 2: Second byte stored Figure 3: Six bytes stored</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image0101.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010_thumb1.jpg" border="0" alt="clip_image010" width="248" height="221" /></a> <a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image012.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image012_thumb.jpg" border="0" alt="clip_image012" width="248" height="191" /></a></p>
<p>Figure 4: Three bytes removed Figure 5: Eleven bytes added, three bytes removed</p>
<p>If the access process is slower than the storing process then the Head location will grow more distant from the Tail around the circle with the Head and Tail changing as the data is added or withdrawn. However the Head is equal the Tail both when the buffer is empty or full, so we have to look at the count to see which is the case. If the buffer is empty, no problem since all that means is that you’ve caught up. But is the buffer is full as shown in Figure 6 you may have a problem and you may start overwriting data that you haven’t read yet. This is not something what you want to happen. Such a condition won’t hurt so much if the streaming data is audio output and only happens occasionally, in which case the listener may hear a glitch, but if the data is for monitoring the core temperature of a nuclear reactor, well&#8230;</p>
<p>To solve this problem, the storing function must monitor the indexes and the count and be able to respond intelligently if things are getting out of hand. For instance, if you are receiving bytes from a PC via the UART and the buffer fills up, then you’ll want to use a communication protocol allowing it to tell the PC to hold off for a while.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image014.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image014_thumb.jpg" border="0" alt="clip_image014" width="248" height="209" /></a></p>
<p>Figure 6: Uh oh, sixteen added, none removed</p>
<p>You can lessen the likelihood of this error occurring by increasing the amount of RAM available for the buffer. However, since RAM is precious on microcontrollers, we have to make a tradeoff of costs and make a judgment call on how large to make a ring buffer.</p>
<p>Also note that while it is technically feasible to dynamically allocate buffers at run time using the C malloc() function, 8-bit microcontroller developers aware of RAM limitations rarely do this &#8211; so we will not. We will allocate the buffers when we design the code and make our size decision then.</p>
<h2><strong>Ring Buffer Functional Requirements Specification</strong></h2>
<p><strong>Ring buffer data type:</strong> ring_t be a data type that will hold a pointer to the buffer, the size of the buffer, the head index, the tail index, and the data count.<strong> </strong></p>
<p><strong>Ring buffer initialization function: </strong>ring_init() will initialize a ring buffer based on receiving a pointer to a ring_t structure, a pointer to a buffer created by the calling function that is of the size provided.</p>
<p><strong>Ring add to buffer function: </strong>ring_add() will add a byte at the next available space in the buffer.</p>
<p><strong>Ring remove from buffer function: </strong>ring_remove() will remove a byte from the oldest valid location in the buffer.</p>
<p><strong>Ring peek at buffer function: </strong>ring_peek() will read an uint8_t ‘count’ number of bytes from the ring buffer into a new buffer provided as a parameter without removing any of the values read from the ring buffer. It will return the number of bytes actually read.</p>
<p><strong>Ring clear function: </strong>ring_clear() will set the tail equal to the head and load 0 into all buffer positions.</p>
<h3>Ring Buffer Applications Programming Interface</h3>
<h4><strong>ring_t</strong></h4>
<p>Description: ring_t is a structure that holds data required to create and manage the ring buffer.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">typedef uint16_t ring_index_t;
typedef uint8_t *ring_buffer_t;
typedef uint8_t ring_count_t;
typedef uint8_t ring_size_t;

typedef struct
{
    ring_buffer_t buffer;
    ring_size_t size;
    ring_index_t head_index;
    ring_index_t tail_index;
    ring_count_t count;
} ring_t;</span></code></pre>
<h4><strong>ring_init()</strong></h4>
<p><strong>Description:</strong> Sets up the ring buffer with ring_t parameters. The clear command is also called to set 0 values within the ring buffer functions.</p>
<p><strong>Syntax:</strong> bool ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size)<br />
<strong>Parameters:</strong></p>
<ul> ring_t *r : a pointer to a ring_t structure.<br />
ring_buffer_t buffer: a pointer to buffer you want to use for the ring buffer.<br />
ring_size_t size: size in bytes of the buffer and must be equal to or greater than 2. The actual amount of storage available in the ring buffer is size &#8211; 1.</ul>
<p><strong>Returns:</strong> boolean true if the buffer was created, false otherwise<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void setup()
{
    // Initialize the ring buffer
    if(!ring_init(ring_t *r, ring_buffer_t buffer, ring_size_t size))
    {
        // Buffer not intitialized so handle the error

   // Okay to use the buffer
}</span></code></pre>
<h4><strong>ring_add()</strong></h4>
<p><strong>Description:</strong> adds a byte of data to the ring buffer.<br />
<strong>Syntax:</strong> bool ring_add(ring_t *r, uint8_t data)<br />
<strong>Parameters:</strong> ring_t *r : a pointer to a ring_t structure.<br />
Data: an 8-bit byte of data to add to the buffer.</p>
<p><strong>Returns:</strong> boolean true if the byte was added, false otherwise.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// receive_ring structure defined elsewhere
bool put_byte(uint8_t b)
{
    return(ring_add(&amp;receive_ring, b));
    <strong>Example:</strong>
}</span></code></pre>
<h4><strong>ring_remove()</strong></h4>
<p><strong>Description:</strong> Removes a byte of data from the ring buffer.<br />
<strong>Syntax:</strong> uint8_t ring_remove(ring_t *r))<br />
<strong>Parameters:</strong><br />
ring_t *r : a pointer to a ring_t structure.<br />
<strong>Returns:</strong> the byte of data removed.<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// receive_ring structure defined elsewhere
uint8_t get_byte()
{
    return(ring_remove(&amp;receive_ring));
}</span></code></pre>
<h4><strong>ring_peek()</strong></h4>
<p><strong>Description:</strong> Reads uint8_t count bytes from the ring buffer into a new buffer provided as a parameter without removing any of the values read from the ring buffer. It returns the number of bytes read.<br />
<strong>Syntax:</strong> uint8_t ring_peek(ring_t *r, uint8_t *buf, uint8_t count)<br />
<strong>Parameters:</strong>ring_t *r : a pointer to a ring_t structure.<br />
uint8_t *buff: a pointer to a buffer to hold the data.<br />
uint8_t count: the number of bytes to load from the ring buffer to buf.</p>
<p><strong>Returns:</strong> the actual number of bytes read.<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// receive_ring structure defined elsewhere
uint8_t get_bytes(uint8_t *buf, uint8_t count)
{
    return(ring_peek(&amp;receive_ring, buf, count));
}</span></code></pre>
<h4><strong>ring_clear()</strong></h4>
<p><strong>Description:</strong> Sets all data in the buffer to 0 and sets the head and tail indexes to 0.<br />
<strong>Syntax:</strong> bool ring_clear(ring_t *r)<br />
<strong>Parameters:</strong> ring_t *r : a pointer to a ring_t structure.<br />
<strong>Returns:</strong> true if successful, false otherwise.<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void end_this()
{
    ring_clear(&amp;receive_ring);
}</span></code></pre>
<h3><strong>Using AVR Studio Simulator</strong></h3>
<p>The AVR Studio Simulator is really great for testing how programs use the AVR memory, but it can be a bit of a pain to use at times. So if you aren’t already familiar with it, open the AVR Studio Help as shown in Figure 7 and then in the HTML Help file open the Debug section and play around in it as shown in Figure 8.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image016.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image016_thumb.jpg" border="0" alt="clip_image016" width="248" height="203" /></a></p>
<p>Figure 7: AVR Studio Help</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image018.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image018" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image018_thumb.jpg" border="0" alt="clip_image018" width="248" height="188" /></a></p>
<p>Figure 8: Debug Help</p>
<p>We will mostly be using the Memory View and the Watch View, so read those sections before doing the testing. I found the Simulator to be a bit arcane and balky at times, but with persistence I was able to run all the memory tests in the Ring Buffer Tester. Note that in the following tests you must set the Project Options Optimization to –O0 meaning no optimization since the compiler will look at this code and think that some bits are stupid and remove them. They are stupid, but they are also needed for testing so kill the optimizer. AND DON’T FORGET to reset the optimization to –Os before compiling any code that you intend to use on a real AVR. Note also that the memory window may not be set to show data when you open it. If anything I do in the tests isn’t entirely clear I suggest you read the help file and if that doesn’t help then put on your waders and ask a question on www.avrfreaks.net using ‘Smiley’s Workshop’ in the title so I might see it.</p>
<h3><strong>Testing the Ring Buffer Library</strong></h3>
<h5>Test 1</h5>
<p>We will start out with a simple test just to show that we are initializing and setting the indexes and count correctly.</p>
<p>Start with the following code:</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">#include "C:\avrtoolbox\libavr\source\general\ring\ring.h"
#include "C:\avrtoolbox\libavr\source\elementary\serial\serial.h"
#define BUFFER_SIZE 16
static uint8_t array1[BUFFER_SIZE];
static uint8_t array2[BUFFER_SIZE];
static uint8_t array3[BUFFER_SIZE];
int main(void)
{
    // declare three ring buffer data structures
    ring_t ring1;
    ring_t ring2;
    ring_t ring3;

    // Create three ring buffers
    ring_init(&amp;ring1, array1, BUFFER_SIZE);
    ring_init(&amp;ring2, array2, BUFFER_SIZE);
    ring_init(&amp;ring3, array3, BUFFER_SIZE);

    // Assign temporary variables so that we can look at
    // them in the Breakpoints and Tracepoint window
    uint16_t volatile temp_head_index = 0;
    uint16_t volatile temp_tail_index = 0;
    uint8_t volatile temp_count = 0;

    // Test 1
    // Store six 0x01 bytes in ring 1
    for(uint8_t i = 0; i &lt; 6; i++)
    {
        ring_add(&amp;ring1, 0x01);
    }
    temp_head_index = ring1.head_index;
    temp_tail_index = ring1.tail_index;
    temp_count = ring1.count;
}</span></code></pre>
<p>We declare three 16 byte arrays, then in the main() functions we declare three ring_t structures, and we initialize these ring buffers with the ring_init() function. Next we create three variables that we will use in our watch window to observe the ring head_index, tail_index, and count parameters.</p>
<p>Click on the ‘Build and Run’ button as shown in Figure 9.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image020.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image020" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image020_thumb.jpg" border="0" alt="clip_image020" width="248" height="81" /></a></p>
<p>Figure 9: Build and Run</p>
<p>You will notice that the Memory window appears and has some bytes set to zero as shown in Figure 10. These are the locations we have reserved for our buffers.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image022.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image022" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image022_thumb.jpg" border="0" alt="clip_image022" width="248" height="210" /></a></p>
<p>Figure 10: Initial Memory</p>
<p>You can find the starting location of each of the three arrays by putting your cursor on the array name in the code as shown in Figure 11.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image024.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image024" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image024_thumb.jpg" border="0" alt="clip_image024" width="248" height="45" /></a></p>
<p>Figure 11: array1 size and location</p>
<p>We see that the arrays start addresses are:<br />
array1 – 0&#215;0100<br />
array2 – 0&#215;0110<br />
array3 – 0&#215;0120</p>
<p>Place your cursor on the temp_head_index variable and click the right mouse button and select ‘Add Watch: “temp_head_index” as shown in Figure 12. The add temp_tail_index and temp_count to the Watch window.</p>
<p>Figure 12: Add Watch</p>
<p>Place the cursor after the last line in the main function, then click on the ‘Run to Cursor’ button as shown in Figure 13.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image028.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image028" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image028_thumb.jpg" border="0" alt="clip_image028" width="248" height="111" /></a></p>
<p>Figure 13: Run to Cursor</p>
<p>We see in Figure 14, that the six bytes beginning at 0&#215;0100, the start of array1, are changed to 0&#215;01.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image030.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image030" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image030_thumb.jpg" border="0" alt="clip_image030" width="248" height="213" /></a></p>
<p>Figure 14: Test 1 puts 6 0&#215;01 in array1</p>
<p>And we see in Figure 15, that the watch window variables have changed. The variable temp_head_index is 6, temp_tail_index is 0, and temp_count is 6 as we would expect.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image032.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image032" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image032_thumb.jpg" border="0" alt="clip_image032" width="248" height="111" /></a></p>
<p>Figure 15: Test 1 changes watched variables</p>
<p>So we have validated that we can create and load one ring buffer.</p>
<h5>Test 2</h5>
<p>Next we run the second test by adding the following code and repeating the preceding procedure.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// Test 2

// First three bytes 'removed' to array3
// Note that the value doesn't change
// but the index does change
for(uint8_t i = 0; i &lt; 3; i++)
{
    ring_add(&amp;ring3, ring_remove(&amp;ring1));
}

temp_head_index = ring1.head_index;
temp_tail_index = ring1.tail_index;
temp_count = ring1.count;</span></code></pre>
<p>In Figure 16 we see that the three bytes have been copied from the first array to the third located at hex 120. Note also that even though those three bytes were ‘removed’ from the first array, they are still present. This is because only the indexes and counts are changed and the actual data isn’t cleared.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image034.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image034" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image034_thumb.jpg" border="0" alt="clip_image034" width="248" height="209" /></a></p>
<p>Figure 16: Test 2 Memory.</p>
<p>Figure 17 shows the Watch window that now shows that the head index is still 6, but now the tail index is 3 since three bytes have been removed and the count is three which is how many bytes remain in the buffer.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image036.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image036" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image036_thumb.jpg" border="0" alt="clip_image036" width="248" height="114" /></a></p>
<p>Figure 17: Test 2 Watch.</p>
<p>Hey, this is looking like that weird pearl lecture at the beginning of this article, cool…</p>
<h5>Test 3</h5>
<p>Let’s test the ring_peek() function by filling the ring2 buffer with a sequence of 16 bytes 0&#215;01 to 0&#215;10, then read 8<sup>th</sup> and 9<sup>th</sup> bytes to see if they really are 0&#215;08 and 0&#215;09.</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// Test 3

// Fill ring2 with sequence of 16 bytes
// 0x01 to 0x10 and then read the 8th and
// 9th bytes to see if they really are 0x08 and 0x09
for(uint8_t i = 1; i &lt;= 16; i++)

{
    ring_add(&amp;ring2, i);
}

uint8_t temp_buf[2];
uint8_t temp_count;

ring_peek(&amp;ring2, temp_buf, temp_count)</span></code></pre>
<p>Placing your cursor over temp_buf, as shown in Figure 18, reveals that it is located at 0x08F8 in the SRAM – but note that it may be located somewhere else when you do this experiment.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image038.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image038" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image038_thumb.jpg" border="0" alt="clip_image038" width="248" height="48" /></a></p>
<p>Figure 18: temp_buf location</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image040.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image040" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image040_thumb.jpg" border="0" alt="clip_image040" width="248" height="119" /></a></p>
<p>Figure 19: Test 3 part 1</p>
<p>Figure 19 shows the sequential bytes written in the second array, Figure 20 shows the results of the ring_peek() that loaded the values of the first four into our temporary buffer that begins at 8F8.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image042.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image042" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image042_thumb.jpg" border="0" alt="clip_image042" width="248" height="120" /></a></p>
<p>Figure 20: Test 3 part 2</p>
<h3>And then…</h3>
<p>We have a bunch more tests to run but no more space to show them and I think that if you got this far in the article, you won’t mind finishing the testing without any more training wheels. I’m also sure at some point during all this testing you will scream “IS THIS REALLY NECESSARY!!!” And the answer I’d screamed backatcha is “OF COURSE NOT, YOU CAN TEST THESE FUNCTIONS WHILE DEBUGING SOME CODE THAT IS ON A TIGHT DEADLINE MONTHS AFTER YOU’VE CREATED THE LIBRARY AND FORGOT HOW IT WORKED!!!” Or in lowercase, “Nobody said software engineering was easy.”</p>
<p>Since last we looked at avrtoolbox I’ve redone the directory structure as shown in Figure 21. Now the top directory is libavr followed by four sub-directories: doc, librarian, source, and testers. The libraries are kept in the librarian directory, one for each of our test platforms (Butterfly, Atmega328 {Arduino board [not IDE]}, and the Atmega644 {BeAVR}). The testers directory has sub-directories for each module, in this case ‘ring’ and the code is written so that it references the libraries and header files as they are in the libavr directory tree. Yeah, it is a little complicated at first, but it seems to me the most logical way to keep all this on one place so I’m sticking with it for a while.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image044.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image044" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image044_thumb.jpg" border="0" alt="clip_image044" width="221" height="248" /></a></p>
<p>Figure 21: avrtoolbox</p>
<p>And if after all this good stuff you just can’t wait and want to get a leg up on real C programming and the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit using the Nuts&amp;Volts magazine or website. Next month, if all goes well, we will continue with avrtoolbox using what we have learned about the ring buffer to apply to creating an AVR USART library.</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/11/08/avrtoolbox-ring-buffer/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>avrtoolbox &#8211; Designing an Elementary Library: Serial Communications.</title>
		<link>http://smileymicros.com/blog/2011/11/08/avrtoolbox-designing-an-elementary-library-serial-communications/</link>
		<comments>http://smileymicros.com/blog/2011/11/08/avrtoolbox-designing-an-elementary-library-serial-communications/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 18:19:44 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[Serial]]></category>
		<category><![CDATA[Smiley’s Workshop 35: avrtoolbox – Designing an Elementary Library: Serial Communications.]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/11/08/avrtoolbox-designing-an-elementary-library-serial-communications/</guid>
		<description><![CDATA[Smiley’s Workshop 35: avrtoolbox – Designing an Elementary Library: Serial Communications. Joe Pardue April 6, 2011 Figure 1: Serial Communication with the AVR Butterfly. Recap: Let’s get back on track with avrtoolbox [http://code.google.com/p/avrtoolbox/] after our two-month detour to learn about &#8230; <a href="http://smileymicros.com/blog/2011/11/08/avrtoolbox-designing-an-elementary-library-serial-communications/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3>Smiley’s Workshop 35: avrtoolbox – Designing an Elementary Library: Serial Communications.</h3>
<p>Joe Pardue April 6, 2011</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image002_thumb.jpg" border="0" alt="clip_image002" width="248" height="206" /></a></p>
<p>Figure 1: Serial Communication with the AVR Butterfly.</p>
<h3>Recap:</h3>
<p>Let’s get back on track with avrtoolbox [<a href="http://code.google.com/p/avrtoolbox/">http://code.google.com/p/avrtoolbox/</a>]</p>
<p>after our two-month detour to learn about the FT232R USB to Serial converter and the revision to my book: <em>Virtual Serial Port Cookbook</em>. If you want to get with the avrtoolbox flow, you can find the first three articles in the January, February, and March 2011 issues of Nuts&amp;Volts or on my blog at www.smileymicros.com\blog. In these articles we see how to create an open source project, manage software versions with SVN, document with doxygen, adopt a C coding standard, put functions in libraries, and keep things organized – all with practical hands on examples.</p>
<h3><span style="font-weight: bold;">Introduction</span></h3>
<p>This month we will learn another two principles for good software project development: the concept of the <strong>Functional Requirements Specification (FRS)</strong> and the <strong>Applications Programmer Interface (API)</strong> both of which are documents that you should create before writing the code. We will learn about these in the context of creating a serial library that will simplify our communications between our AVR and a terminal program on a PC.</p>
<p>This library will provide us with the sorts of easy to use serial functions we might expect from the Arduino or PBASIC, but with no barrier to moving to real C if we so choose. Our serial library will sort of mimic the better features of the Arduino serial library while providing much more capable serial output &#8211; all the while using regular C for use with the standard Atmel tools AVRStudio/WinAVR/avrdude (not the Arduino IDE). In case you are snorting at my claim of ‘much more capable’ let’s just say that what I’m doing is encapsulating the venerable C standard library function printf() in a package that makes it easy to use with the AVR without having to read the dozens of relevant pages in the avrlibc manual or the usart section of your AVR datasheet. So I won’t even bother with IMHO for my ‘much more capable’ assertion. Please remember, I’m not an enemy of Arduino, I think it is the best things to happen to AVRs and embedded systems since the advent of the AVR, but my goal now is not to teach the Arduino (or that get my book <em>An Arduino Workshop</em> from Nuts&amp;Volts). My goal with these Arduino-like libraries is to provide a path from the Arduino simplifications to what I consider to be real embedded systems programming. And if you want to yell at me about that assertion or this article, then after reading my blog entry: <a href="http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/">http://smileymicros.com/blog/2011/01/24/using-an-internet-forum/</a> put on your gas mask and start a thread on www.avrfreaks.net (with ‘Smiley’s Workshop’ in the title) and I might yell backatcha.</p>
<p>To help prevent confusion let me repeat: this article covers three separate topics, two are general software development principles – the <strong>FRS</strong> and the <strong>API</strong> – while the third is an application of all the avrtoolbox software engineering principles discussed so far, to creating a very useful library of serial functions.</p>
<h3><span style="font-weight: bold;">Draw the Blueprints before Sawing the Wood.</span></h3>
<p>So if you were going to build a house would the first thing you do is to go out and buy a bunch of 2x4s and start cutting them up? You’d be surprised at the number of folks who think you can approach writing a program by grabbing cases of Twinkies and Red Bull and just jumping in and starting writing code. Some people are even proud of this approach. And, well if I’m honest, I have to admit that was the way I programmed when I first started out. I knew exactly what I wanted and so I just jumped right in and did it. However, over time that strange property of the universe known as <strong><span style="text-decoration: underline;">reality</span></strong> taught me that this was not just a bad idea; it was a <strong><span style="text-decoration: underline;">very bad</span></strong> idea. I found that I’d get well into something only to discover that I’d neglected to plan for one little thing that generally exploded into one big thing. I’d beat that down and hack away until the next little thing I’d neglected to plan for started intruding. It was a vicious cycle of my arrogance getting pounded into submission by the real world. I eventually learned that I should spend time &#8211; a lot of time &#8211; thinking about a project before allowing myself to write a line of code. I discovered the hard way that the common software engineering concept of writing a ‘functional requirements specification’ before writing any code was not a dumb-bureaucratic-stick-in-the-mud-buzz-kill, but a tool that could help prevent me from committing massive stupidity on a keyboard. It helps reduce the ‘massive’ part even though the ‘stupidity’ part is inherent in programming. And as a general rule I can say that the larger the project, the greater the value of time spent planning.</p>
<p>A FRS states what the functions will do, without stating how the functions will do it. Separating the requirement from the implementation keeps the process focused on what needs to be done. Conceptually this also separates the people who want to use the code from the folks who write it. The users group may or may not know anything about creating software, but they know what they want an application they will be using to do, while the programmer may have no use whatever for the program but knows how to make it do what the user wants.</p>
<p>I’ll share a personal anecdote about a time I helped nearly bankrupt a company that refused to do a FRS up front. I was presented with a program that the client said almost worked and asked me to finish it. The underlying code was a 600 page nightmare that I used as the initial requirements specification, pulling out what the code was supposed to do and tossing the original code in favor of using a bit more modern language that let me re-write it in 60 pages. The boss said, “Great, now I want you to add this one little thing.” I choked a bit thinking that if I’d known about that extra ‘one little thing’ when I got started I would have designed the code differently, but I guessed I could shoe-horn it in without breaking anything – which I did. The boss said, “Great, now I want you to add this one little thing.” At which point I delivered him a strident lecture about software engineering principles and insisted that we get it all decided now. He just grinned and said, “Now how difficult can it be to add bla bla?” So I bent the design further out of shape and added his new requirement and got it all working. The boss said, “Great, now I want you to add this one little thing.” Okay, you are probably getting the picture here. We kept going around this circle, the code getting more and more fragile as I kept bending and patching the base trying to fit in each new requirement. And of course it took longer each time I had to add something. The final straw happened the last time the boss said: “Now how difficult can it be to add bla bla?” And I responded, “It is amazing how easy it is to do something when you don’t know anything about it.” We parted ways shortly after that (go figure) &#8211; me feeling that I’d created a great piece of software under extremely difficult circumstances and him feeling that I’d run his business into the ground. And honestly we were both right. I never should have allowed him to waste his money paying me when I knew that it was hopeless to convince him of the right way to do the project. So back on topic – <strong>don’t write a line of code until you have the <span style="text-decoration: underline;">final</span> requirements specified</strong>. And if some guy writing the checks wants to add a requirement that wasn’t in the original spec, tell him that you will only do that if he agrees to stop the current project and start a new project allowing time to finalize the next set of requirements so that you can redo the design to accommodate the new requirement. And let him know that <strong>ANY</strong> change will require a complete restart. If you think I’m being a bit excessive here then please read Edward Yourdon’s <em>Death March</em>. Your boss may be writing the checks and he can easily replace you with someone who will let him bankrupt himself, but you don’t have to be that guy. Just because someone seems eager to be abused, it doesn’t absolve you from abusing them. The only ethical thing to do when you are hired for your expertise and your employer won’t listen to you is to quit. Whoa, glad I got that out of my system, now lets write that FRS for the serial library! <em> </em></p>
<h3><span style="font-weight: bold;">Serial Library Functional Requirements Specification</span></h3>
<p>The serial library is part of the avrtoolbox elementary libraries and is intended for use by novices. The source code will be written in the C programming language using AVRStudio, WinAVR, and avrlibc. The novice will use this library based on the API document. More advanced users may want to consult the source code. Some of the requirements for these functions (especially the serial_out() function) are somewhat dense without reference to coded examples, so I recommend that the casual reader may want to refer to the API and the examples to understand what is being specified.</p>
<p><strong>Serial initialization function:</strong> serial_begin() will let the user initialize the underlying hardware and software needed to open serial communications with an external uart. This function will allow the user to set the baudrate, but all other uart parameters will be set to the common defaults.<br />
<strong>Serial termination function:</strong> serial_end() will let the user set the underlying hardware parameters back to the system default values.<br />
<strong>Serial input available function:</strong> serial_available() will let the user determine if any data is available in the serial input buffer.<br />
<strong>Serial buffer clear function:</strong> serial_flush() will let the user clear all data from the serial buffers.<br />
<strong>Serial input function:</strong> serial_in() will let the user read data from the serial input buffer one byte at a time.<br />
<strong>Serial output function:</strong> serial_out() will let the user output formatted serial.<br />
This function will:<br />
1. Return the number of characters sent to the USART or a negative number if an error occurred.<br />
2. Accept as that first parameter a string with N data format symbols: This will be a string of characters contained within double quotes containing text to output and conversion symbols for outputting specially formatted data that is contained in the subsequent parameters.<br />
3. Accept as subsequent parameters, data1, data2, … dataN: a list of raw data types that will be converted to printable characters indicated by the conversion symbols in the first parameter string.<br />
4. Will use the following conversion symbols in the first parameter string:</p>
<ul>a. %c – print an ASCII character<br />
b. %s – print a character string<br />
c. %d or %i – print a decimal integer<br />
d. %x or %X – print a hexadecimal integer. Note that we usually precede this with the characters 0x%X to output, for instance if the hexadecimal number is 5A, the output will be 0x5A. Using 0x%x will output 0x2a.</ul>
<p>5. Will use the following control characters:</p>
<ul>a. \n – print a new line<br />
b. \” – print a quotation mark<br />
c. \\ &#8211; print a forward slash</ul>
<h3>Serial Library Application Programmers Interface</h3>
<p>The API tells the user how to use the functions in an application. For avrtoolbox we will create the API by using doxygen (discussed in the January 2011 Smiley’s Workshop article and available on my blog) to provide comments in the header file and these comments will be extracted into .html and .chm help files. The user should only need to read these help files to use the library functions. This means that the user should never have to look at either the contents of the header or the C source files. And this is, of course, the great value of an API: it allows you to use the functions without ever seeing the code for the function. The API provides a sort of contract between the function writer and the user. The writer promises that the function will behave as shown in the API and the user trusts that any changes or bug fixes to the function won’t effect how the function is used. The API generally specifies what parameters a function will take and what data it will return. The following is the serial library initial API, however the user should consult the API document in avrtoolbox for the latest Serial Library API information before using these functions.<br />
<strong> </strong></p>
<p><strong>serial_begin()</strong><br />
<strong>Description:</strong> Sets up the serial communication with the transmission data rate (baudrate).<br />
<strong>Syntax: </strong>serial_begin(baudrate)<br />
<strong>Parameters:</strong> baudrate: 32-bit integer (uint32_t). Recommended that you only use one of the standard rates of: 300, 1200, 2400, 4800, 9600, 14400, 19200, 28800, 38400, 57600, or 115200.<br />
<strong>Returns:</strong> nothing</p>
<p><strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void setup(){
// Set up serial port for 57600 baud
serial_begin(57600);
}</span></code></pre>
<p><strong>serial_end()</strong><br />
<strong>Description:</strong> Returns the serial communications elements to their default values.<br />
<strong>Syntax:</strong> serial_end()<br />
<strong>Parameters:</strong> None<br />
<strong>Returns:</strong> Nothing<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void shut_down()
{
    serial_end();
    sleep();
}
</span></code></pre>
<p><strong>serial_available()</strong><br />
<strong>Description:</strong> Gets the number of bytes that have arrived from the serial port and are available for reading from the 128 byte buffer.<br />
<strong>Syntax:</strong> serial_avaiable()<br />
<strong>Parameters:</strong> Nothing<br />
<strong>Returns:</strong> uint8_t bytes available in the serial receive buffer – up to 128.<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">void loop()
{
    if(serial_available() &gt; 16)
    {
        process_serial_input();
    }
}</span></code></pre>
<p><strong>serial_flush()</strong><br />
<strong>Description:</strong> Clear out any data in the serial buffer. Subsequent calls to serial_in() or serial_available() will only return data that has arrived since the call to serial_flush().<br />
<strong>Syntax:</strong> serial_flush()<br />
<strong>Parameters:</strong> Nothing<br />
<strong>Returns:</strong> Nothing<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
// Received unknown command, restart the conversation
serial_out(“Unknown command: %d, flushing buffer.”, last_command);
// Throw out everything
serial_flush();</span></code></pre>
<p><strong>serial_in()</strong><br />
<strong>Description:</strong> Inputs incoming serial data one byte at a time, returns –1 if no data is available.<br />
<strong>Syntax:</strong> serial_in()<br />
<strong>Parameters:</strong> Nothing<br />
<strong>Returns:</strong> 16-bit signed integer (int16_t) &#8211; the first byte of incoming data or returns –1 if no data available.<br />
<strong>Example:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">// Define and receive a serial byte
int16_t myByte = serial_in();
// Is it ‘!’
if(myByte == ‘!’)
{
    process_exclamation();
}</span></code></pre>
<p><strong>serial_out()</strong><br />
<strong>Description: </strong>Outputs formatted data based on conversion symbols and escape character sequences contained in a string of text.<br />
<strong>Syntax:</strong> serial_out(string_with_N_data_format_symbols, data1, data2, … dataN);<br />
<strong>Parameters:</strong><br />
First parameter: string with data to format<br />
Following parameters: the data to be formatted for printing in the first parameter string.<br />
<strong>Returns:</strong> The number of characters printed or a negative number if an error occurred.<br />
<strong>Note:</strong><br />
Conversion symbols:</p>
<ul>%c – print an ASCII character<br />
%s – print a character string<br />
%d or %i – print a decimal integer<br />
%x – print a hexadecimal integer. Note that we usually precede this with the characters 0x to output, for instance if the hexadecimal number is 5A, the output will be 0x5A.</ul>
<p>Control characters:</p>
<ul>\n – print a new line<br />
\” – print a quotation mark<br />
\\ &#8211; print a forward slash<strong> </strong></ul>
<p><strong> </strong></p>
<p><strong> </strong><br />
<strong> </strong><br />
<strong>Example 1:</strong></p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">uint8_t my_char = ‘!’;
uint8_t my_string[] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’, 0};
my_byte = 42;
serial_out(“Print a character: %c, a string: %c, a decimal integer: %d, a hexadecimal integer: 0x%X, a forward slash: \\, a quote: \”, a new line: \n next line.”, my_char, my_string, my_byte, my_byte);</span></code></pre>
<p><strong> </strong><br />
Which shows in the terminal as:</p>
<ul>Print a character: !, a string: Hello, a decimal integer: 42, a hexadecimal integer: 0x2A, a forward slash \, a quote “, and a new line: next line.,/ul&gt;<br />
<strong>Example 2:</strong>&nbsp;</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">

</span></code>
<ul><code>uint8_t my_day = 21;
uint8_t my_month[] = {‘J’,’u’,’l’,’y’,0};
uint16_t my_year = 1980;
serial_out( “Your date of birth is:\n Day %d \nMonth: %s \nYear %d.”, my_day, my_month, my_year);</code></ul>
</pre>
</ul>
<p>Which shows in the terminal as:</p>
<ul>Your date of birth is:<br />
Day 21<br />
Month July<br />
Year 1980</ul>
<p><strong>NOTE:</strong> DO NOT USE FLOATING POINT DATA (numbers with decimals). That facility is not included since it causes the code size to increase more than is warranted by the convenience. If you really need floating point consider using the special printf() functions as documented in avrlibc.<br />
<strong>Running over the buffer.</strong><br />
After I built the serial library I wrote a program that I thought provided reasonable testing of all the functions and everything worked fine and then as I was about to wrap things up I decided to push things a bit and see if I could choke the buffers and what would happen if I did. Thankfully, nothing crashed, and based on the underlying code I didn’t expect it to, but you never know until you test. I found that if I sent a string greater than the buffer size (64 bytes in the test case) or if called the function twice in succession with the total bytes too high I’d get some random output until the background Interrupt has a chance to catch up. Look at the string in:</p>
<p>serial_out(&#8220;serial_out: Now is the time for all good men to come to the aid of their country.\n&#8221;,0);</p>
<p>You might think this is a reasonable test and if you took typing lessons you might even feel a bit nostalgic, but this string is over 75 bytes and will choke the buffer. And since this library is intended for novices who might think that this is a reasonable sentence, I decided to add a feature that would allow long strings to be printed without choking the buffer. The mechanism I chose has a drawback in that if you try to transmit more than the 2/3 the buffer size then the function will insert a brief delay after each character until the system catches up. [10ms for the Atmega328, which is running at 16MHz and 20ms for the Butterfly, which is poking along at 2MHz. The 2/3 buffersize was selected empirically because 2/3 works but ¾ doesn’t.] This delay isn’t particularly noticeable but as a word of advice to folks who actually RTFM don’t send strings larger than 2/3 of your maximum buffer size if you have any kind of time constraints in your program</p>
<h3>Library Test Application: serial_tester</h3>
<p>The avrtoolbox libraries will each have an application that tests the functions (and as a byproduct, demonstrates how to use the functions). The test application will assure that the functions do what is stated in the FRS according to the API. In a large project with lots of human resources available, software testing is often the job of several people who design rigorous test cases and thoroughly examine every problem they can foresee. This is of course very expensive and not really needed for a small project like ours. Proper testing is a subjective task and we will let the common sense of the developer prevail. Since this is an open source project, if a problem shows up that wasn’t covered in the tests (they will) then the user can file a report in the ‘issues’ section of the project and someone working on the project may eventually get around to looking at the problem.</p>
<p>Since libraries can sometimes be device dependent we will create separate libraries tested for each of our avrtoolbox common devices and development platforms: Atmega169 (Butterfly), Atmega328(on an Arduino board), and the Atmega644 (on the BeAVR). We will call the libraries libserial_butterfly001.a, libserial_atmega328, libserial_atmega644.a.</p>
<p>You can find the serial_tester AVRStudio project and the serial library archives and source code in the avrtoolbox project source code trunk or at: http://tinyurl.com/3cc7qz, and the serial_tester code at: http://tinyurl.com/3jxf5z6. Load the serial_tester project in AVRStudio then load the library archive as follows:<br />
<strong>Using the libraries with AVRStudio</strong><br />
Let’s use the libserial_butterfly_001.a as an example. [If you have an Arduino, you can use the libserial_atmega328_001.a.] Make sure that the library is in the same sub-directory as your AVRStudio project .aps file. Then open the AVRStudio Project menu and select the Project Options. Click on the libraries icon to open the window shown in Figure 2. In the upper part of this window click on the little folder icon (left of the red X) and navigate to your project folder. It will show “.\” in the upper text box and it will also locate the libserial_butterly001.a file and show it in the ‘Available link Objects:’ list below. Highlight the library then click the ‘Add Library-&gt;’ button to add it to the ‘Link with these objects’ list. Click okay and compile the project to generate the .hex file for uploading to the Butterfly.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image004_thumb.jpg" border="0" alt="clip_image004" width="248" height="192" /></a></p>
<p>Figure 2: Project Options<br />
<strong>Uploading the .hex file</strong><br />
You can use avrdude as shown in Smiley’s Workshop 10 <em>Moving Beyond the Arduino</em> in the May 2009 Nuts&amp;Volts magazine also available on my blog at <a href="http://smileymicros.com/blog/2010/10/03/42/">http://smileymicros.com/blog/2010/10/03/42/</a></p>
<p>However, if you want to try something a bit different you can use the uploaders I am working on that put a C# IDE over avrdude making it a bit easier to use. You can get them in the avrtoolbox pc_applications section. You navigate to this directory by opening http://code.google.com/p/avrtoolbox/source/browse/ then click on trunk and then pc_applications. These are beta releases so take that under advisement.</p>
<h5>ButterUp</h5>
<p>ButterUp comes with a user manual and rather than waste trees here, I suggest you just click on the button ‘New to ButterUp? Click here.’ shown at the top of Figure: 3. If you make a mistake the manual .pdf file will automatically be opened which is sort of like yelling RTFM and then pushing it into your face, annoying yes, but then again if you weren’t making mistakes you wouldn’t need the manual would you?</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image006_thumb.jpg" border="0" alt="clip_image006" width="203" height="248" /></a></p>
<p>Figure 3: ButterUp .hex file uploader.</p>
<h5>ArdUp</h5>
<p>Like for ButterUp, I suggest you just click on the button ‘New to ArdUp? Click here.’ shown at the top of Figure: 4 to find out how to use it. This program is similar to ButterUp but uses the DTR modem line to reset the Arduino so that’s it goes directly to the bootloader for use by avrdude. Try and keep in mind that we are using the Arduino board as a generic Atmega328 development platform and not using it as an ‘Arduino’. If you find this concept confusing please consult that ‘<em>Moving Beyond the Arduino</em>’ stuff I mentioned earlier.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image008_thumb.jpg" border="0" alt="clip_image008" width="173" height="248" /></a></p>
<p>Figure 4: ArdUp .hex file uploader.</p>
<p>If you do use either of these, I’d like to hear if you have any problems, you can start a thread on AVRFreaks with either ButterUp or ArdUp in the title, or you can open an issue in the avrtoolbox project.<br />
<strong>Running the test in Bray’s terminal</strong><br />
Open Bray’s terminal as shown in Figure 5 and if you are using a Butterfly make sure the baud is set to 19200 and click the joystick up to get the application to run, if you are using the Arduino board make sure the baud is 57600 and you may need to click the DTR button on Bray’s on and off (or just press the reset button on the board). Once the test output prints then you can send some characters via the send window – in the case in Figure 5 I sent “abcdefghijklmnopqrstuvwxyz01234567890” and, as you can see everything Rx’d and Tx’d just fine.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/11/clip_image010_thumb.jpg" border="0" alt="clip_image010" width="248" height="247" /></a></p>
<p>Figure 5: serial_tester results in Bray’s Terminal.</p>
<p>NOTE: For the AVR Butterfly: this marvelous little board uses a 32.768 kHz watch crystal to keep track of real time and to calibrate the internal RC oscillator to 2 MHz. Since the RC oscillator isn’t particularly accurate you can’t use just any old baudrate and expect it to work consistently, for this reason the serial library for the Butterfly is hardwired for 19200 baud and even if you enter another value in the serial_begin(baud) function, if you are using the libserial_butterfly001.a, it will ignore the baud value and use 19200. Also the Butterfly tries to run the application twice when you toggle the joystick up, once when it goes up and once when it comes down so you may get a partial start before the real start in Brays terminal.</p>
<p>And if after all this good stuff you just can’t wait and want to get a leg up on real C programming and the AVR (while helping support your favorite magazine and technical writer) then buy my C Programming book and Butterfly projects kit using the Nuts&amp;Volts magazine or website. Next month, if all goes well, we will continue with avrtoolbox by learning about how to buffer data and writing a ring (aka circular or FIFO) buffer..</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/11/08/avrtoolbox-designing-an-elementary-library-serial-communications/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BreadboArduino: Arduino on a breadboard</title>
		<link>http://smileymicros.com/blog/2011/06/15/arduino-on-a-breadboard-breadboarduino/</link>
		<comments>http://smileymicros.com/blog/2011/06/15/arduino-on-a-breadboard-breadboarduino/#comments</comments>
		<pubDate>Wed, 15 Jun 2011 16:33:46 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[arduino]]></category>
		<category><![CDATA[FT232R]]></category>
		<category><![CDATA[FTDI]]></category>
		<category><![CDATA[USB]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/2011/06/15/arduino-on-a-breadboard-breadboarduino/</guid>
		<description><![CDATA[Smiley’s Workshop 21: BreadboArduino Joe Pardue February 15, 2010 Figure 1: BreadboArduino on a breadboard. [NOTE: this has been modified from the original to use the Gravitech USB board – you can get the parts for this project at: http://www.smileymicros.com/index.php?module=pagemaster&#38;PAGE_user_op=view_page&#38;PAGE_id=90 &#8230; <a href="http://smileymicros.com/blog/2011/06/15/arduino-on-a-breadboard-breadboarduino/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h3><a name="_Toc229816894"></a><a name="_Toc229817066"></a><a name="_Toc230075380"></a><a name="_Toc232072375"></a><a name="_Toc229816890"></a><a name="_Toc229817062"></a><a name="_Toc230075376"></a><a name="_Toc232072369"></a><a name="_Toc233616889"></a><a name="_Toc233969838"></a><a name="_Toc236301230"></a><a name="_Toc236727493"></a><a name="_Toc236727571"></a><a name="_Toc237255517"></a><a name="_Toc250218105"></a><a name="_Toc253943650">Smiley’s Workshop 21: BreadboArduino</a></h3>
<p>Joe Pardue February 15, 2010</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00242.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0024_thumb2.jpg" border="0" alt="clip_image002[4]" width="248" height="137" /></a></p>
<p>Figure 1: BreadboArduino on a breadboard.</p>
<p>[NOTE: this has been modified from the original to use the Gravitech USB board – you can get the parts for this project at: <a href="http://www.smileymicros.com/index.php?module=pagemaster&amp;PAGE_user_op=view_page&amp;PAGE_id=90">http://www.smileymicros.com/index.php?module=pagemaster&amp;PAGE_user_op=view_page&amp;PAGE_id=90</a> ]</p>
<h3><a name="_Toc253943651">Recap:</a></h3>
<p>Last month we finished a three part series on serial communications between a PC and an Arduino. We used C# .NET Express to build an Arduino Volt Meter GUI, and we also learned a bit more about the FT232R USB to Serial Port IC that makes Arduino communication with a microcontroller so easy. We now have enough background that we can bust up the Arduino and reconstruct our own version from the pieces.</p>
<h3><a name="_Toc253943652">Why bust up a perfectly good system?</a></h3>
<p>There are many folks who are ready to move beyond what Arduino does easily. This leads to attempts to twist the Arduino concept all out of shape to make it do things it just wasn’t designed for. I’m seeing arguments developing on various Internet forums between Arduino novices and folks more experienced with microcontrollers who sometimes seem to be yelling at each other across a Grand Canyon sized gap in knowledge. The novice has found that the things that the Arduino does well, are easy to do and they don’t seem to understand that many of the things that the Arduino doesn’t do easily can be quite difficult to learn. The experienced folks, who probably haven’t messed with the Arduino, know that microcontrollers can be difficult to learn about and don’t seem to understand why anyone would think otherwise. IMHO the main thing that both sides are missing is that the intended audience for the Arduino was never expected to be or become an expert in microcontrollers.</p>
<p>Consider for a moment the intended audience for the Arduino as stated by Massimo Banzi in his book, <em>Getting Started with Arduino:</em></p>
<p>“A few years ago I was given the very interesting challenge: teach designers the bare minimum in electronics so that they could build interactive prototypes of the objects they were designing.” He summarizes his philosophy of ‘learning by tinkering’ with a quote from <a href="http://www.exploratorium.edu/tinkering">www.exploratorium.edu/tinkering</a>: <em>“</em>Tinkering is what happens when you try something you don’t quite know how to do, guided by whim, imagination, and curiosity. When you tinker, there are no instructions – but there are also no failures, no right or wrong ways of doing things. It’s about figuring out how things work and reworking them<em>.”</em></p>
<p>That last sentence is both the most fun and the most difficult to get beyond. Creativity requires this sort of playfulness, but my experience with microcontrollers &#8211; moving beyond what the Arduino does easily – involves about 90% of my time correcting failures. My work habit is to literally fail my way to success. Sorry, but if you want to move beyond being a novice, you have to forget that last sentence: “but there are also no failures, no right or wrong ways of doing things” – because there really are right and wrong ways of doing things and failures are inherent to working with microcontrollers.</p>
<p>I’m going to draw a line in the sand and say that Arduino is excellent for its intended audience: beginners &#8211; and for prototyping within the limits of its library – <strong><span style="text-decoration: underline;">BUT</span></strong> &#8211; if you want to do things that aren’t built into Arduino, you should migrate to a more capable set of tools. <strong><span style="text-decoration: underline;">AND</span></strong> don’t get me wrong, I wrote the book: <strong><em>An Arduino Workshop</em></strong> that along with the associated projects kit (both available from Nuts&amp;Volts and SmileyMicros) provide excellent tools for getting started. But once you’ve exhausted what can be done easily, then it is time to move on.</p>
<p>And here, of course, comes the flames… yes, I know that the stuff underlying the Arduino is all open source and can be rewritten to do anything that any other system for AVR microcontrollers can do. But why bother? There are already perfectly good alternative systems, and I’m going to discuss the free one from Atmel: AVRStudio along with a couple of other open source applications (WinAVR and AVRDude) that have all the AVR and C programming tools you need for more advanced work.</p>
<p>I’ve spent some time with this concept in some in earlier Workshops, but this month we are going to move to more generic AVR development boards by taking the first step of recreating Arduino hardware on a breadboard. We will then write a test program using AVRStudio/WinAVR. And finally we will build on the last three Workshops and use C# Express to write AVRUP-V1, an IDE for uploading code to the AVR.</p>
<h3>BreadboArduino</h3>
<p>Since my surname is Pardue, which has <strong>ardu</strong> (French for steep or difficult &#8211; hmmm…) as does <strong>ardu</strong>ino, I was tempted to dub this design the Parduino, but humility won me over so BreadboArduino it is. This hardware system has two main parts, the communications section using the FT232RL and the microcontroller section using an ATmega328.</p>
<h4><a name="_Toc253943654">Using the FTDI FT232R on a breadboard</a></h4>
<p>In the last few Workshops we looked at the FTDI FT232R USB Serial Port and learned how to communicate with it using the free C# Express .NET program to build a Simple Terminal and an Arduino Volt Meter. You could get the FT232R portion of the Arduino on a separate PCB, such as the BBUSB (the basis for <em>The Virtual Serial Port Cookbook</em> and projects kit available from Nuts&amp;Volts and SmileyMicros).</p>
<p>Our first chore will be to put the FT232R board on a breadboard and then test it to make sure the communications side of our system is working. Please note as we progress that things will get increasingly complex and bug-prone so it will be nice to be able to isolate the sections and test them separately. If you have the final system built and you start seeing flaky stuff (or worse – nothing) on the PC serial monitor side of the cable, then you can pull out the wires, hook in the wire loop and run the loopback test to make sure the PC and USB sections are working okay.</p>
<h5><a name="_Toc253943655">Gravitech FTDI Breakout</a></h5>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00442.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0044_thumb2.jpg" border="0" alt="clip_image004[4]" width="215" height="248" /></a></p>
<p>Figure 2: Gravitech FT232R Breakout</p>
<p>You will need to solder the headers to the board (long legs down) so that you can plug it into a breadboard. The pin labels are kind of hard to tread so I’ve sort of solved that by producing a Word document with the table shown in Figure 3 that, cut out and folded like a tent, has the pins labeled. You can get the label as a word document at</p>
<p>www.smileymicros.com/download/Gravitech hat.doc</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00642.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0064_thumb2.jpg" border="0" alt="clip_image006[4]" width="208" height="248" /></a></p>
<p>Figure 3: Loopback test with hat</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00842.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0084_thumb2.jpg" border="0" alt="clip_image008[4]" width="8" height="9" /></a></p>
<p>Figure 4: FT232R Breakout Schematic</p>
<h5><a name="_Toc253943656">The Loopback Test</a></h5>
<p>After you’ve got your loopback hardware completed, you can test this with the Simple Terminal we built in Workshops 18 and 19.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01042.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0104_thumb2.jpg" border="0" alt="clip_image010[4]" width="248" height="160" /></a></p>
<p>Figure 5: Loopback Test in the Simple Terminal</p>
<h4><a name="_Toc253943657">Building the BreadboArduino</a></h4>
<p>We will simplify our lives in this section by leaving off the Arduino power supply section and using only the power from the USB port. Theoretically we can take 500 mA from the USB, but there are caveats that cause me to advise using less than 100mA. This should be enough to do a Cylon Eyes type project, but probably not enough to run motors.</p>
<h6><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01242.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0124_thumb2.jpg" border="0" alt="clip_image012[4]" width="248" height="248" /></a></h6>
<p>Figure 6: BreadboArduino schematic</p>
<table border="1" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td width="91" valign="top"><strong>Sch. Part</strong></td>
<td width="204" valign="top"><strong>Description</strong></td>
</tr>
<tr>
<td width="91" valign="top">IC1</td>
<td width="204" valign="top">ATmega328 with bootloader</td>
</tr>
<tr>
<td width="91" valign="top">Q1</td>
<td width="204" valign="top">Crystal 16MHz</td>
</tr>
<tr>
<td width="91" valign="top">S1</td>
<td width="204" valign="top">Mini Push Button</td>
</tr>
<tr>
<td width="91" valign="top">C1,C2</td>
<td width="204" valign="top">22pF Capacitor</td>
</tr>
<tr>
<td width="91" valign="top">C3,C4,C5</td>
<td width="204" valign="top">100nF Capacitor</td>
</tr>
<tr>
<td width="91" valign="top">R1</td>
<td width="204" valign="top">10k Ohm Resistor</td>
</tr>
<tr>
<td width="91" valign="top">R2,R3,R4,</td>
<td width="204" valign="top">1K Ohm Resistor</td>
</tr>
<tr>
<td width="91" valign="top">L</td>
<td width="204" valign="top">Red LED</td>
</tr>
<tr>
<td width="91" valign="top"></td>
<td width="204" valign="top">FT232R Breakout Board</td>
</tr>
<tr>
<td width="91" valign="top"></td>
<td width="204" valign="top">Break Away Male Headers</td>
</tr>
<tr>
<td width="91" valign="top"></td>
<td width="204" valign="top">Breadboard</td>
</tr>
<tr>
<td width="91" valign="top"></td>
<td width="204" valign="top">Hook-up Wire (22AWG)</td>
</tr>
</tbody>
</table>
<h6>Table 1: BreadboArduino Bill of Materials</h6>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01442.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0144_thumb2.jpg" border="0" alt="clip_image014[4]" width="161" height="248" /></a></p>
<p>Figure 7: Automatic and manual reset.</p>
<p>When I built the section shown in Figure 7: Automatic and manual reset, I had the upper black wire two spaces to the right and nothing worked. Duh, running /RESET to ground tends to create that symptom. I moved it to the position shown and everything worked.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0164.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0164_thumb.jpg" border="0" alt="clip_image016[4]" width="173" height="248" /></a></p>
<p>Figure 8: TxD andRxD</p>
<p>In Figure 8: TxD andRxD, the serial communication wires are in yellow. You may need to put the paper tent label on the FT232R Breakout board to see where the TxD and RxD go. AND REMEMBER: the TxD on the FT232R board goes to the RxD on the ATmega (pin 2) while the RxD on the FT232R goes to the TxD on the ATmega (pin 3). This confuses a lot of folks, but think about it for a moment, the data being <strong>transmitted</strong> from the PC through to FT232R is being <strong>received</strong> by the ATmega, while the data being received by the PC through the FT232R is being transmitted by the ATmega. Figure 9 provides an enlargement of the section containing the crystal and the power.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0184.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image018[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0184_thumb.jpg" border="0" alt="clip_image018[4]" width="248" height="217" /></a></p>
<p>Figure 9: Crystal and Power</p>
<h3><a name="_Toc253943658">Hello World Program for the BreadboArduino</a></h3>
<p>It is not my intent to scare anyone with a code listing, though I fear that those familiar with the Arduino, but not yet comfortable with regular C programming will feel like they’ve been backing down a dark hallway in an old house shining a flashlight in their own eyes when BUMP they get a look at this code. But relax, this isn’t a slasher film, and we will, over time, learn what all this means. In the meantime, just type it into the AVRStudio editor [or get the source from Workshop21.zip].</p>
<pre><code><span style="font-family: 'Courier New'; font-size: 16px;">
/* ******************************************************
BreadboArduino_Hello_World Joe Pardue February 10, 2010
****************************************************** */

#include &lt;stdio.h&gt;
#include &lt;avr/io.h&gt;
#define FOSC 16000000
#define BAUD 57600
#define MYUBRR FOSC/16/BAUD-1

uint8_t receiveByte( void );
void init();

// From example in avrlibc manual
static int uart_putchar(char c, FILE *stream);
static FILE mystdout = \
FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);

int main(void)
{
    uint8_t b;
    uint8_t count = 0;

    init();

    printf("BBArduino_Hello_Test v 005\n");

    while(1)
    {
        b = receiveByte();
        printf("#%d",count++);
        printf("You sent: %c\n",b);
    }
    return 0;
}

static int uart_putchar(char c, FILE *stream)
{

    if (c == '\n') uart_putchar('\r', stream);

    // wait for UDR to be clear
    loop_until_bit_is_set(UCSR0A, UDRE0);
    UDR0 = c; //send the character
    return 0;
}

void init()
{
    //USART Baud rate: 57600
    UBRR0H = (MYUBRR) &gt;&gt; 8;
    UBRR0L = MYUBRR;
    UCSR0B = (1&lt;&lt;RXEN0)|(1&lt;&lt;TXEN0);
    //set the output stream
    stdout = &amp;mystdout;
}

uint8_t receiveByte( void )
{
    // Wait for data to be received
    while ( !(UCSR0A &amp; (1&lt;&lt;RXC0)) );
    // Get and return received data from buffer
    return UDR0;
}</span></code></pre>
<h3><a name="_Toc253943659">Compiling in AVRStudio</a></h3>
<p>I presume you’ve downloaded and installed the latest and greatest AVRStudio and WinAVR. If not, get them at:</p>
<p>http://www.atmel.com/dyn/products/tools_card.asp?tool_id=2725</p>
<p>http://winavr.sourceforge.net/download.html</p>
<p>Open AVRStudio and click on the Project\New Project menu item as shown in Figure 10:</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0204.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image020[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0204_thumb.jpg" border="0" alt="clip_image020[4]" width="248" height="236" /></a></p>
<p>Figure 10: Select New Project</p>
<p>A Window will open as shown in Figure 11. Highlight ‘AVR GCC’, browse to a location for your file, and name the file under ‘Project name’, then click ‘Next&gt;&gt;’.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0224.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image022[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0224_thumb.jpg" border="0" alt="clip_image022[4]" width="248" height="158" /></a></p>
<p>Figure 11: Project type and file name</p>
<p>In the next window as shown in Figure 12, select the ‘Debug platform’ AVR Simulator, and the Device ‘ATmega168P (unless you got the 328), and finally click finish.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0244.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image024[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0244_thumb.jpg" border="0" alt="clip_image024[4]" width="248" height="158" /></a></p>
<p>Figure 12: Platform and Device</p>
<p>You can now input the program in the edit window as shown in Figure 13.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0264.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image026[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0264_thumb.jpg" border="0" alt="clip_image026[4]" width="248" height="154" /></a></p>
<p>Figure 13: Input program in edit window</p>
<p>Click on the ‘Build Active Configuration’ button as shown in Figure 14, and if all goes well, you’ll get that ‘Build succeeded with 0 Warnings…’ message.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0284.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image028[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0284_thumb.jpg" border="0" alt="clip_image028[4]" width="198" height="242" /></a></p>
<p>Figure 14: Build Active Configuration</p>
<h3><a name="_Toc253943660">AVRUP V1 – An AVR Program Uploader</a></h3>
<p>[NOTE: AVRUP has been replaced by ArdUp – details at:</p>
<p><a href="http://smileymicros.com/blog/2010/10/11/ardup-an-arduino-hex-file-uploader/">http://smileymicros.com/blog/2010/10/11/ardup-an-arduino-hex-file-uploader/</a> ]</p>
<p>The one thing I might miss about the Arduino is how easy it uploads programs to the micro. AVRStudio has AVRProg for uploading, but that thing is so bad that even Atmel no longer supports it. When it works, it is fine, but when there is a problem, it doesn’t give many hints as to what might be wrong. The Arduino uploader function is also great when it works, but when there is a problem – it can be down right scary: the little black box at the bottom of the IDE fills with bright red text listing a bunch of cryptic complaints that the novice has not a chance of understanding. [I’ll assert at this point that if one knows about the underlying avrdude error messages – one is not a novice.] I imagine most novices peek at those bloody looking messages and freak out a bit. One of the goals of AVRUP is to run avrdude in the verbose mode and list everything it has to say in nice black text on a white background, making it easier to get the avrdude manual and figure out what the problem is. [The avrdude manual is in the WinAVR doc directory]</p>
<p>Back in Workshop10, I showed how to use avrdude in the Windows command line but personally I find it can be a PITA to use avrdude casually in Windows because it requires a list of parameters that are daunting to figure out, type in, and remember the next time you use it. None of that are faults in avrdude, a great program, but for me a more automated process helps a lot (get it right once, then forget how you did it) so I decided to write a helper program in C#. Aren’t you glad you paid attention to the last three Workshops?</p>
<p>You can get AVRUP V1 as an application and the full source code in Workshop21.zip. I’m not going to discuss that code further here because all the basics were covered in the last three Workshops that you can get from www.smileymicros.com.</p>
<h4><a name="_Toc253943661">Avrdude on the PC talks to a bootloader on the AVR IC</a></h4>
<p>We usually think of a microcontroller as a general-purpose device that has an application program on it defining specifically what it does. An AVR with one application might control the fuel/air mixture in your cars engine. An identical AVR, but with a different application might control your microwave oven. There are many ways to get an application program loaded onto a microcontroller. But one that I like a lot is a bootloader. For this, the AVR memory is divided into two sections, one to hold the bootloader software, and another to hold the application software. We will leave the problem of how to get the bootloader into the AVR for a later article, but this month we purchase an AVR with the bootloader already on it. The bootloader on the Arduino is a standard AVR bootloader that starts running when the AVR comes out of reset. It spends a few seconds using the USART serial port to see if something is out there wanting to upload a new application and if not, then it gives over control to the resident application program. If something (an uploader) is on the port and knows how to speak bootloader talk, then the bootloader and the uploader collude to take the application program from the PC and put it in the AVR application memory (overwriting the previous application). The bootloader’s final act is to set the AVR to run the application.</p>
<h4><a name="_Toc253943662">Uploading with AVRUP V1</a></h4>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0304.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image030[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0304_thumb.jpg" border="0" alt="clip_image030[4]" width="248" height="179" /></a></p>
<p>Figure 15: AVRUP V1</p>
<p>[NOTE: the following is about AVRUP which has been replaced by ArdUp – read about it at: <a href="http://smileymicros.com/blog/2010/10/11/ardup-an-arduino-hex-file-uploader/">http://smileymicros.com/blog/2010/10/11/ardup-an-arduino-hex-file-uploader/</a>]</p>
<p>Open AVRUP V1, and click on the ‘File to upload’ menu item and select the Hello_World.hex file from where ever you stored it. Next click the ‘Select Port’ item and select the COM port your BreadboArduino is using (this item should be familiar from the last three Workshops). Next click on the ‘Select Board’ item and select the ‘ATmega168.xml’ file. The ‘AVRDude Script’ window should look like the one in Figure 15 (except for the m328p which should be m168p). Now click ‘Upload to Board’ and watch your BreadboArduino LED flash indicating reset and note that the red and green LEDs on the Gravitech board twiddle around as avrdude communicates with the bootloader. The ‘AVRDUDE Response’ textbox fills with lots of information, followed by ‘avrdude.exe done. Thank you’.</p>
<p>Finally, fire up Simple Terminal and test the board as shown in Figure 16.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0324.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image032[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0324_thumb.jpg" border="0" alt="clip_image032[4]" width="248" height="158" /></a></p>
<p>Figure 16: Hello Test</p>
<h3><a name="_Toc253943663">No Seriously…</a></h3>
<p>What are the chances that you are going to build all this and have it go as smoothly as indicated by this Workshop? Remember what I said about failing your way to success? Well, all I can say is that I messed up multiple times at every step, but did eventually get it all working. You have all the source materials and should be able to duplicate my success. Next month we are going to take all we’ve learned of late and build and even more capable system to support our future learning about the AVR architecture and C programming.</p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/06/15/arduino-on-a-breadboard-breadboarduino/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serial Communications Part 2 &#8211; A Simple Terminal</title>
		<link>http://smileymicros.com/blog/2011/06/10/serial-communications-part-2-a-simple-terminal-2/</link>
		<comments>http://smileymicros.com/blog/2011/06/10/serial-communications-part-2-a-simple-terminal-2/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 18:11:43 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[C sharp dot net]]></category>
		<category><![CDATA[FT232R]]></category>
		<category><![CDATA[FTDI]]></category>
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/?p=1160</guid>
		<description><![CDATA[Smiley’s Workshop 19: Serial Communications Part 2 – A Simple Terminal Joe Pardue December 7, 2009 NOTE: the code is improperly formatted in this blog so I suggest you skim over it and look at the code in the file: &#8230; <a href="http://smileymicros.com/blog/2011/06/10/serial-communications-part-2-a-simple-terminal-2/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h1><a name="_Toc229816894"></a><a name="_Toc229817066"></a><a name="_Toc230075380"></a><a name="_Toc232072375"></a><a name="_Toc229816890"></a><a name="_Toc229817062"></a><a name="_Toc230075376"></a><a name="_Toc232072369"></a><a name="_Toc233616889"></a><a name="_Toc233969838"></a><a name="_Toc236301230"></a><a name="_Toc236727493"></a><a name="_Toc236727571"></a><a name="_Toc237255517"></a><a name="_Toc247535839">Smiley’s Workshop 19: Serial Communications Part 2 – A Simple Terminal</a></h1>
<p>Joe Pardue December 7, 2009</p>
<p>NOTE: the code is improperly formatted in this blog so I suggest you skim over it and look at the code in the file: <a href="/download/Workshop 19 Source Code.zip">Workshop 19</a></p>
<h1><a name="_Toc247535840">Recap</a></h1>
<p>Last month we introduced to serial communications between a PC and an Arduino using C# or Visual Basic Express .NET (both free from http://www.microsoft.com/express/. (The article shows the C# examples, and the Visual Basic examples are in Workshop19.zip) This month we will look at selecting a serial port, getting user input, and then we will expand on all this to build a simple terminal.</p>
<h1><a name="_Toc247535841">Getting User Input</a></h1>
<p>In this section we will create a dialog form to allow the user to select an available serial port and set the UART parameters needed for the communication link (Baudrate, Data Bits, Parity, Stop Bits, and Handshaking). To create and test the Settings dialog we will use a test form, PortSetTest, to call it. Later we will access this form by clicking the settings menu item from the Simple Terminal (and next month we will use it for a Arduino Volt Meter program).</p>
<p>· Open either C# Express and create a new project named PortSetTest</p>
<p>· Create a form to look like Figure 1: PortSet Test</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0022.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image002_thumb2.jpg" border="0" alt="clip_image002" width="248" height="222" /></a></p>
<p>Figure 1: PortSet Test</p>
<p>· The text list is made from 6 labels using the text shown.</p>
<p>· In the Solutions Explorer right click ‘PortSetTest’ and from the drop down menus select Add/NewItem as shown in Figure 2: Add New Item.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0042.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image004_thumb2.jpg" border="0" alt="clip_image004" width="201" height="248" /></a></p>
<p>Figure 2: Add New Item</p>
<ul>
<li>In the Add New Item form shown in Figure 3, highlight ‘Windows Form’, change the name to ‘PortSettings.cs’ if C# and click Add.</li>
</ul>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0062.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image006_thumb2.jpg" border="0" alt="clip_image006" width="248" height="156" /></a></p>
<p>Figure 3: Add New Item Form</p>
<ul>
<li>The blank form will open.</li>
<li>In the Properties Window select ‘FormBorderStyle’ and select ‘FixedDialog’. This type of form can post a DialogResult message that the calling form, in this case the Simple Terminal form, can process (don’t panic, this is all done for you and is simpler than is sounds). We will use the DialogResult to learn if the user clicked the Settings form Okay or Cancel button.</li>
<li>Now you should be able to do some stuff without a lot of hand-holding:
<ul>
<li>Change the form name to ‘Setting’.</li>
<li>Add the Smiley.ico icon.</li>
<li>Change the form color to Bisque.</li>
</ul>
</li>
<li>Add the controls shown below:
<ul>
<li>The upper white box with listBoxPorts, is a listBox, which you will name listBoxPorts.</li>
<li>The control with the label ‘Baudrate’ is a ComboBox, change its name to comboBoxBaud.</li>
</ul>
</li>
<li>Your Settings form should look like Figure 4: Settings Form.</li>
</ul>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0082.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image008_thumb2.jpg" border="0" alt="clip_image008" width="201" height="248" /></a></p>
<p>Figure 4: Settings Form</p>
<p>· Add the DevInfo file to the project:</p>
<p>· Copy the DevInfo.cs if C# to the directory containing the PortSettings project files. You will find the DevInfo file in Workshop19.zip.</p>
<p>· Refer to the Add/New Item image as shown in Figure 2: Add New Item.</p>
<p>· Open the same menus in the Solution Explorer, but instead of selecting Add/New Item, select Add/Existing Item and select DevInfo.cs.</p>
<p>· Note that we are intentionally not using the SerialPort GetPortNames function for since it doesn’t work correctly. (Microsoft released a buggy funcion &#8211; hard to believe isn’t it?) We will not look at this file in detail since it contains some advanced concepts, but we will use it to get the names of the available ports. The source code is in Workshop19.zip and if you want to learn the gory details, they are contained in <em>The Virtual Serial Port Cookbook</em> available from Nuts&amp;Volts and Smiley Micros.</p>
<p>· In C# add to the ‘using’ list at the top of the program:</p>
<p>using DevInfo;</p>
<p>· In C# add to the constructor:</p>
<p>public PortSettings()</p>
<p>{</p>
<p>InitializeComponent();</p>
<p>// Get a list of the Serial port names</p>
<p>string[] ports = GetPorts();</p>
<p>int i = 0;</p>
<p>foreach (string s in ports)</p>
<p>{</p>
<p>if (s != &#8220;&#8221;)</p>
<p>{</p>
<p>listBoxPorts.Items.Insert(i++, s);</p>
<p>}</p>
<p>}</p>
<p>// Set first Serial port as default</p>
<p>GetCOM(0);</p>
<p>// Initialize baudrates in combobox;</p>
<p>comboBoxBaud.Items.AddRange(new object[]<strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>{&#8220;75&#8243;,&#8221;110&#8243;,&#8221;134&#8243;,&#8221;150&#8243;,&#8221;300&#8243;,&#8221;600&#8243;,<strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>&#8220;1200&#8243;,&#8221;1800&#8243;,&#8221;2400&#8243;,&#8221;4800&#8243;,&#8221;7200&#8243;,&#8221;9600&#8243;,<strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>&#8220;14400&#8243;,&#8221;19200&#8243;,&#8221;38400&#8243;,&#8221;57600&#8243;,&#8221;115200&#8243;,&#8221;128000&#8243;});</p>
<p>// Set Handshaking selection</p>
<p>// We will only use these handshaking types</p>
<p>comboBoxHandshaking.Items.Add(&#8220;None&#8221;);</p>
<p>comboBoxHandshaking.Items.Add(&#8220;RTS/CTS&#8221;);</p>
<p>comboBoxHandshaking.Items.Add(&#8220;Xon/Xoff&#8221;);</p>
<p>// Set Parity types</p>
<p>foreach (string s in Enum.GetNames(typeof(Parity)))</p>
<p>{</p>
<p>comboBoxParity.Items.Add(s);</p>
<p>}</p>
<p>// Set Databits</p>
<p>// FT232R UART interface supports only 7 or 8 data bits</p>
<p>//comboBoxDataBits.Items.Add(&#8220;5&#8243;); // not supported</p>
<p>//comboBoxDataBits.Items.Add(&#8220;6&#8243;); // not supported</p>
<p>comboBoxDataBits.Items.Add(&#8220;7&#8243;);</p>
<p>comboBoxDataBits.Items.Add(&#8220;8&#8243;);</p>
<p>// Set Stopbits</p>
<p>// FT232R UART interface supports only 1 or 2 stop bits</p>
<p>//comboBoxStopBits.Items.Add(&#8220;None&#8221;); // not supported</p>
<p>comboBoxStopBits.Items.Add(&#8220;1&#8243;);</p>
<p>//comboBoxStopBits.Items.Add(&#8220;1.5&#8243;); // not supported</p>
<p>comboBoxStopBits.Items.Add(&#8220;2&#8243;);</p>
<p>comboBoxBaud.Text = &#8220;19200&#8243;;</p>
<p>comboBoxParity.Text = &#8220;None&#8221;;</p>
<p>comboBoxDataBits.Text = &#8220;8&#8243;;</p>
<p>comboBoxStopBits.Text = &#8220;1&#8243;;</p>
<p>comboBoxHandshaking.Text = &#8220;None&#8221;;</p>
<p>}</p>
<p>· Note the word <strong><em><span style="text-decoration: underline;">‘</span></em></strong><strong><em><span style="text-decoration: underline;">wrap</span></em></strong><strong><em><span style="text-decoration: underline;">’</span></em></strong>. This means that the prior line of code was too long to display so it was wrapped to the next line for the book only and not wrapped for the actual source code. We will use this as a convention throughout this book. If you enter <strong><em><span style="text-decoration: underline;">‘</span></em></strong><strong><em><span style="text-decoration: underline;">wrap’</span></em></strong><strong><em><span style="text-decoration: underline;"> </span></em></strong>in your code, you’ll get an error. If you think I’m over-explaining this, you haven’t seen my email inbox.</p>
<p>· From the Settings Designer form click the Okay button and the Cancel buttons and then in the Settings text editor window add the following DialogResults to the functions:</p>
<p>· In C# add:</p>
<p>private void buttonOkay_Click(object sender, EventArgs e)</p>
<p>{</p>
<p>DialogResult = DialogResult.OK;</p>
<p>}</p>
<p>private void buttonCancel_Click(object sender, EventArgs e)</p>
<p>{</p>
<p>DialogResult = DialogResult.Cancel;</p>
<p>}</p>
<p>· These functions close the form and post the DialogResult message for the PortSettingsTest form, which called the Settings form.</p>
<p>· You may have noticed that in the source code in Workshop19.zip you will see #region and #endregion. The IDE uses #region and #endregion to show or hide code sections. When you click on the + or &#8211; to the left #region the code section collapses or expands. We use these to simplify the code visually making it easier to follow the overall code logic. Collapsing the regions looks like Figure 5: Regions.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0102.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image010_thumb2.jpg" border="0" alt="clip_image010" width="248" height="167" /></a></p>
<p>Figure 5: Regions</p>
<p>· Create data assessors and indexChanged functions by clicking the ‘SelectedIndexChanged’ event in the events section (lightning bolt) of the Properties window.</p>
<p>· In C# add:</p>
<p>#region Data Assessors</p>
<p>// Data assessors and index changed functions</p>
<p>// FT232R UART interface supporta</p>
<p>// 7 or 8 data bits</p>
<p>// 1 or 2 stop bits</p>
<p>// odd / even / mark / space / no parity.</p>
<p>// So these will be the only options available</p>
<p>#region Port Name</p>
<p>// Assessor for the selected port name</p>
<p>private string SelectedPort = &#8220;&#8221;;</p>
<p>public string selectedPort</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedPort;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedPort = value;</p>
<p>labelPort.Text = &#8220;Selected Port = &#8221; + SelectedPort;</p>
<p>}</p>
<p>}</p>
<p>#endregion</p>
<p>#region Baudrate</p>
<p>private int SelectedBaudrate;</p>
<p>public int selectedBaudrate</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedBaudrate;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedBaudrate = value;</p>
<p>comboBoxBaud.Text = value.ToString();</p>
<p>}</p>
<p>}</p>
<p>private void comboBoxBaud_SelectedIndexChanged(object sender, EventArgs e)</p>
<p>{</p>
<p>selectedBaudrate = <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>Convert.ToInt32(comboBoxBaud.Items[comboBoxBaud.SelectedIndex]);</p>
<p>}</p>
<p>#endregion</p>
<p>#region Parity</p>
<p>private Parity SelectedParity;// = Parity.None;</p>
<p>public Parity selectedParity</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedParity;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedParity = value;</p>
<p>comboBoxParity.Text = value.ToString();</p>
<p>}</p>
<p>}</p>
<p>private void comboBoxParity_SelectedIndexChanged(object sender, EventArgs e)</p>
<p>{</p>
<p>string temp = comboBoxParity.Items[comboBoxParity.SelectedIndex].ToString();</p>
<p>switch (temp)</p>
<p>{</p>
<p>case &#8220;Even&#8221;:</p>
<p>selectedParity = Parity.Even;</p>
<p>break;</p>
<p>case &#8220;Mark&#8221;:</p>
<p>selectedParity = Parity.Mark;</p>
<p>break;</p>
<p>case &#8220;None&#8221;:</p>
<p>selectedParity = Parity.None;</p>
<p>break;</p>
<p>case &#8220;Odd&#8221;:</p>
<p>selectedParity = Parity.Odd;</p>
<p>break;</p>
<p>case &#8220;Space&#8221;:</p>
<p>selectedParity = Parity.Space;</p>
<p>break;</p>
<p>default:</p>
<p>selectedParity = Parity.None;</p>
<p>break;</p>
<p>}</p>
<p>}</p>
<p>#endregion</p>
<p>#region StopBits</p>
<p>private StopBits SelectedStopBits = StopBits.One;</p>
<p>public StopBits selectedStopBits</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedStopBits;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedStopBits = value;</p>
<p>comboBoxStopBits.Text = value.ToString();</p>
<p>}</p>
<p>}</p>
<p>private void comboBoxStopBits_SelectedIndexChanged(object sender, EventArgs e)</p>
<p>{</p>
<p>string temp = <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>comboBoxStopBits.Items[comboBoxStopBits.SelectedIndex].ToString();</p>
<p>switch (temp)</p>
<p>{</p>
<p>case &#8220;None&#8221;:</p>
<p>selectedStopBits = StopBits.None;</p>
<p>break;</p>
<p>case &#8220;1&#8243;:</p>
<p>selectedStopBits = StopBits.One;</p>
<p>break;</p>
<p>//case &#8220;1.5&#8243;: // not supported by FT232R</p>
<p>//SelectedStopBits = StopBits.OnePointFive;</p>
<p>//break;</p>
<p>case &#8220;2&#8243;:</p>
<p>selectedStopBits = StopBits.Two;</p>
<p>break;</p>
<p>default:</p>
<p>selectedStopBits = StopBits.One;</p>
<p>break;</p>
<p>}</p>
<p>}</p>
<p>#endregion</p>
<p>#region DataBits</p>
<p>private int SelectedDataBits = 8;</p>
<p>public int selectedDataBits</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedDataBits;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedDataBits = value;</p>
<p>comboBoxDataBits.Text = value.ToString();</p>
<p>}</p>
<p>}</p>
<p>private void comboBoxDataBits_SelectedIndexChanged(object sender, EventArgs e)</p>
<p>{</p>
<p>if (comboBoxDataBits.SelectedIndex == 0) selectedDataBits = 7;</p>
<p>else selectedDataBits = 8;</p>
<p>}</p>
<p>#endregion</p>
<p>#region Handshaking</p>
<p>// We will only use None, Xon/Xoff, or Hardware (which is RTS/CTS)</p>
<p>private Handshake SelectedHandshaking = Handshake.None;</p>
<p>public Handshake selectedHandshaking</p>
<p>{</p>
<p>get</p>
<p>{</p>
<p>return SelectedHandshaking;</p>
<p>}</p>
<p>set</p>
<p>{</p>
<p>SelectedHandshaking = value;</p>
<p>comboBoxHandshaking.Text = value.ToString();</p>
<p>}</p>
<p>}</p>
<p>private void comboBoxHandshaking_SelectedIndexChanged(object sender, EventArgs e)</p>
<p>{</p>
<p>if (comboBoxHandshaking.SelectedIndex == 0) selectedHandshaking = <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>Handshake.None;</p>
<p>else if (comboBoxHandshaking.SelectedIndex == 1) selectedHandshaking = <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>Handshake.RequestToSend;</p>
<p>else if (comboBoxHandshaking.SelectedIndex == 2) <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>selectedHandshaking = Handshake.XOnXOff;</p>
<p>else selectedHandshaking = Handshake.None;</p>
<p>}</p>
<p>#endregion</p>
<p>· We will test the Settings dialog by displaying the data in the PortSetTest form.</p>
<p>· Open Form1 (PortSettingsTest) and add the following code.</p>
<p>· In C# add:</p>
<p>public partial class Form1 : Form</p>
<p>{</p>
<p>private string portname = &#8220;Not Initialized&#8221;;</p>
<p>private string baudrate = &#8220;Not Initialized&#8221;;</p>
<p>private string parity = &#8220;Not Initialized&#8221;;</p>
<p>private string stopbits = &#8220;Not Initialized&#8221;;</p>
<p>private string databits = &#8220;Not Initialized&#8221;;</p>
<p>private string handshaking = &#8220;Not Initialized&#8221;;</p>
<p>// Instantiate the PortSettings class</p>
<p>PortSettings p = new PortSettings();</p>
<p>public Form1()</p>
<p>{</p>
<p>InitializeComponent();</p>
<p>}</p>
<p>private void clearSettings()</p>
<p>{</p>
<p>portname = &#8220;&#8221;;</p>
<p>baudrate = &#8220;&#8221;;</p>
<p>databits = &#8220;&#8221;;</p>
<p>stopbits = &#8220;&#8221;;</p>
<p>parity = &#8220;&#8221;;</p>
<p>handshaking = &#8220;&#8221;;</p>
<p>}</p>
<p>private void buttonTest_Click(object sender, EventArgs e)</p>
<p>{</p>
<p>if (p.ShowDialog() == DialogResult.Cancel)</p>
<p>{</p>
<p>// clear out settings</p>
<p>clearLabels();</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>// set labels to Settings values</p>
<p>setLabels();</p>
<p>}</p>
<p>}</p>
<p>private void clearLabels()</p>
<p>{</p>
<p>labelPortName.Text = &#8220;PortName&#8221;;</p>
<p>labelBaudRate.Text = &#8220;BaudRate&#8221;;</p>
<p>labelParity.Text = &#8220;Parity&#8221;;</p>
<p>labelDataBits.Text = &#8220;DataBits&#8221;;</p>
<p>labelStopBits.Text = &#8220;StopBits&#8221;;</p>
<p>labelHandShaking.Text = &#8220;HandShaking&#8221;;</p>
<p>}</p>
<p>private void setLabels()</p>
<p>{</p>
<p>labelPortName.Text = &#8220;PortName: &#8221; + p.selectedPort;</p>
<p>labelBaudRate.Text = &#8220;BaudRate: &#8221; + p.selectedBaudrate.ToString();</p>
<p>labelParity.Text = &#8220;Parity: &#8221; + p.selectedParity.ToString();</p>
<p>labelDataBits.Text = &#8220;DataBits: &#8221; + p.selectedDataBits.ToString();</p>
<p>labelStopBits.Text = &#8220;StopBits: &#8221; + p.selectedStopBits.ToString();</p>
<p>labelHandShaking.Text = &#8220;HandShaking: &#8221; + <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>p.selectedHandshaking.ToString();</p>
<p>}</p>
<p>}</p>
<p>· In the IDE click the Debug menu and select the ‘start debugging’ item. You should see the blank PortSettingsTest form shown in Figure 1: PortSet Test.</p>
<p>· Click the Test button and you should see the Settings form as shown in Figure 6: Settings Test.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0122.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image012_thumb2.jpg" border="0" alt="clip_image012" width="184" height="248" /></a></p>
<p>Figure 6: Settings Test</p>
<p>· The actual port names will of course (barring a stunning coincidence) be different from those shown. By highlighting and selecting the items as shown and clicking Okay, the settings will propagate back to the PortSettingTest form as shown in Figure 7: Settings Test Result.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0142.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image014_thumb2.jpg" border="0" alt="clip_image014" width="152" height="136" /></a></p>
<p>Figure 7: Settings Test Result</p>
<p>We have covered a lot so far. In the last workshop we created a GUI for our Simple Terminal. Then in this workshop we created and tested a Settings form. You may be a bit tired of PC GUIs by now, and I have some good news. We will be able to use the Settings object in future projects by simply copying the source code to the new projects directory and using the Add/Existing Item technique shown above to get this object into our code. So the good news is: <strong>we never have to code this again!</strong> Now you see one of the values of object oriented programming. You can build and test a useful software object, then forget all about how it works and just use it like a black box.</p>
<h1><a name="_Toc247535842">The Serial Port Class</a></h1>
<p>You may have looked at some of the uses of the Serial Port Class in the source code for the Simple Terminal from Workshop 18. You may even have had one of those ‘what the…’ moments with some of the delegate stuff. Put simply, the code that is communicating with the serial port isn’t actually running with the code for the GUIs. This concerns ‘threads’ or bits of software that are running separately in Windows (each gets a part of each second to run so that all the threads seem like they are running at the same time to the user). When you want one thread to put stuff in another thread you set a delegate that the first thread can call from the second thread. So we have to create a delegate in our GUI that allows the serial port thread to set the text in our richTextBox. Yeah, its complex, but we don’t really have to go too deep at this point just to use the serial port. This is one of those cases where cookbook coding really comes in handy and you can safely just use the source code and move on till you have time to burn out a few more brain cells and learn the details. If you get to that point you might consider the book: Virtual Serial Port Cookbook available on both Nuts&amp;Volts and Smiley Micros.</p>
<p>Now that we have built and tested the portSettings class, lets add it to the GUI that we built last month and get our simple terminal communicating between the PC and the Arduino.</p>
<h1><a name="_Toc247535843">Bringing it all together</a></h1>
<p>In Workshop 18 we built the Simple Terminal GUI, now we want to add the portSettings stuff we just built so that we can make the GUI communicate using the serial port.</p>
<p>· Create a new Simple Terminal directory for your work and add these files:</p>
<ul>
<li>In C# from the PortSetTest C# directory copy:
<ul>
<li>Port Settings.cs</li>
<li>Port Settings.Designer.cs</li>
<li>Port Settings.resz</li>
<li>DevInfo.cs</li>
</ul>
</li>
<li>Then paste the files into your new directory.</li>
<li>Following the Add/Existing Items instructions given earlier, add Port Settings and DevInfo to the project.</li>
</ul>
<p>· In C# in the ‘using’ list add:</p>
<p>using PortSet;</p>
<p>Now that you have added the PortSettings and DevInfo Classes to your Simple Terminal project you are ready to use the .NET System.IO.Ports library that contains the SerialPort Class.</p>
<p>· Open the Form1 designer and from the Toolbox drag and drop serialPort1.</p>
<p>· We will set the serial port properties according to the data we enter in the Port Settings class.</p>
<p>· In C# add:</p>
<p>private void settingsToolStripMenuItem_Click(object sender, EventArgs e)</p>
<p>{</p>
<p>// Make sure the port isn&#8217;t already open</p>
<p>if (serialPort1.IsOpen)</p>
<p>{</p>
<p>MessageBox.Show(&#8220;The port must be closed before changing the settings.&#8221;);</p>
<p>return;</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>// creat an instance of the settings form</p>
<p>PortSettings settings = new PortSettings();</p>
<p>if (settings.ShowDialog() == DialogResult.OK)</p>
<p>{</p>
<p>if (settings.selectedPort != &#8220;&#8221;)</p>
<p>{</p>
<p>// set the serial port to the new settings</p>
<p>serialPort1.PortName = settings.selectedPort;</p>
<p>serialPort1.BaudRate = settings.selectedBaudrate;</p>
<p>serialPort1.DataBits = settings.selectedDataBits;</p>
<p>serialPort1.Parity = settings.selectedParity;</p>
<p>serialPort1.StopBits = settings.selectedStopBits;</p>
<p>// show the new settings in the form text line</p>
<p>showSettings();</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>MessageBox.Show(&#8220;Error: Settings form returned with <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>no Serial port selected.&#8221;);</p>
<p>return; // bail out</p>
<p>}</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>MessageBox.Show(&#8220;Error: buttonSetup_Click &#8211; Settings <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>dialog box did not return Okay.&#8221;);</p>
<p>return; // bail out</p>
<p>}</p>
<p>// open the port</p>
<p>try</p>
<p>{</p>
<p>serialPort1.Close();</p>
<p>serialPort1.Open();</p>
<p>menuStrip1.Items[1].Text = &#8220;Close Port&#8221;;</p>
<p>showSettings();</p>
<p>}</p>
<p>catch (System.Exception ex)</p>
<p>{</p>
<p>MessageBox.Show(&#8220;Error &#8211; setupToolStripMenuItem_Click <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>Exception: &#8221; + ex);</p>
<p>}</p>
<p>}</p>
<p>}</p>
<p>// show the settings in the form text line</p>
<p>private void showSettings()</p>
<p>{</p>
<p>this.Text = &#8220;Smiley Micros &#8211; &#8221; +</p>
<p>serialPort1.PortName + &#8221; &#8221; +</p>
<p>serialPort1.BaudRate.ToString() + &#8220;,&#8221; +</p>
<p>serialPort1.Parity + &#8220;,&#8221; +</p>
<p>serialPort1.DataBits.ToString() + &#8220;,&#8221; +</p>
<p>serialPort1.StopBits;</p>
<p>if (serialPort1.IsOpen)</p>
<p>{</p>
<p>this.Text += &#8221; &#8211; Port is open&#8221;;</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>this.Text += &#8221; &#8211; Port is closed&#8221;;</p>
<p>}</p>
<p>}</p>
<p>· In the form designer click on the ‘Open Port’ menu item.</p>
<p>· In C# add:</p>
<p><code>private void openPortToolStripMenuItem_Click(object sender, EventArgs e)</code></p>
<p><code>{</code></p>
<p><code>try</code></p>
<p><code>{</code></p>
<p><code>if (serialPort1.IsOpen)</p>
<p>{</p>
<p>serialPort1.Close();</p>
<p>openPortToolStripMenuItem.Text = "Open Port";</p>
<p>}</p>
<p>else</p>
<p>{</p>
<p>serialPort1.Open();</p>
<p>openPortToolStripMenuItem.Text = "Close Port";</p>
<p>}</p>
<p>showSettings();</p>
<p>}</p>
<p>catch (System.Exception ex)</p>
<p>{</p>
<p>MessageBox.Show("Error - openPortToolStripMenuItem_Click Exception: <strong><em><span style="text-decoration: underline;">wrap</span></em></strong></p>
<p>" + ex);</p>
<p>}</p>
<p>}</p>
<p>· In the form designer select the richTextBoxSend component.</p>
<p>· In the properties window click the ‘KeyPress’ event and to the event handler created in C# add:</p>
<p>private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)</p>
<p>{</p>
<p>sendChar(e.KeyChar);</p>
<p>}</p>
<p>private void sendChar(char c)</p>
<p>{</p>
<p>char[] data = new Char[1];</p>
<p>data[0] = c;</p>
<p>try</p>
<p>{</p>
<p>serialPort1.Write(data, 0, 1);</p>
<p>}</p>
<p>catch</p>
<p>{</p>
<p>MessageBox.Show("Error: sendByte - failed to send.\nIs the port open?");</p>
<p>}</p>
<p>}</p>
<p>· Our receive functions use a delegate to allow the serial port read thread to write to our receive text box. This is a bit complex, so for the time being just use it as-is.</p>
<p>· In C# add:</p>
<p>#region receive functions</p>
<p>// We want to have the serial port thread report back data received, but to</p>
<p>// display that data we must create a delegate function to show the data in the</p>
<p>// richTextBox</p>
<p>// define the delegate</p>
<p>public delegate void SetText();</p>
<p>// define an instance of the delegate</p>
<p>SetText setText;</p>
<p>// create a string that will be loaded with the data received from the port</p>
<p>public string str = “”;</p>
<p>// note that this function runs in a separate thread and thus we must use a</p>
<p>// delegate in order to display the results in the richTextBox.</p>
<p>private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)</p>
<p>{</p>
<p>// instantiate the delegate to be invoked by this thread</p>
<p>setText = new SetText(mySetText);</p>
<p>// load the data into the string</p>
<p>try</p>
<p>{</p>
<p>str = serialPort1.ReadExisting();</p>
<p>}</p>
<p>catch (System.Exception ex)</p>
<p>{</p>
<p>MessageBox.Show(“Error – port_DataReceived Exception: “ + ex);</p>
<p>}</p>
<p>// invoke the delegate in the MainForm thread</p>
<p>this.Invoke(setText);</p>
<p>}</p>
<p>// create the instance of the delegate to be used to write the received data to</p>
<p>// the richTextBox</p>
<p>public void mySetText()</p>
<p>{</p>
<p>// show the text</p>
<p>richTextBox2.Text += str.ToString();</p>
<p>moveCaretToEnd();</p>
<p>}</p>
<p>// This rigaramole is needed to keep the last received item displayed</p>
<p>private void richTextBoxReceive_TextChanged(object sender, System.EventArgs e)</p>
<p>{</p>
<p>moveCaretToEnd();</p>
<p>}</p>
<p>private void moveCaretToEnd()</p>
<p>{</p>
<p>richTextBox1.SelectionStart = richTextBox1.Text.Length;</p>
<p>richTextBox1.SelectionLength = 0;</p>
<p>richTextBox1.ScrollToCaret();</p>
<p>}</p>
<p></code></p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p><code>#endregion</code></p>
<p>And that will give you a working terminal program. For more details you might want to look at the free first six chapters of the <em>Virtual Serial Port Cookbook</em>. You can get that book and hardware projects kit from both Nuts&amp;Volts and Smiley Micros. Next month we will use this code to create an Arduino Volt Meter that shows ADC data on the PC monitor.</p>
<h1><a name="_Toc247535844">The Arduino Projects Kit:</a></h1>
<p>Smiley Micros and Nuts&amp;Volts are selling a special kit: The Arduino Projects Kit. Beginning with Workshops 9 we started learning simple ways to use these components, and in later Workshops we will use them to drill down into the deeper concepts of C programming, AVR microcontroller architecture, and embedded systems principles.</p>
<p><strong>With the components in this kit you can:</strong><br />
· Blink 8 LEDs (Cylon Eyes)<br />
· Read a pushbutton and 8-bit DIP switch<br />
· Sense Voltage, Light, and Temperature<br />
· Make Music on a piezo element<br />
· Sense edges and gray levels<br />
· Optically isolate voltages<br />
· Fade LED with PWM<br />
· Control Motor Speed<br />
· And more…</p>
<p>NOTE: the code is improperly formatted in this blog so I suggest you skim over it and look at the code in the file: <a href="/download/Workshop 19 Source Code.zip">Workshop 19</a></p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/06/10/serial-communications-part-2-a-simple-terminal-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Serial Communications Part 3 &#8211; Arduino Volt Meter And FT232R</title>
		<link>http://smileymicros.com/blog/2011/06/10/serial-communications-part-3-arduino-volt-meter-and-ft232r/</link>
		<comments>http://smileymicros.com/blog/2011/06/10/serial-communications-part-3-arduino-volt-meter-and-ft232r/#comments</comments>
		<pubDate>Fri, 10 Jun 2011 16:17:14 +0000</pubDate>
		<dc:creator>joepardue</dc:creator>
				<category><![CDATA[arduino]]></category>
		<category><![CDATA[avrtoolbox]]></category>
		<category><![CDATA[C sharp dot net]]></category>
		<category><![CDATA[FT232R]]></category>
		<category><![CDATA[FTDI]]></category>
		<category><![CDATA[USB]]></category>

		<guid isPermaLink="false">http://smileymicros.com/blog/?p=1093</guid>
		<description><![CDATA[Smiley’s Workshop 20: Serial Communications Part 3 Joe Pardue January 18, 2010 Figure 1: Arduino Volt Meter Recap This is the third and last part of our mini-series on serial communications between a PC and the Arduino. We will do &#8230; <a href="http://smileymicros.com/blog/2011/06/10/serial-communications-part-3-arduino-volt-meter-and-ft232r/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<h1>Smiley’s Workshop 20: Serial Communications Part 3</h1>
<h3>Joe Pardue January 18, 2010</h3>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00241.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image002[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0024_thumb1.jpg" border="0" alt="clip_image002[4]" width="248" height="225" /></a></p>
<p>Figure 1: Arduino Volt Meter</p>
<h1><a name="_Toc250218106">Recap</a></h1>
<p>This is the third and last part of our mini-series on serial communications between a PC and the Arduino. We will do two things this month. First we will use what we learned in the last two articles about C# .NET programming to build an Arduino Volt Meter that displays ADC data on the PC. Second we will introduce the FT232R device that the Arduino board uses to mediate serial communications. For this device we will learn how to use some of the extra FT232R pins, and we’ll look at how the Arduino uses this device to automatically reset the board.</p>
<p><strong><br />
</strong></p>
<h1><a name="_Toc250218107">Arduino Volt Meter</a></h1>
<h2><a name="_Toc250218108">Using the Arduino Volt Meter</a></h2>
<p>A word of warning for those who think running with scissors is a good idea. The Arduino Volt Meter hooks directly to the Arduino analog input pin0, which can measure up to 5 volts. <strong>THIS CIRCUIT IS NOT PROTECTED IN ANY WAY</strong>. It will not forgive your doing something stupid like trying to measure the voltage in the wall socket. If you survive such a Darwinian experiment, your hardware won’t and that could include the PC you’ve got your Arduino hooked up to (most USB ports are protected, but you can never be absolutely certain).</p>
<h3>The Arduino Software</h3>
<p>The Arduino Volt Meter running on the PC (shown in Figure 1) is communicating with the following AVR_Test program running on the Arduino:</p>
<pre><code>
// AVM_Test
// Joe Pardue December 17, 2009
// based on Tom Igoe's example in the
// Arduino Serial.print(data) documentation

void setup()
{
  // begin the serial communication
  Serial.begin(19200);
}

// variable to hold the analog input value
int analogValue = 0; 

void loop()
{
  // read the analog input on pin 0
  analogValue = analogRead(0);   

  // print as an ASCII-encoded decimal
  Serial.print(analogValue, DEC);

  // print a terminal newline character so the AVR Voltmeter
  // will know that it has received the full string
  Serial.print('\n');

  // delay 1 second before the next reading:
  delay(1000);
}</code></pre>
<h3>The PC Software</h3>
<p>The Arduino Volt Meter (AVM) source code in C# is provided in Workshop20Source.zip and requires Visual Studio Express .NET to open and run it. [This can be downloaded from the Nuts&amp;Volts or Smiley Micros website.]</p>
<p>The program is built from many of the components used for the Simple Terminal discussed last month. You access the Arduino by clicking the ‘Select Device’ menu item, which then opens the Settings dialog as shown in Figure 2.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00441.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image004[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0044_thumb1.jpg" border="0" alt="clip_image004[4]" width="248" height="238" /></a></p>
<p>Figure 2: Select your Arduino</p>
<p>The AVM uses the .NET Serial Port control Readline() function that returns a string, which is defined as a sequence of characters terminated by the ‘\n’ character. The Arduino sends the ADC value and then a ‘\n’ character as shown in the source code so that the AVM will interpret the input as a string. The AVM will then display the ADC value in the lower text window and convert that value into a voltage that it displays as a big fake red LED display in the upper window. The voltage is calculated from the ADC value using:</p>
<pre><code>
// Calculate volts
myVolts = ((Double)myADC * VoltsPerADC);
</code></pre>
<p><code> </code><br />
Based on the constants:</p>
<pre><code>
static Double maxVoltage = 5.0;
static Double maxADC = 1023.0;
Double VoltsPerADC = maxVoltage / maxADC;
</code></pre>
<p><code> </code></p>
<p>&nbsp;</p>
<h2><a name="_Toc240367180"></a><a name="_Toc242871823"></a><a name="_Toc250218109">Voltage across resistance</a></h2>
<p>Let’s use this with a circuit and play with Ohm’s Law. We put 10 of the 1K ? from the Arduino Projects Kit on the breadboard so that they are each connected in series and then connect one end of that series to +5V and the other end to the GND as shown in Figure 3: Schematic &#8211; resistors in series, and Figure 4: Layout &#8211; resistors in series. [This arrangement of resistors is called a voltage divider.] The Figures 3 and 4 show the Arduino Analog Input pin 0 attached between the third and fourth resistors closest to the +5V end.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00641.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image006[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0064_thumb1.jpg" border="0" alt="clip_image006[4]" width="220" height="248" /></a></p>
<p>Figure 3: Schematic &#8211; resistors in series</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image00841.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image008[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0084_thumb1.jpg" border="0" alt="clip_image008[4]" width="26" height="29" /></a></p>
<p>Figure 4: Layout- resistors in series</p>
<p>We know that Ohm’s law is Voltage (V) is equal to Current (I) times Resistance (R):</p>
<p>V = IR</p>
<p>(And if ‘<strong>we</strong>’ don’t know this already, then take my word for it.) We also know that we have 5 volts and a total of 10k ? resistance in our circuit, so we can use a little beginning algebra to calculate the unknown variable, current (I):</p>
<p>I = V/R</p>
<p>I = 5/10000 = 0.0005 Amps</p>
<p>0.0005 Amps is the same as 0.5 milliAmps which we will usually show as 0.5mA. So we have 0.5mA current running through each of the 10 resistors and since each resistor is 1k ? and we can solve Ohm’s Law for the voltage across each resistor:</p>
<p>V = IR</p>
<p>V = 0.0005 * 1000 = 0.5 Volts</p>
<p>So, theoretically, we should be able to measure the voltage between the seventh and eighth resistor above 0V and it should conform to Ohm’s Law where the total resistance of the 7 resistors is 7k ?:</p>
<p>V = IR</p>
<p>V = 0.0005 * 7000 = 3.5 Volts</p>
<p>I ran the Arduino Voltmeter as shown in Figure 1 and got 3.47 volts.</p>
<p>Okay, 3.47 isn’t equal to 3.5, but it is about as close as we can expect with a set up like this. Our resistors only claim 5% accuracy so each one can be plus or minus 50 ? and, again using Ohm’s Law we see:</p>
<p>R = V/I</p>
<p>R = 3.47/0.0005 = 6940 ?</p>
<p>And 6940 is actually pretty darn close since 5% of 7000 ? is 350 ?, our theoretical error, but we are only 60 ? off. Your results will vary a bit but should be within a similar range.</p>
<h4><a name="_Toc250218110">Building the Arduino Voltmeter in C# Express .NET</a></h4>
<p>By this point in your PC-serial-GUI-development-using-C# career, and assuming you built the last two months projects, you should be able to build the Arduino Volt Meter GUI just by looking at Figure 1: Arduino Volt Meter and winging it. You may not have seen such things as how to make the textbox text white and the background black, but you should be familiar enough with our chosen tool that can figure this out for yourself, especially since you have the original source code to look at. And if you think I just threw you into the deep end, well… okay I did, so start swimming, because in the next section we are going to go off the high board.</p>
<p><strong><br />
</strong></p>
<h1><a name="_Toc250218111">Introducing the FT232R</a></h1>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01041.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image010[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0104_thumb1.jpg" border="0" alt="clip_image010[4]" width="244" height="182" /></a></p>
<p>Figure 5: FT232R on the Arduino Duemilanove</p>
<p><a name="_Toc248138761"></a></p>
<p>As we’ve seen, the Arduino is not a single thing but a toolset that consists of, among other things: a hardware board, a PC IDE (Integrated Development Environment), and a communications link between them. Now let’s take a look at the communications hardware that intermediates between the USB on the PC and the USART on the Arduino: the FTDI FT232R.</p>
<p>After all this time playing with the Arduino hardware, you might not realize that the Duemilanove board has two microcontrollers on it. In addition to the general-purpose Atmel AVR ATmega328 that we’ve spending all our time on, there is a special-purpose FTDI FT232R USB UART IC (http://www.ftdichip.com/Products/FT232R.htm) that controls our serial communications between the Arduino and the PC, see Figure 5: FT232R on the Arduino Duemilanove.</p>
<p>I first discussed the FT232R in Nuts and Volts (before there even was a Smiley’s Workshop) in the article: ‘<em>The Serial Port is Dead: Long Live the Serial Port</em>’. That article discussed the concept of a Virtual Serial Port over USB, using the FTDI chip FT232R on a breadboardable PCB, the BBUSB. This powerful little device is also the basis for the book: <em>The Virtual Serial Port Cookbook</em> and an associated hardware projects kit available from the Smiley Micros web shop. The pins on the FT232R have at least two possible uses for each pin. Eight of the pins can be used as modem lines for converting USB to RS232 style UART signals; these pins can also be used for GPIO (General Purpose Input Output) as the 8-pin DBus. Four other pins can be used as the CBus or for special functions such as to blink LEDs when you have UART traffic as is done on the Arduino to blink the Tx and Rx LEDs. We will look at using some of the more accessible FT232R pins in both the modem and GPIO modes.</p>
<p>Let me repeat some praise about the Arduino: it is a really good thing for beginners that you can use it without knowing anything about the FT232R (or bootloaders, or WinAVR, or AVRDude for that matter). We however are well beyond that beginner phase and are going deeper so that we can make our system even more useful. In addition to the USB pins, there are five other pins of the FT232R that the Arduino uses when communicating with the PC, they are pin 1 TXD (transmit), pin 5 RXD (receive), pin 22 and 23 to blink the Tx and Rx LEDs, and pin 2 DTR (Data Terminal Ready). (See Figure 8: FT232RL in Arduino Schematic.) That last one may be a bit of a surprise, but it is used off-label to reset the Arduino so that you can automatically upload code from the Arduino IDE to the AVR. The DTR pin resets the AVR so that the bootloader becomes active at the same time that the Arduino IDE activates the program AVRDude to upload the code.</p>
<p>Okay, so why is it called DTR and not ‘reset’? Well, that is because it is actually one of 8 modem pins on the FT232R that are part of the concept of a virtual ‘RS232’ serial port from a USB. Many serial ports on microcontrollers ignore all but two of these (RxD and TxD) and a few use a couple of other pins, but it is rare to find any system that uses them all – so you’ll usually have extra pins to play with. If you read ‘The Serial Port is Dead…’ article this will all make more sense, for now, let’s just say that DTR has a long and interesting history but for our purposes it is a pin that we can use in the modem mode to toggle from the PC using old fashioned serial port commands (in our C# example we set this pin to 1 with serialPort1.DtrEnable = true; and to 0 with serialPort1.DtrEnable = false;)and thus provide a signal to the AVR reset pin that will force the AVR to jump to the bootloader so that we can upload a program.</p>
<p>There are also other modem pins (see Figure 6: FT232R pins on the Arduino) available on the FT232R that, with a little effort, you can get at on the Arduino board. Four of these are easy to use since they are brought out on the X3 connector shown in Figure 5. A table of these pins is shown in Figure 6: FT232R pins on the Arduino. [And FYI the pinouts for the FT232RL used by the Arduino are different from those shown in the article ‘The Serial Port is Dead…’ which uses the FT232RQ.]</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01241.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image012[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0124_thumb1.jpg" border="0" alt="clip_image012[4]" width="248" height="104" /></a></p>
<p>Figure 6: FT232R pins on the Arduino</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image01441.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image014[4]" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0144_thumb1.jpg" border="0" alt="clip_image014[4]" width="239" height="248" /></a></p>
<p>Figure 7: FT232RL pins</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0161.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image016" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image016_thumb1.jpg" border="0" alt="clip_image016" width="248" height="181" /></a></p>
<p>Figure 8: FT232RL in Arduino Schematic</p>
<p>In case this isn’t entirely clear, let me repeat: we can use some of the FT232R pins in the modem mode for off-label uses such as using DTR for resetting the Arduino, or we can use the pins for general purpose I/O. When we use them in the modem mode to communicate between the PC and the Arduino they can only be used for input or output as shown in the table, but when used in the bus mode they can be used as either input or output (but not serial communications). NOTE: YOU CAN’T USE BOTH THE MODEM AND BIT-BANG MODES AT THE SAME TIME.</p>
<h2><a name="_Toc250218112">Accessing the FT232R pins</a></h2>
<p>Before proceeding with these experiments, I strongly suggest you remove the ATmega328 from its socket to protect it from possible damage (use a small flathead screw driver and gently pry it up a little on each end until it pops out). All of the FT232R pins can be accessed the hard way by directly attaching wires to the FT232R pins (tiny wire, microscope, fine-tipped soldering iron, patience of Job (not Steve, but the Old Testament guy)). Since we aren’t either Job, I suggest we forgo the temptation and limit ourselves to probing the pins individually as we test them. We can probe the FT232R pins using the schematic shown in Figure 9: Circuit to probe input and output. And by probe, I mean a random piece of wire as shown in Figure 10, where I use the RTS output to light up and LED.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0181.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image018" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image018_thumb1.jpg" border="0" alt="clip_image018" width="244" height="242" /></a></p>
<p>Figure 9: Circuit to probe input and output</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0201.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image020" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image020_thumb1.jpg" border="0" alt="clip_image020" width="173" height="248" /></a></p>
<p>Figure 10: Wire to RTS controls LED</p>
<h3><a name="_Toc250218113">Modem Mode</a></h3>
<h4>Using the Pin Change Tester Application</h4>
<p>In order to light up that LED, you’ll need some PC-side software that lets you set and clear the RTS line. I wrote a little program in C# as shown in Figure 11 that lets you toggle the output on RTS and DTR while also reading the input on the CTS, DSR, DCD, and RI lines. You will find the Pin Change Tester C# source code in the Workshop20Source.zip file. I didn’t generate this as a separate application so you will have to run it in Microsoft Visual C# Express Edition which is okay since you want to see the code anyway don’t you? Plug your Arduino into the PC USB port, then run the Pin Change Tester program. Using the Settings menu item to open the port as shown last month for the Simple Terminal.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0221.jpg"><img style="background-image: none; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image022" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image022_thumb1.jpg" border="0" alt="clip_image022" width="248" height="144" /></a></p>
<p>Figure 11: Pin Change Test: click RTS to turn LED on or off</p>
<h3><a name="_Toc250218114">Bit-bang Mode</a></h3>
<p>To test the FT232R pins in the bit-bang mode we will use a program that was shown in ‘The Serial Port is Dead…’ article, the Bit-bang Test. The C# source code is include in Workshop20Source.zip file, again not as an application but as a project that you can open in Visual Studio .NET Express. You can repeat the probe tests you did above, but this time each pin is not forced to be either input or output but can be used as either depending on how you set the pin in the D Bus block on the program. Click the button as shown in Figure 12 to set each pin as either input or output. If you select input then the associated LED at the bottom will become active and either light up or dim down depending on the state it is reading. If you set it for output then you can click on the on/off buttons in the middle row to turn the associated pin on or off allowing you to use your probe as shown in Figure 10 to light up an external LED. Also notice that the D0 and D1 pins are the same as the TX and RX and are brought out on the Arduino female header pins 0 and 1, so these are the easiest to access.</p>
<p><a href="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image0241.jpg"><img style="background-image: none; padding-left: 0px; padding-right: 0px; display: inline; padding-top: 0px; border: 0px;" title="clip_image024" src="http://smileymicros.com/blog/wp-content/uploads/2011/06/clip_image024_thumb1.jpg" border="0" alt="clip_image024" width="248" height="152" /></a></p>
<p>Figure 12: Bit-bang Test</p>
<p>COOL! I just got my first Vista BSOD (Blue Screen Of Death). I was running the Bit-Bang test code and then tried to open the same device in Developer Terminal JUST TO SEE WHAT WOULD HAPPEN. Now I know that my laptop with dozens of programs open can burn all the way down to the foundations and with a simple restart &#8211; it can survive. However, &gt;I&lt; almost didn’t, when my system crashed I’m sure my blood pressure went off the charts while I was waiting to see how much work I’d lost. End of story: I’d saved everything right before I did the tests with my C# programs because I had a slight fear that maybe the idiot who wrote the code (&gt;me&lt;) might try something dangerously stupid. Moral: before using any of &gt;my&lt; code make sure &gt;you&lt; have backed everything up, saved your recent work, have your heart medications handy, and have the time to wait for Windows to figure out how to come back from the dead.</p>
<p>Okay, having a BSOD is a terrible way to end a workshop, but sometimes you have to face the fact that this stuff can get weird quickly. If, however, you have come to embrace the weirdness and want to look deeper then you might want to get the Arduino Projects Kit and <em>The Virtual Serial Port Cookbook </em>and associated projects kit available from the Smiley Micros webshop.</p>
<p>Source Code: <a href="/download/Workshop 20 Source Code.zip">Workshop 20</a></p>
]]></content:encoded>
			<wfw:commentRss>http://smileymicros.com/blog/2011/06/10/serial-communications-part-3-arduino-volt-meter-and-ft232r/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

