Monday, July 7, 2014

#7 Jeremy Blum Video: Arduino And Processing Sketches

Today’s blog post takes a look at some of the programming concepts used in the #7 Jeremy Blum ‘Arduino tutorial series’ video.
#7 video exercise Arduino circuitry

The Arduino exercise in the #7 video uses a Microchip Technology TC74A0-5.0VAT temperature sensor to acquire temperature data and display it on the computer to which your Arduino circuitry is connected. To do these two tasks, you’ll need two programs. An Arduino program will be used to grab and transmit the temperature data. Then a Processing program will be used to take that temperature data and display it in the specified font on your computer’s monitor.

The Arduino program Jeremy wrote is called read_temp.pde. He makes the programs for the video tutorial series available online, but you’ll gain a lot more skill with Arduinos if you type the programs yourself rather than downloading them, at least while you’re learning new programming concepts. Arduino.cc explains the .pde files from the Arduino IDE (Integrated Development Environment) this way:
“The Arduino environment uses the concept of a sketchbook: a standard place to store your programs (or sketches)...Beginning with version 1.0, files are saved with a .ino file extension. Previous versions use the .pde extension. You may still open .pde named files in version 1.0 and later, the software will automatically rename the extension to .ino.”
So the reason Jeremy’s read_temp Arduino file is has a .pde extension instead of .ino is because the video is a couple years old, and he was using an earlier version of the Arduino IDE. The current IDE version is 1.0.5, with the Beta version being at 1.5.7. The .pde file extension (Processing Development Environment) is the one used by the Processing, Wiring and early-version Arduino IDEs. Processing is often used as an educational tool to teach foundational programming skills in a visual environment and is Java based rather than C.

To have the Arduino get the temperature data from the Microchip sensor, which is done with read_temp.pde, Jeremy starts out by importing the I2C library. For Arduino this is the Wire library. Importing the Wire library is done with the command:

#include <Wire.h>

Next you set the I2C temperature address. For the sensor he used, the I2C address ID was 72, per the #6 video.

int temp_address = 72;

In the setup section for the sketch, you have to start the serial communication and initialize the Arduino listening on I2C communication bus, using:

Serial.begin(9600);
Wire.begin();

The loop section of the sketch has the components shown below. I won’t write out all the code here -- when you go through the exercise, you’ll get a chance to learn what’s needed to accomplish each task shown in the list of loop section comments below.

//Send a request
//Start talking
//Ask for Register zero
//Complete transmission
//Request 1 byte
//Wait for response
//Get the temperature
//Convert from Celsius to Fahrenheit
//Print the results
//Delay, then do it again

Warming temperature sensor; terminal window temperature display
After the above steps are all written for the Arduino sketch, you upload it to your Arduino. Following a successful upload of the Arduino sketch, you’ll see the current temperature of the sensor displayed in a terminal window. Jeremy then puts his finger and thumb over the sensor to confirm that the sensor can measure the difference between the room air and Jeremy's skin temperature. To get a temperature display other than just in the terminal window, you need to write a Processing sketch. This will display on your computer monitor the temperature results generated by the temperature sensor circuitry and the Arduino sketch. The Processing file Jeremy wrote to display the temperature on the computer’s monitor is display_temp.pde.

Associated with display_temp.pde is the .vlw file AgencyFB-Bold-200.vlw. The .vlw file type is a font file created by the Processing language. Processing will create the .vlw data file for a font that’s on your computer system when you use the Tools / Create Font command. After you create the data file you can use it in your Arduino / Processing program with the loadFont() function. If you want to dig into the loadFont() function in Processing, two resources are the relevant Processing reference webpage and a tutorial from Purchase College.
Creating a font in Processing

Start out by selecting Tools / Create Font in the Processing sketch window. Select one of the font styles shown in the Create Font window. Next, select the font size you want to use. Jeremy selects 200 for the size so it will create a large font on the computer monitor. When you click OK in the Create Font window, it will create a .vlw file for the specified size font.

