Wireless Arduino Programming With Electric Imp - Learn .

3y ago
15 Views
3 Downloads
1.63 MB
31 Pages
Last View : 1d ago
Last Download : 3m ago
Upload by : Abby Duckworth
Transcription

Wireless Arduino Programming with ElectricImp a learn.sparkfun.com tutorialAvailable online at: http://sfe.io/t198ContentsGetting StartedBootloading 101Hardware ConnectionsSoftware ConnectionsGetting HEXResources and Going FurtherGetting StartedLoading a new sketch via wirelessThis tutorial will show you how to use an Electric Imp to repogram an Arduino from a webpage. Yep,you read that right. Now you can reprogram an Arduino (and an Imp) from anywhere in the world!Page 1 of 31

The Electric Imp before modification for bootloadingThe Electric Imp is a powerful device that allows you to connect to the internet relatively easily. Fora lot of my Imp projects, I use an Arduino to handle the interface between the various bits ofhardware. While reprogramming the Imp is extremely easy via their web-based IDE, reprogrammingan Arduino is much more tedious and requires plugging in a computer and downloading new code.Why not use the Imp's wireless connection to push new Arduino sketches as well?If you've ever installed an Arduino into a place that required a scissor lift, in a water tight enclosure,on the top of a building, or into a paper-mache piñata, you understand how problematic it can be tofix that bug you never imagined. With a few bits of hardware you can have an Arduino attachedfirmly to the Internet of things as well as making the Imp Arduino a heck of a lot easier toreprogram.What in the world is Tomatoless Boots? Sorry. It's a joke first told by Rob Faludi:Wireless is a pointless way to describe wireless. It only describes what wireless is not, not what it is.For example, it also has no tomatoes, so we might as well call it 'tomatoless'.And since it's a bootloader of sorts, we decided (against good judgement) to call itTomatolessBoots. Zomg thank you Aron Steg for writing the original Imp code. We took his code and made afew improvements to dramatically improve the bootload time and to get it to work with generalArduinos.Required MaterialsParts you'll need:Page 2 of 31

Imp Arduino Bootloading Wishlist SparkFun WishListArduino Stackable Header Kit - R3PRT-11417These headers are made to work with the Arduino Uno R3, Leonardo and new Arduino boards going forward. Th SparkFun RedBoard - Programmed with ArduinoDEV-12757At SparkFun we use many Arduinos and we're always looking for the simplest, most stable one. Each board is a b SparkFun Electric Imp ShieldDEV-12887If you aren't familiar with the Electric Imp, it essentially provides an easy, integrated way to connect almost any ha Electric ImpWRL-11395We know what you're thinking, "What's the big deal? Looks like an SD card." Well this is no SD card! The Electric View Imp Arduino Bootloading Wishlist on SparkFun.comAlong with the above parts, you'll need the following tools.Exacto KnifeSoldering iron and a bit of wireLocal Wifi accessThis reprogramming-over-wifi trick only works with ATmega328 based Arduinos with a serialbootloader such as the Arduino Uno, Fio, LilyPad, Pro, Pro Mini, and RedBoard. This tutorial will notwork with the Due, Leonardo, Micro, Galileo, or Teensy. There are probably some really good waysof getting these other boards to bootload over wifi but their bootloaders are different enough thatthis tutorial doesn't attempt to cover them.Suggested ReadingOther tutorials you may want to brush up on before diving into this one:Getting Started with the Electric ImpHow to use a multimeterHow to install and solder Arduino HeadersBootloading 101Now for a bit of history and bootloader basics:Page 3 of 31

The Optiboot LogoThere have been lots of serial bootloaders written throughout the years for lots of differentmicrocontrollers. I wrote one for the PIC ages ago and one to wirelessly bootload Arduinos overXBee as well. The Arduino originally used the STK500 bootloader written by Atmel(seeapp noteAVR061) that was then updated by Peter Knight and Bill Westfield to become the shrunk downOptiboot. Optiboot and a handful of similar bootloaders are what are installed on every ATmega328based Arduino today.The serial bootloader is activated each time the ATmega328/Arduino is powered up or reset. For abrief period of time (about 500ms), the microcontroller will listen for a special set of characters. If ithears nothing from the computer, then the ATmega will exit the bootloader and begin to run theuser's code that resides in flash memory. However, if the microcontroller hears those specialcharacters, then it will know that a new program needs to be downloaded and begins to wait for aHEX file to be sent. Normally this communication is done while connected to a computer (via aUSBto serial connection), but anything capable of attaching to the serial port on the Arduino has theoption to reprogram it. The Imp can talk serial with ease, and the fact that it connects to the worldwide web so easily makes it a good choice for wirelessly bootloading your board.Hardware ConnectionsPage 4 of 31

Imp Shield with no headersThe very first step is to solder the Arduino headers to the Imp shield. For more information abouthow to do this, checkout this tutorial.Page 5 of 31

Schematic for the Imp ShieldNext, we need to re-route the Imp's UART to the Arduino's serial pins (0 and 1). By default theImpShield connects the Imp's serial port (pins 5 and 7) to Arduino's pins 8 and 9.Page 6 of 31

The TX and RX pads with default traceLuckily, the genius behind the Imp shield design had the foresight to make it easy to switch pins(Jim is awesome). On the back of the shield, you'll find two jumpers labeled RX and TX. In theimage above, you should see a small trace connecting the TX and RX pins of the Imp to the rightpads labeled 8 and 9.Page 7 of 31

Default trace has been cutCarefully use an exacto knife to cut the default trace. If you've never cut a trace before don't worry it's easy! Just take your time. Cutting a trace is less like cutting through metal and more like scoringtile or scraping ice off your windshield; it takes a few passes. Once you've cut the traces, use amultimeter to do a continuity test to verify that you have indeed severed the connection between thecenter pad and the pad to the right.Page 8 of 31

New connections jumperedNext, add some solder and jumper the center pads to their matching left pad. The Imp should nowbe wired directly to the Arduino's serial port.Jumper wire addedPage 9 of 31

The final hardware modification is a jumper from P1 of the Imp to RST on the shield. This will allowthe Imp to reset the Arduino whenever it pulls the P1 pin low.Full stack with jumper in placeOnce you've soldered the jumpers and single wire, add the Imp shield to your Arduino and connecta USB cable. Assuming you have commissioned your Imp to your local wifi, the Imp should powerup, blink red, then blink green as it attaches to the Internet.Now why did I tell you to take your time cutting the default traces? Because I made a big mistakewhen cutting the default TX trace. Have a second look:Page 10 of 31

Don't see the problem? How about now:Uh oh.I was going too fast, the cut I made was too long, and I ended up cutting the TX trace to the Imp.Page 11 of 31

When I attached everything to my Imp bootloading failed to work; everything was timing outbecause the Imp never heard a response from the Arduino (because the TX trace was cut). Luckily,I had a second functioning setup, so I tested my code on that. Everything worked, so I knew it mustbe a hardware problem with the board I was using for this tutorial. After a few minutes of scratchingmy head I used a multimeter to start probing for continuity. Once I discovered TX was notconnected I tracked down this bad cut.Green wire fixWith some 30AWG wire wrap wire and some hemostats, the trace was quickly repaired, and theboard started working as expected.Take extra time when cutting traces so as to not cut beyond or knick nearby traces.Software ConnectionsWe are going to assume that you have already commissioned your Imp and gotten it onto your localwifi. Log in to your Electric Imp account and open the Imp IDE. Here is the code you'll need to loadcode into the Agent:/*Code originally from Aron Steg: 904Modified February 1st, 2014 by Nathan SeidlePage 12 of 31

Modified February 1st, 2014 by Nathan SeidleMany great fixes were made by Aaron Steg, May 2014.Currently, the only difference between this code and Aaron's original is we invertthe reset line logic to work with standard Arduinos.Original license:Copyright (c) 2014 Electric ImpThe MIT License g("Agent started, URL is " http.agenturl());const MAX PROGRAM SIZE 0x20000;const ARDUINO BLOB SIZE 128;program - --------------------------------html - @" !doctype html HTML lang 'en' head meta name 'viewport' content 'width device-width, initial-scale 1.0' !-- Bootstrap -- !-- Latest compiled and minified CSS -- link rel 'stylesheet' href tstrap.min.css' !-- Optional theme -- link rel 'stylesheet' href tstrap-theme.min.css' /head BODY div class 'container' h1 Program the ATmega328 via the Imp. /h1 form method 'POST' enctype 'multipart/form-data' Step 1: Select an Intel HEX file to upload: input type file name hexfile br/ Step 2: input type submit value Press to upload the file. br/ Step 3: Check out your Arduino br/ /form form method 'POST' id 'hex-upload-form' input type hidden name hexfile id 'hex-file' /form h2 OR /h2 div class 'panel panel-default' div class 'panel-heading' id 'dropbox-button' /div div class 'panel-body' Page 13 of 31