Next, write the initial components of the code shown on the video, including things like defining the variables for the program, then do the setup and draw sections of the sketch. After the initial components of the sketch are written, you setup the ‘canvas’ where you’ll display the font, using the command:

size (400, 400);

After setting up the canvas, set up the serial port, using the command:

port = new Serial(this, “COM3”, 9600);

Once the serial port is set up, you tell it to keep looking for information until it gets to the end, which has been defined by a period. You tell it to look for that info with the command:

port.bufferUntil(‘.’);

Next, set up the font, specifying the .vlw file that you created earlier, using the commands:

font = loadFont(“AgencyFB-Bold-200.vlw”);
textFont (font, 200);

I think the 200 is optional in the second line, since the .vlw file specified already defines that it’s a 200 point font. I don’t know if you can use a non-sized font file in the loadFont function, such as AgencyFB-Bold.vlw, then specify the size in the textFont function. Haven’t had time to dig into that Processing function yet; maybe a blog post reader can point out where the Processing.org website explains that, or I might research it in the future. For now, I’ll just type it the way Jeremy did.

Next, write the commands for the draw section of the sketch, which tells the computer what characters to display on the monitor. Do this with the background, fill and text commands. Per the discussions in the recent blog post, “#7 Jeremy Blum Video: I2C And Processing,” you’ll have to use an RGB color chart or list to specify what color you want the background and the text. You also have to specify which variable strings (temperature labels to go with the temperature data) the Processing sketch should ‘draw.’

Now write the serialEvent section of the sketch to grab the temperature data off the serial port, then use a substring command to reformat the information by removing the period at the end, using the commands:

data = port.readStringUntil(‘.’);
data = data.substring(0, data.length() - 1);

Next you write the code for finding the comma in the string, for fetching the Celsius data and Fahrenheit data (as shown in the video).

Once you’re done writing the Processing sketch as described above, click on the Run icon in the Processing sketch window and your computer should display the temperature currently being
measured by the Microchip temperature sensor, as captured and transmitted by your Arduino. If it doesn’t display the temperature, review your code versus what Jeremy shows in the video and make any needed changes in your code so it matches his code. Good luck on not needing any debugging!

Hope to see you at the July 10th meeting for the Humboldt Microcontrollers Group, 6 - 8 PM at 1385 8th Street, Arcata, California. The main topic for the meeting is discussing the I2C and Processing concepts used in the above temperature sensing exercise, as well as any problems people had with the exercise, and maybe some interesting I2C, Processing, or temperature sensing tips and tricks people know of or discovered in the past two weeks.

**********

Sunday, July 6, 2014

The United States of America just celebrated Independence Day -- the 4th of July. In honor of that, I decided to take a look at microcontrollers (MCUs) involved in that celebration, which
primarily seems to involve MCU fireworks launchers.

One good reason to build a reliable MCU fireworks launcher is safety. Every year at least a few people get hurt when they light fireworks, sometimes losing a finger or suffering even worse injuries. MCUs can be used to build complex fireworks launchers, but even a simple launcher that safely lights off one firework at a time would be worth building. A simple electronic launcher for fireworks doesn't need an MCU to be safe and effective, but it makes it more fun and interesting to build.

If you want to build a slightly complex launcher, my recommendation is that you first look at the SparkFun "Firework Igniter" project. If that isn't quite what you're looking for, two more possibilities to check out are the "Microcontroller Launcher" by Adam Melton, which was featured on Hackaday, and the "DIY wireless firework control" at tuckie.net. For someone not satisfied with those three choices of MCU projects, the next step would probably be to spend time on the pyrotechnic forums. You'd likely be able to connect with someone who knows of one or more people who have built their own fireworks launchers.
SparkFun Firework Igniter