div class 'panel-body' table class 'table' thead tr th # /th th File Name /th th Action /th /tr /thead tbody id 'link-text' /tbody /table /div /div /div script src ery.min.js' /script script src strap.min.js' /script script type 'text/javascript' src '//www.dropbox.com/static/api/2/dropins.js' id 'dropboxjs' data-app-key '8 script type 'text/javascript' function uploadFile(fileLink) { ('#hex-file').val(fileLink); ('#hex-upload-form').submit();}function buildLinkRow(idx, fileLink) { ('#link-text').append(' tr id \'link-row-' idx '\' td ' idx ' /td td ' fileLink ' /td td button type but ('#upload-button-' idx).click({value: fileLink}, function(e) {uploadFile(e.data.value);}); ('#remove-button-' idx).click({value: idx, link: fileLink}, function(e) { ('#link-row-' e.data.value).remove();links.splice(idx - 1, 1);buildLinkTable();});}function buildLinkTable() { ('#link-text').empty();if( links.length 0 ) {for( var i 0; i links.length; i ) {buildLinkRow(i 1, links[i]);}if( window.localStorage ) localStorage['links'] JSON.stringify(links);} else { ('#link-text').append(' tr id \'empty-row\' td colspan 3 Please select a file. /td /tr ');}} /script Page 14 of 31

/script script type 'text/javascript' options {success: function(files) el: function() {},linkType: 'direct',multiselect: false,extensions: ['.hex']};var button Dropbox.createChooseButton(options); ('#dropbox-button').html(button);var emptyRow;var links [];if( window.localStorage ) {var linksStr localStorage['links'];if( linksStr ) {links JSON.parse(linksStr);}} else {console.log('local storage not supported.');}buildLinkTable(); /script /BODY /HTML -----------------------------// Parses a HTTP POST in multipart/form-data formatfunction parse hexpost(req, res) {local boundary req.headers["content-type"].slice(30);local bindex req.body.find(boundary);local hstart bindex boundary.len();local bstart req.body.find("\r\n\r\n", hstart) 4;local fstart req.body.find("\r\n\r\n--" boundary "--", bstart);return req.body.slice(bstart, fstart);}Page 15 of 31

---------------------------// Parses a hex string and turns it into an integerfunction hextoint(str) {local hex 0x0000;foreach (ch in str) {local nibble;if (ch '0' && ch '9') {nibble (ch - '0');} else {nibble (ch - 'A' 10);}hex (hex 4) nibble;}return --------------------------------// Breaks the program into chunks and sends it to the devicefunction send program() {if (program ! null && program.len() 0) {local addr 0;local pline {};local max addr program.len();device.send("burn", {first true});while (addr max addr) {program.seek(addr);pline.data - program.readblob(ARDUINO BLOB SIZE);pline.addr - addr / 2; // Address space is 16-bitdevice.send("burn", pline)addr pline.data.len();}device.send("burn", {last ------------------------------------// Parse the hex into an array of blobsfunction parse hexfile(hex) {try {// Look at this doc to work out what we need and don't. Max is about 122kb.// "Parsing hex file");Page 16 of 31

server.log("Parsing hex file");// Create and blank the program blobprogram blob(0x20000); // 128k maximumfor (local i 0; i program.len(); i ) program.writen(0x00, 'b');program.seek(0);local maxaddress 0, from 0, to 0, line "", offset 0x00000000;do {if (to 0 to null to hex.len()) break;from hex.find(":", to);if (from 0 from null from 1 hex.len()) break;to hex.find(":", from 1);if (to 0 to null from to to hex.len()) break;line hex.slice(from 1, to);// server.log(format("[%d,%d] %s", from, to, line));if (line.len() 10) {local len hextoint(line.slice(0, 2));local addr hextoint(line.slice(2, 6));local type hextoint(line.slice(6, 8));// Ignore all record types except 00, which is a data record.// Look out for 02 records which set the high order byte of the address spaceif (type 0) {// Normal data record} else if (type 4 && len 2 && addr 0 && line.len() 12) {// Set the offsetoffset hextoint(line.slice(8, 12)) 16;if (offset ! 0) {server.log(format("Set offset to 0x%08X", offset));}continue;} else {server.log("Skipped: " line)continue;}// Read the data from 8 to the end (less the last checksum byte)program.seek(offset addr)for (local i 8; i 8 (len*2); i 2) {local datum hextoint(line.slice(i, i 2));program.writen(datum, 'b')}Page 17 of 31

// Checking the checksum would be a good idea but skipped for nowlocal checksum hextoint(line.slice(-2));/// Shift the end point forwardif (program.tell() maxaddress) maxaddress program.tell();}} while (from ! null && to ! null && from to);// Crop, save and send the programserver.log(format("Max address: 0x%08x", maxaddress));program.resize(maxaddress);send program();server.log("Free RAM: " (imp.getmemoryfree()/1024) " kb")return true;} catch (e) {server.log(e)return -----------------------------------// Handle the agent requestshttp.onrequest(function (req, res) {// return res.send(400, "Bad request");// server.log(req.method " to " req.path)if (req.method "GET") {res.send(200, html);} else if (req.method "POST") {if ("content-type" in req.headers) {if (req.headers["content-type"].len() 19&& req.headers["content-type"].slice(0, 19) "multipart/form-data") {local hex parse hexpost(req, res);if (hex "") {res.header("Location", http.agenturl());res.send(302, "HEX file uploaded");} else {device.on("done", function(ready) {res.header("Location", http.agenturl());res.send(302, "HEX file uploaded");server.log("Programming completed")Page 18 of 31