The SparkFun project would probably be my choice for a fireworks launcher starter system. The author put enough detail in the write-up that you wouldn't have to figure everything out on your own, but his design isn't so complex that you'll break the bank or have to do a lot of case building and modding. Some of the cases for the launchers are pretty elaborate. You might end up doing quite a bit of work just to have a suitable case for the electronics you've put together. Putting a lot of work into the case would be worth it if you knew exactly how you wanted the launcher to work and you knew the electronic circuit design would work the way you designed it. But if you're building your first launcher, it would be good to get at least one 4th of July under your belt with a launcher you built before working on a deluxe 16 or 32 station fire control system.
Adam Melton Launcher

If you absolutely know you want a more visually impressive system than the SparkFun one, the 16 station unit like Adam Melton's project might be a good choice. He found a case that worked for his design by going with a Plano waterproof case from Academy Sports. The case and electronics for the DIY wireless fire control system at tuckie.net is even more elaborate -- see the picture to the left below. My overall point is that when you're figuring out how much time and money you'll spend building your launcher, make sure you take into account the case you'll need for the electronics you put together.
Tuckie.net Launcher

Although a fairly simple fireworks launcher might be your first 4th of July MCU project, as the Internet of Things drives the production of MCUs up and the cost of them down, there will no doubt be some spectacular and interesting fireworks displays that use MCUs to create new and impressive visual effects. The BetaNews article about a Chinese artist embedding microchips in 'smart fireworks' shows one new use for MCUs in fireworks. According to the article,
MCU Fireworks by Cai Guo-Qiang
"At the Arab Museum of Modern Art in Doha, Qatar this week, Chinese artist Cai Guo-Qiang put on his largest "explosion event" of the last three years, utilizing microchip-controlled explosives to form incredible designs and patterns. The video we've embedded of the event is an impressive testament to how a volatile black powder explosion can be controlled and shaped by computer. Each set of explosions was calculated to paint a different picture. One series of explosions created black smoke clouds that looked like "drops of ink splattered across the sky." In another, 8,300 shells embedded with computer microchips exploded in a pyramid shape over the desert...In 2001, Cai began developing a technique to use microcontrollers to more accurately time his explosions. Fireworks are typically ignited by a fuse, and the delay of the explosion is simply determined by the length of that fuse. However, this is an extremely imprecise science due to the variation in fuses and construction of fireworks."
The video in the BetaNews article is worth watching to see how the MCUs are used.

I hope your 4th of July was safe and enjoyable!

**********

Saturday, July 5, 2014

A Yarn About Microcontrollers And Textile Projects

Yesterday’s post on this blog was about the Tetris Shirt, a textile computing project. Today’s post will follow up on that topic with a couple related ideas and articles.
Conductive yarn

First up is the primary focus of the post -- ‘smart' yarn. A few days ago I read a Wired article titled "This Smart Yarn Makes Gadget Interactions Magical." The article discusses a relatively unique approach to textile computing projects. This novel type of yarn combines conductive steel fiber and non-conductive yarn fiber.
"A new project from Royal College of Art student Yen Chen Chang explores what happens when you replace glass, metal and plastic with textile control mechanisms. The result? A totally new way to interact with our everyday devices. Using conductive yarn made from 80 percent polyester and 20 percent stainless steel...Chang knit and crocheted a series of
objects that control devices by pulling, squeezing and stroking. When manipulated, the overlap of the metal fiber causes the textile to change conductivity which is then measured by an Arduino and communicated to the gadgets...Chang developed the
Squeezy Juicer, a juicer that only works when you squeeze an oversized knit ball between two people. The faster you squish the ball, the quicker you’ll have your orange juice...“When you integrate different sensing technology into today’s electronics, you can make something look totally different,” he says
."
Dezeen's article explains how Chang's conductive yarn came to be.
"Knit Sensors was Yen Chen Chang's graduation project from the Design Products course at London's RCA, and involved experimenting with conductive textiles to provide a more tangible alternative to touch screens and other typical interfaces...The designer began his project by exploring the possibility of knitting standard electrical cables into self-supporting structures, which he realised generated a small amount of resistance because of the complexity of their intertwined surfaces. Recognising that manipulating the surfaces affected the amount of resistance, Chang began to explore the possibility of weaving with conductive yarns connected to sensors that translate actions like stretching and pulling into voltage changes."
Yarn glove electronics
Two other websites to look at if this yarn is of interest to you are the alphafit and Eeonyx sites. The alphafit technology involves pressure sensitive textiles. The company states:
"For the first time it is now possible...to measure surface pressure on three-dimensional variable surfaces. The filament itself measures the pressure. We have developed a textile system that works without the need of inserting any industrial sensors. This measurement system can be integrated into any textile."
Eeonyx makes an electronics-friendly yarn that is says consists of,
"...a conductive polymer coated yarn with precisely tunable electrical resistance and excellent uniformity of linear resistance. EeonYarn™ is durable, able to stand up to real world conditions of abrasion and repeated washings. Applications for EeonYarn™ include radar absorbing fabrics and composites, resistive fabric heaters, and woven pressure sensors."
Adafruit tilt sensor
More readily available, or maybe lower cost, textile microcontroller (MCU) project supplies and techniques are described in Adafruit's datasheet titled "Handcrafting Textile Sensors From Scratch." This PDF document shows a whole slew of supplies and tools for textile sensor projects. It shows the basics of making textile sensors such as a pressure sensor matrix and a tilt sensor. A worthwhile read for someone interested in textile computing projects. Another great background guide for this topic is Katie's "Soft Electronics Tutorial."

Two other random 'textile computing' items I'll throw in here at the end are the Lilypad Arduino, an alternative to the Adafruit FLORA mentioned in yesterday's blog post, and ChipChick's article titled "Dragon Inspired Outfit Hits the Fashionware Runway Show" which has some pretty interesting projects. The Lilypad has been used in many projects -- just Google   Lilypad project   and you'll find more wearable computing projects than you have time to read about. The ChipChick article, although not solely about MCU fashion items, does talk about relevant products, saying:
"CE Week may be over but the fashion will always live on. A one stop shop for NY’s geek-erati, but this year they got treated to a bit of high fashion as well. The runway show combined wearable fitness, one of a kind high tech fashion design, robotics, and program for young kids...The Dragon Queen is a collaborative design evolved from Victoria Secret Wings...The dragon interacts with the audience through a mobile app that controls its movement through WiFi.
Lilypad Arduino
The dragon’s power comes from a combination of an EZ robot controller, a speaker, 3D printed eyes, and LED strip lights...Strokes and Dots is an outfit inspired by early modern art but it combines speed, graphic design and technology. The LEDs woven into the fabric are motion and sound responsive
..."
The textile computing world is big and getting bigger every day! What project would you like to do with fabrics and microcontrollers? If you do a lot of fabric work and want help with the microcontroller or electronics part of your project, consider coming to a Humboldt Microcontrollers Group meeting and explaining what you'd like to do. Or ask questions you have about how MCUs work or what their capabilities are. We'll do our best to help you out, and it might result in you heading out into a whole new world of fabric projects.

**********

Friday, July 4, 2014

Mobile Computing: Tetris Shirt And Other Wearables

You've heard of mobile gaming and wearable computing. Well here's a twist on those terms -- a mobile game that someone is wearing.

It was recently the 30th anniversary of the classic video game Tetris. Tetris was extremely popular and has an addictive tune that will get stuck in your head, especially if you spent hours in your formative years playing the game. Here's how Wikipedia describes Tetris' popularity:
"The game (or one of its many variants) is available for nearly every video game console and computer operating system, as well as on devices such as graphing calculators, mobile phones, portable media players, PDAs, Network music players and even as an Easter egg on non-media products like oscilloscopes. It has even inspired Tetris serving dishes and been played on the sides of various
buildings...Electronic Gaming Monthly's 100th issue had Tetris in first place as
"Greatest Game of All Time"...In January 2010, it was announced that Tetris had
sold more than 170 million copies, approximately 70 million physical copies and over 100 million copies for cell phones, making it the highest paid-downloaded game of all time
."
One fan of Tetris, Marc Kerger from Luxembourg, decided that Tetris deserved to be playable on his clothing. So he hacked a shirt with readily available components from the DIY world of microcontrollers (MCUs), and he now has his playable shirt.