server.log("Programming completed")})server.log("Programming started")parse hexfile(hex);}} else if (req.headers["content-type"] "application/json") {local json null;try {json http.jsondecode(req.body);} catch (e) {server.log("JSON decoding failed for: " req.body);return res.send(400, "Invalid JSON data");}local log "";foreach (k,v in json) {if (typeof v "array" typeof v "table") {foreach (k1,v1 in v) {log format("%s[%s] %s, ", k, k1, v1.tostring());}} else {log format("%s %s, ", k, v.tostring());}}server.log(log)return res.send(200, "OK");} else if(req.headers["content-type"] "application/x-www-form-urlencoded") {server.log(req.body);local data http.urldecode(req.body);local url data.hexfile;server.log("url: " url);local hex http.get(url).sendsync();//server.log("hex: " hex.body);device.on("done", function(ready) {res.header("Location", http.agenturl());res.send(302, "HEX file uploaded");server.log("Programming completed")})server.log("Programming started")parse hexfile(hex.body);} else {return res.send(400, "Bad request");}} else {return res.send(400, "Bad request");}}})Page 19 of 31

-----------------------------// Handle the device coming onlinedevice.on("ready", function(ready) {if (ready) send program();});This Gist brought to you by gist-it.tomatoless.agent.nut viewrawAbove is the code for the Imp AgentAnd here is the code you'll need to load into the Imp Device:/*Code originally from Aron Steg: 904Modified February 1st, 2014 by Nathan SeidleMany great fixes were made by Aaron Steg, May 2014.This code was modified slightly to work with the Electric Imp Shieldfrom SparkFun: https://www.sparkfun.com/products/11401The reset control was inverted and status LEDs re-routed but everything else was the same.Zomg thank you Aron Steg: 904Two hardware modifications are required:* Cut two RX/TX traces to 8/9 on the back of the Imp Shield then solder blob to 0/1* Wire from P1 of Imp to RST on shield.It takes the Arduino approximately 400ms from reset going high to be able torespond to incoming bootload commands.Original license:Copyright (c) 2014 Electric ImpThe MIT License g("Device started, impee id " hardware.getimpeeid() " and mac " --------------------------------------------// Uart57 for TX/RXSERIAL - hardware.uart57;Page 20 of 31

SERIAL - hardware.uart57;SERIAL.configure(19200, 8, PARITY NONE, 1, NO CTSRTS);// Set pin1 high for normal operation// Set pin1 low to reset a standard ArduinoRESET - hardware.pin1;RESET.configure(DIGITAL OUT);RESET.write(1); //Leave Arduino in normal (non-reset) state// Pin 9 is the yellow LED on the Imp ShieldACTIVITY - hardware.pin9;ACTIVITY.configure(DIGITAL OUT);ACTIVITY.write(1);// Pin 8 is the orange LEDLINK - hardware.pin8;LINK.configure(DIGITAL OUT);LINK.write(1);// Sequence numberseq - --------------------------------/* STK500 constants list, from AVRDUDE */const MESSAGE START 0x1B;const TOKEN 0x0E;const STK OK 0x10;const STK FAILED 0x11; // Not usedconst STK UNKNOWN 0x12; // Not usedconst STK NODEVICE 0x13; // Not usedconst STK INSYNC 0x14; // ' 'const STK NOSYNC 0x15; // Not usedconst ADC CHANNEL ERROR 0x16; // Not usedconst ADC MEASURE OK 0x17; // Not usedconst PWM CHANNEL ERROR 0x18; // Not usedconst PWM ADJUST OK 0x19; // Not usedconst CRC E

Getting Started Bootloading 101 Hardware Connections Software Connections Getting HEX Resources and Going Further Getting Started Loading a new sketch via wireless This tutorial will show you how to use an Electric Imp to repogram an Arduino from a webpage. Yep, you read that right. Now you can reprogram an Arduino (and an Imp) from anywhere in .

Related Documents:

Arduino compatible components. Personal computer running Arduino software Arduino software is free to download and use from: www.arduino.cc Arduino board Such as: Arduino Uno Freetronics Eleven Genuino Uno or any Arduino compatible board that has a standard Arduino UNO header l

arduino-00 -win.zip Recommended Path c:\Program Files\ ( - version #) Step 3: Shortcut Icon Open c:\program files\arduino-00 Right Click Arduino.exe (send to Desktop (create shortcut)) \ ( - version #) Step 4: Plug In Your Arduino Plug your Arduino in: Using the included USB cable, plug your Arduino board into a free USB port. Wait for a box to .

Hence we given interesting top five easy to make Arduino projects with code and library link. Happy learning Arduino 1. Heart Rate Monitor AD8232 Interface Arduino 2. Fingerprint sensor-scanner with Arduino 3. Giving Voice Recognition Ability to Arduino 4. Soil Moisture Sensor and Arduino 5. How to Interface RFID with Arduino?

Arduino programming . These three lectures can be broken down as follows: 1.) Getting Started with Arduino - Outlines basics of Arduino hardware, software, an d robotics programming 2.) Arduino Programming Language - Details sketch structure, programming syntax notes, and pin functionality 3.) Starting Arduino Examples

arduino’s analog pin 4 (SDA). And the pin labelled as SCL on the MPU 6050 to the arduino’s analog pin 5 (SCL). And that’s it, you have finished wiring up the Arduino MPU 6050. Step 2: Uploading the code and testing the Arduino MPU 6050 To test the Arduino MPU 6050, first download the arduino library for MPU 6050, developed by Jeff Rowberg.

3. Then, use the Arduino IDE to write code to send to Arduino. Once a code is sent to the Arduino, it lives on the Arduino Uno. Any future edits to that code on the computer will not be sent to the Arduino unless it is manually uploaded to the Arduino Uno. When using the Arduino

117. Password access with arduino 118. Arduino Voltmeter Code 119. Easily control your iPod using Arduino 120. Candy Tossin Coffin using an Arduino 121. Arduino 7 segment Displays Digital Clock With Charlieplexing LEDs 122. Arduino controlled webcam panner 123. Binary/ Analog Clock 124. Universal Gripper

Upload your custom Arduino code with the corresponding library file 3. Add the used libraries 4. Select the used in-outputs in the Arduino IO Simulator 5. Connect the Arduino IO Simulator to the Arduino board with the right se-rial port 1. Connect the Arduino Board The Arduino IO Simulator works with a lot of