His shirt's Tetris game was created with an Arduino Uno, two Adafruit Matrix controllers, a 2 X 64 LED matrix (8 X 8) Flat SMD RGB LEDs (only one color soldered), four AA rechargeable batteries, 3D printed housings for the Arduino and the batteries and 3D printed soft material for the game-play buttons. Oh yeah, and Marc's shirt.
Marc, playing his Tetris shirt

In Adafruit's blog post about this mobile game shirt, they mention that,
"Every Wednesday is Wearable Wednesday here at Adafruit! We’re bringing you the blinkiest, most fashionable, innovative, and useful wearables from around the web and in our own original projects featuring our wearable Arduino-compatible platform, FLORA."
Sewable Arduino-compatible FLORA
While it will take a lot more work than just a FLORA and a couple LEDs to make a textile computing project comparable to the Tetris shirt, a FLORA project might be a good place to start if you haven't done any fabric-based wearable computing projects. One Adafruit FLORA project that might be of interest to Humboldt residents is the 'Light Up Your Skateboard' project. Or maybe you'd like to wear a 'Sound-Reactive Baseball Hat' to the next Crabs game. The FLORA is only one of many MCU options for textile computing projects, but it's a good basis for a beginning project in this genre.

When we have a couple people in the Humboldt Microcontrollers Group who are interested in doing a fabric wearable computing project, we'll connect with a few people skilled with sewing machines at Origin Design Lab in Eureka and see if we can get a collaborative project going.

**********

Thursday, July 3, 2014

#7 Jeremy Blum Video: I2C And Processing

So tonight I started working on the #7 Jeremy Blum ‘Arduino basics’ video tutorial. This video covers I2C communication and the Processing programming language.

I2C (Inter-Integrated Circuit), most commonly pronounced I-Squared-C, lets an Arduino communicate with I2C or TWI (Two Wire Interface) devices. In the case of Jeremy’s #7 video, the device is a temperature sensor. The other focus of this video tutorial is the Processing programming language, and that is used in this video to display the temperature data on a computer display.

I2C will be used a lot for microcontroller (MCU) projects, so you’ll want to become familiar and skilled with it. Wikipedia has this to say about I2C:
“I²C...is a multimaster serial single-ended computer bus invented by the Philips semiconductor division, today NXP Semiconductors, and used for attaching low-speed peripherals to a motherboard, embedded system, cellphone, or other digital electronic devices. Several competitors, such as Siemens AG...now Intel mobile communications, NEC, Texas Instruments, STMicroelectronics...Motorola...and Intersil, have introduced compatible I²C products to the market...”
SparkFun has a pretty good tutorial on I2C that provides excellent background reading for better understanding the #7 video. The tutorial gives this overview of the protocol:
“The Inter-integrated Circuit (I2C) Protocol is a protocol intended to allow multiple “slave” digital integrated circuits (“chips”) to communicate with one or more “master” chips. Like the Serial Peripheral Interface (SPI), it is only intended for short distance communications within a single device. Like Asynchronous Serial Interfaces (such as RS-232 or UARTs), it only requires two signal wires to exchange information….I2C requires a mere two wires, like asynchronous serial, but those two wires can support up to 1008 slave devices. Also, unlike SPI, I2C can support a multi-master system, allowing more than one master to communicate with all devices on the bus (although the master devices can’t talk to each other over the bus and must take turns using the bus lines).”
The master / slave issue is one that will affect your MCU projects that have multiple I2C devices, like a bunch of temperature sensors. Each slave device needs to have its own ID number, and Jeremy mentions that you can sometimes order an I2C device with a specific ID. So that’s something you’ll need to figure out before you order the components for a project.

Jeremy also talks about the SDA and SCL lines. The SparkFun tutorial says this about those:
“Each I2C bus consists of two signals: SCL and SDA. SCL is the clock signal, and SDA is the data signal. The clock signal is always generated by the current bus master...Messages are broken up into two types of frame: an address frame, where the master indicates the slave to which the message is being sent, and one or more data frames, which are 8-bit data messages passed from master to slave or vice versa. Data is placed on the SDA line after SCL goes low, and is sampled after the SCL line goes high...To initiate the address frame, the master device leaves SCL high and pulls SDA low. This puts all slave devices on notice that a transmission is about to start.”
If you want to dive deeper into I2C, here are a couple good places, in addition to the above links, to spend a bit of your time:
  1. Adafruit MCP9808 Precision I2C Temperature Sensor Guide (another look at temperature sensors and IC2)
  2. The tronixstuff tutorial on Arduino and IC2
  3. Arduino’s in-depth reference to the Arduino Wire library
  4. Maxim Integrated’s “Proven Implementation of the I2C bus”
The temperature sensor used in the #7 video exercise is a Microchip Technology TC74A0-5.0VAT, which you can get from Newark, Digikey and other electronic component distributors. Jeremy mentions checking the Microchip datasheet for the sensor to find out what each pin is for on the sensor. Those pins are shown in the picture to the right.

On the subject of sourcing electronic components, if you haven’t tried using Octopart, a search engine for electronic parts, you might want to give it a try. It’s been very useful for most parts I’ve researched on it. For the #7 video temperature sensor, it gave a helpful view of the cost and availability of the component.

The above temperature sensor is only one of many available temperature sensors. Microchip Technology makes many models, as do other manufacturers like Texas Instruments or Honeywell. There are also temperature sensors which use different technologies, such as thermistor, thermocouple and RTD. I’m doing background research on temperature sensors for a future post on this blog, so if you have questions about temperature sensors, or have a favorite sensor to recommend, email me at arcatabob (at) gmail {dott} com.
Processing language

With regards to the Processing programming language, the main topics in the #7 video are (1) setting the font to be displayed by the Arduino on your computer screen and (2) writing the code to convert the temperature sensor’s input to the Arduino into a computer display of the measured temperature, in both Celsius and Fahrenheit. If you don’t already know how, you’ll learn how to set up the code to let your temperature sensing circuit use Processing, choose and configure your font, grab the temperature data the sensor sends to the Arduino and do math with those signals. For the font, you need to specify color ‘numbers’ for the R, G and B values (red, green, blue). There are lots of tools to help you with figuring out the color values you want, with a 500+ color chart from Cloford.com or the RGB color codes chart from RapidTables being good places to start if you don’t already have a resource for helping you specify color values.
Arduino LED color picker

Two somewhat technical and time-consuming options to consider are color selectors for a smartphone, such as the apps for Android, or, in a slightly recursive twist, the Arduino LED color picker from Andrew Rapp which, in a way, helps you learn about color after you learn about color.  

I guess that’s enough for tonight on I2C, temperature sensing and Processing. If you think you might be able to come to the July 10 meeting of the Humboldt Microcontrollers Group, take a look at the #7 Blum video and read up on those topics a bit. The topics in the video will be the focus of the July 10 meeting. If you have the electronic parts and the time, go through the exercise in the video.

** Important Note ** -- One of the main goals of this blog and the Humboldt Microcontrollers Group is to help connect and expand the community of microcontroller users in Humboldt County and the North Coast. So even if you can’t find the time to go through the video, if you’re interested in I2C temperature-sensing MCU projects or Processing, if you know lots about one of those topics and want to answer questions or share tips, or if you’re just interested in microcontrollers and want to learn more, please show up at the July 10 meeting from 6 to 8 PM at 1385 8th Street, Arcata, California. If you're coming, bring a friend. If you can't come, send a friend!

**********

Wednesday, July 2, 2014

New Arduino Add-Ons: USB Host Shield and In-System Programmer

Official Arduino USB host shield
If you're a fan of the 'official' Italian Arduino components, their blog just announced two new items -- a USB host shield and an In-System Programmer (ISP).

The Arduino Uno comes with a USB B port, and you use a USB A-to-B cable to connect the Uno to your computer for uploading sketches to the Uno. However, to make your Arduino a USB host, you need to add a shield. There are other USB host shields for the Arduino, such as the SparkFun one for $24.95 or the Circuits@Home one for $25 (a mini one is also available for $20). The official Arduino USB host shield is available from arduino.cc for 24 euros, which is about $33 right now. I couldn't
SparkFun USB host shield
find the official shield at any of the distributors I looked at tonight, probably because it's just been released.

So why might you want to get a USB host shield? Well, the Arduino announcement has a long list of uses:

  1. HID devices: keyboards, mice, joysticks, etc.
  2. Game controllers: Sony PS3, Nintendo Wii, Xbox360.
  3. USB to serial converters: FTDI, PL-2303, ACM, as well as certain cell phones and GPS receivers.
  4. ADK-capable Android phones and tables.
  5. Digital cameras: Canon EOS, Powershot, Nikon DSLRs and P&S, as well as generic PTP.
  6. Mass storage devices: USB sticks, memory card readers, external hard drives, etc.
  7. Bluetooth dongles.
If any of those particular use cases are of interest to you, but you still aren't totally clear on what is meant by a USB host, or why and how you want to use a USB host shield, Hardware Fun has a good post going into depth about USB host shields for Arduino. Their post explains 'USB host' like this:
"...let’s first understand what is an USB Host Shield. It is a shield which provides USB Host support for Arduino...The USB protocol defines two types of devices. One is called the host (or server) and the other one is called peripheral (client). The Host device controls the peripheral device and also provides power to it. When you connect any USB device like a mouse or a keyboard to your computer, your computer acts as the host and controls (or polls) the client device (keyboard or mouse or even an Arduino). For a successful communication to happen using USB protocol, you need at least one of the device to be the host, which means that you cannot connect two keyboards together and expect them to communicate with each other...Once you have this shield, your Arduino board can act as USB Host and you can connect other USB devices like keyboard, mouse or even an Android phone..."
For lots of technical details and to gain a better understanding of the USB host shield hardware, click on over to the Circuits@Home hardware manual for their USB host shield. The Arduino blog announcement for the official shield says "it can be used with the “USB Host Library for Arduino” hosted by Oleg Mazurov and Alexei Glushchenko from circuits@home" so a lot of the info in the hardware manual will likely also be applicable to, or helpful in understanding, the official Arduino shield. There's also a reference page for the shield on the arduino.cc site.

The other official Arduino hardware release was an Arduino AVR In-System Programmer. I might do a future post with more about the ISP and programming AVR microcontrollers, but here's what the Arduino blog says about this new hardware:
"It’s a tiny AVR-ISP...useful to anyone needing more space on the Arduino board. Uploading a sketch with an external programmer can be used for three main reasons:
  • remove the bootloader and use the extra space for your sketch 

  • burn the bootloader on your Arduino, so you can recover it if you accidentally corrupt the bootloader. 

  • when you use a new ATmega microcontroller in your Arduino, and you need the bootloader in order to upload a sketch in the usual way."
If either of these items sound useful for your microcontroller projects, you might want to read a bit more about them or place an order!

**********

Tuesday, July 1, 2014

Programming Arduino Uno: Hardware Memory Types

In a previous post, I referenced a Linux Journal article looking at Arduino code development from a programmer’s viewpoint. Today’s ‘Arduino programming’ post will address what types of memory hardware are in the Arduino Uno and a little bit about how those different types of memory are used.
Arduino Uno hardware components (from Zenbike.com)

All the memory of a standard Arduino Uno R3 board is found in the Atmel ATmega328P microcontroller (MCU). If you look at the Arduino Uno Zenbike photo on the right that has the Arduino hardware components labeled, you can see where the microcontroller is located on the board. To begin understanding Arduino programming from a hardware standpoint, we need to know what chunks of memory hardware are inside that Atmel MCU.

The ATmega328P has three types of memory hardware:


Memory and CPU from ATmega328P block diagram
ISP flash memory is where most of programming is stored. The Atmel MCU in the Arduino Uno has 32 KB of ISP flash. This is more room for program storage than some MCUs, especially other 8-bit MCUs, but there are many MCUs that have more memory. So if you’re working with a complex program on the Arduino Uno and run out of storage space, one option might be to use a different MCU that has more program memory capacity. For more info regarding the specifics of ISP flash on the Atmel AVR MCUs, see Atmel's application note about that topic. Here's how Adafruit describes the ATmega328's flash:
“Flash memory is used to store your program image and any initialized data. You can execute program code from flash, but you can't modify data in flash memory from your executing code. To modify the data, it must first be copied into SRAM. Flash memory is the same technology used for thumb-drives and SD cards. It is non-volatile, so your program will still be there when the system is powered off. Flash memory has a finite lifetime of about 100,000 write cycles.”
The ATmega328P’s 2 KB of SRAM is used in three main ways in the Arduino (info from above Adafruit link):
  • “Static Data - This is a block of reserved space in SRAM for all the global and static variables from your program. For variables with initial values, the runtime system copies the initial value from Flash when the program starts.
  • Heap - The heap is for dynamically allocated data items. The heap grows from the top of the static data area up as data items are allocated. 
  • Stack - The stack is for local variables and for maintaining a record of interrupts and function calls.”
If you’ve gotten to the point where your MCU project’s program is controlling many items, receiving lots of inputs and just generally doing a lot of work, you might start taxing the SRAM. If that happens, or maybe to prevent that from happening, you might want to read Adafruit’s guide to optimizing use of SRAM, which says,
“SRAM is the most precious memory commodity on the Arduino...SRAM shortages are probably the most common memory problems on the Arduino...If your program is failing in an otherwise inexplicable fashion, the chances are good you have crashed
Hackaday -- CPLD shield with 2 MB SRAM
the stack due to a SRAM shortage. There are a number of things that you can do to reduce SRAM usage. These are just a few guidelines
...”
If you think you’ve crashed your Arduino because of program complexity, especially a program which might be expecting a lot in the areas of static data, heap and stack, try some of Adafruit’s suggestions for improving SRAM use. Also, because SRAM is the “most precious memory commodity on the Arduino,” you may want to consider a shield that provides more SRAM. Hackaday has a post showing a CPLD (Complex Programmable Logic Devices) shield that increases SRAM from the standard 1 KB by three orders of magnitude up to 2 MB.

Tronixstuff.com has a pretty good post about what the 1 KB of EEPROM in the Arduino Uno can be used for.
“EEPROM...is a form of non-volatile memory that can remember things with the power being turned off, or after resetting the Arduino...we can store data generated within a sketch on a more permanent basis...where data that is unique to a situation needs a more permanent home. For example, storing the unique serial number and manufacturing date of a commercial Arduino-based project – a function of the sketch could display the serial number on an LCD, or the data could be read by uploading a ‘service sketch’. Or you may need to count certain events and not allow the user to reset them – such as an odometer or operation cycle-counter.”  
If you find yourself needing more than 1 KB for storing data, there are EEPROM shields like the one shown at the left. However, as mentioned above, if memory capacity becomes an issue, you should first determine if a different MCU with more internal memory might be more appropriate for your use case.

Arduino beginners don’t need to be too concerned about where the different parts of their programs and data are being stored while they’re learning how to make an LED blink or doing the early Blum tutorials. As your Arduino programs get larger and more complex, however, you’ll probably want to put more effort into managing memory use on your Arduino. If this memory hardware guide for your Arduino doesn’t point you to a helpful resource for that memory management, you can put Google to work finding other resources for you.

**********