Id
stringlengths
1
5
Tags
stringlengths
3
75
Title
stringlengths
15
150
CreationDate
stringlengths
23
23
Body
stringlengths
51
27.6k
Answer
stringlengths
42
31k
1
|arduino-uno|web-server|ethernet|
Is an Arduino capable of running 24/7?
2014-02-11T22:24:09.530
<p>I'm making a simple Arduino web server and I want to keep it turned on all the time. So it must endure to stay working continuously. </p> <p>I'm using an Arduino Uno with a Ethernet Shield. It's powered with a simple outlet power supply 5V @ 1A.</p> <p>My Questions:</p> <ul> <li>Will I have any problems leaving the Arduino turned on all the time?</li> <li>Is there some other Arduino board better recommended for this?</li> <li>Are there any precautions that I need to heed regarding this?</li> </ul>
<p>It certainly can run 24/7. I either use 5V to the 5V pin, or a 7808 to the Vin pin to offload the vreg. Ideally it would be 6.5V, but I don’t have such supplies. You may want a decoupler cap on 5V though, to soak any minor spikes when powering up your supply.</p> <p>Any hardware attached which runs at 5V, I feed with a 7805. You can use LM317s or LM350s in lieu of 78XXs, but you’ll need a few resistors for those, perhaps trimpots.</p>
4
|ethernet|arduino-yun|web|
How to get HTTPS on Arduino?
2014-02-11T22:43:08.173
<p>Put plainly: is there a way to get an HTTPS connection on the Arduino?</p> <p>I have been looking in to it, and I have found it is impossible with the standard library and the Ethernet shield, but is there a custom library that can do it? </p> <p>What about a coprocessor, i.e. like the WiFi shield has? Anyone know if the Arduino yún has ssl?</p>
<p>Using of WiFi shield can be a solution - it supports HTTPS. </p> <p><a href="https://www.arduino.cc/en/Reference/WiFi101" rel="nofollow noreferrer">https://www.arduino.cc/en/Reference/WiFi101</a></p>
6
|power|battery|
What are (or how do I use) the power saving options of the Arduino to extend battery life?
2014-02-11T22:48:30.837
<p>For solar &amp; battery powered projects, decreasing power consumption is a necessity.</p> <p>I know a little bit about using a timer and interrupt to put the microcontroller into sleep when it isn't doing anything.</p> <p>I have also read that you can disable some peripherals to further save power.</p> <p>Here is a page explaining these: <a href="http://arduino720.wikispaces.com/Power+Saving+Techniques">Power Saving Techniques</a></p> <p>My question:</p> <ul> <li>What other techniques are there to save power?</li> <li>Are there any libraries that make using these AVR features easier?</li> </ul>
<p>Once your project is working and you need to deploy to "production" environment, you can opt to replace the Arduino with a bare meta ATMega328 or any of the ATTiny family chips. This will get rid of all the power eaters on the Arduino board you don't need. I found: </p> <ul> <li>Arduino board of 9V block battery - 56 mA</li> <li>ATTiny85 bare on 8 MHz without sleep modes etc - 10 mA</li> <li>ATTiny85 bare on 8 MHz in sleep mode - 0.03 mA</li> </ul> <p><strong>Some more information</strong></p> <p><a href="http://www.instructables.com/id/Program-an-ATtiny-with-Arduino/">Program an ATtiny with Arduino</a></p> <p><a href="https://code.google.com/p/arduino-tiny/">ATTiny files for Arduino IDE</a></p>
14
|arduino-yun|linux|bootloader|
Yún boot from SD card
2014-02-11T23:57:39.350
<p>I have an Arduino Yún, and it only has 16mb flash onboard for the Linux. I was wondering of it is possible to put a bootloader on the flash that uses the sd card as a rootfs? i want to be able to do more projects on it than those that can fit in 16 MB flash.</p>
<p>And the Arduino team finally figured it out:</p> <p><a href="http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/" rel="noreferrer">http://blog.arduino.cc/2014/05/06/time-to-expand-your-yun-disk-space-and-install-node-js/</a></p>
17
|uploading|avrdude|faq|
"avrdude: stk500_getsync(): not in sync: resp=0x00," aka Some Dude Named Avr Won't Let Me Upload My Program
2014-02-12T00:08:14.933
<p>I made an awesome program the other day, and I wanted to upload it to my Arduino. After clicking the upload button, some mean dude named avr came along and stopped me, saying:</p> <blockquote> <p>avrdude: stk500_getsync(): not in sync: resp=0x00</p> </blockquote> <p><em>All</em> I want to do is just upload my program, but avr won't let me. He's even unintelligible, so can someone tell me what the heck he's trying to say and how to get rid of him?</p> <hr> <p>i.e.:</p> <p>Whenever I try to upload a program to my Arduino, I get this error message:</p> <blockquote> <p>avrdude: stk500_getsync(): not in sync: resp=0x00</p> </blockquote> <p>What does this mean, and how can I fix it?</p>
<p>If you use <code>arduino-cli</code> and a Arduino Nano clone, you can change the bootloader to the old one, as said in other answers, by using the following command to upload to the Arduino:</p> <pre><code>arduino-cli upload -v -p /dev/ttyUSB0 --fqbn arduino:avr:nano:cpu=atmega328old program_name </code></pre> <p>Explanation:</p> <div class="s-table-container"> <table class="s-table"> <thead> <tr> <th style="text-align: left;">command</th> <th style="text-align: right;">explanation</th> </tr> </thead> <tbody> <tr> <td style="text-align: left;"><code>arduino-cli</code></td> <td style="text-align: right;">call <code>arduino-cli</code></td> </tr> <tr> <td style="text-align: left;"><code>-v</code></td> <td style="text-align: right;">Use verbose output</td> </tr> <tr> <td style="text-align: left;"><code>-p /dev/ttyUSB0</code></td> <td style="text-align: right;">The port, use <code>arduino-cli board list</code> to find the right port</td> </tr> <tr> <td style="text-align: left;"><code>--fqbn arduino:avr:nano:cpu=atmega328old</code></td> <td style="text-align: right;">Use avr board library, nano board and the Atmega328 CPU with the old bootloader</td> </tr> <tr> <td style="text-align: left;"><code>program_name</code></td> <td style="text-align: right;">Replace this with the name of the program you want to upload</td> </tr> </tbody> </table> </div>
25
|severino|reset|
Why Arduino Severino (S3V3) sometimes needs reseting when uploading a sketch?
2014-02-12T00:49:24.257
<p>I have an original Arduino UNO R3 that I bought and an <a href="http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3" rel="nofollow">Arduino Severino (S3V3)</a> that I've built.</p> <p>I have no problems uploading sketches to the UNO, but sometimes, when uploading to the Severino board, I have to hard reset it at a specific time during the upload process, when the IDE says something like this below:</p> <pre><code>avrdude: Version 5.11, compiled on Sep 2 2011 at 19:38:36 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" Using Port : \\.\COM1 Using Programmer : arduino Overriding Baud Rate : 115200 avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] </code></pre> <p>If I don't reset it when one of the <code>Send</code> messages are being displayed, I get the <code>not in sync</code> message, as below:</p> <pre><code>avrdude: Recv: avrdude: stk500_getsync(): not in sync: resp=0x00 </code></pre> <p>Other times, if I'm lucky, I can upload to the Severino board without having to reset it.</p> <p>So, my questions are:</p> <ol> <li><p><strong>Why does that happen? Why Severino needs a hard reset during upload?</strong></p></li> <li><p><strong>Why is the problem intermitent?</strong> Why does it happen sometimes and others it doesn't?</p></li> <li><p><strong>How can I fix that problem?</strong> Is there a simple change to the Severino design that would fix that?</p></li> </ol>
<p><strong>Why does that happen?</strong></p> <p>When the serial port is opened by either monitor, avrdude or other it toggles the DTR pin of the serial port. Which in turn is AC coupled through C4 100nF. This toggling is converted to a up and down pulse on the ATmega(CPU)'s RESET pin. The subsequent reset starts initially with the boot loader, which typically in turn waits for a avrdude's semiphore (e.i. Send: 0 [30] [20] ) and if seen then responds in turn and if not seen after a timeout period (typically 5s) it continues on with the application in flash space. </p> <p>You behavior is describing either; not hearing the response. Or the reset is not getting triggered. Since it does work some times I suspect its prior, but the later. </p> <p><strong>Why Severino needs a hard reset during upload?</strong></p> <p>This statement further supports the later.</p> <p><strong>Why is the problem intermitent?</strong></p> <p>the pulse is almost long and strong enough, where the DTR toggle is in code and likely has some significant inconsistency. </p> <p><strong>How can I fix that problem?</strong></p> <p>Yes, change the value of C4 100nF and or R11 10K, to better pass the toggle. I could derive some EE explanation of what value to pick. But I would suggest some trial and error.</p> <p>It should also have 5V clamping, as the RS232 levels can reach +/-12V (typically +/-9V) where the AC coupling prevents the DC and burn out. but the AC will stress it.</p>
26
|severino|serial|
Custom Arduino board beeps and process freezes while I'm uploading a sketch to it. Why?
2014-02-12T01:10:46.997
<p>The strangest thing is happening to a standalone Arduino board that I designed and built. The board (whose schematics are below) has the following features:</p> <ol> <li>It has a ATmega328P with a 5V voltage regulator and usual circuitry when set up as a standalone controller. </li> <li>It controls a scoreboard with several 7-display digits linked through the connectors on the right (JP1 through JP12). </li> <li>It has cursor buttons decoded using a voltage ladder through ANALOG_0 (A0).</li> <li>It has a Real Time Clock to keep time when it's turned off.</li> <li>It has an RF receiver module.</li> <li>It has a UART header (JP17) so I can program the board using a serial port.</li> <li>It has a speaker attached to digital pin 3 (D3). </li> </ol> <p><img src="https://i.stack.imgur.com/21kgT.png" alt="Controller schematics"></p> <p>I upload sketches to it using a RS232-to-TTL adapter that I've also built (schematics also below) and a Serial-to-USB cable. When programming it, the board behaves much like a <a href="http://arduino.cc/en/Main/ArduinoBoardSerialSingleSided3" rel="noreferrer">Severino board</a>.</p> <p><img src="https://i.stack.imgur.com/h3HJq.png" alt="enter image description here"></p> <p>What's strange is that, when I upload a sketch, the process is paused in the middle and then the speaker starts to beep continually. It pauses with the following avrdude messages:</p> <p>avrdude: Version 5.11, compiled on Sep 2 2011 at 19:38:36 Copyright (c) 2000-2005 Brian Dean, <a href="http://www.bdmicro.com/" rel="noreferrer">http://www.bdmicro.com/</a> Copyright (c) 2007-2009 Joerg Wunsch</p> <pre><code> System wide configuration file is "C:\arduino-1.0.3\hardware/tools/avr/etc/avrdude.conf" Using Port : \\.\COM1 Using Programmer : arduino Overriding Baud Rate : 115200 </code></pre> <p>When I press reset on the board, avrdude continues outputting its messages (such as below), the beep stops, the upload continues and the sketch is uploaded successfully to the board.</p> <pre><code>avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] ... messages and upload continue and completes successfully. </code></pre> <p>I don't have the rest of the messages handy here, but I hope you get the idea.</p> <p>So, my questions are:</p> <ol> <li><strong>What is making the upload process pause?</strong></li> <li><strong>Why is the buzzer beeping when the process pauses?</strong></li> </ol>
<p>I finally found what was causing the problem: the reset signal from pin 4 (DTR - Data Terminal Ready) on the DB9-Female connector was spiking up to 10V before going to 0V and was triggering high-voltage programming on the ATmega. Below is a scope shot showing the situation:</p> <p><img src="https://i.stack.imgur.com/IM3RF.png" alt="Scope shot showing voltage spike to 10V"></p> <p>The yellow trace is <code>DTR</code> signal while the green trace is the <code>RESET</code> signal on the ATmega.</p> <p>According to Atmel's <a href="http://www.atmel.com/images/atmel-2521-avr-hardware-design-considerations_application-note_avr042.pdf" rel="nofollow noreferrer">Atmel AVR042: AVR Hardware Design Considerations application note</a>, one should add an ESD diode between ATmega's <code>RESET</code> and <code>Vcc</code> to prevent the reset signal from triggering high-voltage programming mode, like so:</p> <p><img src="https://i.stack.imgur.com/GJuGd.png" alt="Recommended RESET pin connection for ATmegas"></p> <p>After adding such a small signal diode (1N4148) like the app note recommended, I got the issue fixed. See below the scope shot taken after the diode was added.</p> <p><img src="https://i.stack.imgur.com/kwpzB.png" alt="Scope shot after fixing the board"></p> <p>Now the 10V peak is gone. </p> <p>That was a tricky one!! But I could never find what was wrong without research and the right tools. Money on a scope is money well spent!!</p>
27
|time|millis|
How do I get an accurate time?
2014-02-12T01:34:28.287
<p>I've made a clock using an Arduino, but the time seems to drift. I am aware of the <a href="https://arduino.stackexchange.com/questions/1/is-an-arduino-capable-of-running-24-7/2#2">rollover</a> issue; the clock seems to drift by about 15 minutes over the course of a week.</p> <p>I'm using a custom PCB with <a href="http://www.digikey.com/product-search/en/crystals-and-oscillators/resonators/852887?k=x908-nd">this resonator</a> from Digi-key. The code reads the millis() function at the beginning of each loop, and works from that value.</p> <p>My question is: How can I measure time with an Arduino, accurately enough to make a passable desk clock?</p>
<p>You do not need an RTC to build a clock: the ATmega chip has all the hardware needed to perform the duties of the RTC itself. Here is how:</p> <ol> <li><p>Get a 32768&nbsp;Hz watch crystal: either buy it or disassemble an old clock. These crystals, specifically designed for time keeping, have an <em>extremely</em> small temperature drift. You would also need one of those if you wanted to use an RTC chip.</p></li> <li><p>Configure the fuses of your ATmega to run off the 8&nbsp;MHz RC oscillator. This will make your <code>millis()</code> function horribly inaccurate, and also free the XTAL1 and XTAL2 pins.</p></li> <li><p>Connect the watch crystal to the TOSC1 and TOSC2 pins. These are the same pins as XTAL1 and XTAL2 (9 and 10 on the 328P). The different names are used to mean different functions.</p></li> <li><p>Configure the Timer/Counter 2 for asynchronous operation, normal counting mode, prescaler set to 128, and enable the timer overflow interrupt.</p></li> </ol> <p>Now you will get a TIMER2_OVF interrupt at a very steady rate of once per second. You only need to advance the clock display by one second in the ISR. In between the interrupts, you can put the MCU in very deep sleep (power-save sleep mode: nothing runs but Timer/Counter 2) and run for years on a couple of AA cells. Unless the display is power-hungry, obviously.</p> <p>I did exactly this to build my <a href="http://unsecure.logre.eu/wiki/Horloge_analogique_24h/en">24-hour one handed wall clock</a>. This link points now to the English translation of the original documentation in French.</p> <h2>Quartz calibration</h2> <p>If you do not calibrate your quartz, you can expect a significant drift, typically <strong>a few seconds per week</strong>. The drift rate depends on the stray capacitance of the traces that connect the crystal to the MCU. In principle, it could be removed by adding some extra, finely tuned capacitance. It is worth noting that you would have <em>the same drift problem</em> with an RTC.</p> <p>If you are satisfied with this kind of accuracy, then live with it and be happy. However, if you care to measure the drift, you will notice that it is very stable. You can then easily compensate for it in software, and achieve an accuracy of <strong>a few seconds per year</strong>.</p> <p>The algorithm for correcting the drift is very simple. From the measured drift, you figure out the precise delay between the interrupts, which should be very close to 10<sup>9</sup>&nbsp;nanoseconds, then:</p> <pre class="lang-c prettyprint-override"><code>#define ONE_SECOND 1000000000 // in nanoseconds #define ONE_INTERRUPT 999993482 // for example ISR(TIMER2_OVF_vect) { static uint32_t unaccounted_time; unaccounted_time += ONE_INTERRUPT; while (unaccounted_time &gt;= ONE_SECOND) { advance_display_by_one_second(); unaccounted_time -= ONE_SECOND; } } </code></pre> <p>In the above example, the quartz is slightly too fast, and the software compensates by “missing” a tick every few days. If the quartz was too slow, the same code would instead double-tick once every few days.</p> <p>This kind of calibration could also be done for an RTC, but it would be significantly more complex because the RTC reports the time in a broken-down form that does not naturally lend itself to arithmetic operations.</p>
28
|arduino-uno|matlab|
How to pause Arduino for 1 millisecond through MATLAB?
2014-02-12T01:37:23.670
<p>I have been able to connect MATLAB to my Uno with this line of code: <code>a = arduino('COM4');</code> through this package: <a href="http://www.mathworks.com/matlabcentral/fileexchange/32374-matlab-support-package-for-arduino-aka-arduinoio-package" rel="noreferrer">Matlab support package for Arduino</a>.</p> <p>Right now, MATLAB is my main script that will synchronize all the components [like the Arduino].</p> <p>I am able to send pulses to my stepper-motor just by using:</p> <pre><code>void loop() { digitalWrite(2, HIGH); delay(1); digitalWrite(2, LOW); delay(1); } </code></pre> <p>This works fine, and will make the motor move about once every 2 milliseconds. My problem is that I cannot find a way to produce this same delay through MATLAB's interface. I do know that MATLAB has a <code>pause()</code> function, but when I set up a loop in MATLAB like this:</p> <pre><code>a = arduino('COM4'); for m = 1:400 a.digitalWrite(2, 1); pause(0.001); a.digitalWrite(2, 0); pause(0.001); end </code></pre> <p>Each step takes WAY longer - about 200 milliseconds each.</p> <p>What are other options for creating the pause between digital High / Low being sent to the Arduino? It would be nice if I could control the outcome from Matlab, through Arduino.</p>
<p>It's not clear from your question whether you are trying to get real-time execution without latency or simply want to adjust the motor delay time from MATLAB. If the latter, a good way is to send delay data (e.g. a number that represents how long you want between pulses) vie serial, which your Arduino program will receive and update the motor delay as desired. Or, bearing in mind RAM limitations, you can send a whole sequence of delays that can run one after another with precise timing.</p>
36
|web-service|
Post Data To a Web Service From Arduino
2014-02-12T02:59:15.323
<p>If you want to submit sensor data such as temperature to a remote server/database somewhere you need to use some kind of call to a web server since it isn't possible to connect directly to a database from the Arduino.</p> <p>How do you post data to a JSON web service from an Arduino that's connected to the Internet?</p>
<p>Check <a href="http://playground.arduino.cc/Code/WebClient" rel="nofollow">this</a> from Arduino docs. </p> <p>In the "Post method request" code example just define your JSON as plain text like <code>char jsonData[] = "{name: 'yourName', data: 'yourData'}"</code> for example, and then call <code>byte postPage(char* domainBuffer,int thisPort,char* page,char* thisData)</code> function passing "jsonData" variable defined before for "thisData" parameter.</p> <p>It worked for me, hope it helps.</p>
37
|compile|sketch-size|avr-gcc|gcc|
Is there a preprocessor constant for memory size
2014-02-12T03:05:17.680
<p>I would like my compiles to exclude some code depending upon the flash/program space available. To be used in the demo code of a library I support. Whereas my current solution is to use a #ifdef of processor type. But I would like to be more general and not have to specify all the various chips. Rather it would be nice if there was a pre-processor constant that stated the available size. </p> <p>Where I am not fluent enough in gcc and or avr-gcc I might expect to find some constants similar those that define the beginning and end of the heap.</p> <p>On case example. Is that both the UNO and Leo have 32K of Flash. But the Leo's core library uses 4K for USB support, resulting in only 28K available. My Library's demo is near max'ed out on the UNO and I would like to automatically trim out based on available program space. </p>
<p>Find the <code>io__.h</code> file for your microcontroller, on Linux it is located in <code>/usr/lib/avr/include/avr</code>, on Windows it will be in a somewhat similar location.</p> <p>Scroll down to the part that says <code>/* Constants */</code>. There are couple interesting macros defined there, <code>FLASHEND</code> being the one you should be interested in. You can use it for example as follows:</p> <pre><code>#if FLASHEND &gt; 0x8000 /* Include some extra code when sufficient flash is available. */ #endif </code></pre>
39
|ethernet|arduino-uno|shields|
Arduino Uno R2 and Ethernet Shield R3 compatibility
2014-02-12T04:10:06.223
<p>I bought an <a href="http://arduino.cc/en/Main/ArduinoEthernetShield" rel="noreferrer">Ethernet Shield R3</a> for my <a href="http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/" rel="noreferrer">Arduino Uno R2</a>, but since R3 has extra pins it does not fit. Can I use the shield? Should I cut off the extra pins. What do I need to do to make it work?</p>
<p>The only issue that may create an incompatibility seems to be the IOREF pin next the 5V output pin which is extra on Revision 3 but not in Revision 2.</p> <p>However, I just had a look at the board schematics and the shield does not use IOREF.</p> <blockquote> <p><img src="https://i.stack.imgur.com/hOkcc.png" alt=""></p> </blockquote> <p><sub><strong>Pin 2 is extending IOREF</strong></sub></p> <p>So, the shield should work correctly with the Uno Revision 2. As far as the extra pins are concerned, I would recommend not damaging them in any way. If you absolutely <em>need</em> to, then just try to bend them outwards very carefully.</p>
40
|programming|arduino-ide|c++|ide|
What are the other IDEs for Arduino?
2014-02-12T04:22:30.253
<p>The basic Arduino IDE lacks a lot of the sophistication present in other IDEs such as code completion, code collapsing, folder organisation, etc. Are there other IDEs that allow programming in C or C++ and improve on these aspects?</p>
<p>I use Eclipse and Sublime Text for editing Arduino code, and I build in the Arduino IDE with it set to "external editor" mode, or using the Arduino Command Line tools. Eclipse has a fantastic indexer and makes understanding the Arduino core much easier. I've written a detailed PDF about using and setting up Eclipse for professional software development, incl for Arduino, here: <a href="https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf" rel="nofollow noreferrer">https://github.com/ElectricRCAircraftGuy/eRCaGuy_dotfiles/blob/master/eclipse/Eclipse%20setup%20instructions%20on%20a%20new%20Linux%20(or%20other%20OS)%20computer.pdf</a>.</p> <p>Note that I'm using regular Eclipse for C/C++, with no Arduino plugins. I don't find them that useful since they can never seem to keep up with the latest Arduino build tools anyway. </p> <p>See my document for full setup information in general.</p> <h1>Related:</h1> <ol> <li><a href="https://arduino.stackexchange.com/questions/816/c-vs-the-arduino-language/50839#50839">C++ vs. The Arduino Language?</a></li> </ol>
42
|software|avr-toolchain|
Assembly on the Arduino: IO registers
2014-02-12T04:24:33.670
<p><strong>Question:</strong> What registers do I use to access the IO on the Arduino Uno when I am using assembly for programming?</p> <p><strong>Background:</strong> I was interested in practicing my assembly language skills on the Arduino (I thought it would be easier to turn LEDs on/off than to worry about console IO). From doing a <a href="https://electronics.stackexchange.com/q/12750/17375">preliminary search</a>, I have found that the AVR toolchain can be used to program the Arduino. Yet, I don't quite know how to find the corresponding registers for the IO pins.</p>
<p>The datasheets for the AVR microcontrollers are reasonably good to read. Just Google for the exact controller on your Arduino (eg. ATmege328) and find the "Complete" datasheet on the <em>atmel.com</em> website. Don't download the "Summary", it doesn't include a lot of information. Download the datasheet from atmel.com, that is the only location with the most recent documentation.</p> <p>There are three registers used in basic IO (check the chapter called "I/O-Ports"):</p> <p>Where <em>n</em> is a port identifier, a letter ranging from A, B, C, ... depending on the number of IO pins your controller has. Each bit in each register represents a single GPIO pin (yes, you need some basic knowledge on binary to fully understand this).</p> <ul> <li><strong>DDR</strong><em>n</em>, Data Direction Register: This basically configures a pin for either input (0) or output (1). </li> <li><strong>PORT</strong><em>n</em>, Port n Data Register: When a pin is set as output, the related bit toggles the output pin high (1) or low (0). When configured as input, this enables a weak pull up resistor on the output pin.</li> <li><strong>PIN</strong><em>n</em>, Port n Input Register: Use this register to read the current level on a pin that is configured as input.</li> </ul>
52
|arduino-uno|safety|reliability|
How do I figure out if my board is approaching end of life?
2014-02-12T04:54:51.720
<p>I have a uno that I have been using for 3 years now. I will be using it again in a rather critical project in which failure on the part of the board could be rather expensive and dangerous. So, I would like to be sure that the board is not approaching end of life or going to fail anytime soon. Is there any reliable way to figure out how long the board will function without failing or reduction in performance?</p>
<p>One of the sections of the Arduino that is likely to become unreliable over time is its memory. There are <a href="http://arduino.cc/en/Tutorial/Memory" rel="nofollow noreferrer">three pools of memory</a> in the microcontroller used on avr-based Arduino boards:</p> <ul> <li>Flash memory (program space), is where the Arduino sketch is stored.</li> <li>SRAM (static random access memory) is where the sketch creates and manipulates variables when it runs.</li> <li>EEPROM is memory space that programmers can use to store long-term information.</li> </ul> <p>The memory is one part of the board that can be checked and verified, and thus evaluated for reliability/health. A very basic way to check memory would be to write a certain 8-bit pattern (byte character) over every address in the memory and then read the value present from every address. If the value that was written matches the value that is read, then that specific 8 bit block in memory is functioning correctly at the present moment.</p> <p>Wear in ROM memory usually occurs in a blockwise pattern i.e. n*8-bit blocks become degraded over time. So, for a 2K byte ROM chip, the health of the chip can be estimated by writing and reading from every byte on the chip, and calculating the percentage of correctly functioning blocks. If the percentage of failed blocks is significant (15%-20%), that means that the memory is likely to fail soon.</p> <p>The test code can be written using separate methods for each of the memory sections.</p> <h3>SRAM</h3> <p>Any variables declared statically or dynamically are allocated on the SRAM. So, we could declare a large character array (~2000) and fill every element with 255 (all bits 1). Then, we could attempt to read each of those elements and see if the value being read is indeed 255.</p> <h3>EEPROM</h3> <p>The EEPROM can be manipulated using the <a href="http://www.arduino.cc/en/Reference/EEPROM" rel="nofollow noreferrer">EEPROM library</a>. The library provides functions to read and write from specific locations in the EEPROM. So, all memory addresses can be tested by simply looping over the entire memory space. <em>This operation will require 500 writes and reads.</em></p> <p>Depending on the board usage, EEPROM is most likely to fail first but is not critical to board operation.</p> <h3>Flash</h3> <p>Data can be stored on the flash memory using the <a href="http://www.arduino.cc/en/Reference/PROGMEM" rel="nofollow noreferrer"><code>PROGMEM</code></a> directive. Similar to SRAM, a large array can be declared and initialized here. Then, values can be read and checked.</p>
57
|web-service|
What's the best way to put in a database sensors data's
2014-02-12T05:21:37.753
<p>I have not already started to try but I'm a good webmaster and I'm just asking which way is more suitable for sending and keeping data from sensors and I/0 state in a database.</p> <p>Here are some points:</p> <ul> <li>Post versus get</li> <li>MySQL or others types</li> <li>Security layers</li> <li>Graphics render of data's (google API?)</li> <li>PHP, ruby, JavaScript...</li> <li>Able to send data request's to Arduino's</li> <li>Ethernet shield, wifi, I2c ???</li> <li>Access via Android app...</li> </ul> <p>Anyway, the goal here is to know pros and cons of integrate all my Arduino through database.</p>
<p>It depends on your skills and what you have in your Arduino "box". Let's assume you have an ethernet or WiFi shield.</p> <p>I would go with a PHP script (I'm a PHP dev, but any language will fit) that accepts POST requests sent by the board and store them in a SQLite db.</p> <p><strong>Why SQLite instead of MySQL?</strong> Well, it's just a matter of data portability. You copy the SQLite file or send it via email and you're done: there are plenty of clients out there to read your db, in *nix based machines is frequently integrated in the OS. </p> <p>MySQL requires a sort of "infrastructure" to be written/read.</p>
61
|emulation|testing|
Can I program for Arduino without having a real board?
2014-02-12T06:15:47.017
<p>I would like to start the development of some basic Arduino projects but I don't own an Arduino board yet. Is there a way I can write my code and emulate/test it using a desktop computer so after my board arrives I just have to upload and run my project on it?</p>
<p>An alternative to simulators are services similar to online compilers like <a href="http://coliru.stacked-crooked.com/" rel="nofollow noreferrer">coliru</a>, which allow users to build and run their code on a remote system. This approach has the same limitations as online compilers:</p> <ul> <li><p>The hardware configuration and state cannot be altered remotely, except for explicitly defined interfaces.</p> </li> <li><p>The changes to the hardware state cannot be observed, again, except for explicitly defined interfaces.</p> </li> </ul> <p>Typically, most online compilers provide users with access to command line and process STDOUT. On Arduino, providing remote access to the serial port would provide a similar degree of control: users would be able to observe and control their running sketch through UART, but would not be able to connect/remove wires, push buttons, act on external sensors, etc.</p> <p>Surprisingly, I couldn't find any such online services, so I ended up writing my own - <a href="https://github.com/dimag0g/hwfarm" rel="nofollow noreferrer">HW Farm</a>. If you have a web server and Arduinos you can connect to it, you can install HW Farm on it and let people access those Arduinos through a web interface. I also <a href="https://dimagog.ddns.net/hwfarm/" rel="nofollow noreferrer">host</a> such a server myself, which has a single Arduino Mega with a bunch of I2C devices connected to it. You can try it out, but don't expect it to be online and available all the time.</p>
71
|clones|
Compatibility between Arduino and Arduino clones
2014-02-12T07:22:41.363
<p>In a project I am using a Seeeduino v3.0 as an Arduino clone. On the seeeduino website it says that </p> <blockquote> <p>It is based on the Duemilanove schematic, 100% compatible to its existing program, shield and IDEs.</p> </blockquote> <p>In fact I never had any problems with shields or the IDE.</p> <p>My question is now: Is the seeeduino and other clones really 100% compatible? The seeeduino board was considerable cheaper then an arduino.</p>
<p>I have found that most clones will do what you expect them to do, but as <a href="https://arduino.stackexchange.com/users/32/x4mer">x4mer</a> states in his <a href="https://arduino.stackexchange.com/questions/71/compatibility-between-arduino-and-arduino-clones#answer-90">answer</a>, be prepared.</p> <p>The most annoying issue, and even then it <em>is</em> quite minor, is that a lot of Chinese clones do not use an ATMega for the USB and instead use a <strong>CH340G</strong>. These chips, while fine when connecting to a PC running Windows 7, have great difficulties with the drivers on OS X, and end up just not being recognised. It is possible <a href="http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html" rel="nofollow noreferrer">to find a driver for the CH340G</a>, but when I installed it, it immediately crashed the MacBook, upon plugging in the cloned UNO..!</p> <p>I had to buy three or four clones on eBay until I got an Uno with an <em>actual</em> 16u2 implementing the USB interface, which would actually be recognised by the MacBook Pro, and would allow me to code using the Arduino IDE running on OS X.</p> <p>Before that, I had to use a Wintel laptop.</p>
74
|arduino-uno|enclosure|
Does Arduino Uno R3 require cooling in a closure?
2014-02-12T07:36:18.303
<p>I was looking at getting an enclosure to house my Arduino Uno R3, but I'm not sure if I should also attach a fan. Does anyone have experience with this? It doesn't look like much heat is being generated, but with no ventilation except some slits in the enclosure, there won't be much air circulation without a fan. My concern with adding a fan was the fact that I'd need to power it.</p>
<p>No, You shouldn't need any type of cooling device such as a fan as long as the case has a few holes in order to allow the heat to rise out of the case. I do not recommend using cases that are completely sealed, unless you are using it in an environment that has things that could hard the Arduino such as ROVs or Nuclear waste facility (although I don't know why you would be at one in the first place).</p>
85
|serial|pins|uploading|arduino-uno|
Why can't I upload a sketch while other components/devices are connected to my Uno?
2014-02-12T10:22:23.107
<p>I wanted to make a fairly simple circuit which would flash a series of LEDs in sequence, using my Arduino Uno (more specifically, a SainSmart clone). I wrote my sketch and it compiled fine. After that, I connected 8 LEDS+resistors to pins 0 through 7, and then connected the Uno to my computer via USB.</p> <p>I've uploaded sketches successfully in the past, so I'm sure my settings and drivers etc. are correct. However, when I tried to upload my sketch this time, it didn't work.</p> <p>I tried removing everything I'd connected to the Arduino's pins, and suddenly the upload worked again.</p> <p>Why does this happen? Does it mean I have to disconnect everything from the board every time I upload a sketch?</p>
<p>" Peter R. Bloomfield " I used to upload sketch in my arduino uno by connecting Rx and Tx pin but my sketch get uploaded. Actually problem is arduino uno driver may be deleted in your case</p>
88
|pins|arduino-uno|current|
Is there a limit on how much current a pin can sink?
2014-02-12T11:40:08.950
<p>I've been experimenting with an 8x8 LED matrix controlled by an Arduino Uno. As I think is typical, the matrix uses a common anode for each row, and a common cathode for each column. </p> <p>At the moment, I've got all the matrix pins connected directly to IO pins on the Uno, and I haven't had any problems lighting the LEDs one-by-one. Going through the whole matrix like this makes updates a little slow though, meaning the LEDs aren't as bright as I'd like.</p> <p>As far as I know, I can't safely light up an entire row at once, because an individual pin on the Uno isn't capable of sourcing enough current to drive 8 separate LEDs at the same time (requiring at least 10mA each to be bright enough).</p> <p>It occurred to me that the reverse might be safer. If I light up an entire column at a time, then each pin only has to source enough current for one LED, which should be no problem. However, it relies on one pin potentially sinking the current from all 8, totalling at least 80mA.</p> <p>Is this possible, or am I going to fry my board?</p>
<p><a href="https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins/67094#67094">I'm going to steal my answer from when I answered this question on the last arduino SE attempt.</a></p> <hr> <p>This is a bit complex. Basically, there are a number of limiting factors:</p> <p>The IO lines from the microcontroller (i.e. the analog and digital pins) have both an aggregate (e.g. total) current limit, and an per-pin limit:</p> <p><img src="https://i.stack.imgur.com/nLAlB.png" alt="enter image description here"><br> <sup><sub>From the <a href="http://www.atmel.com/Images/doc8161.pdf" rel="noreferrer">ATmega328P datasheet</a>.</sub></sup></p> <p>However, depending on how you define the Arduino "Pins", this is not the entire story. </p> <p>The 5V pin of the arduino is <em>not connected through the microcontroller</em>. As such, it can source significantly more power. When you are powering your arduino from USB, the USB interface limits your total power consumption to 500 mA. This is shared with the devices on the arduino board, so the available power will be somewhat less.<br> When you are using an external power supply, through the barrel power connector, you are limited by the local 5V regulator, which is rated for a maximum of <strong>1 Amp</strong>. However, this it also <em>thermally limited</em>, meaning that as you draw power, the regulator will heat up. When it overheats, it will shut down temporarily.</p> <p>The 3.3V regulated output is able to supply 150 mA max, which is the limit of the 3.3V regulator.</p> <hr> <h2>In Summary</h2> <ul> <li>The <em>absolute maximum</em> for any single IO pin is <strong>40 mA</strong> (<sub><sup>this is the <em>maximum</em>. You should never actually pull a full 40 mA from a pin. Basically, it's the threshold at which Atmel can no longer guarantee the chip won't be damaged. You should always ensure you're safely <em>below</em> this current limit.</sub></sup>)</li> <li>The total current from all the IO pins together is <strong>200 mA max</strong> </li> <li>The 5V output pin is good for <strong>~400 mA on USB, ~900 mA when using an external power adapter</strong> <ul> <li>The 900 mA is for an adapter that provides ~7V. As the adapter voltage increases, the amount of heat the regulator has to deal with also increases, so the maximum current will drop as the voltage increases. <sub><sup>This is called <em>thermal limiting</em></sup></sub></li> </ul></li> <li>The 3.3V output is capable of supplying <strong>150 mA</strong>. <ul> <li>Note - Any power drawn from the 3.3V rail <em>has to go through the 5V rail</em>. Therefore, if you have a 100 mA device on the 3.3V output, you need to <em>also</em> count it against the 5V total current.</li> </ul></li> </ul> <p><strong><sub>Note: This does not apply to the Arduino Due, and there are likely some differences for the Arduino Mega. It is likely generally true for any Arduino based off the ATmega328 microcontroller.</sub></strong></p>
91
|lcd|shields|
Is there a color LCD display for an arduino?
2014-02-12T12:43:33.707
<p>I currently have a Mega2560 with the LCD4884 Shield. The Shield is good for putting out text and simple pixel images. But I am wondering if there is something that has a full range of colours that would work with the Arduino? The screen size would only have to be a few inches in size.</p>
<p>Another very cool screen is the official <a href="http://store.arduino.cc/index.php?main_page=product_info&amp;products_id=288#.UwlAY_kiEw8" rel="nofollow">Arduino TFT LCD Screen</a>. (<a href="http://arduino.cc/documents/datasheets/A000096_Datasheet_HTF0177SN-01-SPEC.pdf" rel="nofollow">Datasheet</a> if you're curious.)</p> <p>It's a 1.77" screen, with a resolution of 160x128. It has a micro-SD slot in it, which is easily accessible. It is a color screen, with up to 18 bit per pixel. </p> <p>The extremely nice thing with this screen is that since it's officially supported, you don't need to do anything extra to support it. The <a href="http://arduino.cc/en/Reference/TFTLibrary#.UwlB__kiEw8" rel="nofollow">official Arduino TFT library</a> works perfectly with it. However, according to <a href="http://www.jameco.com/1/1/52373-a000096-tft-lcd-screen-runs-5vdc-shields.html" rel="nofollow">Jameco</a>:</p> <blockquote> <p>Library Update: There is a known issue with the TFT library supplied in IDE versions 1.0.5 and 1.5.4 Beta. You will need to replace the library. We have zipped up the updated TFT library for both versions available here. Just delete the existing library and copy in the replacement for the appropriate IDE version and restart the IDE. (IDE v1.0.5 or v1.5.4)</p> </blockquote> <p>So beside that minor fix, everything should be easy and quick to work with. <a href="http://arduino.cc/en/Reference/TFTLibrary#.UwlB__kiEw8" rel="nofollow">This page</a> has some code samples which should make it easy to work with.</p>
96
|power|heat|
Why is the regulator very hot?
2014-02-12T13:41:46.053
<p>We have an LED strip connected to output 6 and is powered by the Uno board itself. Shouldn't be drawing too much current, only have 10 elements on the LED strip. While this LED strip is connected to the Uno, I noticed that the regulator is getting very hot.</p> <p>One thing we haven't done yet is to power the LED strips from an external source, which will be necessary since there will be many strips. At the moment, the students are simply trying to debug their program with the small strip.</p>
<p>When a circuit is hot, it's very likely that it is drawing too much current. It may be a component that's getting more current than it's designed for, or a PCB track, or a wire.</p> <p>So, before you do anything else, I strongly suggest that you get a DMM and measure the current drawn by the board when powering the led strip. Google for ways to measure current with a DMM, as it can be tricky if you never done it before. </p> <p>Then, compare the value to those specified by the voltage regulator datasheet. The current should be within those values shown in the "Electrical Characteristics", and well below those from "Absolute Maximum Ratings". </p>
105
|programming|python|
Programming an Arduino using Python, rather than C/C++
2014-02-12T15:31:17.143
<p>I am not very skilled with the C Language and I was wondering if there is a way in which python could be used to program an Arduino. This would most likely require a different IDE in order to be able to debug the scripts them self. </p>
<p>You gotta use pyfirmata because that's the only way to make your son a PRO engineer who makes robots. Also, python can do more advanced stuff so use pyfirmata.</p>
113
|time|millis|
Is it possible to find the time taken by millis?
2014-02-12T16:04:13.967
<p>The function <code>millis</code> would be running in the span of 100+ microseconds or less. Is there a reliable way to go about measuring the time taken by a single millis call?</p> <p>One approach that comes to mind is using <code>micros</code>, however, a call to <code>micros</code> will include the time taken by the function call of <code>micros</code> itself as well, so depending on how long micros takes, the measurement for <code>millis</code> may be off.</p> <p>I need to find this as an application I am working on requires accurate time measurements for every step taken in the code, including <code>millis</code>.</p>
<p>If you want to know <em>exactly</em> how long something will take, there is only one solution: Look at the disassembly!</p> <p>Starting with the minimal code: </p> <pre><code>void setup(){}; volatile uint16_t x; void loop() { x = millis(); } </code></pre> <p>This code compiled and then fed into <code>avr-objdump -S</code> produces a documented disassembly. Here are the interesting excerpts:</p> <p><code>void loop()</code> produces: </p> <pre><code>000000a8 &lt;loop&gt;: a8: 0e 94 a7 00 call 0x14e ; 0x14e &lt;millis&gt; ac: 60 93 00 01 sts 0x0100, r22 b0: 70 93 01 01 sts 0x0101, r23 b4: 80 93 02 01 sts 0x0102, r24 b8: 90 93 03 01 sts 0x0103, r25 bc: 08 95 ret </code></pre> <p>Which is a function call (<code>call</code>), four copies (which copy each of the bytes in the <code>uint32_t</code> return value of <code>millis()</code> (note that the arduino docs call this a <code>long</code>, but they are incorrect to not be explicitly specifying the variable sizes)), and finally the function return.</p> <p><code>call</code> requires 4 clock cycles, and each <code>sts</code> requires 2 clock cycles, so we have a minimum of 12 clock cycles just for function call overhead.</p> <p>Now, lets look at the disassembly of the <code>&lt;millis&gt;</code> function, which is located at <code>0x14e</code>: </p> <pre><code>unsigned long millis() { unsigned long m; uint8_t oldSREG = SREG; 14e: 8f b7 in r24, 0x3f ; 63 // disable interrupts while we read timer0_millis or we might get an // inconsistent value (e.g. in the middle of a write to timer0_millis) cli(); 150: f8 94 cli m = timer0_millis; 152: 20 91 08 01 lds r18, 0x0108 156: 30 91 09 01 lds r19, 0x0109 15a: 40 91 0a 01 lds r20, 0x010A 15e: 50 91 0b 01 lds r21, 0x010B SREG = oldSREG; 162: 8f bf out 0x3f, r24 ; 63 return m; } 164: b9 01 movw r22, r18 166: ca 01 movw r24, r20 168: 08 95 ret </code></pre> <p>As you can see, the <code>millis()</code> function is fairly simple:</p> <ol> <li><code>in</code> saves the interrupt register settings (1 cycle)</li> <li><code>cli</code> turns off the interrupts (1 cycle)</li> <li><code>lds</code> copy one of the 4 bytes of the current value of the milli counter into a temporary register (2 clock cycles)</li> <li><code>lds</code> Byte 2 (2 clock cycles)</li> <li><code>lds</code> Byte 3 (2 clock cycles)</li> <li><code>lds</code> Byte 4 (2 clock cycles)</li> <li><code>out</code> restore interrupt settings (1 clock cycle)</li> <li><code>movw</code> shuffle registers around (1 clock cycle)</li> <li><code>movw</code> and again (1 clock cycle)</li> <li><code>ret</code> return from subroutine (4 cycles)</li> </ol> <p>So, if we add them all up, we have a total of 17 clock cycles in the <code>millis()</code> function itself, plus a call overhead of 12, for a total of 29 clock cycles.</p> <p>Assuming a 16 Mhz clock rate (most arduinos), each clock cycle is <code>1 / 16e6</code> seconds, or 0.0000000625 seconds, which is 62.5 nanoseconds. 62.5 ns * 29 = 1.812 microseconds.</p> <p>Therefore, the total execution time for a single <code>millis()</code> call on <em>most</em> Arduinos will be <strong>1.812 microseconds</strong>.</p> <hr> <p><a href="http://www.atmel.com/images/doc0856.pdf" rel="noreferrer">AVR Assembly reference</a></p> <p><sub>As a side-note, there is space for optimization here! If you update the <code>unsigned long millis(){}</code> function definition to be <code>inline unsigned long millis(){}</code>, you would remove the call overhead (at the cost of <em>slightly</em> larger code size). Furthermore, it looks like the compiler is doing two unnecessary moves (the two <code>movw</code> calls, but I haven't looked at it that closely).</sub></p> <p><sub>Really, considering the function call overhead is 5 instructions, and the actual <em>contents</em> of the <code>millis()</code> function is only 6 instructions, I think the <code>millis()</code> function should really be <code>inline</code> by default, but the Arduino codebase is rather poorly optimized.</sub></p> <hr> <p>Here is the full disassemby for anyone interested: </p> <pre><code>sketch_feb13a.cpp.elf: file format elf32-avr Disassembly of section .text: 00000000 &lt;__vectors&gt;: SREG = oldSREG; return m; } unsigned long micros() { 0: 0c 94 34 00 jmp 0x68 ; 0x68 &lt;__ctors_end&gt; 4: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 8: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 10: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 14: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 18: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 1c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 20: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 24: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 28: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 2c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 30: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 34: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 38: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 3c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 40: 0c 94 5f 00 jmp 0xbe ; 0xbe &lt;__vector_16&gt; 44: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 48: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 4c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 50: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 54: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 58: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 5c: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 60: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 64: 0c 94 51 00 jmp 0xa2 ; 0xa2 &lt;__bad_interrupt&gt; 00000068 &lt;__ctors_end&gt;: 68: 11 24 eor r1, r1 6a: 1f be out 0x3f, r1 ; 63 6c: cf ef ldi r28, 0xFF ; 255 6e: d8 e0 ldi r29, 0x08 ; 8 70: de bf out 0x3e, r29 ; 62 72: cd bf out 0x3d, r28 ; 61 00000074 &lt;__do_copy_data&gt;: 74: 11 e0 ldi r17, 0x01 ; 1 76: a0 e0 ldi r26, 0x00 ; 0 78: b1 e0 ldi r27, 0x01 ; 1 7a: e2 e0 ldi r30, 0x02 ; 2 7c: f2 e0 ldi r31, 0x02 ; 2 7e: 02 c0 rjmp .+4 ; 0x84 &lt;.do_copy_data_start&gt; 00000080 &lt;.do_copy_data_loop&gt;: 80: 05 90 lpm r0, Z+ 82: 0d 92 st X+, r0 00000084 &lt;.do_copy_data_start&gt;: 84: a0 30 cpi r26, 0x00 ; 0 86: b1 07 cpc r27, r17 88: d9 f7 brne .-10 ; 0x80 &lt;.do_copy_data_loop&gt; 0000008a &lt;__do_clear_bss&gt;: 8a: 11 e0 ldi r17, 0x01 ; 1 8c: a0 e0 ldi r26, 0x00 ; 0 8e: b1 e0 ldi r27, 0x01 ; 1 90: 01 c0 rjmp .+2 ; 0x94 &lt;.do_clear_bss_start&gt; 00000092 &lt;.do_clear_bss_loop&gt;: 92: 1d 92 st X+, r1 00000094 &lt;.do_clear_bss_start&gt;: 94: ad 30 cpi r26, 0x0D ; 13 96: b1 07 cpc r27, r17 98: e1 f7 brne .-8 ; 0x92 &lt;.do_clear_bss_loop&gt; 9a: 0e 94 f0 00 call 0x1e0 ; 0x1e0 &lt;main&gt; 9e: 0c 94 ff 00 jmp 0x1fe ; 0x1fe &lt;_exit&gt; 000000a2 &lt;__bad_interrupt&gt;: a2: 0c 94 00 00 jmp 0 ; 0x0 &lt;__vectors&gt; 000000a6 &lt;setup&gt;: a6: 08 95 ret 000000a8 &lt;loop&gt;: a8: 0e 94 a7 00 call 0x14e ; 0x14e &lt;millis&gt; ac: 60 93 00 01 sts 0x0100, r22 b0: 70 93 01 01 sts 0x0101, r23 b4: 80 93 02 01 sts 0x0102, r24 b8: 90 93 03 01 sts 0x0103, r25 bc: 08 95 ret 000000be &lt;__vector_16&gt;: #if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ISR(TIM0_OVF_vect) #else ISR(TIMER0_OVF_vect) #endif { be: 1f 92 push r1 c0: 0f 92 push r0 c2: 0f b6 in r0, 0x3f ; 63 c4: 0f 92 push r0 c6: 11 24 eor r1, r1 c8: 2f 93 push r18 ca: 3f 93 push r19 cc: 8f 93 push r24 ce: 9f 93 push r25 d0: af 93 push r26 d2: bf 93 push r27 // copy these to local variables so they can be stored in registers // (volatile variables must be read from memory on every access) unsigned long m = timer0_millis; d4: 80 91 08 01 lds r24, 0x0108 d8: 90 91 09 01 lds r25, 0x0109 dc: a0 91 0a 01 lds r26, 0x010A e0: b0 91 0b 01 lds r27, 0x010B unsigned char f = timer0_fract; e4: 30 91 0c 01 lds r19, 0x010C m += MILLIS_INC; e8: 01 96 adiw r24, 0x01 ; 1 ea: a1 1d adc r26, r1 ec: b1 1d adc r27, r1 f += FRACT_INC; ee: 23 2f mov r18, r19 f0: 2d 5f subi r18, 0xFD ; 253 if (f &gt;= FRACT_MAX) { f2: 2d 37 cpi r18, 0x7D ; 125 f4: 20 f0 brcs .+8 ; 0xfe &lt;__vector_16+0x40&gt; f -= FRACT_MAX; f6: 2d 57 subi r18, 0x7D ; 125 m += 1; f8: 01 96 adiw r24, 0x01 ; 1 fa: a1 1d adc r26, r1 fc: b1 1d adc r27, r1 } timer0_fract = f; fe: 20 93 0c 01 sts 0x010C, r18 timer0_millis = m; 102: 80 93 08 01 sts 0x0108, r24 106: 90 93 09 01 sts 0x0109, r25 10a: a0 93 0a 01 sts 0x010A, r26 10e: b0 93 0b 01 sts 0x010B, r27 timer0_overflow_count++; 112: 80 91 04 01 lds r24, 0x0104 116: 90 91 05 01 lds r25, 0x0105 11a: a0 91 06 01 lds r26, 0x0106 11e: b0 91 07 01 lds r27, 0x0107 122: 01 96 adiw r24, 0x01 ; 1 124: a1 1d adc r26, r1 126: b1 1d adc r27, r1 128: 80 93 04 01 sts 0x0104, r24 12c: 90 93 05 01 sts 0x0105, r25 130: a0 93 06 01 sts 0x0106, r26 134: b0 93 07 01 sts 0x0107, r27 } 138: bf 91 pop r27 13a: af 91 pop r26 13c: 9f 91 pop r25 13e: 8f 91 pop r24 140: 3f 91 pop r19 142: 2f 91 pop r18 144: 0f 90 pop r0 146: 0f be out 0x3f, r0 ; 63 148: 0f 90 pop r0 14a: 1f 90 pop r1 14c: 18 95 reti 0000014e &lt;millis&gt;: unsigned long millis() { unsigned long m; uint8_t oldSREG = SREG; 14e: 8f b7 in r24, 0x3f ; 63 // disable interrupts while we read timer0_millis or we might get an // inconsistent value (e.g. in the middle of a write to timer0_millis) cli(); 150: f8 94 cli m = timer0_millis; 152: 20 91 08 01 lds r18, 0x0108 156: 30 91 09 01 lds r19, 0x0109 15a: 40 91 0a 01 lds r20, 0x010A 15e: 50 91 0b 01 lds r21, 0x010B SREG = oldSREG; 162: 8f bf out 0x3f, r24 ; 63 return m; } 164: b9 01 movw r22, r18 166: ca 01 movw r24, r20 168: 08 95 ret 0000016a &lt;init&gt;: void init() { // this needs to be called before setup() or some functions won't // work there sei(); 16a: 78 94 sei // on the ATmega168, timer 0 is also used for fast hardware pwm // (using phase-correct PWM would mean that timer 0 overflowed half as often // resulting in different millis() behavior on the ATmega8 and ATmega168) #if defined(TCCR0A) &amp;&amp; defined(WGM01) sbi(TCCR0A, WGM01); 16c: 84 b5 in r24, 0x24 ; 36 16e: 82 60 ori r24, 0x02 ; 2 170: 84 bd out 0x24, r24 ; 36 sbi(TCCR0A, WGM00); 172: 84 b5 in r24, 0x24 ; 36 174: 81 60 ori r24, 0x01 ; 1 176: 84 bd out 0x24, r24 ; 36 // this combination is for the standard atmega8 sbi(TCCR0, CS01); sbi(TCCR0, CS00); #elif defined(TCCR0B) &amp;&amp; defined(CS01) &amp;&amp; defined(CS00) // this combination is for the standard 168/328/1280/2560 sbi(TCCR0B, CS01); 178: 85 b5 in r24, 0x25 ; 37 17a: 82 60 ori r24, 0x02 ; 2 17c: 85 bd out 0x25, r24 ; 37 sbi(TCCR0B, CS00); 17e: 85 b5 in r24, 0x25 ; 37 180: 81 60 ori r24, 0x01 ; 1 182: 85 bd out 0x25, r24 ; 37 // enable timer 0 overflow interrupt #if defined(TIMSK) &amp;&amp; defined(TOIE0) sbi(TIMSK, TOIE0); #elif defined(TIMSK0) &amp;&amp; defined(TOIE0) sbi(TIMSK0, TOIE0); 184: ee e6 ldi r30, 0x6E ; 110 186: f0 e0 ldi r31, 0x00 ; 0 188: 80 81 ld r24, Z 18a: 81 60 ori r24, 0x01 ; 1 18c: 80 83 st Z, r24 // this is better for motors as it ensures an even waveform // note, however, that fast pwm mode can achieve a frequency of up // 8 MHz (with a 16 MHz clock) at 50% duty cycle #if defined(TCCR1B) &amp;&amp; defined(CS11) &amp;&amp; defined(CS10) TCCR1B = 0; 18e: e1 e8 ldi r30, 0x81 ; 129 190: f0 e0 ldi r31, 0x00 ; 0 192: 10 82 st Z, r1 // set timer 1 prescale factor to 64 sbi(TCCR1B, CS11); 194: 80 81 ld r24, Z 196: 82 60 ori r24, 0x02 ; 2 198: 80 83 st Z, r24 #if F_CPU &gt;= 8000000L sbi(TCCR1B, CS10); 19a: 80 81 ld r24, Z 19c: 81 60 ori r24, 0x01 ; 1 19e: 80 83 st Z, r24 sbi(TCCR1, CS10); #endif #endif // put timer 1 in 8-bit phase correct pwm mode #if defined(TCCR1A) &amp;&amp; defined(WGM10) sbi(TCCR1A, WGM10); 1a0: e0 e8 ldi r30, 0x80 ; 128 1a2: f0 e0 ldi r31, 0x00 ; 0 1a4: 80 81 ld r24, Z 1a6: 81 60 ori r24, 0x01 ; 1 1a8: 80 83 st Z, r24 // set timer 2 prescale factor to 64 #if defined(TCCR2) &amp;&amp; defined(CS22) sbi(TCCR2, CS22); #elif defined(TCCR2B) &amp;&amp; defined(CS22) sbi(TCCR2B, CS22); 1aa: e1 eb ldi r30, 0xB1 ; 177 1ac: f0 e0 ldi r31, 0x00 ; 0 1ae: 80 81 ld r24, Z 1b0: 84 60 ori r24, 0x04 ; 4 1b2: 80 83 st Z, r24 // configure timer 2 for phase correct pwm (8-bit) #if defined(TCCR2) &amp;&amp; defined(WGM20) sbi(TCCR2, WGM20); #elif defined(TCCR2A) &amp;&amp; defined(WGM20) sbi(TCCR2A, WGM20); 1b4: e0 eb ldi r30, 0xB0 ; 176 1b6: f0 e0 ldi r31, 0x00 ; 0 1b8: 80 81 ld r24, Z 1ba: 81 60 ori r24, 0x01 ; 1 1bc: 80 83 st Z, r24 #if defined(ADCSRA) // set a2d prescale factor to 128 // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range. // XXX: this will not work properly for other clock speeds, and // this code should use F_CPU to determine the prescale factor. sbi(ADCSRA, ADPS2); 1be: ea e7 ldi r30, 0x7A ; 122 1c0: f0 e0 ldi r31, 0x00 ; 0 1c2: 80 81 ld r24, Z 1c4: 84 60 ori r24, 0x04 ; 4 1c6: 80 83 st Z, r24 sbi(ADCSRA, ADPS1); 1c8: 80 81 ld r24, Z 1ca: 82 60 ori r24, 0x02 ; 2 1cc: 80 83 st Z, r24 sbi(ADCSRA, ADPS0); 1ce: 80 81 ld r24, Z 1d0: 81 60 ori r24, 0x01 ; 1 1d2: 80 83 st Z, r24 // enable a2d conversions sbi(ADCSRA, ADEN); 1d4: 80 81 ld r24, Z 1d6: 80 68 ori r24, 0x80 ; 128 1d8: 80 83 st Z, r24 // here so they can be used as normal digital i/o; they will be // reconnected in Serial.begin() #if defined(UCSRB) UCSRB = 0; #elif defined(UCSR0B) UCSR0B = 0; 1da: 10 92 c1 00 sts 0x00C1, r1 #endif } 1de: 08 95 ret 000001e0 &lt;main&gt;: #include &lt;Arduino.h&gt; int main(void) 1e0: cf 93 push r28 1e2: df 93 push r29 { init(); 1e4: 0e 94 b5 00 call 0x16a ; 0x16a &lt;init&gt; #if defined(USBCON) USBDevice.attach(); #endif setup(); 1e8: 0e 94 53 00 call 0xa6 ; 0xa6 &lt;setup&gt; for (;;) { loop(); if (serialEventRun) serialEventRun(); 1ec: c0 e0 ldi r28, 0x00 ; 0 1ee: d0 e0 ldi r29, 0x00 ; 0 #endif setup(); for (;;) { loop(); 1f0: 0e 94 54 00 call 0xa8 ; 0xa8 &lt;loop&gt; if (serialEventRun) serialEventRun(); 1f4: 20 97 sbiw r28, 0x00 ; 0 1f6: e1 f3 breq .-8 ; 0x1f0 &lt;main+0x10&gt; 1f8: 0e 94 00 00 call 0 ; 0x0 &lt;__vectors&gt; 1fc: f9 cf rjmp .-14 ; 0x1f0 &lt;main+0x10&gt; 000001fe &lt;_exit&gt;: 1fe: f8 94 cli 00000200 &lt;__stop_program&gt;: 200: ff cf rjmp .-2 ; 0x200 &lt;__stop_program&gt; </code></pre>
117
|pins|arduino-uno|
Is there a way to have more than 14 Output pins on arduino?
2014-02-12T16:42:31.307
<p>Is it possible to have more than 14 output pins on the Arduino, I am working on a project in which I need to light up several LEDs individually. I only have an Arduino Uno, and I don't want to get a Mega. </p>
<p>There is a wealth of good answers here, but if you costed your time you'd find it cheaper to buy a Mega.</p> <p>My 3/2-d worth.</p>
122
|library|
What are the steps involved in porting an Arduino library?
2014-02-12T17:28:00.757
<p>I want to use the <a href="http://learn.adafruit.com/adafruit-cc3000-wifi" rel="nofollow noreferrer">Adafruit CC3000</a> and its <a href="https://github.com/adafruit/Adafruit_CC3000_Library" rel="nofollow noreferrer">Arduino libraries</a> on another platform. In this case it's the Arduino pin compatible <a href="http://www.cypress.com/?rID=77780" rel="nofollow noreferrer">PSOC4 Pioneer Kit</a>. This is an ARM Cortex M0 based platform.</p> <p>My question is: How would I go about porting a library like this? What are the steps, key files etc?</p> <p>One obvious issue is that PSOC Creator does not readily support C++.</p> <p>One positive might be that the Arduino Due board is based on the Atmel SAM3X8E ARM Cortex-M3 CPU.</p> <p>NOTE: If you think this question is off topic; please head over to <a href="https://arduino.meta.stackexchange.com/questions/22/is-it-ok-to-ask-questions-about-arduino-compatible-micros-not-clones">this question</a> on Arduino Meta to voice your opinion on whether questions on Arduino Compatible devices are appropriate for this list.</p>
<p>I did essentially the same thing with getting the Adafruit ST7735 library working in chipKIT. <a href="http://forums.adafruit.com/viewtopic.php?f=47&amp;t=42966">I started a support thread here which can lead you through my process</a>.</p> <p>I tackled it the same way I do general programming:<br> 1-» Copy over Libraries, get it so your compiler can actually SEE them.<br> 2-» Start trying to compile and then triage errors from the "top level" down:<br> 3-» Look for stlib functions you recognize as should be working and fix those.<br> 4-» Look for AVR specific code and comment those out. I normally also add my initials and a comment: <code>ckck - bitbanging SPI</code>, so I can search for these later.<br> Repeat 3 and 4 until it works or you quit. :)</p> <p>Reach out to the forums for your target; they might have been there done that -- or like in my case, you introduce them to something that they want, so they dive in and help.</p>
129
|arduino-uno|atmega328|
Is my ATmega broken, and would replacing it with another break that one, too?
2014-02-12T21:54:44.307
<p>I was communicating between my computer and my Arduino Uno R3 through Bluetooth using <a href="http://www.mdfly.com/index.php?main_page=product_info&amp;cPath=8_47&amp;products_id=769&amp;zenid=6f2b3946847b73b5ef2185e5e756e498" rel="nofollow noreferrer">this Bluetooth module</a>. The connector I use has a red wire where it connects to GND, and a black wire where it connects to +5V.</p> <blockquote> <p><img src="https://i.stack.imgur.com/upJ7C.png" alt="enter image description here"></p> <pre><code> ↓ ↓ to Uno ↓ ↓ +5V GND pin 0 pin 1 </code></pre> </blockquote> <p>I forgot this one time when I connected the Bluetooth module to the Uno, so the polarity was reversed. This fried the Bluetooth module.</p> <p>After getting a new module, I discovered that the Uno was apparently fried too. Plugging a USB cable into the Uno made the little green integrated LED turn on, but that was all that happened; none of the pins put out any electricity. When I tried to upload a program, it gave the infamous <code>avrdude: stk500_getsync(): not in sync: resp=0x00</code> error. I could upload programs to my other Uno fine, and I could not upload to the broken Uno on my other computer.</p> <p>Two of the Arduino experts I know told me that the ATmega328 chip might be the only broken part. Is this likely to be the case? I have an Uno R2 with a working ATmega328. Would temporarily replacing the R3's ATmega with that R2's ATmega have a change of damaging anything?</p>
<p>Besides breaking a pin while removing the IC from its socket, or static electricity during manipulation, I don't see what could fry the ATmega. </p> <p>However, it is possible that the R2 ATmega has a different bootloader and that may be an issue.</p> <p>If I was you I would just remove the ATmega from the R3 board and test it on a breadboard (don't need a lot of components to do that); at least that could tell you if it is fried or if it is the R3 board that is fried...</p>
132
|pins|arduino-uno|
What are the AREF, IOREF, and the unlabeled pin next to IOREF on the Uno R3?
2014-02-13T00:17:38.463
<p>There are some pins on the Arduino which I haven't been able to find out anything about:</p> <ul> <li><code>IOREF</code></li> <li><code>AREF</code></li> <li>An unlabeled one next to <code>IOREF</code></li> </ul> <p>What are they?</p>
<p>Concerning the <code>AREF</code> pin, you have to remember that the Arduino comes with a 10bit ADC (Analog-Digital-Converter), which converts incoming voltages between 0V and 5V to integer values between 0 and 1023. This results in a resolution of roughly 4.8 mV.</p> <p>If a sensor only delivers a lower maximum voltage, it is resonable to apply this voltage to the <code>AREF</code> pin, just in order to obtain a higher resolution.</p>
136
|arduino-uno|revisions|
What is the difference between the revisions of the Arduino Uno board?
2014-02-13T02:04:23.007
<p>There are three different revisions of the Arduino Uno. What changed in each revision?</p>
<h3>User Side Changes</h3> <ul> <li>Both revision 2 and 3 boards add four solder pads (JP2) connecting to pins PB4 to PB7 of the USB ATMEGA.</li> <li>Revision 2 and 3 boards are both supplied with header pins in the USB ATMEGA ICSP header rather than just solder pads in the Arduino Uno.</li> <li>The revision 3 board changes the 8 pin connector that contains Arduino pins 8 to 13, GND and AREF for a 10 pin connector. The extra 2 pins are connected to AD4/SDA and AD5/SCL. These are the two analog input pins that can be used for I2C.</li> <li>Revision 3 boards change the 6 pin connector that has the reset pin connected to it to an 8 pin connector. One of the new pins on this header is the IOREF pin that allows shields connected to the board to adapt to the voltage of the board. The second pin is reserved for future use.</li> </ul> <h3>Electronics Based Changes</h3> <ul> <li>The Arduino Uno and Arduino Uno revision 2 both have an ATMEGA8U2 USB microcontroller on board – this is upgraded to an ATMEGA16U2 on the revision 3 board.</li> <li>Revision 3 adds a diode across the USB ATMEGA reset pin pull-up resistor.</li> <li>Both revision 2 and 3 boards add a 1k pull-down resistor to the DTR (HWB) line coming from the USB ATMEGA microcontroller – from the PD7 pin.</li> <li>The Arduino Uno and Arduino Uno revision 2 both have a LED and resistor connected in series on Arduino pin 13. The revision 3 board buffers this LED/resistor through a unity gain op-amp. This is the spare op-amp that was unused on previous boards.</li> </ul> <h3>Sources:</h3> <ol> <li><a href="http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/" rel="noreferrer">http://startingelectronics.com/articles/arduino/uno-r3-r2-differences/</a></li> </ol>
141
|programming|software|
Programming options other than C++
2014-02-13T02:53:07.690
<p>Can I program my Arduino using any programming language other than C++? If so, which programming languages? What software would I need for compiling and loading my code onto the Arduino?</p>
<p>I'm surprised that nobody has mentioned <a href="https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html" rel="nofollow noreferrer">AVR Assembly</a>!</p> <p>Assembly is not often thought to be the most interesting, or even an easy method of programming, but it's nonetheless, 100% possible with all AVR based arduino. SAM boards will likely not work with this flavor, but it's still possible to use assembly in their programming.</p> <p>All Arduino boards (as of posting) support assembly programming via <a href="https://www.microchip.com/mplab/avr-support/atmel-studio-7" rel="nofollow noreferrer">Atmel Studio</a>, The SDK made for Atmel based chips.</p> <p>Assembly is naitively supported by all Atmel devices, and requires no boot loader in order to work, so all programs are inherently real-time.</p>
142
|programming|
Code for one-time execution in Arduino
2014-02-13T02:56:18.943
<p><strong>Question:</strong> Where do I put code if I want it to execute only once per Arduino startup?</p> <p><strong>Background:</strong> I tend to use my Arduino to perform tasks that should be executed once per power cycle. (For example, my robot should only drive forward <em>once</em> every time I turn it on--more than that, and it might fall off the table.)</p> <p>The standard Arduino IDE "template" consists of a <code>loop()</code> and a <code>setup()</code> function. The <code>setup</code> code is run once per power cycle, and the <code>loop</code> is re-started every time it finishes.</p> <p>I see two approaches to code "1 time tasks:"</p> <h2>Method 1: "Loop once"</h2> <pre><code>void setup() { //do setup stuff } void loop() { //do task while(1) ; //Repeat forever, preventing function from re-starting } </code></pre> <h2>Method 2: "Setup only"</h2> <pre><code>void setup() { //do setup stuff //do task } void loop() { //do nothing } </code></pre> <p><strong>More detailed form of question:</strong> Is one of these methods "better" from a hardware/software sense? (e.g. is there anything "special" about the <code>setup</code> function, like it can only run for so much time?)<br> And, if they are the same from a hardware/software perspective, is there a "best practice" or standard way of writing code for these situations in the Arduino community?</p>
<p>I'm kind of confused by your question. You ask where you want to put once-per-startup setup functions, and then discuss the setup function. <em>That's what the setup function is for.</em></p> <p>As such, one-time setup functionality goes in the setup function.</p> <p>FWIW, if you look in the file that <em>calls</em> the <code>setup</code> and <code>loop</code> functions: </p> <pre><code>#include &lt;Arduino.h&gt; int main(void) { init(); #if defined(USBCON) USBDevice.attach(); #endif setup(); for (;;) { loop(); if (serialEventRun) serialEventRun(); } return 0; } </code></pre> <p>For all intents and purposes, the two options are completely identical. Either way, you get a empty busy-wait loop. Frankly, I'd expect the two different options to probably emit the same machine code anyways, so the whole thing is a non-issue.</p> <p>Note:<br> <code>if (serialEventRun) serialEventRun();</code> appears to be a facility to allow you to attach a function that is called upon reception of serial data, but if you do not define a function <code>void serialEvent(){}</code> in your code, it will compile out completely and not be present in the produced machine code.</p>
143
|safety|
What I should be aware before I touch my Arduino?
2014-02-13T03:14:23.623
<p>Before you start to mess with a computer there are basic guidelines to be aware of, such as turn the power off and watch out for static electricity. What guidelines should I be aware of when I work with an Arduino board if I don't want to harm neither myself nor the board. The three kind of activity that requires touching the Arduino and what I'm asking about:</p> <ul> <li>Setting up wire, component layout or breadboard.</li> <li>Debugging a running setup.</li> <li>Moving, mounting up the board somewhere.</li> </ul>
<p>One of the most common bad things I have seen is connecting LEDs directly to addition pins without a current limiting resistor.</p> <p>Basically, in electronics there are a few main sources of problems. Too much current, too much voltage, overheating, and physical damage.</p> <p>Too much current usually comes from shorting things, too much voltage(or reversed polarity) usually comes from not paying attention to what is being connected, overheating comes from too much current or not using a heatsink when you should be.</p> <p>Basically, just think before you connect things and you'll be fine. Learn some basic circuit theory if you haven't already, get in the habit of knowing the ratings of the parts you want to use, and double check stuff before turning it on.</p> <p>I like this list here of things not to do: <a href="http://ruggedcircuits.com/html/ancp01.html" rel="nofollow">http://ruggedcircuits.com/html/ancp01.html</a></p>
156
|serial|arduino-due|
Connecting breakout board to Arduino with UART
2014-02-13T08:19:39.940
<p>I'm using a <a href="http://digistump.com/wiki/digix" rel="nofollow noreferrer">DigiX</a> (Arduino Due based 3.3V) board to connect to a GPRS/GSM SIM908 breakout board. The SIM908 EVB board has the following pins on its RS232:<img src="https://i.stack.imgur.com/zNZ90.png" alt="RS232 pinout"></p> <p>I've got all three UART TX lines hooked up to the RX Lines (and RX to TX) on my Arduino but the board keeps resetting, which I would guess is some sort of voltage issue (I turned the board off immediately). However there are three MAX3232s on the underside of the board, which I thought would have made it so I could just connect the lines directly to the Arduino. Does anyone know why this might be happening or how to properly connect these two devices?</p> <p>Additional info:</p> <p><a href="http://digistump.com/wiki/digix/tutorials/pinout" rel="nofollow noreferrer">Pinout of the DigiX</a>.</p> <p><a href="http://digispark.s3.amazonaws.com/DigiX-V1-Final-Production.pdf" rel="nofollow noreferrer">Schematic of the DigiX</a>. </p> <p>(The below links are in Chinese):</p> <p>Here is <a href="http://pan.baidu.com/share/link?shareid=1471365276&amp;uk=4130796101&amp;third=15" rel="nofollow noreferrer">a SIM908 Hardware guide</a>.</p> <p><a href="http://pan.baidu.com/share/link?shareid=1470501867&amp;uk=4130796101&amp;third=15" rel="nofollow noreferrer">The full schematic of the breakout board</a>.</p>
<p>Both the DigiX and the SIM908 are natively 3.3V boards. They should be able to connect to each other directly.</p> <p>For some reason, the SIM908 breakout seems to only offer RS232 level serial outputs for the GPRS and GPS. On U3 (the SIM908 module itself) Pins 68/71 offer 3.3V levels for the GPRS (GPRS-TXD and GPRS-RXD) and 15/16 offer 3.3V levels for the GPS (GPS-TXD and GPS-RXD).</p> <p>These are converted to RS232 levels by the MAX3232 and presented on J3 and J13. I can't see any point where the 3.3V signals are presented on a connector.</p> <p>You could either:</p> <ul> <li>Breakout the 3.3V signals onto connectors by modifying the SIM908 breakout board. </li> <li>Build a level converter to take the 3.3V signals from the DigiX to RS232 and then connect them as before.</li> </ul> <p>You may have damaged the DigiX board connecting RS232 levels directly to it however. The ARM based Arduinos are far less tolerant of voltage abuse than the ATmega based Arduinos.</p>
158
|i2c|
How do I use I2C devices with Arduino?
2014-02-13T10:08:53.917
<p>I have a few useful I2C components, such as a 16-bit port expander (MCP23017), which I'd like to use in various projects.</p> <p>What do I need to do to make these work with Arduino? Will it work with any Arduino, or do I need a specific board or shield?</p>
<p>For future readers: use the Adafruit_MCP23017 library.</p>
168
|programming|arduino-ide|compile|
Why can't I declare a class in another tab in Arduino IDE?
2014-02-13T15:03:20.657
<p>I wanted to move some of my code out into a second tab in the Arduino IDE, to keep things better organised. At first, I only tried moving a function, and it seemed to work fine. I could call the function from the <code>setup()</code> function in my main tab, and there were no problems compiling or uploading.</p> <p>However, I tried putting a whole class into the second tab, and suddenly it didn't work any more. For example:</p> <p><strong>Tab 1:</strong> </p> <pre><code>TestClass obj; void setup() { obj.init(); } void loop() { //... } </code></pre> <p><strong>Tab 2:</strong></p> <pre><code>class TestClass { public: void init() { //... } }; </code></pre> <p>When I tried to compile this, it gave me the following errors:</p> <pre><code>tab1:1: error: 'TestClass' does not name a type tab1.ino: In function 'void setup()': tab1:5: error: 'obj' was not declared in this scope </code></pre> <p>Why does it recognise a function in another tab, but not a class? Is there a way to make it work in the Arduino IDE, or do I need to use an alternative like Eclipse?</p>
<p>The way the Arduino IDE works is that it compiles your code (the code you write in the IDE) as the &quot;main&quot; code. Then it pulls code from all of the libraries you have imported and compiles that along with the main code. To do what you are suggesting would require you to create a library for Arduino.</p> <h3>Here is some more information on Arduino libraries:</h3> <p><a href="http://arduino.cc/en/Guide/Libraries" rel="nofollow noreferrer">http://arduino.cc/en/Guide/Libraries</a></p> <h3>And here is some on how to create a library:</h3> <p><a href="http://arduino.cc/en/Hacking/LibraryTutorial" rel="nofollow noreferrer">http://arduino.cc/en/Hacking/LibraryTutorial</a> //this one is the easiest to understand imo<br /> <a href="http://playground.arduino.cc/Code/Library" rel="nofollow noreferrer">http://playground.arduino.cc/Code/Library</a> <br /> <a href="http://www.divilabs.com/2013/03/write-your-own-arduino-library.html#" rel="nofollow noreferrer">http://www.divilabs.com/2013/03/write-your-own-arduino-library.html#</a> <br /></p> <p>Here is an example library I wrote <a href="https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftRegister" rel="nofollow noreferrer">https://github.com/jamolnng/Arduino/tree/master/libraries/ShiftRegister</a> as you can see there is no problem with calling Arduino functions from the .cpp file (I know, I've tested the library)</p>
169
|arduino-nano|prototype|wires|
Is there a semi-permanent way to attach wires to the Nano?
2014-02-13T15:25:07.000
<p>At least for prototyping, is there a semi-permanent way to attach wires to the Nano posts?</p> <p><img src="https://i.stack.imgur.com/0n9s9.jpg" alt="Arduino nano"></p> <p>And yes, usually the Nano is hanging in free space by its wires (yes I know, quick and dirty, should be using something cleaner, even for prototypes). So I'm hoping for the best of both worlds, sturdy "enough" to stay attached, yet possible to remove and switch around. Having no luck finding such advice on the internet, perhaps searching for the wrong terms.</p> <p><strong>EDIT:</strong> I neglected one important point, each wire is attached individually just like the SparkFun wires with the female header as mentioned in @TheDoctor's answer below. </p>
<p><a href="http://www.aliexpress.com/item/Free-shipping-NANO-3-0-controller-Terminal-Adapter-for-NANO-terminal-expansion-board-for-arduino-Nano/1921109123.html" rel="nofollow">Here's what I use</a>, repeatedly, successfully. It fits the Nano headers, and gives you screw terminals for proto work.</p>
176
|serial|string|terminal|
How do I print multiple variables in a string?
2014-02-13T19:22:59.960
<p>Say I have some variables that I want to print out to the terminal, what's the easiest way to print them in a string?</p> <p>Currently I do something like this:</p> <pre><code>Serial.print("Var 1:");Serial.println(var1); Serial.print(" Var 2:");Serial.println(var2); Serial.print(" Var 3:");Serial.println(var3); </code></pre> <p>Is there a better way to do this?</p>
<p>I've been using PrintEx for years, and it works great. See <a href="https://www.arduino.cc/reference/en/libraries/printex/" rel="nofollow noreferrer">enter link description here</a></p>
179
|sketch|
Is there any way to download a sketch from an Arduino?
2014-02-13T21:23:36.390
<p>I made a sketch, but then I lost it. However, I uploaded it to the Arduino before losing it. Is there any way I can get it back?</p>
<p>Another approach might be to treat the program onboard the Arduino as a black-box exercise. That is, run the program and take careful notes of what happens (via Serial Monitor or whatever). If, in fact there is any output that you can observe, make it a task to create your own new code to emulate what the program DOES. This won't be productive unless the original programmer liberally included Serial.print() statements throughout the code, something I STRONGLY RECOMMEND as a programming habit to develop. Doing so, facilitates just the exercise I am suggesting. (Ask me why I developed that habit for everything I have coded for the past 30 years.)</p> <p>Unfortunately, most people sprinkle a few comments here and there, which is helpful 5 years later if you have the source code. Personally, I comment EVERY LINE of source code. But comments in the source don't help later in this sort of situation, as the compiler doesn't put them in the machine code it generates. (Perhaps that might be a valuable option for the compiler. Yes, it takes bytes, but how valuable might it be years later for an important project?)</p> <p>My two cents worth, which probably is worth the price the reader of this post paid to see it!</p>
188
|programming|arduino-uno|
What happens when I call exit() from my program?
2014-02-14T01:28:32.887
<p>In either of <code>setup</code> or <code>loop</code>, if I were to add an <code>exit(0)</code> call, where would control be passed to? What would the next state of the microcontroller be? Would it stop execution and power down?</p> <p>I am using a revision 2 Arduino Uno.</p>
<p>My initial guess is wrong. I would have thought it would simply return from loop and the core library would just call loop() again. However, I see the following code was created. Noticing that __stop_program is a hard loop...</p> <p>An extract of Blink.ino's listing, with exit(0) added:</p> <pre><code>// the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second exit(0); } </code></pre> <p>The disassembly of the above:</p> <pre><code>// the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) 100: 80 91 00 01 lds r24, 0x0100 104: 61 e0 ldi r22, 0x01 ; 1 106: 0e 94 ca 01 call 0x394 ; 0x394 &lt;digitalWrite&gt; delay(1000); // wait for a second 10a: 68 ee ldi r22, 0xE8 ; 232 10c: 73 e0 ldi r23, 0x03 ; 3 10e: 80 e0 ldi r24, 0x00 ; 0 110: 90 e0 ldi r25, 0x00 ; 0 112: 0e 94 f7 00 call 0x1ee ; 0x1ee &lt;delay&gt; digitalWrite(led, LOW); // turn the LED off by making the voltage LOW 116: 80 91 00 01 lds r24, 0x0100 11a: 60 e0 ldi r22, 0x00 ; 0 11c: 0e 94 ca 01 call 0x394 ; 0x394 &lt;digitalWrite&gt; delay(1000); // wait for a second 120: 68 ee ldi r22, 0xE8 ; 232 122: 73 e0 ldi r23, 0x03 ; 3 124: 80 e0 ldi r24, 0x00 ; 0 126: 90 e0 ldi r25, 0x00 ; 0 128: 0e 94 f7 00 call 0x1ee ; 0x1ee &lt;delay&gt; exit(0); 12c: 80 e0 ldi r24, 0x00 ; 0 12e: 90 e0 ldi r25, 0x00 ; 0 130: 0e 94 1e 02 call 0x43c ; 0x43c &lt;_exit&gt; ... 0000043c &lt;_exit&gt;: 43c: f8 94 cli 0000043e &lt;__stop_program&gt;: 43e: ff cf rjmp .-2 ; 0x43e &lt;__stop_program&gt; </code></pre> <p>Note that if _exit had not called cli, interrupts would be able to do stuff. But that is not the case.</p>
189
|sketch|
What happens if there is a runtime error?
2014-02-14T01:33:03.127
<p>What happens if there is a runtime error in a program? Will execution of the program just stop? Is there some way I can get the Arduino to tell me what the error is?</p>
<p>I wrote an *.ino environment:</p> <pre class="lang-cpp prettyprint-override"><code>// Testing environment for Arduino sketch files. // Aduino IDE 2.3.0 // Author : Anders Munck // Released : 2024 02 09 #include &lt;iostream&gt; const bool LOW=false; const bool HIGH=true; const bool INPUT=false; const bool OUTPUT=true; const unsigned char LED_BUILTIN=13; using namespace std; void where(std::string hank) { cout &lt;&lt;&quot;Where : &quot;&lt;&lt;hank&lt;&lt;&quot;\n&quot;; } int random(int max) { return std::rand(); } unsigned long klokken=0; unsigned long int millis() { klokken++; cout &lt;&lt;&quot;When : &quot;&lt;&lt; klokken &lt;&lt;&quot;\n&quot;; return klokken; } class SERIAL { public: void begin(int Baud) { cout&lt;&lt;&quot;Arduino sketch : Serial.begin()\n&quot;; }; void end() { cout&lt;&lt;&quot;Arduino sketch : Serial.end()\n&quot;; }; void print(std::string A) { cout&lt;&lt;&quot;Arduino sketch : print()\n&quot;; }; void println(std::string A) { cout&lt;&lt;&quot;Arduino sketch : println()\n&quot;; }; } Serial=SERIAL(); void digitalWrite(unsigned char A,bool S) { cout &lt;&lt; &quot;Arduino sketch : digitalWrite()\n&quot;; } void pinMode(unsigned char A,bool S) { cout &lt;&lt; &quot;Arduino sketch : pinMode()\n&quot;; } // Include Your Arduino sketch file here: #include &quot;signal.ino&quot; int main() { setup(); for(int i=0;i&lt;100;i++){ loop(); }; return 0; } </code></pre> <p>The purpose is to get run time error messages from the *.ino sketch.</p> <p>You will not get usefull timing information this way, as the program is running on another processor.</p> <p>I run it with a GPU C++ IDE.</p> <p>Please regard my code as preliminary ad-hoc program; You may need to develop further for Your needs.</p>
203
|serial|
Sending Large Amounts of Serial Data
2014-02-14T07:58:54.977
<p>So in the fields of robotics sometimes you need multiple boards and or computers linked together to share information or save statistical data. Currently I need to send a few different variables over a serial connection and was wondering what was the best way to go about doing such?</p> <p>So far I've determined that sending structures would probably be the easier way to send data. Does anyone know of any other way that might be more efficient?</p> <p>Please keep in mind that I will essentially be having to send the data for 4 motors, compressor, different temperatures, random things, and the 3 sections of the arm.</p>
<h2>Send struct data across serial</h2> <p>Nothing fancy. Sends a struct. It uses an escape character '^' to delimit the data.</p> <h2>Arduino code</h2> <pre><code>typedef struct { float ax1; float ay1; float az1; float gx1; float gy1; float gz1; float ax2; float ay2; float az2; float gx2; float gy2; float gz2; } __attribute__((__packed__))data_packet_t; data_packet_t dp; template &lt;typename T&gt; void sendData(T data) { unsigned long uBufSize = sizeof(data); char pBuffer[uBufSize]; memcpy(pBuffer, &amp;dp, uBufSize); Serial.write('^'); for(int i = 0; i&lt;uBufSize;i++) { if(pBuffer[i] == '^') { Serial.write('^'); } Serial.write(pBuffer[i]); } } void setup() { Serial.begin(57600); } void loop(){ dp.ax1 = 0.03; // Note that I didn't fill in the others. Too much work. ;p sendData&lt;data_packet_t&gt;(dp); } </code></pre> <h2>Python Code:</h2> <pre><code>import serial from copy import copy from struct import * ser = serial.Serial( # port='/dev/cu.usbmodem1412', port='/dev/ttyUSB0', # port='/dev/cu.usbserial-AL034MCJ', baudrate=57600 ) def get_next_data_block(next_f): if not hasattr(get_next_data_block, "data_block"): get_next_data_block.data_block = [] while (1): try: current_item = next_f() if current_item == '^': next_item = next_f() if next_item == '^': get_next_data_block.data_block.append(next_item) else: out = copy(get_next_data_block.data_block) get_next_data_block.data_block = [] get_next_data_block.data_block.append(next_item) return out else: get_next_data_block.data_block.append(current_item) except : break for i in range(1000): # just so that the program ends - could be in a while loop data_ = get_next_data_block(ser.read) try: print unpack('=ffffffffffff', ''.join(data_)) except: continue </code></pre>
206
|safety|pins|led|resistor|
What happens to the Arduino if you don't use a resistor with an LED?
2014-02-14T12:06:10.727
<p>Making a blinking light seems to be one of the most common beginner projects with Arduino. A typical approach is to connect an LED + resistor (in series) to an IO pin, and connect the other end to ground. In code, you make the pin an output, and bring it <code>HIGH</code> and <code>LOW</code> repeatedly to flash the LED.</p> <p>What happens if you leave that resistor out? Obviously you're going to wreck the LED, but will it also damage the Arduino in some way?</p>
<p>I have done this once (being a beginner concerning electronics). The LED died, luckily the Arduino survived (without any pin problems).</p> <p>Wouldn't recommend this as it is not good for the Arduino.</p>
210
|arduino-uno|pwm|arduino-leonardo|analogwrite|
Why do some pins have a different PWM frequency?
2014-02-14T15:08:09.547
<p>According to the <a href="http://arduino.cc/en/Reference/AnalogWrite">Arduino reference for <code>analogWrite()</code></a>, the PWM frequency on most pins is ~490 Hz. However, it's ~980 Hz for pins 5 and 6 on the Uno, and for pins 3 and 11 on the Leonardo.</p> <p>Why are these different? Is it a deliberate design feature, or is it somehow dictated by the hardware?</p>
<p>Those aren't the only frequencies available for the PWM signals. However, they are the frequencies as determined by the applied prescaler (which you can readily change as detailed below).</p> <p>Each of the 3 pairs of PWM pins is tied to one timer, each of which has its own base frequency, as follows:</p> <ul> <li>Pins 5 and 6 are paired on timer0, with base frequency of 62500Hz</li> <li>Pins 9 and 10 are paired on timer1, with base frequency of 31250Hz</li> <li>Pins 3 and 11 are paired on timer2, with base frequency of 31250Hz</li> </ul> <p>Then each set of pins have a number of prescaler values that can be chosen, that will divide the base frequency of that pair of pins. The prescaler values available are:</p> <ul> <li>Pins 5 and 6 have prescaler values of 1, 8, 64, 256, and 1024</li> <li>Pins 9 and 10 have prescaler values of 1, 8, 64, 256, and 1024</li> <li>Pins 3 and 11 have prescaler values of 1, 8, 32, 64, 128, 256, and 1024</li> </ul> <p>The different combinations yield different frequencies in a given PWM pin. Notice that timer 2 (tied to pins 3 and 11) have more prescaler values available, resulting in more frequencies available.</p> <p>Now, why timer 2 is different, that's a separate question.</p> <p>Edit: Here's a list of possible PWM frequencies per pin (from <a href="http://arduino-info.wikispaces.com/Arduino-PWM-Frequency">this article</a>):</p> <blockquote> <p>For pins 6 and 5 (OC0A and OC0B):</p> <ul> <li>If TCCR0B = xxxxx001, frequency is 64kHz</li> <li>If TCCR0B = xxxxx010, frequency is 8 kHz</li> <li>If TCCR0B = xxxxx011, frequency is 1kHz (this is the default from the Diecimila bootloader)</li> <li>If TCCR0B = xxxxx100, frequency is 250Hz</li> <li>If TCCR0B = xxxxx101, frequency is 62.5 Hz</li> </ul> <p>For pins 9, 10, 11 and 3 (OC1A, OC1B, OC2A, OC2B):</p> <ul> <li>If TCCRnB = xxxxx001, frequency is 32kHz</li> <li>If TCCRnB = xxxxx010, frequency is 4 kHz</li> <li>If TCCRnB = xxxxx011, frequency is 500Hz (this is the default from the Diecimila bootloader)</li> <li>If TCCRnB = xxxxx100, frequency is 125Hz</li> <li>If TCCRnB = xxxxx101, frequency is 31.25 Hz </li> </ul> </blockquote> <p><code>TCCRnB</code> is where you set the prescaler bits for timer <code>n</code>, replacing <code>n</code> by 0, 1 or 2, depending on the timer you want to set. If you are still unsure about bitwise operations, read this <a href="http://playground.arduino.cc/Code/BitMath">bit math tutorial</a>.</p> <p>My sources:</p> <ul> <li><a href="http://playground.arduino.cc/Code/PwmFrequency">http://playground.arduino.cc/Code/PwmFrequency</a></li> <li><a href="http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM">http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM</a></li> <li><a href="http://arduino.cc/en/Tutorial/PWM">http://arduino.cc/en/Tutorial/PWM</a></li> <li><a href="http://arduino-info.wikispaces.com/Arduino-PWM-Frequency">http://arduino-info.wikispaces.com/Arduino-PWM-Frequency</a></li> </ul> <p>Note that there seems to be divergence in those sources about whether pins 9 and 10 have the same behavior as 5 and 6 or 3 and 11, but you get the idea anyway. I'm reading the datashet to try and figure out which is correct, or whether this is a difference between boards.</p>
221
|flash|sketch-size|
What can I do if I run out of Flash memory or SRAM?
2014-02-15T01:09:33.157
<p>According to the Arduino documentation, the ATmega328 has 32KB of Flash memory for the bootloader + uploaded sketch, and only 2KB SRAM for runtime data. The ATmega2560 has quite a bit more, totalling 256KB and 8KB respectively.</p> <p>In either case, those limits seem rather small, especially when compared to similarly sized consumer devices, such as smartphones.</p> <p>What can you do if you run out? E.g. if your sketch is too big, or you need to process a lot of data (such as strings) at runtime? Is there any way to expand the Flash or SRAM?</p>
<p>There are two things to do if you run out of storage:</p> <ul> <li>Somehow "optimize" your code so it needs less storage; or at least uses less of the particular kind of storage that you ran out of (and uses more of the kind of storage that you still have plenty of). Or,</li> <li>Add more storage.</li> </ul> <p>There are lots of tips online on how to do the first (and for the vast majority of things people do with the Arduino, the build-in storage is more than enough after "optimizing"). So I'll focus on the second:</p> <p>There are 3 things that use up flash or SRAM; each one needs a slightly different approach to adding storage:</p> <ul> <li><p>variable storage: it is possible to expand SRAM, as sachleen has already pointed out. <strong>SRAM, FRAM, and NVSRAM</strong> are all appropriate for rapidly-changing variables. (While in principle you could use flash to store variables, then you have to worry about flash wear-out). SPI (a serial protocol) is the easiest to connect to the Arduino. The <a href="http://playground.arduino.cc/Main/SpiRAM">SpiRAM library</a> works with the Microchip <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/22100D.pdf">23K256</a> serial SRAM chip. The Ramtron <a href="http://www.cypress.com/?docID=44787">FM25W256 serial FRAM</a> chip (now owned by Cypress) also uses SPI. The Cypress <a href="http://www.cypress.com/?rID=45568">CY14B101 NVSRAM</a> also uses SPI. Etc.</p></li> <li><p>constant data that needs to still be there the next time the power comes on: this is almost as simple as expanding SRAM. There are many external <strong>EEPROM, FRAM, NVSRAM, and FLASH</strong> storage devices available. Currently the lowest cost per MB are <strong>SD flash cards</strong> (which can accessed via SPI). The Ramtron FM25W256 (see above), the Cypress CY14B101 (see above), etc. can also store constant data. Many expansion shields include a SD card slot, and several <a href="http://arduino.cc/en/Reference/SDCardNotes">libraries</a> and <a href="http://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/look-out">tutorials</a> support reading and writing to (flash) SD cards. (We can't use SRAM for this, because SRAM forgets everything when the power goes out).</p></li> <li><p>executable code: Unfortunately, expanding an Arduino's Flash memory to increase program space isn't possible. However, a programmer can always refactor a sketch to reduce code size at the expense of increasing data size and making it run slightly slower. (In theory, you could go so far as translate your entire sketch into some interpreted language, store that version of your sketch on a SD card, and then write a interpreter for that language that runs on the Arduino to fetch and execute instructions from the SD card -- <a href="http://playground.arduino.cc//CommonTopics/ForthOnArduino">Forth on Arduino</a>, a BASIC interpreter, a Tom Napier Picaro interpreter, some application-specific language, etc.).</p></li> </ul>
224
|uploading|arduino-uno|
Is it possible to program an Arduino Pro Mini using an Arduino Uno R3?
2014-02-15T03:50:16.547
<p>I've recently received an Arduino Pro Mini as a gift, and I don't have an external USB programmer to program the Pro Mini. However, I do own an Arduino Uno R3, and I think it would be possible because they both have the same clock speed and micro-controller (16Mhz with an atmega328).</p> <p>Is it possible to program an Arduino Pro Mini using an Arduino Uno? If yes, how does one do so?</p>
<p>There is another method by which you can upload your sketch programs. Program the UNO with the "Arduino as ISP" sketch and connect the pro mini via the SPI pins (plus reset line). See "Upload with Programmer" on the Arduino website and elsewhere on the internet including stack exchange. This method will allow you to use the full memory of the chip and avoid using the bootloader, but you will need to upload with SPI each time. </p>
226
|eeprom|
What is the real lifetime of EEPROM?
2014-02-15T04:09:14.367
<p>ATMEL says the cell lifetime of an EEPROM cell is about 100,000 write cycle/ cell. Is this actually how the EEPROM performs in the wild?</p> <p>If I do not change the value of a cell, does this stress the lifetime? For example, if I write the value <code>0xFF</code> to the same cell again and again, is this any different to writing <code>0x00</code>, <code>0xFF</code>, <code>0x00</code> etc.</p>
<p>Couple years ago I made run time logger for piece of equipment. Memory got corrupted after 6 months 40 hours logged with 1s resolution => 144000 writes. My solution was to spread writes over entire eeprom.</p>
233
|library|i2c|1-wire|
Are there any good and maintained libraries for using DS2482 I2C to 1-Wire bridge?
2014-02-15T10:49:28.927
<p>The <a href="http://www.maximintegrated.com/datasheet/index.mvp/id/4382" rel="nofollow">DS2482-100</a> and <a href="http://www.maximintegrated.com/datasheet/index.mvp/id/4338" rel="nofollow">DS2482-800</a> are I2C to 1-Wire bridges which are useful for driving complex 1-Wire networks.</p> <p>These are natively supported by a number of packages in Linux so you can interface easily with them on a Raspberry Pi.</p> <p>I was surprised to find there is not an obvious library for accessing them on an Arduino however.</p> <p>I have found the following:</p> <ul> <li>An <a href="https://github.com/paeaetech/paeae" rel="nofollow">Arduino library</a> - has some quirks and not-maintained.</li> <li><a href="https://github.com/dreamiurg/avr-liberty/blob/e08e41d073be523a8a8e4202afb5b3c1e061d300/src/rsl/ds2482.c" rel="nofollow">Part</a> of AVR-Liberty - less quirks, not sure if maintained, not "Arduino" as such, more AVR.</li> </ul> <p>It is helpful to be able to rely on maintained libraries to deal with any changes to the Arduino environment. </p> <p>Arduino libraries are often easier to use than ones designed for AVR in general, which means more people are able to use the software.</p> <p>Is there a better library available?</p>
<p>I believe the library linked by Cybergibbons has a bug in </p> <p>uint8_t OneWire::wireSearch(uint8_t *address)</p> <p>A discrepancy at i = 0 (bit zero in this library, id_bit_number = 1 in a Maxim example) only follows the direction = 1 path and fails to find ROM addresses where bit zero = 0 (i.e. even family codes are missed when mixed devices, some with even and others with odd family codes, are present on the 1-wire bus).</p> <p>A fix I have just implemented and appears to work is to modify the library to declare searchLastDiscrepancy and last_zero as int8_t (not uint8_t), initialise/reset them to -1 (not zero) and, near the end of the method</p> <pre><code> if (!last_zero) searchLastDeviceFlag = 1; </code></pre> <p>becomes</p> <pre><code> if (last_zero == -1) searchLastDeviceFlag = 1; </code></pre> <p>I hope that helps.</p>
242
|time|arduino-due|
Arduino Time Clock Accuracy
2014-02-15T23:54:05.670
<p>I'm currently trying to create an Arduino time clock by using the PJRC Time library (<a href="http://www.pjrc.com/teensy/td_libs_Time.html">http://www.pjrc.com/teensy/td_libs_Time.html</a>). I know that since most of the Arduino boards are running with a 16MHz clock and a single resonator, the time can become "out-of-sync" after a certain period of time. </p> <p>However, I was wondering if anyone has an idea about the accuracy of the Time library when used on the Arduino DUE with a 84MHz clock. I've been testing it out and so far, the clock has been kept in sync for a few hours. Thanks!</p>
<p>Re-visiting an old question... as I found a very informative blog post that sheds new light into it. But let me first provide some context before giving the link.</p> <p>When assessing the quality of a time base, be it a crystal, a ceramic resonator or a lab-grade frequency standard, there are two notions that should be distinguished:</p> <ul> <li><strong>accuracy</strong>: how close is the frequency of the time base to its <em>nominal</em> value</li> <li><strong>stability</strong>: how much does that frequency drift over time</li> </ul> <p>Accuracy is important if you want your clock to give correct time “out of the box”. However, if you are willing to spend some time calibrating your clock, then you do not really care because you are going to calibrate out any inaccuracy you measure. jfpoilpret's answer provides an example of a “manual” calibration protocol, which is by necessity quite lengthy. If you can borrow a GPS module with a 1PPS output, the calibration could be done in a few seconds.</p> <p>Stability is a more serious issue. If the frequency of the time base drifts randomly, this will defeat your calibration efforts. Essentially, the calibration will tell you how fast or slow your clock is running <em>right now</em>, but it will not allow you to predict how fast or slow it will run <em>in the future</em>.</p> <p>Here is the promised link: <a href="http://jorisvr.nl/article/arduino-frequency" rel="nofollow noreferrer">Arduino clock frequency accuracy</a>, by Joris van Rantwijk.</p> <p>What Joris did is measure the accuracy and stability of an Arduino Pro Mini (clocked off a ceramic resonator) and an old Duemilianove (quartz crystal). From my perspective, the main takeaways are:</p> <ul> <li>both clocks are <em>grossly</em> inaccurate, thus both would need user calibration in order to be used as timepieces</li> <li>the quartz crystal of the Duemilianove has decent stability, better than 1.5e-8 at 6 h averaging time</li> <li>the stability of the Pro Mini’s ceramic resonator is pathetic, more than <em>two orders of magnitude</em> worse than the crystal, which makes it essentially useless as a time piece</li> </ul> <p>Here is his <a href="https://en.wikipedia.org/wiki/Allan_variance" rel="nofollow noreferrer">Allan deviation</a> plot, which measures clock instability as a function of observation time:</p> <p><a href="https://i.stack.imgur.com/Cy5Le.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cy5Le.png" alt="Allan deviation of Arduino Clock Frequency"></a><br> <sub>(source: <a href="http://jorisvr.nl/images/arduinofreq/allandev_small.png" rel="nofollow noreferrer">jorisvr.nl</a>)</sub> </p> <p>Although this study has some limitations (only two boards were tested, and the observation time is too short), it is well thought and very informative. I encourage you to read it in whole.</p>
246
|library|signal-processing|
Are there any signal smoothing libraries for Arduino?
2014-02-16T13:57:37.557
<p>I am working on a mobile robot controlled via a wireless 2.4 GHz link.The receiver is connected to the Arduino Uno which serves onboard as the main controller. The most critical (and main) input channel coming from the receiver produces a very noisy signal, which leads to lots of minor changes in the output of the actuators, even though these are not needed.</p> <p><em><pre> <img src="https://i.stack.imgur.com/Z1yB0.png" alt="enter image description here"> Plot of the input of the Arduino in a 30 second interval.</pre></em></p> <p>I am looking for libraries that can perform efficient smoothing. Are there any signal smoothing libraries available for the Arduino (Uno)?</p>
<p>Check out <a href="https://github.com/ripred/Smooth" rel="nofollow noreferrer">the Arduino Smooth library</a>. It uses absolutely no arrays, no looping over past values, it's fast with constant compute time, and the objects take up 8 bytes regardless of the sample window size.</p>
249
|remote-control|ir|
Infrared TV Remote to Arduino
2014-02-16T17:35:27.827
<p>On the hardware side of things, what is involved in making the Arduino receive signals from a TV Remote? What kind of infrared receiver is needed? Do TV remotes use some kind of channels, encoding, or encryption requiring special receivers or else additional programming work to decrypt the signals?</p>
<p>I used TSOP1738 which is easily available at cheap price and I recorded values from more than 10 remotes and it worked very well.</p> <p><a href="http://pastebin.com/gpFxDbkP" rel="nofollow">Here</a> is a file which contain recorded values of a Videocon DTH setup box's remote</p>
269
|arduino-uno|sensors|arduino-mega|
Using the Waspmote Sensor Board
2014-02-17T04:28:35.933
<p>Spanish company Libelium makes this pretty impressive sensor board:</p> <p><a href="http://www.libelium.com/products/waspmote/sensors/" rel="nofollow">http://www.libelium.com/products/waspmote/sensors/</a></p> <p>for their Waspmote series of boards. These are not meant for Arduino compatibility, but they are not only interesting for combining so many sensors, the availability of calibrated sensor sets makes it even more unique.</p> <p>So here is the challenge: can we reasonably leverage these from an Uno or a Mega?</p>
<p>Too long for a comment...</p> <p>Look at some of their docs for <a href="http://www.libelium.com/development/waspmote/examples/ga-11-co-sensor-on-socket4-reading/" rel="nofollow">examples</a>. seems like they have a very similar platform to Arduino.</p> <blockquote> <p>Their forums suggest making the connection is not trivial, but may be possible: <a href="http://www.libelium.com/forum/viewtopic.php?f=15&amp;t=8811" rel="nofollow">http://www.libelium.com/forum/viewtopic.php?f=15&amp;t=8811</a></p> </blockquote> <p>All that's saying is you can't simply plug in a sensor into your Arduino like a shield, because it's not a shield. You'd have to hook up the connections to the right pins and then use their libraries and code to communicate with it.</p> <p>That involves reading their documentation and code to figure out what pins it uses to communicate with what. You may have to modify the code slightly to work with Arduino (mainly changing pin numbers).</p> <p>All in all, I wouldn't invest my time or effort into it. Don't lock yourself into a product that isn't intended to be used the way you're using it. You'll get no support from the company and there's no guarantee future versions of their product will work. Or things like this (from the <a href="http://www.libelium.com/forum/viewtopic.php?f=15&amp;t=8811" rel="nofollow">forum link</a>):</p> <blockquote> <p>Anyway, I'm afraid the Libelium's sales policy implies a minimum first order including five Waspmotes, five batteries and one Gateway.</p> </blockquote> <p>Simply not worth the effort. You'd be much better off making your own sensor board to fit your requirements.</p>
273
|relay|mosfet|transistor|
When should I use a transistor, mosfet, and when should I use a relay?
2014-02-17T15:18:42.393
<p>I am used to relays some, and they are useful, especially for large loads like a incandescent light bulb or other 120V AC device. However, it seems like overkill to use a relay for a bunch of LEDs linked together (parallel) that use 60 mA (too much for the Arduino). Also, it wouldn't work if you wanted to turn it on/off frequently or do PWM. <strong>I've heard some about transistors and MOSFETS and know a little about them. When should I use each one and how do I know what type to get?</strong> Also, it seems like relays can be more expensive than transistors/MOSFETS.</p> <p><strong>Edit:</strong> How can I use these with my Arduino?</p>
<p>Big differences between relays and transistors are:</p> <ul> <li>relays are all-or-nothing (like switches) whereas transistors can transmit more or less current through the <strong>collector</strong> based on the current present on their <strong>base</strong>.</li> <li>relays provide isolation between the command circuit (the one with the electromagnet) and the controlled circuit (the one on the switch side of the relay)</li> </ul> <p>If you want to play with arduino, you definitely need to know about transistors; using relays is more akin to special applications.</p>
274
|programming|
What will happen when I use an invalid pin number?
2014-02-17T15:26:30.470
<blockquote> <p>Related to: <a href="https://arduino.stackexchange.com/questions/189/what-happens-if-there-is-a-runtime-error">What happens if there is a runtime error?</a></p> </blockquote> <p>This question is similar to the one above, however this is an alternate situation:</p> <pre><code>int pin = 999; pinMode(pin, OUTPUT); digitalWrite(pin, HIGH); </code></pre> <p>What would happen in this instance? The compiler might catch it but if you used a random number would the IDE catch it?</p>
<p>The compiler will not detect any error and the code will compile and execute. Hence, to see what happens we need to explore the behind-the-scenes magic. <em>For a summary, skip to end.</em></p> <hr> <p>The second line in your code is where the magic will happen and thats where we need to focus. </p> <pre><code>pinMode(pin, OUTPUT); </code></pre> <p>The portion of <code>pinMode</code> relevant to this discussion is:</p> <pre><code>void pinMode(uint8_t pin, uint8_t mode) { uint8_t bit = digitalPinToBitMask(pin); //The first instance where pin is used uint8_t port = digitalPinToPort(pin); if (port == NOT_A_PIN) return; //Do something } </code></pre> <p>(The complete implementation can be found in <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/wiring_digital.c">wiring_digital.c</a>)</p> <p>So, here, <code>digitalPinToBitMask</code> seems to be using <code>pin</code> to compute an intermediate bit. Exploring further, <code>digitalPinToBitMask</code> is a macro defined in <a href="https://github.com/arduino/Arduino/blob/cc6d7cdbd1f97aa90ffcb759b5fc4c5ba553304e/hardware/arduino/cores/arduino/Arduino.h"><code>Arduino.h</code></a> whose definition is this one-liner:</p> <pre><code>#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) ) </code></pre> <p>This weird looking one liner does a very simple task. It indexes the P<sup>th</sup> element in the array <code>digital_pin_to_bit_mask_PGM</code> and returns it. This array <code>digital_pin_to_bit_mask_PGM</code> is defined in <a href="https://github.com/arduino/Arduino/blob/2a8c06381fbc6fdb7e6363d0cb5d1c16019ccab0/hardware/arduino/variants/standard/pins_arduino.h"><code>pins_arduino.h</code></a> or the pin map for the specific board being used.</p> <pre><code>const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = { _BV(0), /* 0, port D */ _BV(1), _BV(2), _BV(3), _BV(4), _BV(5), _BV(6), _BV(7), ... }; </code></pre> <p>This array has 20 elements in total, so we are out of luck. 999 will index a memory location in the flash memory outside of this array, thereby leading to unpredictable behavior. <em>Or will it?</em></p> <p>We still have another line of defense against runtime anarchy. Its the next line of the function <code>pinMode</code>:</p> <pre><code>uint8_t port = digitalPinToPort(pin); </code></pre> <p><code>digitalPinToPort</code> takes us along a similar path. It is defined as a macro along with <code>digitalPinToBitMask</code>. Its definition is:</p> <pre><code>#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) ) </code></pre> <p>Now, we index the P<sup>th</sup> element of <code>digital_pin_to_port_PGM</code> which is an array defined in the pin map:</p> <pre><code>const uint8_t PROGMEM digital_pin_to_port_PGM[] = { PD, /* 0 */ PD, .... PC, PC, }; </code></pre> <p>This array contains 20 elements, so 999 is again out of range. Again, this command reads and returns a value from flash memory of whose value we cannot be certain. This will again lead to unpredictable behavior from here on.</p> <p>There is still one last line of defense. That is the <code>if</code> check in <code>pinMode</code> on the return value of <code>digitalPinToPort</code>:</p> <pre><code>if (port == NOT_A_PIN) return; </code></pre> <p><code>NOT_A_PIN</code> is defined as 0 in <code>Arduino.h</code>. So, if the returned byte from <code>digitalPinToPort</code> happens to be zero, then <code>pinMode</code> will silently fail and return. </p> <p>In any case, <code>pinMode</code> cannot save us from anarchy. 999 is destined to result in doom.</p> <hr> <p><strong>TL;DR, the code will execute and the result of this will be unpredictable.</strong> Most likely, no pin will be set to <code>OUTPUT</code>, and <code>digitalWrite</code> will fail. If you happen to have exceptionally bad luck, then a random pin may get set to <code>OUTPUT</code>, and <code>digitalWrite</code> may set it to <code>HIGH</code>.</p>
286
|arduino-uno|threads|
How can I create multiple running threads?
2014-02-18T15:11:41.877
<p>Is there a way I can have multiple parts of the program running together without doing multiple things in the same code block?</p> <p>One thread waiting for an external device while also blinking a LED in another thread.</p>
<p>And here is yet another microprocessor cooperative multitasking library – PQRST: a Priority Queue for Running Simple Tasks.</p> <ul> <li><a href="https://nxg.me.uk/dist/pqrst/" rel="nofollow noreferrer">Home page</a></li> <li><a href="https://nxg.me.uk/dist/pqrst/docs/" rel="nofollow noreferrer">Class-level documentation</a></li> <li><a href="https://bitbucket.org/nxg/pqrst/" rel="nofollow noreferrer">Repository</a>, with <a href="https://bitbucket.org/nxg/pqrst/downloads/" rel="nofollow noreferrer">downloads</a> and issues list</li> </ul> <p>In this model, a thread is implemented as a subclass of a <code>Task</code>, which is scheduled for some future time (and possibly rescheduled at regular intervals, if, as is common, it subclasses <code>LoopTask</code> instead). The <code>run()</code> method of the object is called when the task becomes due. The <code>run()</code> method does some due work, and then returns (this is the cooperative bit); it'll typically maintain some sort of state machine to manage its actions on successive invocations (a trivial example is the <code>light_on_p_</code> variable in the example below). It requires a slight rethinking of how you organise your code, but has proven very flexible and robust in fairly intensive use.</p> <p>It's agnostic about the time units, so it is as happy running in units of <code>millis()</code> as <code>micros()</code>, or any other tick that is convenient.</p> <p>Here is the ‘blink’ program implemented using this library. This shows only a single task running: other tasks would typically be created, and started within <code>setup()</code>.</p> <pre><code>#include "pqrst.h" class BlinkTask : public LoopTask { private: int my_pin_; bool light_on_p_; public: BlinkTask(int pin, ms_t cadence); void run(ms_t) override; }; BlinkTask::BlinkTask(int pin, ms_t cadence) : LoopTask(cadence), my_pin_(pin), light_on_p_(false) { // empty } void BlinkTask::run(ms_t t) { // toggle the LED state every time we are called light_on_p_ = !light_on_p_; digitalWrite(my_pin_, light_on_p_); } // flash the built-in LED at a 500ms cadence BlinkTask flasher(LED_BUILTIN, 500); void setup() { pinMode(LED_BUILTIN, OUTPUT); flasher.start(2000); // start after 2000ms (=2s) } void loop() { Queue.run_ready(millis()); } </code></pre>
292
|serial|arduino-yun|sensors|
Serial sensors and the Yun
2014-02-18T22:56:12.727
<p>I am involved in a project that is going to measure PH and chlorine in a swimming pool. The plan is to use a Arduino Yun. The sensors we are going to use are connected using serial. Since we may be using multiple sensors, is there any difference in reliability, latency, known issues (bugs) of using software serial versus pin0 and pin1? Is it any way to avoid software serial pitfalls (if there are any)?</p>
<p>The Yun is a bit different to other Arduinos. The main microcontroller is a ATmega32U4 with a build in USB interface. This is used for the connection to the PC so the single USART is not used for this purpose.</p> <p>However, the single USART is used for connecting to the built in wireless processor. This means that you can't use the wireless and hardware serial at the same time. I presume you are using the Yun for wireless, so disabling this is not desirable.</p> <p>SoftwareSerial is relatively good, but does consume a lot of cycles. You can only listen on a single port at a time. It is possible to use pin change interrupts to listen for activity on multiple ports and switch to the one required, but this requires that the other end can wait for a response.</p> <p><a href="https://www.pjrc.com/teensy/td_libs_NewSoftSerial.html#cpu" rel="nofollow">SoftwareSerial</a> will tie up the microcontroller whilst sending, which can lead to problems when supporting <em>low</em> baud rates. Conversely, because it is CPU heavy, it can also have problems with <em>high</em> baud rates. There is a window, between 9600 and 38400 baud, where it seems to work best.</p> <p>There is another software serial version called <a href="https://www.pjrc.com/teensy/td_libs_AltSoftSerial.html" rel="nofollow">AltSoftSerial</a>. This works faster than SoftwareSerial and can transmit and receive at the same time.</p> <p>You can use the USART, SoftwareSerial and AltSoftSerial all at the same time. Be warned that because all three of these use interrupts and some use timers, you are highly likely to end up with complex, hard to debug interactions.</p> <p>Note than in older versions of Arduino (pre v1), SoftwareSerial was very, very poor. It was replaced entirely with "NewSoftSerial". </p> <p>Sensors are often have very basic USART hardware with limited buffer sizes, and drop data when they aren't serviced in a timely manner.</p> <p>I am not a massive fan of the Yun. It isn't popular, the wireless is still relatively hard to use (compared to the TI CC3000), and the wireless interface uses valuable pins. Personally, if I was to work on a project that required multiple serial interfaces, I would either</p> <ol> <li>Use a board with multiple USART, such as a ATmega1280 (2 USARTs) or ATmega2560 (4 USARTs) and a CC3000 (SPI connected) wireless board.</li> <li>Use SPI/I2C->USART bridges. This allows a single SPI/I2C port to control multiple USARTs. Sparkfun <a href="https://www.sparkfun.com/products/9981" rel="nofollow">sell one</a>, there are many others available.</li> </ol> <p>Be cautious of falling into the trap of using hardware because it is what you have available. </p>
294
|clones|counterfeit|
What's the difference between a clone and a counterfeit Arduino?
2014-02-19T00:48:23.407
<p>I've been hearing a lot about clones and counterfeits. <strong>What are the differences between the two?</strong></p>
<p>A <strong>clone</strong> is an exact or almost exact replica of an original Arduino board, with a different branding.</p> <p>A <strong>derivative</strong> is a board based or inspired by Arduino boards, with some specific addition or modification (different layouts, built-in sensors...)</p> <p>A <strong>counterfeit</strong> is a clone of an Arduino board, with the same branding of an Arduino board.</p> <p>More info on an <a href="http://blog.arduino.cc/2013/07/10/send-in-the-clones" rel="noreferrer">article</a> on the Arduino blog.</p>
296
|arduino-uno-smd|
How high of a baud rate can I go (without errors)?
2014-02-19T03:16:57.470
<p>The standard is 9600 baud. That's just the <em>standard</em>. Using a Arduino Uno SMD R2, what is the highest practical baud rate I can achieve?</p> <p>Bonus points for the audacious: how would you go about creating an error checking mechanism and then increasing the baud rate ridiculous high to get high transfer rates?</p>
<p>Error checking is actually very easy and there is an AVR lib that does this in a one liner. </p> <p>Read up on <a href="http://www.nongnu.org/avr-libc/user-manual/group__util__crc.html" rel="nofollow"><code>util/crc16.h</code></a> and you should be good to go in no time with the included examples.</p> <p>CRC is quite robust and fast for simple applications.</p>
304
|pins|arduino-uno|clones|
What are the SVG pins for on the SainSmart Uno clone?
2014-02-19T14:30:38.310
<p>I bought a SainSmart clone board which is compatible with the Arduino Uno R3. Alongside each of the standard IO pins, there is a row of 3 additional pins (male). They are arranged in columns, marked S, V, and G.</p> <p>They can be seen on this image:</p> <p><img src="https://i.stack.imgur.com/rwQpm.jpg" alt="Photo of SainSmart Uno R3 clone board"></p> <p>Most of them are immediately above the SainSmart and UNO logos. The SVG pins corresponding to the analog pins can be seen immediately below the microprocessor.</p> <p>What are these pins for? Is this a standard format for some applications, or is it something unique to the SainSmart?</p>
<p>SVG = Signal, Voltage, Ground.</p> <p>The Signal pin will carry the actual output, which may be high or low at any given time. It's basically just a male version of the corresponding standard GPIO pin. The Voltage pin will always be high (which can be 5v or 3.3v on this board, depending on the output level switch). The Ground pin is exactly what the name suggests -- it's connected to the board's ground.</p> <p>This obviously means there is a lot of duplication. Why have two signal pins? And why bother having so many Voltage and Ground pins if they're all the same anyway?</p> <p>The reason is simply convenience.</p> <p>If you have a standalone external component (such as a motor), you would normally have to run 3 separate wires to it. With the regularly-spaced SVG pins on the board, you can instead use a 3-way cable with a suitable female header block. You can run that to an equivalent set of 3 pins on the external component. That means you are able to attach/detach the component by plugging/unplugging (effectively) a single cable.</p> <p>I don't think the SVG idea is a 'standard' as such, largely because (in this form) it's only really of benefit to people who are experimenting or prototyping (as opposed to designing a more permanent system). It seems to be fairly popular among hobbyists and enthusiasts though. You just need to watch out for components which may put their equivalent SVG pins in a different order.</p>
307
|arduino-uno-smd|revisions|
Are there different revisions of Arduino Uno SMD?
2014-02-19T22:11:19.283
<p>I know there are different revisions of the Arduino Uno itself, but are there any revisions of the SMD? If they are is SMD R2 identical to through-hole R2? I have a board marked R2 SMD and I am wondering if that is the only version that they produced in SMD format and just are signifying that it is compatible with the standard R2.</p>
<p>The only difference with the SMD Uno is the fact you can't remove the chip. There are also 2 extra analog comparators not connected to anything.</p> <p>The SMD boards are compatible with the thru-hole boards, but they have SMD components, which apparently make them easier to make and cheaper. As I said before, the two extra analog inputs (A7 and A6) are left unconnected on the official boards.</p> <p>Here is my Uno R3:</p> <p><img src="https://i.stack.imgur.com/5miJQ.jpg" alt="enter image description here"></p>
316
|pins|interrupt|isr|
Can a function be called automatically when an input changes?
2014-02-20T00:42:53.183
<p>Currently, my sketch is checking an input pin every time round the main loop. If it detects a change, it calls a custom function to respond to it. Here's the code (trimmed down to the essentials):</p> <pre><code>int pinValue = LOW; void pinChanged() { //... } void setup() { pinMode(2, INPUT); } void loop() { // Read current input int newValue = digitalRead(2); // Has the input changed? if (newValue != pinValue) { pinValue = newValue; pinChanged(); } } </code></pre> <p>Unfortunately, this doesn't always work properly for very short changes on the input (e.g. brief pulses), especially if <code>loop()</code> is running a bit slowly.</p> <p>Is there a way to make the Arduino detect the input change and call my function automatically?</p>
<p>In the event that you want to detect a voltage passing a <strong>threshold</strong>, rather than being merely HIGH or LOW, you can use the analog comparator. Example sketch:</p> <pre class="lang-C++ prettyprint-override"><code>volatile boolean triggered; ISR (ANALOG_COMP_vect) { triggered = true; } void setup () { Serial.begin (115200); Serial.println ("Started."); ADCSRB = 0; // (Disable) ACME: Analog Comparator Multiplexer Enable ACSR = bit (ACI) // (Clear) Analog Comparator Interrupt Flag | bit (ACIE) // Analog Comparator Interrupt Enable | bit (ACIS1); // ACIS1, ACIS0: Analog Comparator Interrupt Mode Select (trigger on falling edge) } // end of setup void loop () { if (triggered) { Serial.println ("Triggered!"); triggered = false; } } // end of loop </code></pre> <p>This can be useful for things like light-detectors, where you might need to detect a change from (say) 1V to 2V on an input.</p> <p>Example circuit:</p> <p><img src="https://i.stack.imgur.com/HnZp5.png" alt="enter image description here"></p> <p>You can also use the Input Capture Unit on the processor, which will remember the exact time of certain inputs, by saving the current count of Timer/Counter 1. This lets you store the exact (well, almost exact) moment that the event of interest occurred, rather than introducing the delay (of probably a few microseconds) before an ISR can be used to capture the current time.</p> <p>For timing-critical applications, this can give somewhat increased accuracy.</p> <p>Example application: <a href="http://www.gammon.com.au/forum/?id=12075" rel="nofollow noreferrer">Turn your Arduino into a capacitor tester</a></p>
318
|pwm|pulsein|timing|
How precise is the timing of pulseIn()?
2014-02-20T11:03:18.267
<p>I've been using the <code>pulseIn()</code> function for processing PWM-based binary data encoding. It works well for distinguishing pulses which are significantly different lengths, e.g. 500us vs. 1500us. That makes it more than sufficient for handling typical IR remotes.</p> <p>However, I want to make my own IR system which can use more than 2 pulse lengths, so that data transfer can occur faster. Ideally, I'd like to use 8 different pulse lengths for octal encoding (e.g. 200us, 400us, 600us, etc.).</p> <p>I've noticed quite significant variations in the values returned by <code>pulseIn()</code> though (+/- 10%). I expect at least some of it is introduced by the IR transmitter and receiver modules, but I don't have good enough equipment to verify that.</p> <p>Assuming I can mitigate that external error, is <code>pulseIn()</code> likely to be precise enough to distinguish such similar pulses?</p>
<p>The pulsein() function is very lossy, in that it is a hard loop and returns a number * the assumed clock cycles it takes for per loop</p> <pre><code>... // wait for the pulse to stop while ((*portInputRegister(port) &amp; bit) == stateMask) { if (numloops++ == maxloops) return 0; width++; } // convert the reading to microseconds. The loop has been determined // to be 20 clock cycles long and have about 16 clocks between the edge // and the start of the loop. There will be some error introduced by // the interrupt handlers. return clockCyclesToMicroseconds(width * 21 + 16); </code></pre> <hr> <p>The most accurate method for capturing the timing of a PIN is use the INPUT CAPTURE FEATURE. Look at the <a href="https://gist.github.com/mpflaga/4404996">this example </a>. It enables the input capture at 1x of CPU for max resolution and each edge of the input pin captures the timer's clock value for reading from the generated Interrupt service. It also enables the timer overflow interrupt to as to maintain large absolute time, to be capture. Since the 1x will roll rather quickly. The captures store the time into an array for reading by the main loop.</p> <hr> <p>Where for signals over IR the typical library to use is <a href="https://github.com/shirriff/Arduino-IRremote">shirriff/Arduino-IRremote</a> library. Where it has several demo's that will read and send the IR from a demodulated signal. To allow one to build a sketch of their own design. This code originally creates a timer interrupt that polls the input pin at a rate determine by </p> <pre><code>#define USECPERTICK 50 // microseconds per clock interrupt tick </code></pre> <p>in the IRremote.h file. For my purposes I have change it to 25 us. Where I find this still can be intermittently missing pulse streams. </p> <p>Note the demodulation is best accomplished within the IR receiver, which in turn outputs this signal of interest. Where to add some background. Using the typical 38KHz modulation, equates to a minimum resolution of 26.3uS per pulse's cycle. sherriff's library shows typically most bauds or bits are in the order of 10+ pulses. Which appear to meet your desired timings.</p> <p><a href="https://github.com/microtherion/Arduino-IRremote">microtherion/Arduino-IRremote</a> fork of shirriff's work improves the reception by replacing the timer interrupt polling of the pin with the use of PinChangeInterrupts. Which I have merged into my own <a href="https://github.com/mpflaga/Arduino-IRremote">mpflaga/Arduino-IRremote</a> fork, that adds several other features.</p> <p>So you could use any of the above libraries. Or create your own app that uses either of the below to capture edges.</p> <ol> <li>polls on a Timer event (e.g. 50uS)</li> <li>captures the micros() on a PinChangeInterrupt</li> <li>uses Input Capture Interrupts to grab the exact time </li> </ol>
319
|programming|c++|data-type|performance|
Why is int only 2 bytes?
2014-02-20T11:37:03.207
<p>When using C/C++ on other platforms, the <code>int</code> type is typically 4 bytes (or potentially more). However, on Arduino, it's only 2 bytes.</p> <p>Why is it different? Does it affect performance if I always use the 4 byte <code>long</code> instead?</p>
<p>One important fact about C and C++ languages is that their respective standards do not define the size (in bytes) of integral and floating point number types.</p> <p>They just define minimal ranges and relation between these ranges, e.g.</p> <pre><code>range(short) &lt;= range(int) &lt; range(long) </code></pre> <p>So the size of e.g. an <code>int</code> will typically depend on:</p> <ul> <li>the target platform (processor)</li> <li>the compiler itself</li> </ul>
322
|library|c++|build|
Why do I need to include libraries used in other libraries?
2014-02-20T14:06:18.787
<p>I have a simple library which uses another library. </p> <p>Here is the header:</p> <pre><code>#ifndef __DERIVEDCLASS_H__ #define __DERIVEDCLASS_H__ #include &lt;HardwareSerial.h&gt; class DerivedClass { private: HardwareSerial* serial; public: DerivedClass(); }; #endif </code></pre> <p>And the CPP:</p> <pre><code>#include "DerivedClass.h" DerivedClass::DerivedClass() { } </code></pre> <p>And the sketch:</p> <pre><code>#include &lt;DerivedClass.h&gt; void setup() { } void loop() { } </code></pre> <p>This works fine.</p> <p>However, if I change the library header to this:</p> <pre><code>#ifndef __DERIVEDCLASS_H__ #define __DERIVEDCLASS_H__ #include &lt;SoftwareSerial.h&gt; class DerivedClass { private: SoftwareSerial* serial; public: DerivedClass(); }; #endif </code></pre> <p>The sketch fails to compile:</p> <blockquote> <p>/Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9: error: ISO C++ forbids declaration of 'SoftwareSerial' with no type /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9: error: expected ';' before '*' token</p> </blockquote> <p>If I change the sketch to:</p> <pre><code>#include &lt;DerivedClass.h&gt; #include &lt;SoftwareSerial.h&gt; void setup() { } void loop() { } </code></pre> <p>i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.</p> <p>If I expand the library out so it actually performs actions, then if it compiles, it works.</p> <p>Why is this? HardwareSerial is a built-in part of the Arduino, located in <em>hardware/arduino/cores/arduino</em> and SoftwareSerial is in <em>libraries</em>, but why would the build process differentiate between the two.</p>
<p>If I remember correctly this is in fact a limitation of the <strong>Arduino IDE</strong>.</p> <p>If you use a better IDE (personally I use Eclipse with the Arduino plugin) it works as it should, i.e. if you include a library A that includes another library B, then in the end you won't get compile-time errors and both B and A will be included in the final binary.</p>
323
|library|build|
How can I adapt the DallasTemperature library to accept another 1-Wire class?
2014-02-20T14:15:29.497
<p>A commonly used library is the <a href="http://milesburton.com/Dallas_Temperature_Control_Library" rel="noreferrer">DallasTemperature</a> library, used to access DS18B20 sensors on a 1-Wire bus. When creating a DallasTemperature object you pass a reference to a <a href="http://www.pjrc.com/teensy/td_libs_OneWire.html" rel="noreferrer">OneWire</a> object. OneWire can create a 1-Wire bus on pretty much any port of an Arduino.</p> <p>An example of this is like so:</p> <pre><code>// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs) OneWire oneWire(ONE_WIRE_BUS); // Pass our oneWire reference to Dallas Temperature. DallasTemperature sensors(&amp;oneWire); </code></pre> <p>However, there are some issues with using OneWire to drive a 1-Wire bus, mainly around driving longer bus lengths, dealing with shorts, and other errors. </p> <p>There is a commonly available chip called the DS2482-100 that can drive longer busses (hundreds of feet), deals with shorts and other errors. It is also less CPU heavy and it deals with a number of the slower aspects of 1-Wire.</p> <p>For this reason, I would like to be able to pass a reference to a library that I have created instead. Currently, I am doing this by:</p> <ul> <li>Calling the library OneWire</li> <li>Replicating all the methods called by the DallasTemperature library</li> <li>Swapping out the OneWire library for mine</li> </ul> <p>This is relatively messy. I would ideally like to be able to pass either a reference to my library or a 1-Wire library, so that people can chose which interface to use.</p> <p>How would I go about doing this?</p>
<blockquote> <p>The DS2482-100 is an I2C-to-1-Wire®bridge device that interfaces directly to standard (100kHz max) or fast (400kHz max) I2C masters to perform bidirectional protocol conversion between the I2C master and any downstream 1-Wire slave devices.</p> </blockquote> <p>It uses a higher level protocol over I2C which does not directly match the bit-banged OneWire interface above. </p> <p>A possible solution is to "only" reuse the OneWire interface and reimplement it. Sub-classing will not work as the member functions are not virtual. Unfortunately this will not work directly due to error handing, timing, etc. The DallasTemperature class will also need modifying. </p> <p>Please see the <a href="http://datasheets.maximintegrated.com/en/ds/DS2482-100.pdf" rel="nofollow">DS2482-100 product description and protocol</a>.</p> <p>To achieve your goal of allowing either bit-banged or DS2482-100 based 1-Wire master would require 1) an abstract interface (class) used by 1-Wire master device drivers, 2) sub-classes for each implementation master variant. </p> <p>As the 1-Wire protocol has a number of common commands a delegation pattern is more useful. Please see the <a href="https://github.com/mikaelpatel/Cosa/blob/master/libraries/OWI/OWI.hh" rel="nofollow">Cosa OWI::Driver</a> and <a href="https://github.com/mikaelpatel/Cosa/blob/master/libraries/DS18B20/DS18B20.hh" rel="nofollow">DS18B20</a> device driver for an example of the delegation pattern. </p>
331
|arduino-uno|lcd|oscillator-clock|
Can I link another device to the Uno's clock?
2014-02-21T10:14:47.667
<p>I'm trying to use an unusual 16x2 LCD display with my Uno. As far as I know, it's an EA-X16027AR. It doesn't seem to be compatible with the HD44780 driver, which is typically used for Arduino LCD's.</p> <p>According to the datasheet, the display's ENB (Enable) pin requires a clock input, described as follows:</p> <blockquote> <p>Basical Clock to perform Instructions in Controller LSI. The Clock at the same timing as MPU are usually input.</p> </blockquote> <p>The timing graphs elsewhere in the datasheet show it wants a speed of around 2 MHz.</p> <p>Is it possible to get the internal clock signal from the Uno, scale it down to 2 MHz, and output it to a GPIO pin or similar? Alternatively, is it possible to emulate a clock signal at that speed on-board, without adding additional timing components?</p>
<p>Rather than using microprocessor-specific low-level programming, I was able to get a suitable signal using the core <code>tone()</code> function:</p> <pre><code>tone(11, 2000000); </code></pre> <p>It can be used to generate a 50% duty cycle square wave of a custom frequency on any individual GPIO pin (I'm using 11 in this case). Given the name, it's obviously designed for producing simple audio output, and 2 MHz is way above the range of human hearing.</p> <p>The documentation doesn't list any upper limit on the frequency though, and the code it's based on doesn't appear to introduce any limitations. With that said, it clearly can't run faster than the internal timer it's based on (which I think will typically be 8 or 16 MHz).</p> <p>It seems reasonable to assume that it will be in-sync with the microprocessor's internal clock, although I haven't been able to confirm that empirically as I don't have suitable equipment at home. Similarly, I haven't been able to confirm that it's <em>actually</em> producing a 2 MHz signal, but the LCD display is working properly so it's likely to be in the right vicinity. I had previously tried running it from regular PWM, but that didn't work, so frequency is obviously important here.</p> <p>The signal can be stopped by calling:</p> <pre><code>noTone(11); </code></pre> <p>There are a couple of caveats to be aware of when using <code>tone()</code>. First of all, it can only work on a single pin at a time, so you can't generate multiple signals with it. And secondly, it will prevent some PWM output from working properly (on pins 3 and 11, according to the documentation). This is because it has to reconfigure one of the internal timers which is normally used for PWM.</p>
332
|motor|
Can a stepper motor be controlled directly from an Arduino?
2014-02-21T12:21:09.433
<p>I'm planning to build a simple XY plotter, and have been looking at the possibility of using a pair of small 5V 4-phase steppers to provide the movement. In my research, I've often seen stepper driver boards advertised, ranging from very big and expensive, through to quite small and cheap. Some of them actually look like little more than a darlington array on a PCB.</p> <p>Do I really need one of those external driver boards, or can I control the steppers directly from my Arduino?</p>
<p>Generally, stepper motors cannot be controlled by an Arduino pin. They have a current draw of over the 20mA any single pin can supply.</p> <p>Kickback is also a problem. Because the motors have moving magnetic parts inside, they will continue to generate electricity after power has been cut. this will almost certainly cause enough negative voltage that is enough to fry your Arduino.</p> <p>A solution is to use a motor driver chip or shield. <a href="https://www.sparkfun.com/products/9815">This one</a> is a good example. These have transistor based chips that can drive enough current to power a motor, and diodes to mitigate the kickback from the motors.</p>
337
|programming|avr-gcc|performance|
Would an infinite loop inside loop() perform faster?
2014-02-21T15:36:19.237
<p>When you're writing a typical sketch, you usually rely on <code>loop()</code> being called repeatedly for as long as the Arduino is running. Moving in and out of the <code>loop()</code> function must introduce a small overhead though.</p> <p>To avoid that, you could presumably create your own infinite loop, like this:</p> <pre><code>void loop() { while (true) { // do stuff... } } </code></pre> <p>Is that a viable way to improve performance? Will it cause other problems if <code>loop()</code> never returns?</p>
<p><a href="https://arduino.stackexchange.com/questions/337/would-an-infinite-loop-inside-loop-perform-faster#339">Cybergibbons's answer</a> describes quite nicely the assembly code generation and the differences amongst the two techniques. This is intended to be a complementary answer looking at the issue in terms of <em>practical</em> differences, i.e. how much of a difference either approach will make in terms of <em>execution time</em>.</p> <hr> <h2>Code Variations</h2> <p>I did an <a href="http://github.com/AsheeshR/Arduino-Loop-Analysis" rel="nofollow noreferrer">analysis</a> involving the following variations:</p> <ul> <li>Basic <code>void loop()</code> (which gets inlined on compilation)</li> <li>Un-inlined <code>void loop()</code> (using <code>__attribute__ ((noinline))</code>)</li> <li>Loop with <code>while(1)</code> (which gets optimized)</li> <li>Loop with un-optimized <code>while(1)</code> (by adding <code>__asm__ __volatile__("");</code>. This is a <code>nop</code> instruction that prevents optimization of the loop without resulting in additional overheads of a <code>volatile</code> variable)</li> <li>An un-inlined <code>void loop()</code> with optimized <code>while(1)</code></li> <li>An un-inlined <code>void loop()</code> with un-optimized <code>while(1)</code></li> </ul> <p>The sketches can be found <a href="http://github.com/AsheeshR/Arduino-Loop-Analysis/tree/master/Code/Sketches" rel="nofollow noreferrer">here</a>.</p> <h2>Experiment</h2> <p>I ran each of these sketches for 30 seconds, thereby accumulating <a href="http://github.com/AsheeshR/Arduino-Loop-Analysis/tree/master/Data" rel="nofollow noreferrer">300 data points each</a>. There was a 100 millisecond <code>delay</code> call in each loop (without which <a href="https://electronics.stackexchange.com/q/12300/18583">bad things happen</a>). </p> <h2>Results</h2> <p>I then calculated the mean execution times of each loop, subtracted 100 milliseconds from each and then plotted the results. </p> <p><a href="http://github.com/AsheeshR/Arduino-Loop-Analysis/blob/master/Data/Munged/runtime.csv" rel="nofollow noreferrer">http://raw2.github.com/AsheeshR/Arduino-Loop-Analysis/master/Figures/timeplot.png</a></p> <h1>Conclusion</h1> <ul> <li>An un-optimised <code>while(1)</code> loop within <code>void loop</code> is faster than a compiler optimised <code>void loop</code>. </li> <li>The time difference between the un-optimized code and default Arduino optimized code is insignificant <em>practically</em>. You will be better off compiling manually using <code>avr-gcc</code> and using your own optimisation flags rather than depending on the Arduino IDE to help you with it (if you need microsecond optimisations). </li> </ul> <hr> <p><sub> <strong>NOTE:</strong> The actual time values are not of significance here, the difference between them is. The ~90 microseconds of execution time includes a call to <code>Serial.println</code>, <code>micros</code> and <code>delay</code>. </sub></p> <p><sub> <strong>NOTE2:</strong> This was done using the Arduino IDE and the default compiler flags that it supplies. </sub></p> <p><sub> <strong>NOTE3:</strong> Analysis (plot and calculations) was done using R. </sub></p>
342
|fat|sd-card|
Logging multiple gigabytes of data with Arduino
2014-02-21T19:30:53.623
<p>I have Arduino Uno with SD card shield. I'm planning to log a huge amount of data from various sensors - including accelerometers and 3D compass - to the SD card. </p> <p>However, I have understood that Arduino, 64GB SD, FAT and large amount of data are not working too well.</p> <p>Does Arduino work well with this amount of data on FAT? There's no need to read any data from SD on Arduino. If not, is there a better approach? Writing directly to SD without FAT? </p> <p>This data logger will be on the environment where no computer or network connection is available. Performance is not an issue - around 8kB/s (over three months) is already enough.</p>
<p>You should consider using <a href="http://code.google.com/p/sdfatlib/" rel="nofollow">sdfatlib</a>. This is currently supported version. Where an early version of this was the predecessor the IDE's stock SD library. SdFat better supports newer and larger SdCards, along with more features.</p>
343
|programming|compile|
Why do sketches take up so much space and memory?
2014-02-21T21:29:25.117
<p>When I compile this sketch for the Yún:</p> <pre><code>int led = 7; void setup() { pinMode(led, OUTPUT); } void loop() { digitalWrite(led, HIGH); } </code></pre> <p>I get:</p> <blockquote> <p>Sketch uses 5,098 bytes (17%) of program storage space. </p> <p>Maximum is 28,672 bytes. Global variables use 153 bytes (5%) of dynamic memory, leaving 2,407 bytes for local variables. Maximum is 2,560 bytes.</p> </blockquote> <p>Even when I compile the BareMinimum sketch:</p> <pre><code>void setup() { // setup } void loop() { // loop } </code></pre> <p>I get:</p> <blockquote> <p>Sketch uses 4,548 bytes (15%) of program storage space.</p> <p>Maximum is 28,672 bytes. Global variables use 151 bytes (5%) of dynamic memory, leaving 2,409 bytes for local variables. Maximum is 2,560 bytes.</p> </blockquote> <p>Why does a bare minimum sketch take up 15% of the program storage space allocated? And why does a very simple sketch take up 17% of the program storage space? According to <a href="http://arduino.cc/en/Tutorial/Memory#.UwfEavkiEw8">the Arduino website</a>:</p> <blockquote> <p>It's easy to use it all up by having lots of strings in your program. For example, a declaration like: <code>char message[] = "I support the Cape Wind project.";</code> puts 33 bytes into SRAM (each character takes a byte, plus the '\0' terminator).</p> </blockquote> <p>However, there aren't any strings declared in either of these sketches.</p> <p>It seems as if they might import or use other libraries/classes that I don't specify. Maybe it imports a system default library? Or is it something else?</p>
<p>You already have some perfectly good answers. I am posting this only to share some stats I did one day I asked myself the same sort of questions: What is taking so much space on a minimal sketch? What is the minimum needed to achieve the same functionality?</p> <p>Below are three versions of a minimal blinky program that toggles the LED on pin 13 every second. All three versions have been compiled for an Uno (no USB involved) using avr-gcc 4.8.2, avr-libc 1.8.0 and arduino-core 1.0.5 (I do not use the Arduino IDE).</p> <p>First, the standard Arduino way:</p> <pre class="lang-c++ prettyprint-override"><code>const uint8_t ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() { digitalWrite(ledPin, HIGH); delay(1000); digitalWrite(ledPin, LOW); delay(1000); } </code></pre> <p>This compiles to 1018 bytes. <a href="https://arduino.stackexchange.com/a/12684">Using both <code>avr-nm</code> and disassembly</a>, I broke down that size into individual functions. From largest to smallest:</p> <pre><code> 148 A ISR(TIMER0_OVF_vect) 118 A init 114 A pinMode 108 A digitalWrite 104 C vector table 82 A turnOffPWM 76 A delay 70 A micros 40 U loop 26 A main 20 A digital_pin_to_timer_PGM 20 A digital_pin_to_port_PGM 20 A digital_pin_to_bit_mask_PGM 16 C __do_clear_bss 12 C __init 10 A port_to_output_PGM 10 A port_to_mode_PGM 8 U setup 8 C .init9 (call main, jmp exit) 4 C __bad_interrupt 4 C _exit ----------------------------------- 1018 TOTAL </code></pre> <p>In the list above, the first column is the size in bytes, and the second column tells whether the code comes from the Arduino core library (A, 822 bytes total), the C runtime (C, 148 bytes) or the user (U, 48 bytes).</p> <p>As can be seen in this list, the largest function is the routine servicing the timer 0 overflow interrupt. This routine is responsible of tracking time, and is needed by <code>millis()</code>, <code>micros()</code> and <code>delay()</code>. The second largest function is <code>init()</code>, which sets the hardware timers for PWM, enables TIMER0_OVF interrupt and disconnects the USART (that was used by the bootloader). Both this and the previous function are defined in <code>&lt;Arduino directory&gt;/hardware/arduino/cores/arduino/wiring.c</code>.</p> <p>Next is the C + avr-libc version:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;avr/io.h&gt; #include &lt;util/delay.h&gt; int main(void) { DDRB |= _BV(PB5); /* set pin PB5 as output */ for (;;) { PINB = _BV(PB5); /* toggle PB5 */ _delay_ms(1000); } } </code></pre> <p>The break-down of the individual sizes:</p> <pre><code>104 C vector table 26 U main 12 C __init 8 C .init9 (call main, jmp exit) 4 C __bad_interrupt 4 C _exit ---------------------------------- 158 TOTAL </code></pre> <p>This is 132 bytes for the C runtime and 26 bytes of user code, including the inlined function <code>_delay_ms()</code>.</p> <p>It could be noted that, since this program does not use interrupts, the interrupt vector table is not needed, and regular user code could be put in its place. The following assembly version does exactly that:</p> <pre><code>#include &lt;avr/io.h&gt; #define io(reg) _SFR_IO_ADDR(reg) sbi io(DDRB), 5 ; set PB5 as output loop: sbi io(PINB), 5 ; toggle PB5 ldi r26, 49 ; delay for 49 * 2^16 * 5 cycles delay: sbiw r24, 1 sbci r26, 0 brne delay rjmp loop </code></pre> <p>This is assembled (with <code>avr-gcc -nostdlib</code>) into only 14 bytes, most of which are used to delay the toggles so that the blink is visible. If you remove that delay loop, you end up with a 6-byte program that blinks too fast to be seen (at 2&nbsp;MHz):</p> <pre><code> sbi io(DDRB), 5 ; set PB5 as output loop: sbi io(PINB), 5 ; toggle PB5 rjmp loop </code></pre>
348
|project|version-control|
How to organize my Arduino projects' structure for easy source control?
2014-02-22T07:31:10.457
<p>It's been a long time I've been looking for a good answer to this question.</p> <p>Typically, any Arduino project but the simplest one will include:</p> <ul> <li>The main source code file <code>MyProject.ino</code></li> <li>Libraries specific to the project (<code>MyProjectLibrary1.h</code>, <code>MyProjectLibrary1.cpp</code>...)</li> <li>Third-party libraries (generally free open source, added manually to Arduino libraries directory)</li> <li>Schematics, PCB diagrams</li> <li>Documentation</li> <li>...</li> </ul> <p>All this makes it hard to keep the whole code and doc of one project under Source Code Management (e.g. on Subversion, Git or GitHub).</p> <p>Managing source control of your project means managing the version of all files used by the project including 3rd-party libraries.</p> <p>Now for a single project, I need to define a directory structure that:</p> <ul> <li>Includes all project files as described above</li> <li>I can entirely commit to a Source Code Management tool (including 3rd-party dependencies)</li> <li>I can checkout anywhere on my hard drive and build the project from there (does it have to be a single location as imposed by Arduino IDE)</li> <li>I can zip into a self-contained archive that I can send to a friend for him to build as easily as possible (no extra manual download)</li> </ul> <p>What I find particularly tricky with Arduino projects is the management of external libraries dependencies. Java projects developers have <a href="http://maven.apache.org">maven</a> repositories for that and that helps a lot in managing all external deps. But we don't have an equivalent system for Arduino libraries.</p> <p>I would be interested to know how other Arduino project makers deal with these aspects in their own projects.</p> <p>Also note that I am open to changing my development process, including my IDE (currently I use Eclipse with the Arduino plugin most of the time, and then I ensure my projects can also work directly with the Arduino IDE).</p>
<pre class="lang-none prettyprint-override"><code>MyProject |_MyProject |_MyProject.ino |_data | |_documentation | |_PCB | |_schematics |_src |_MyProjectLibrary1 |_ThirdPartyLibrary </code></pre> <h2>MyProject folder (repository root)</h2> <p>The reason I suggest the seemingly redundant <code>MyProject</code> root folder is that you mentioned using GitHub. When you download (rather than clone) the contents of a GitHub repository the branch or tag name is appended to the repository name (e.g. <code>MyProject-master</code>). The Arduino IDE requires that the sketch folder name match the sketch file name. If you open an .ino file that is in a folder that does not match the sketch name the Arduino IDE prompts you create an appropriately named sketch folder and move the sketch to that folder. In addition to this not being a very good initial experience for the user, the greater problem is that the Arduino IDE may not copy all the other associated files to the newly created folder, which could cause the program to no longer compile. By putting the sketch in a subfolder you avoid GitHub altering the name of the sketch folder.</p> <p>If the GitHub file name thing is not an issue for you then the redundant root folder is not necessary.</p> <h2>data folder</h2> <p>I recommend using the <code>data</code> subfolder for your non-code files because the Arduino IDE has a special treatment of subfolders of that name. They are copied to the new location when you do a <strong>File > Save As...</strong>. Subfolders of any other name are not.</p> <h2>src folder</h2> <p>The <code>src</code> subfolder has the special property of allowing <a href="https://github.com/arduino/arduino-builder/pull/148" rel="noreferrer">recursive compilation</a>. This means that you can leave the libraries in that folder and include them from your sketch like this:</p> <pre class="lang-cpp prettyprint-override"><code>#include "src/MyProjectLibrary1/MyProjectLibrary1.h" #include "src/ThirdPartyLibrary/ThirdPartyLibrary.h" </code></pre> <p>The <a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#layout-of-folders-and-files" rel="noreferrer">Arduino 1.5 Library format folder structure</a> is also supported, you only need to adjust your <code>#include</code> statements accordingly.</p> <p>Note that only Arduino IDE 1.6.10 (arduino-builder 1.3.19) and newer support recursive sketch compilation.</p> <p>Unfortunately some libraries use the incorrect <code>#include</code> syntax for local file includes (e.g. <code>#include &lt;ThirdPartyLibrary.h&gt;</code> instead of <code>#include "ThirdPartyLibrary.h"</code>). This still works when the library is installed to one of the Arduino <code>libraries</code> folders but does not work when the library is bundled with the sketch. So some libraries may require minor edits to use this way.</p> <p>I greatly prefer this to the alternative of dumping all the library files in the root of the sketch folder because that is messy and every library file will be shown in the Arduino IDE as tabs when you open the sketch (Of course any source files you do want to be editable from the Arduino IDE should be placed in the sketch root folder).</p> <p>Being able to use bundled libraries in place is also in line with another of your goals:</p> <blockquote> <p>send to a friend for him to build as easily as possible</p> </blockquote> <p>Removing the requirement to manually install libraries makes the project much easier to use.</p> <p>This will also avoid any chances of conflict with other versions of library files of the same name that may be previously installed.</p>
353
|arduino-mega|
How can I rename how my Arduino shows up on the computer?
2014-02-23T00:31:46.827
<p>I have a clone of a Mega 2560, and the Chinese manufacture apparently had a broken shift key. To my annoyance, whenever I connect it to my computer it reads, <code>arduino compatible mega 2560</code>. With my extreme <em>annoyance</em> with <em>slightly</em> misspelled or incorrectly capitalised English, it has been very distracting to me.</p> <p>However, the reason that I'm asking this question is for more than how to rename it to be capitalised. Think of how many projects could be simplified by this! Or for many Arduinos, you can label they physically and then rename them <code>Arduino #1</code>, etc. so you can tell which port it is on using device manager. If you designed a product with Arduino, then you can even rename it to your product name.</p> <p><strong>I would imagine that there would be an easy way to do this by reburning the firmware to the [Insert USB chip model #### here].</strong> I've seen it done for keyboards on the Uno, so I would imagine that you could modify it somehow.</p>
<p>This string is contained in the FT232 USB to UART interface chip and the manufacturer has released <a href="http://www.ftdichip.com/Support/Utilities.htm" rel="nofollow noreferrer">the FT_PROG tool</a> to reprogram it. But do take note of the warning on their website: "<strong>PLEASE NOTE - The use of some of these utilities by an end user may result in a device being rendered useless</strong>". Another word of warning is to <strong>ensure there is only one device connected with an FTDI-chip</strong>.</p> <p>Here is a screenshot of the MProg tool:</p> <p><img src="https://i.stack.imgur.com/8outD.jpg" alt="enter image description here"></p>
355
|programming|sram|
How much can I recurse? How much can I recurse? How much ca!@#QFSD@$RFW
2014-02-23T02:40:20.173
<p>The Arduino Uno board has limited RAM which means it has a limited call stack available. Sometimes, recursion is the only quick option to implement a certain algorithm. So, given that the call stack is severely limited, what would be a way to find out that given a certain program running on the board, exactly how many recursive calls can you afford before there is a stack overflow (and bad things happen)?</p>
<p>I had this exact same question as I was reading <a href="https://www.cprogramming.com/c++book/" rel="nofollow noreferrer">Jumping into C++ by Alex Allain</a>, Ch 16: Recursion, p.230, so I ran some tests. </p> <h1>TLDR;</h1> <p><strong>My Arduino Nano (ATmega328 mcu) can do 211 recursive function calls (for the code given below) before it has a stack overflow and crashes.</strong> </p> <h1>First off, let me address this claim:</h1> <blockquote> <p>Sometimes, recursion is the only quick option to implement a certain algorithm.</p> </blockquote> <p>[Update: ah, I skimmed the word "quick". In that case you have some validity. Nevertheless, I think it's worth saying the following.]</p> <p>No, I don't think that is a true statement. I'm pretty certain <strong>all</strong> algorithms have both a recursive and a non-recursive solution, without exception. It's just that sometimes it is significantly <em>easier</em> to use a recursive algorithm. Having said that, recursion is very much frowned upon for use on microcontrollers and would probably never be allowed in safety-critical code. Nevertheless, it is possible of course to do it on microcontrollers. To know how "deep" you can go into any given recursive function, just test it! Run it in your real-life application in a real-life test case, and remove your base condition so that it will infinitely recurse. Print out a counter and see for yourself how "deep" you can go so you know whether or not your recursive algorithm is pushing the limits of your RAM too close to be used practially. Here's an example below to force stack overflow on an Arduino. </p> <h1>Now, a few notes:</h1> <p>How many recursive calls, or "stack frames" you can get is determined by a number of factors, including:</p> <ul> <li>The size of your RAM</li> <li>How much stuff is already on your stack or taken up in your heap (ie: your free RAM matters; <code>free_RAM = total_RAM - stack_used - heap_used</code>, or you might say <code>free_RAM = stack_size_allocated - stack_size_used</code>)</li> <li>The size of each new "stack frame" which will be placed onto the stack for every new recursive function call. This will depend upon the function being called and its variables and memory requirements, etc. </li> </ul> <h1>My results:</h1> <ul> <li>20171106-2054hrs - Toshiba Satellite w/16 GB RAM; quad-core, Windows 8.1: final value printed before crash: <strong>43166</strong> <ul> <li>took several seconds to crash--maybe 5~10?</li> </ul></li> <li>20180306-1913hrs Dell high-end laptop w/64 GB RAM; 8-core, Linux Ubuntu 14.04 LTS: final value printed before crash: <strong>261752</strong> <ul> <li>followed by the phrase <code>Segmentation fault (core dumped)</code></li> <li>took only ~4~5 sec or so to crash </li> </ul></li> <li>20180306-1930hrs Arduino Nano: TBD---is at ~250000 and still counting---the Arduino optimization settings must have caused it to optimize out the recursion...??? Yes, that is the case. <ul> <li>Add <code>#pragma GCC optimize ("-O0")</code> to the top of the file and redo:</li> </ul></li> <li>20180307-0910hrs Arduino Nano: 32 kB flash, 2 kB SRAM, 16 MHz processsor: final value printed before crash: <strong>211</strong> <code> Here are the final print results: 209 210 211 ⸮ 9⸮ 3⸮ </code> <ul> <li>took only a fraction of a second once it started printing at 115200 serial baud-rate--maybe 1/10 sec</li> <li>2 kiB = 2048 bytes / 211 stack frames = 9.7 bytes/frame (assuming ALL of your RAM is being used by the stack--which actually isn't the case) --but this seems very reasonable nonetheless.</li> </ul></li> </ul> <h1>The code:</h1> <h2>The PC application:</h2> <pre><code>/* stack_overflow - a quick program to force a stack overflow in order to see how many stack frames in a small function can be loaded onto the stack before the overflow occurs By Gabriel Staples www.ElectricRCAircraftGuy.com Written: 6 Nov 2017 Updated: 6 Nov 2017 References: - Jumping into C++, by Alex Allain, pg. 230 - sample code here in the chapter on recursion To compile and run: Compile: g++ -Wall -std=c++11 stack_overflow_1.cpp -o stack_overflow_1 Run in Linux: ./stack_overflow_1 */ #include &lt;iostream&gt; void recurse(int count) { std::cout &lt;&lt; count &lt;&lt; "\n"; recurse(count + 1); } int main() { recurse(1); } </code></pre> <h2>The Arduino "Sketch" program:</h2> <pre><code>/* recursion_until_stack_overflow - do a quick recursion test to see how many times I can make the call before the stack overflows Gabriel Staples Written: 6 Mar. 2018 Updated: 7 Mar. 2018 References: - Jumping Into C++, by Alex Allain, Ch. 16: Recursion, p.230 */ // Force the compiler to NOT optimize! Otherwise this recursive function below just gets optimized into a count++ type // incrementer instead of doing actual recursion with new frames on the stack each time. This is required since we are // trying to force stack overflow. // - See here for all optimization levels: https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html // - They include: -O1, -O2, -O3, -O0, -Os (Arduino's default I believe), -Ofast, &amp; -Og. // I mention `#pragma GCC optimize` in my article here: http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html #pragma GCC optimize ("-O0") void recurse(unsigned long count) // each call gets its own "count" variable in a new stack frame { // delay(1000); Serial.println(count); // It is not necessary to increment count since each function's variables are separate (so the count in each stack // frame will be initialized one greater than the last count) recurse (count + 1); // GS: notice that there is no base condition; ie: this recursive function, once called, will never finish and return! } void setup() { Serial.begin(115200); Serial.println(F("\nbegin")); // First function call, so it starts at 1 recurse (1); } void loop() { } </code></pre> <h1>References:</h1> <ol> <li><a href="https://www.cprogramming.com/c++book/" rel="nofollow noreferrer">Jumping into C++ by Alex Allain</a>, Ch 16: Recursion, p.230</li> <li><a href="http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html" rel="nofollow noreferrer">http://www.electricrcaircraftguy.com/2014/01/the-power-of-arduino.html</a> - literally: I referenced my own website during this "project" to remind myself how to change Arduino compiler optimization levels for a given file with the <code>#pragma GCC optimize</code> command since I knew I had it documented there.</li> </ol>
356
|programming|python|sketch|
How can I use Python from a sketch?
2014-02-23T05:06:01.823
<p>I'd like to be able to use Python from a sketch. According to <a href="http://playground.arduino.cc/interfacing/python#.Uwl-r6go6aw" rel="nofollow">the Arduino playground</a>, one can use PySerial from a computer to talk with an Arduino via Python. </p> <p>It looks like from that page you can also use various API's to use Python with an Arduino from a computer. However, I'd like to know if you can execute Python directly from a sketch. It would be nice because then you could execute Python directly from a sketch, and not all of it would have to be written in Python.</p> <p>If this is not possible, is there an easy way to execute Python on an Arduino? Looking at the various API's it was hard to determine exactly what they did, and if you could execute a <code>.py</code> script from a computer or from anything on the Arduino.</p>
<blockquote> <p>It looks like from that page you can also use various API's to execute Python directly on the Arduino.</p> </blockquote> <p>I don't see that, at all. All those links show you how to communicate with the Arduino over serial using Python on the host side.</p> <p>You'd need a python interpreter to be able to run python on the Arduino. There is the <a href="https://code.google.com/p/python-on-a-chip/">Python On A Chip</a> project and it seems like they have support for the Mega.</p> <blockquote> <p>2010/09/01 (1bdb8d31f27b) New platform: Arduino Mega.</p> </blockquote> <p>Some more info from the <a href="https://wiki.python.org/moin/PyMite">PyMite page</a>:</p> <blockquote> <p>any device in the AtMega family which meets these requirements: 20KiB Flash and 4K RAM, will run today</p> </blockquote> <p>I doubt you'll find anything that'll let you mix Arduino and Python code in the same sketch.</p>
403
|pins|voltage-level|
How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?
2014-02-23T20:42:26.537
<p>I'm looking for a broadly applicable solution, one that can be adapted to a variety of projects.</p> <p>I'm currently working on several projects that each require controlling devices ranging from 800mA to 2A from an Arduino Uno. One controls stepper motors, one controls 12vdc solenoid actuators, and one controls 12vdc pneumatic valves. </p> <p>For example:</p> <p>The Arduino monitors a button, and each time the button is pressed it triggers the solenoid actuator. Because the Arduino is unable to source the current required by the solenoid, a seperate power supply is required with the Arduino controlling a switch (relay, transistor, etc.) that allows the higher current to pass. For the stepper motor, the layout is more complex as there would need to be four pins controlling four separate switches (to maintain interoperability of the circuit). The relay controls an air valve and requires 12vdc as well. </p> <p>I'm trying to figure out how to use a single circuit that can be used in each of these applications (and any future projects) that involve controlling higher current devices than the Arduino pins can handle. </p> <p>Prototyping speed, standardized components, and low cost are the driving factors. Switching speed, useful life, and noise are also important.</p> <p>Is there a breakout board, circuit, or component that can be connected to an Arduino pin and used to control a high current device? Ideally with a software controlled potentiometer so that the resistance for different projects could be set in the sketch itself.</p>
<p>I made an Arduino( Arduino Nano) circuit to power a 12V Peltier(which is also a high power source.) using a MTP3055V MOSFET 60V 12A transistor. And the circuit is operating very well.</p>
408
|pins|button|
Why does my sketch report too many button presses?
2014-02-23T21:43:22.787
<p>I've been using a button to interact with a sketch (on my Uno), and it's mostly working fine. However, sometimes it seems to be detecting multiple presses when it's only pressed once.</p> <p>It's a small circuit-mounted momentary button, which is normally open. It's connected from +5V directly to an input pin. I've also added a 10K pull-down resistor on the pin to make sure the input isn't left floating.</p> <p>Here's a test sketch I've been using, which reports the number of presses to the serial monitor:</p> <pre class="lang-cpp prettyprint-override"><code> int oldState = LOW; int numPresses = 0; void setup() { pinMode(5, INPUT); Serial.begin(9600); } void loop() { const int newState = digitalRead(5); if (newState != oldState) { if (newState == HIGH) Serial.println(++numPresses); oldState = newState; } } </code></pre> <p>Sometimes when I press the button once, the serial monitor shows two presses in a row. It sometimes even reports a press when I <em>release</em> the button.</p> <p>Is it possible to fix this? Or do I just have a faulty button or pin or something?</p>
<h1>Contact Bounce</h1> <p>This is known as contact bounce and happens when the metal contacts in the button or switch bounce against each other when you push it. The microcontroller is fast enough to pick up these bounces and, as far as it's concerned, you're toggling the switch many times in as much as 10 milliseconds of time.</p> <p>Different switches and buttons will have a different amount of contact bounce, and even one switch will behave differently between two presses.</p> <p>Here's a button press captured on a scope (image from <a href="http://www.maximintegrated.com/app-notes/index.mvp/id/159" rel="noreferrer">Maxim</a>):</p> <p><img src="https://i.stack.imgur.com/ZrNMs.gif" alt="enter image description here"></p> <p>At 2ms/div we don't see a stable signal until 6ms after initial contact!</p> <h1>Solutions</h1> <h2>Add a delay</h2> <p>The absolute simplest solution is to introduce a short delay after you read the button input. This will prevent the code from picking up any bounces and when it resumes, the signal should be stable.</p> <pre><code>if (digitalRead(A3) == 0) { // do something here delay(500); } </code></pre> <p>In the example above, I delay 500ms after reading the state of the pin. The button is normally high so when I press it down, the state of the pin goes to logic 0. I pick that up in the code and do something and then wait at least 500ms before continuing.</p> <p>Obviously, this code will just halt for half a second every time you push a button, which may or may not be acceptable in your application. You can decrease the amount of delay depending on the contact bounce time of your switch, too, but I play it safe here.</p> <h1>Ignore button presses too close to each other</h1> <p>Similar to the solution above but instead of adding a hard delay, you use the <code>millis()</code> function to keep track of when the last time the switch was triggered. Every time you see a switch trigger, you compare against the time and, if not enough time has elapsed (say like 500ms in my previous example), you ignore it.</p> <p>This solves the problem of having to use <code>delay()</code> in your code.</p> <h1>Switch debouncer IC</h1> <p>There are things like the <a href="http://www.maximintegrated.com/datasheet/index.mvp/id/1896" rel="noreferrer">MAX6816</a> which is an IC that you put in between your switch and microcontroller input. It will denounce the signal for you. At a price of $1.62 @1k you'll probably never use this.</p> <h2>Other</h2> <p>There are many solutions to this problem... I always do it in software, but some others include using a <a href="http://tech.thetonegod.com/debounce/debounce.html" rel="noreferrer">latch or capacitor</a>.</p> <p><a href="http://hackaday.com/2010/11/09/debounce-code-one-post-to-rule-them-all/" rel="noreferrer">Debounce Code – one post to rule them all</a></p>
412
|arduino-uno|ir|timers|
How can an Arduino output a specific (i.e. 56 kHz) carrier frequency?
2014-02-24T00:55:35.033
<p>I'm working on a free space optics project to send data wirelessly between two points. To accomplish this I'm using an IR LED connected to an Arduino Uno that pulses with a 56&nbsp;kHz carrier frequency for the transmitter and a second Arduino with a 56&nbsp;kHz IR detector module for the receiver.</p> <p>I tried using delayMicroseconds() between pin high and pin low commands in order to create the carrier frequency. This kind of works, but the frequency isn't always the same and any additional delays for pulsing the signal (i.e. the time required to call the function and decrementing) can change it.</p> <p>Reading the datasheet for the ATmega328 it appears that there is a way to set a more accurate pulse using the chip's timers. Is that possible, and if so, how do you create a 56&nbsp;kHz pulse using the timers?</p>
<p>There is no need to use an ISR to create the carrier. Just set up a timer to produce a 50% PWM output at the required carrier frequency. The ISR is then just in charge of modulating the carrier - typically at 0.5 or 1ms intervals - a far more comfortable rate. In my experience a 5% error in carrier frequency is tolerated by most IR receivers. I used a Freetronics EtherMega 2560 (which has plenty of timers) but I'm sure other CPUs will do just as well.</p>
414
|timers|programming|
Could someone explain this weird looking code, used to setup timers?
2014-02-24T02:06:06.347
<p>While looking at sketches other people have written, I occasionally come across code that looks somewhat like this:</p> <pre><code>TCCR1A = 0; TCCR1B = 0; TCNT1 = 34286; TCCR1B |= (1 &lt;&lt; CS12); TIMSK1 |= (1 &lt;&lt; TOIE1); </code></pre> <p>All I know is that is has something to with timing/timers (I think). How can I decipher—and create—code like this? What are <code>TCCR1A</code>, <code>TCCR1B</code>, <code>TCNT1</code>, <code>CS12</code>, <code>TIMSK1</code>, and <code>TOIE1</code>?</p>
<p>CS12 has a value of 2 since it represents bit 2 of the TCCR1B register. </p> <p>(1 &lt;&lt; CS12) takes the value 1 (0b00000001) and shifts it left 2 times to get (0b00000100). The order of operations dictates that things in () happen first, so this is done before the "|=" is evaluated.</p> <p>(1 &lt;&lt; CS10) takes the value 1 (0b00000001) and shifts it left 0 times to get (0b00000001). The order of operations dictates that things in () happen first, so this is done before the "|=" is evaluated.</p> <p>So now we get TCCR1B |= 0b00000101, which is the same as TCCR1B = TCCR1B | 0b00000101.</p> <p>Since "|" is "OR", all the bits other than CS12 in TCCR1B are unaffected.</p>
418
|arduino-uno|serial|pins|arduino-due|voltage-level|
How can a 5v Uno talk to a 3.3v Due?
2014-02-24T12:23:42.077
<p>I currently have an Uno (which operates at 5v), and I'm looking at buying a Due (which only operates at 3.3v). I'd like to make them communicate via Serial or SPI or similar, but presumably connecting them directly isn't an option (I guess the Due's pins would get damaged).</p> <p>Is there any way to make the connection safe? Or is there an alternative form of communication I could safely use between them instead?</p>
<ul> <li>For a 5V logic output to a 3V3 logic input, you can use a resistive divider to lower the voltage.</li> <li>When unloaded, a 3V3 logic output is just enough to drive a 5V logic input. Check the AVR datasheet for the exact voltages (0.6 × Vcc = 3V, found under DC Characteristics in the datasheet).</li> </ul> <p>In other words, with a little bit of special care it may just work.</p> <p>To construct a more reliable and bidirectional solution, use a level shifter. There are several listed on <a href="http://www.nxp.com/products/logic/level_shifters_translators/#products">this page</a> but other manufacturers make similar devices.</p> <p><a href="http://www.nxp.com/documents/application_note/AN10441.pdf">This document</a> describes how a MOSFET can be used to bidirectionally convert logic levels between different supply voltages.</p>
430
|arduino-uno|power|safety|
What will happen if I give my Arduino Uno more or less than 5 volts?
2014-02-25T05:44:28.927
<p>Will it still run on less than 5 volts? Will it break?</p>
<h1>Will it break at &lt; 5V? Not likely.</h1> <ul> <li>Check the datasheet for the IC's on the board and find the minimum power supply voltage the device works at.</li> <li>At typical ATmega328 Safe Operating Area (under "Speed grades" in the datasheet) specifies approximately 4.1V for 16MHz.</li> <li>If you require to use the USB interface, you'll have to check the datasheet for that chip too.</li> </ul> <h1>Will it run at &lt; 5V? Maybe.</h1> <ul> <li>If the supply voltage gets below the minimum operational voltage, the controller may behave erratically. That means it can do anything (un)expected. This value is in the datasheet and probably somewhere around 2.7V.</li> <li>If the Brown Out circuit is configured (in fuses), then the controller will switch itself off when supply voltage gets too low to prevent undefined situations. Once the supply voltage returns, it restarts.</li> </ul> <h1>Will it break at > 5V? Depends on where you apply it.</h1> <ul> <li>V(IN) should work fine for 7-20VDC as it is fed through an on board regulator. Notice though that the regulator has to dissipate the excess voltage and can get pretty hot when you draw a fair bit of current. The regulator will fail if the voltage goes over 20V or gets too hot too often;</li> <li>+5V should work fine up to 5V, and I personally wouldn't worry if an external supply delivers up to 5.5V unloaded. Above that 5.5V you will probably release the magic blue smoke.</li> </ul>
432
|arduino-uno|wifi|xbee|
How can I connect to an Arduino using WiFi?
2014-02-25T06:50:47.410
<p>I'm working on building a solar powered, Arduino based weather station. The weather station consists of a temperature sensor and a photoresistor, and I plan to add an anemometer in the future. I would like to connect the weather station to my wireless network so that I can retrieve the sensor data from my computer without having to run wires (I live in a rental).</p> <p>What are the different options for connecting the Arduino to WiFi? I've looked at ethernet shields, WiFi shields, and something called Xbee, but I don't understand what each of them are for. </p> <p>I also have a wireless home router that I could use. Is it possible to connect my Arduino Uno to the router via the routers ethernet or USB port and then receive data from and send commands to the Arduino wirelessly over my home network? If so, how would this be accomplished? </p> <p>I currently have a bare Arduino Uno.</p>
<p>After several trials &amp; errors in my IoT project, I would recommend working on ESP32 over ESP8266(and also Arduino Uno &amp; Nano), <strong>except if you know very well the scope of your project.</strong></p> <p>Advantages of ESP32 over ESP8266:</p> <ol> <li>Bigger RAM, ESP8266: 32KB instruction &amp; 80 KB user data, ESP32: 520 KB</li> </ol> <p>I'm working on an IoT project and trying to authenticate the device on GCP using a certificate. The root certificate of GCP is already about 120 KB, so it does not fit into ESP8266. There are alternatives but that complicates things.</p> <ol start="2"> <li>ESP32 has bluetooth &amp; ESP8266 not</li> </ol> <p>Well at some point of your IoT project you might want bluetooth to connect your device with your phone ...</p> <ol start="3"> <li>Some versions of ESP32 has integrated ports for the camera (search ESP32 CAM)</li> </ol> <p>With ESP8266 you can surely use a camera but that will involve more coding &amp; wiring and potentially worse performance.</p> <p>And at last, I tried to wire a wifi chip with Arduino Uno &amp; Nano but I encountered some bugs and problems with the AT commands. Thus now I'm quite happy with ESP32 because everything is integrated.</p>
438
|serial|library|
How does this code line detect if a serial interface is connected?
2014-02-25T22:48:32.067
<p>I am working with some code for remote temperature sensor nodes. They turn the debug interface on and off depending on if anything is conneced to the serial port or not.</p> <p>The code is on Github <a href="https://github.com/openenergymonitor/emonTH/blob/master/emonTH_DHT22_DS18B20/emonTH_DHT22_DS18B20.ino" rel="noreferrer">here</a>. Line <a href="https://github.com/openenergymonitor/emonTH/blob/40b8d4d42ad301b7877c1f5f18d492cc0e4317a9/emonTH_DHT22_DS18B20/emonTH_DHT22_DS18B20.ino#L111" rel="noreferrer">111</a> is the line of interest:</p> <pre><code>if (Serial) debug = 1; else debug=0; //if serial UART to USB is connected show debug O/P. </code></pre> <p>So, a simple question: On a hardware and software level, how does this work? I can't see anything in HardwareSerial or Stream that would return true/false if anything was connected or not.</p> <p>Note that I am not confident that it actually works. This simple test indicates it doesn't work as the LED flashes regardless of the presence of a serial adapter or connection:</p> <pre><code>boolean debug; const int toggle = 6; void setup() { if (Serial) debug = 1; else debug = 0; pinMode(toggle, OUTPUT); digitalWrite(toggle, LOW); if (debug) { Serial.begin(9600); Serial.println("Setup"); digitalWrite(toggle, HIGH); delay(1000); digitalWrite(toggle, LOW); } } void loop() { if (debug) { Serial.println("Loop"); digitalWrite(toggle, HIGH); delay(1000); digitalWrite(toggle, LOW); delay(1000); } } </code></pre>
<p>While it may not be possible to detect whether a device is connected to the Arduino serial connection or not, it is possible to <em>enable the debug messages over the serial connection</em> based on the presence of a device on the serial connection.</p> <p>Considering that you will be using the debug interface of your sketch only when connected to a computer capable of serial communication, it is possible to incorporate a simple test into the sketch based on which debug mode is enabled or not.</p> <p>When the sketch starts, you can check to see if any data is available on the Serial connection or not. If there is, then a device is present and debugging can be enabled. On the computer side, everytime you want to start the debugging mode on the Arduino, simply send a byte over the serial connection during the <code>setup</code> phase and sit back.</p> <p>Here is a sample sketch showing the same:</p> <pre class="lang-cpp prettyprint-override"><code>int debug = 0; void setup() { pinMode(13, OUTPUT); Serial.begin(9600); //Wait for four seconds or till data is available on serial, //whichever occurs first. while(Serial.available()==0 &amp;&amp; millis()&lt;4000); //On timeout or availability of data, we come here. if(Serial.available()&gt;0) { //If data is available, we enter here. int test = Serial.read(); //We then clear the input buffer Serial.println("DEBUG"); //Give feedback indicating mode debug = 1; //Enable debug } } void loop() { if(debug==1) Serial.println("ON"); digitalWrite(13,HIGH); delay(1000); if(debug==0) Serial.println("OFF"); //Turn off if serial is not available digitalWrite(13,LOW); delay(1000); } </code></pre>
439
|serial|arduino-ide|
Why does starting the serial monitor restart the sketch?
2014-02-25T22:51:03.030
<p>If I upload any sketch that sends serial data, I immediately see the TX/RX LEDs flash once the sketch is uploaded. If I then start the serial monitor, the sketch appears to restart.</p> <p>A bare minimum sketch that shows this behaviour:</p> <pre class="lang-cpp prettyprint-override"><code> void setup() { Serial.begin(9600); Serial.println(&quot;Setup&quot;); } void loop() { Serial.println(&quot;Loop&quot;); delay(1000); } </code></pre> <p>Tested with several boards and Mac and Windows versions of the IDE.</p> <p>Example output - it goes back to &quot;Setup&quot; when I open the serial monitor:</p> <p><img src="https://i.stack.imgur.com/mokWb.png" alt="Restart" /></p> <p>Why is this?</p>
<p>Arduino uses the <strong>DTR line</strong> (data terminal ready)</p> <p>So, with the Arduino Serial Monitor it is not possible to change the restart when established the rs232 connection.</p> <p>But I'm using for example the freeware &quot;HTerm&quot; (under Windows). By default, it does not use the DTR signal. Meanwhile I changed to the freeware &quot;<strong>CoolTerm</strong>&quot; (a bit more comfortable...): You have to deactivate &quot;DTR Off&quot; unter &quot;Connection Options&quot;. In Linux I'm using the &quot;moserial&quot;. Under &quot;PortSetup&quot; you must deactivate the &quot;handshake&quot; ;-)</p> <p>This way is more comfortable for me then adjusting the RESET pin. Also, its a nice benefit saving all the data in a log file for later analyzing…</p>
455
|arduino-ide|
Why does opening the Tools menu take so long?
2014-02-26T14:20:39.883
<p>Every time I open the <code>Tools</code> menu, the IDE freezes for a few seconds. Why is that? It happens on both of my computers, and nothing I do makes a difference in how long it takes. I've tried restarting the IDE, unplugging my Uno, and many other things, but nothing helps.</p> <p>I'm on windows, running IDE version 1.0.2.</p>
<p>I had the same issue on my laptop (win 7, 64). Renaming file ListComPorts.exe to ListComPorts.exe.xxx as mentioned above worked. I also had to switch to a standard USB port (not 2.0) for sketch to load properly. </p>
473
|bootloader|
How do I burn the bootloader?
2014-02-26T22:09:57.103
<p>I was instructed to "burn the bootloader" to my Arduino to fix an error I was getting. How can I do this? (And what exactly is the bootloader?)</p>
<h3>What is a bootloader?</h3> <blockquote> <p>And what exactly is the bootloader? </p> </blockquote> <p>The bootloader is a small piece of code residing in the "high" part of program memory. Normally it is not erased when you upload new sketches. Its purpose it to be activated immediately after a reset (the fuses are configured to commence code at the bootloader address rather than address 0x0000). The bootloader will wait a short time (such as one second) to see if "programming" data is arriving on the serial port.</p> <ul> <li><p>If so, it reads that data, and decodes it to reprogram the rest of the flash memory. Working in conjunction with the uploading program (normally avrdude) the new sketch is sent via the serial port. The bootloader erases pages of flash memory, and replaces them with the new code. Once done, it executes the new code.</p></li> <li><p>If no instructions arrive, the bootloader jumps to address 0x0000 to execute the existing sketch on the board.</p></li> </ul> <hr> <h3>How to replace the bootloader</h3> <p>An alternative method to program a bootloader is to use a sketch I wrote a while ago which runs on a:</p> <ul> <li>Uno (or similar, such as Duemilanove)</li> <li>Leonardo</li> <li>Mega2560</li> </ul> <p>The "programming" board runs the sketch which has bootloaders for a number of boards hard-coded into it. You connect the programming board to the target board (the board wanting the bootloader) with 6 hook-up wires as shown.</p> <p><img src="https://i.stack.imgur.com/WA4yE.jpg" alt="Bootloader programmer for Uno"></p> <p>That particular photo illustrates one Uno programming another one.</p> <p>You run the sketch (operating via the Serial Monitor to give it commands). First it identifies the target chip:</p> <pre><code>Atmega chip programmer. Written by Nick Gammon. Entered programming mode OK. Signature = 0x1E 0x95 0x0F Processor = ATmega328P Flash memory size = 32768 bytes. LFuse = 0xFF HFuse = 0xDE EFuse = 0xFD Lock byte = 0xCF Bootloader address = 0x7E00 Bootloader length = 512 bytes. Type 'L' to use Lilypad (8 MHz) loader, or 'U' for Uno (16 MHz) loader ... Type 'G' to program the chip with the bootloader ... </code></pre> <p>The you press <strong>G</strong> to program it.</p> <pre><code>Erasing chip ... Writing bootloader ... Committing page starting at 0x7E00 Committing page starting at 0x7E80 Committing page starting at 0x7F00 Committing page starting at 0x7F80 Written. Verifying ... No errors found. Writing fuses ... LFuse = 0xFF HFuse = 0xDE EFuse = 0xFD Lock byte = 0xCF Done. Type 'C' when ready to continue with another chip ... </code></pre> <p>For a Uno this takes one second. To program a Mega2560 takes 3 seconds.</p> <p>Detailed instructions at <a href="http://www.gammon.com.au/bootloader" rel="noreferrer">Atmega bootloader programmer</a></p> <p>Code can be downloaded from <a href="https://github.com/nickgammon/arduino_sketches" rel="noreferrer">Github: nickgammon/arduino_sketches </a></p>
482
|ide|emulation|debugging|
How do I debug on-chip with Arduino?
2014-02-27T11:46:28.300
<p>Though an emulator is quite useful for debugging code that has no side effects, most real-world applications include some circuitry besides the Arduino. If a microcontroller on an Arduino had a JTAG interface, it would be pretty straight-forward, but what if it's e.g. an Arduino Uno?</p>
<p>This might not be right for you, but the <a href="http://www.visualmicro.com/" rel="nofollow noreferrer">Visual Micro</a> plugin for Atmel Studio and Visual Studio has a <a href="http://www.visualmicro.com/page/Debugging-for-Arduino.aspx" rel="nofollow noreferrer">USB debugger</a> which only uses Arduino code.</p> <p>In the background the debugger uses Serial which might affect some time-sensitive applications.</p> <p><img src="https://i.stack.imgur.com/6Mqkn.png" alt="Enter image description here"></p>
484
|arduino-uno|serial|
Arduino as USB HID
2014-02-27T14:37:49.173
<p>Is it possible to build a HID device (like a keyboard) using an Arduino uno?</p> <p>At the time being, I have button inputs on the Arduino giving outputs on the serial line. So, how can I transform my current firmware into something that can behave like a HID keyboard?</p> <ul> <li>Shall I write a new window device driver?</li> <li>Shall I create a software layer that could take my serial data and have windows read it as HID input?</li> <li>Is there any better way to achieve this, if it is possible at all?</li> </ul>
<p>I created a project that fully replaces the Arduino Bootloader. You are able to upload sketches and use it as HID. See Project HID on Github: <a href="https://github.com/NicoHood/HID" rel="noreferrer">https://github.com/NicoHood/HID</a></p>
485
|sd-card|
Combining Strings into a datestamp
2014-02-27T16:51:23.440
<p>I'm creating a weather station / environmental datalogger and am saving my data to a SD card Breakout. The SD card works fine but I would like to name the files I am saving on it after the date when the readings were taken.I've tryed multiple things but I can't work out how to combine the date from my RTC and put them in a file name. I've tryed this:</p> <pre><code>dataFile = SD.open(String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv",FILE_WRITE); </code></pre> <p>But this gives me an error -</p> <pre><code>char dateName[13] = {String(now.day()) + "-" + String(now.month()) + "-" + String(now.year()) + ".csv"}; dataFile = SD.open(dateName,FILE_WRITE); </code></pre> <p>But this gives me this error:</p> <pre><code> cannot convert 'StringSumHelper' to 'char' in initialization </code></pre> <p>Help! How do I do this? </p>
<p>Well:</p> <pre><code> char buffer[15]; snprintf(buffer, sizeof(buffer), "%02d-%02d-%04d.csv", now.day(), now.month(), now.year()); </code></pre> <p>After <code>snprintf</code> call, <code>buffer</code> contains the name of the file.</p> <p>This solution use constant fixed space in RAM (just 15 bytes for buffer), while all others solutions demands tons of RAM for creating multiple String objects.</p> <p>And it's faster, because it only do the format part, minus all creations, conversions, and deletion using String.</p> <p>Finally, generated names are always the same length, from 1-1-2018 thru 31-12-2018.</p> <p>Don't use String with Arduino.</p>
488
|sensors|system-design|
Best way to determine if a 5 gallon water jug is getting empty
2014-02-27T17:27:04.717
<p>I have an espresso machine that gets its water from one of those 5 gallon blue water bottles (I would plumb it, but our water here is WAAAAY too hard).</p> <p>If I ever accidentally let the bottle run out of water, the rotary pump in the espresso machine will be ruined, which would be a costly mistake.</p> <p>I know that I can install some sort of magnetic float sensor inside the water bottle, but since I have to change it out once every few weeks, having another thing inside the bottle would make changing it out harder, and microbial contamination more likely. The pump that pumps water out of the bottle forms a tight seal at the lid, and anything running under it or through it would compromise that seal.</p> <p>Is there something I could use to detect if the water level is low from the outside of the bottle? Like a laser sensor?</p>
<p>Try a non contact water sensor: <a href="https://www.dfrobot.com/product-1493.html" rel="nofollow noreferrer">https://www.dfrobot.com/product-1493.html</a> I use them and they work very well. You stick it on the outside of the jug, If it falls off the jug will show empty protecting your pump. The ones I use are similar and have an open collector, so no micro is required. I think I paid about $6 a year or so ago. They make adjustable ones. Nice point nothing touches the water or can contaminate it.</p>
493
|sketch|c++|
sprintf() to assemble String and float pieces locks up
2014-02-27T23:29:52.217
<p>I'm trying to parse many variables into a URL so that I can update a website through a simple HTTP API with sensor data. After talking to a buddy of mine, he suggested going with the code below. </p> <p>When I put this in, the Arduino Yun boots up. I see the L13 red LED turn on, but then it hoses. When I comment out the <code>sprintf();</code> line, everything works fine — except no URL is parsed.</p> <p>I've tried to debug to the best of my ability and am looking for thoughts on what may be happening. </p> <p>I'm not sure how much code to post without posting the whole 130 line sketch, so I'm just dumping the parts from the <code>loop</code> that is trying to piece together the URL.</p> <pre><code> // Get update time Process date; date.runShellCommand("date --utc \"+%Y-%m-%d%%20%H:%M:%S\""); String utcDateString = ""; while (date.available()) { char d = date.read(); utcDateString += d; } char url[512]; url[0]='\0'; float humid, baro, windspeed, raingauge; int winddir; Serial.print("humid: "); Serial.println(humid); Serial.print("baro: "); Serial.println(baro); Serial.print("windspeed: "); Serial.println(windspeed); Serial.print("raingauge: "); Serial.println(raingauge); Serial.print("winddir: "); Serial.println(winddir); //sprintf(url,"http://weatherstation.wunderground.com/weatherstation/updateweatherstation.php?ID=123456&amp;PASSWORD=xxxxxx&amp;dateutc=%s&amp;temp=%2.2f&amp;humidity=%2.2f&amp;baromin=%f&amp;winddir=%d&amp;windspeedmph=%3.2f&amp;rainin=%3.2f&amp;softwaretype=Custom%%20Arduino&amp;action=updateraw", // utcDateString,Thermistor(analogRead(0)),humid,baro,winddir,windspeed,raingauge); Serial.print("url: "); Serial.println(url); double Thermistor(int RawADC) { double Temp; Temp = log(11100.0/((1024.0/RawADC-1))); // Was 10000... Manually dialed down to increase accuracy. 9400 is a good value. Changing again to match wunderground Temp = 1 / (0.001129148 + (0.000234125 + (0.0000000876741 * Temp * Temp ))* Temp ); Temp = Temp - 273.15; // Convert Kelvin to Celcius Temp = (Temp * 9.0)/ 5.0 + 32.0; // Convert Celcius to Fahrenheit return Temp; } </code></pre> <p>Here's the output from those <code>Serial.print()</code> calls:</p> <pre><code>humid: 0.00 baro: 0.00 windspeed: 0.00 raingauge: 0.00 winddir: 0 url: </code></pre> <p>I'm not sure how else to debug this because when I uncomment <code>sprintf();</code> the Yun locks up and I have to press the <code>32U4 Reset</code> button and power cycle the Arduino to get it to work again.</p>
<p>This variable:</p> <pre><code>String utcDateString = ""; </code></pre> <p>Is a C++ String, not a character array like sprintf() is expecting. To convert this string to a character array such that sprintf is expecting, you must use .c_str() in your sprintf, i.e.:</p> <pre><code>sprintf(foo,"This is a format for %s", utcDateString.c_str()); </code></pre> <p>Doing this should prevent the sprintf line from causing a memory fault.</p>
501
|sensors|
Sensor for underground water tank level
2014-02-28T05:28:50.783
<p>In a similar way to the question "<a href="https://arduino.stackexchange.com/questions/488/best-way-to-determine-if-a-5-gallon-water-jug-is-getting-empty"><strong>best way to determine if a 5 gallon water jug is getting empty</strong></a>", I'm looking for a way to measure water in a container. This is so it can be connected to an Arduino for logging and reporting. But it's a very different container.</p> <p>I have a home with the household water supplied from an underground concrete tank (around 3000 US gallons, 11000 litres). Although there is a float switch cutout when it gets empty (to protect the pump), I'd like to know it's gettting low long before that (as it takes a while before a tanker delivers a fresh load). Ideally something that measures exactly or in steps (at least in eights of a load), so software can predict when it'll run out based on average usage, and it can be monitored online when away.</p> <p>The tank has a heavy concrete hatch, and a small hole that has an existing primitive dipstick, so access is limited. It's in a harsh desert environment, but the pump room and power are only a few feet away.</p> <p>Some ideas I had:</p> <ul> <li>suspend an array of float switches with strings of different lengths from a bar inside the tank, and wire them all back to a controller. Hard to install, ugly, low tech. Or something similar on a vertical pole.</li> <li>contacts (like a US 2 pin plug) on a vertical pole that again are connected back to a controller (probably using a ribbon cable). Corrosion/anodes might be a problem, although power could just be a short pulse at times. Condensation, spiders webs and dead bugs may give false readings.</li> <li>run a fully insulated cable vertically down it, and use as an antenna to send a pulse through, and use the difference between how it works as an antenna in air, and in water, (like an SWR meter) to calculate how far down the water is.</li> <li>ultrasonic (or light?) distance finder mounted under the hatch. Range needs to be up to 2 metres (6 feet).</li> <li>depth finder (sonar) on a float. Biggest challenge here is getting the signal out (long cable might get tangled when the tank fills).</li> </ul> <p>The last two would be even better if they were wireless (to save running a cable that might get damaged) but I don't think I'd get the battery life I'd like (1 year or more).</p> <p>Any other ideas? Has anybody ever done this?</p>
<p>You could take a piece of 2 conductor wire in a U shape that is weighted at the bottom of the "U" to rest at the bottom of the tank. (The reason to use a U shaped wire instead of a straight wire is to prevent having to insulate one end from the water). You would then measure the capacitance of the wire, where some baseline capacitance is the wire when dry and any wire that is wet would increase the capacitance proportional to the length that is wet. Any wire that is rated for outdoor operation, i.e. does not absorb water would do and actually the thicker the jacket the better as the baseline capacitance would be lower.</p> <p>The capacitance could be measured in the same way as a capacitive touch sensor or a capacitance to frequency converter (Sometimes called an "Oscillator").</p>
506
|programming|c++|coding-standards|
Is it better to use #define or const int for constants?
2014-02-28T09:46:51.437
<p>Arduino is an odd hybrid, where some C++ functionality is used in the embedded world—traditionally a C environment. Indeed, a lot of Arduino code is very C like though.</p> <p>C has traditionally used <code>#define</code>s for constants. There are a number of reasons for this:</p> <ol> <li>You can't set array sizes using <code>const int</code>.</li> <li>You can't use <code>const int</code> as case statement labels (though this does work in some compilers)</li> <li>You can't initialize a <code>const</code> with another <code>const</code>.</li> </ol> <p>You can check <a href="https://stackoverflow.com/questions/1674032/static-const-vs-define-in-c">this question</a> on StackOverflow for more reasoning.</p> <p>So, what should we use for Arduino? I tend towards <code>#define</code>, but I see some code using <code>const</code> and some using a blend.</p>
<ol> <li> <blockquote> <p>You can't set array sizes using <code>const int</code>.</p> </blockquote> <p>You can with <code>constexpr int</code>:</p> <pre><code>constexpr auto size{ 15 }; int array[size]{}; </code></pre> </li> <li> <blockquote> <p>You can't use <code>const int</code> as case statement labels (though this does work in some compilers)</p> </blockquote> <p>Again, you can with <code>constexpr int</code>:</p> <pre><code>constexpr auto zero{ 0 }; constexpr auto one{ 1 }; int number{ 1 }; switch (number) { case zero: Serial.println(&quot;zero!&quot;); break; case one: Serial.println(&quot;one!&quot;); break; default: Serial.println(&quot;neither!&quot;); break; } </code></pre> </li> <li> <blockquote> <p>You can't initialize a <code>const</code> with another <code>const</code>.</p> </blockquote> <p>You can even initialize a <code>constexpr</code> with another <code>constexpr</code>:</p> <pre><code>constexpr int x{ 1 }; const int y{ x }; constexpr int z{ x }; </code></pre> </li> </ol> <p>Furthermore, <code>constexpr</code> guarantees that the variable gets evaluated at compile-time, unlike <code>const</code>. <code>constexpr</code> also doesn't have some of the disadvantages that preprocessor macros have<sup>(<a href="https://www.learncpp.com/cpp-tutorial/const-constexpr-and-symbolic-constants/" rel="nofollow noreferrer">learncpp</a>)</sup>:</p> <ol> <li>Debuggers like Visual Studio's don't let you <em>watch</em> preprocessor macros.</li> <li>Macros can conflict with normal code.</li> <li>Macros don't have scope, which increases the chance of naming conflicts.</li> </ol>
508
|power|transistor|voltage-level|
How to switch an external circuit with Arduino?
2014-02-28T11:05:39.467
<p>I have an object with a series of led and I want to turn on and off these leds from my Arduino. The input of the LED circuit is 24v DC 100mA.</p> <p>What I've done is the following:</p> <ul> <li>I've cut a wire of this object and I connected one end to the collector and the other end to the emitter of a NPN transistor</li> <li>I connected the base of the transistor to a digital output (through a 1k resistance)</li> <li>I connected the power to the led series while the digital pin was LOW (actually completely disconnected)</li> </ul> <p><strong>But with no current on the base of the transistor, the LED has turned on to my surprise.</strong> I may have completely misused the transistor and other items. How do I fix this circuit?</p>
<p>If I understand your writeup correctly, this is what you have built:</p> <p><img src="https://i.stack.imgur.com/8zae1.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f8zae1.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/">CircuitLab</a></sup></p> <p>What you didn't mention in your question is that you made a connection from Arduino ground to the base of the transistor and the seconds circuit's ground connection. I drew the extra lead 'loose' for illustration only, but you see where it should connect. Current needs a return path, it is not sufficient to only have the forward path (from Arduino through R1 and base-Q1). The return path is emitter-Q1 to Arduino-GND.</p> <p>Do notice though that the two batteries / power supplies must be floating with respect to each other otherwise you're going to short them out.</p>
532
|button|ui|display|
What design patterns can I use to handle user input and display updating?
2014-03-01T09:46:43.670
<p>I've used enough products with embedded microcontrollers and unresponsive UIs to know that it can make or break a product. Even a slight delay or lag between the button presses and the display updating, or button presses being ignored or double counted, can be extremely frustrating.</p> <p>What design patterns can be used to deal with user input (from buttons) and updating displays without causing these issues?</p> <p>I currently use the following kind of pattern (this is simplified down to the bare minimum):</p> <pre><code>#include &lt;Bounce.h&gt; #define GREEN_LED 6 // Pin for green LED #define BUTTON_PIN 15 // Pin for button - uses external pull down so active high #define DISPLAY_REFRESH_INT 100 // How many MS between display updates Bounce button = Bounce(BUTTON_PIN, 5); // To signal between the button read and the display update bool ledState = false; // Used to keep track of last display update long displayUpdate = 0; void setup() { pinMode(GREEN_LED, OUTPUT); pinMode(BUTTON_PIN, INPUT); } void loop() { // Read the button status if (button.update()) { if (button.risingEdge()) { ledState = !ledState; } } // Update the display periodically if (millis() - displayUpdate &gt; DISPLAY_REFRESH_INT) { displayUpdate = millis(); digitalWrite(GREEN_LED, ledState); } } </code></pre> <p>What other options are there? Is it ever worth using pin change interrupts to read buttons (if we are not considering battery life!).</p>
<p>As Chris K i've also implemented a static menu library with a wide variety of output options like Serial,LCD,TFT, etc.. I've started it to help in a friends project and I'm also sharing it open source for people that with similar problems, hope you can find it useful.</p> <p><a href="https://github.com/neu-rah/ArduinoMenu" rel="nofollow noreferrer">https://github.com/neu-rah/ArduinoMenu</a></p>
533
|programming|
What is the difference between declaring a variable outside of loop and declaring static inside loop?
2014-03-01T10:00:28.807
<p>These are two ways I can hold a variable outside of loop (or any function).</p> <p>First, I can declare it with global scope outside of loop:</p> <pre><code>void setup() { Serial.begin(9600); } int count = 0; void loop() { Serial.println(count); count++; delay(250); } </code></pre> <p>I can also declare it static inside the loop:</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { static int count = 0; Serial.println(count); count++; delay(250); } </code></pre> <p>What difference, if any, will this make?</p>
<p>Both variables are static - they persist for the entire execution session. The global is visible to any function if it declares - not defines - the global, or if the function follows the definition in the same compilation unit (file + includes).</p> <p>Moving the definition of <code>count</code> to inside of a function both limits its scope of visibility to the nearest enclosing set of <code>{}</code>es, and gives it function invocation lifetime (it is created and destroyed as the function is entered and exited). Declaring it <code>static</code> as well gives it execution session lifetime it exists from the start to the end of the execution session, persisting across function invocations.</p> <p>BTW: be cautious about using initialized statics within a function, as I have seen some versions of the gnu compiler get this wrong. An automatic variable with an initializer should be created and initialized on every function entry. A static with an initializer should only be initialized once, during the execution setup, before main() is given control (just as a global would be). I have had local statics get reinitialized on each function entry as though they were automatics, which is incorrect. Test your own compiler to be sure.</p>
539
|ide|
How to debug an Arduino sketch on a Mac?
2014-03-01T15:13:27.810
<p>I have 2 Lowpowerlab WaterMote's talking to each other using the 'out of the box' pre-installed <a href="http://www.arduino.cc/en/Tutorial/Sketch" rel="nofollow">sketch</a> that just confirm they're talking to each other. I verified this by opening a COM connection and saw traffic of 'receiving packets...' That was just to show that they are functioning and talking to each other.</p> <p>Now, using Arduino IDE on Mac&nbsp;OS&nbsp;X 1.9.x (Lion?) I have loaded the WaterMote sketch (found on <a href="http://en.wikipedia.org/wiki/GitHub" rel="nofollow">Github</a>) on the Moteino with the sensor (not the gateway) as it should be. The traffic looks like it's working, except the text being transmitted (number of Gallons) stays the same at 0.02 Gallons.</p> <p>So... I want to debug the WaterMote sketch, <em>but</em> I do not see an option in my Arduino IDE on Mac&nbsp;OS&nbsp;X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).</p> <p>My current setup</p> <ul> <li>Moteino Gateway (as out of the box) connected to a <a href="http://en.wikipedia.org/wiki/Raspberry_Pi" rel="nofollow">Raspberry Pi</a> (with ssh enabled) <ul> <li>Connected via USB to the RasPi</li> </ul></li> <li>Moteino with WaterMote sketch loaded <ul> <li>Connected via USB to the MacBook Pro</li> <li>Arduino IDE running, but I see strange "[][][]" square output in the Serial connection.</li> <li>I do not know what to make of this since that text is not in the WaterMote sketch.</li> </ul></li> </ul> <p>Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?</p> <p>I found a debugging article:</p> <ul> <li><a href="http://www.instructables.com/id/Arduino-Debugging-Breakpoints-Tracepoints-and-E/" rel="nofollow">Visual Micro</a></li> </ul>
<blockquote> <p>So... I want to debug the WaterMote sketch, but I do not see an option in my Arduino IDE on Mac OS X. Is there a way to debug sketches using Macs? Searching online shows various and preferred options, but mostly on Windows (of which I don't have any at home).</p> </blockquote> <p>It's definitely possible to debug a sketch with OS&nbsp;X. But it's definitely an advanced AVR topic, and if you're not experienced enough with embedded programming you should first try to avoid it, except if it is really necessary.</p> <p>Debugging a sketch for an <a href="http://www.atmel.com/devices/atmega328.aspx" rel="nofollow">ATmega328</a> implies:</p> <ul> <li>Running a flasher such as the AVR Dragon, the JTAG ICE 3, the STK500 or the AVR ONE; no cheap flasher implements the <code>DebugWire</code> protocol;</li> <li>Setting up the debug fuse, which is an operation that can brick your <a href="http://en.wikipedia.org/wiki/Microcontroller" rel="nofollow">MCU</a>.</li> </ul> <p>If you're using an <a href="http://www.atmel.com/devices/atmega32u4.aspx" rel="nofollow">ATmega32U4</a> (or alike), you won't be able to do it out of the box, as the 32U4 needs a <a href="http://en.wikipedia.org/wiki/Joint_Test_Action_Group" rel="nofollow">JTAG</a> connection for on-chip debugging.</p> <p>Finally, once you got through that, you can bind a <code>gdb</code> to the AVR using <a href="http://avarice.sf.net" rel="nofollow">AVaRICE</a>. I'm not getting you through all that, because I really, really, strongly advise you not to do it until you're experienced enough to know what you're doing.</p> <blockquote> <p>Moteino with WaterMote sketch loaded connected via USB to the MacBook Pro Arduino IDE running, but I see strange "[][][]" square output in the Serial connection. I do not know what to make of this since that text is not in the WaterMote sketch. Is there a way to debug sketches loaded on Arduino clones using Arduino IDE on Macs?</p> </blockquote> <p>It is very likely you did not setup the correct baudrate for the serial outputs. Arduino IDE defaults to 9600&nbsp;bits/s connections, whereas the <a href="https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L31" rel="nofollow">WaterMote source code</a> defines a 115,200&nbsp;bits/s connection. When you open the <code>Serial Monitor</code> change the setting at the right of the status bar.</p> <p>And finally, be sure to uncomment the <a href="https://github.com/LowPowerLab/WaterMote/blob/master/WaterMote.ino#L30" rel="nofollow"><code>#define SERIAL_EN</code> line</a> to enable the serial communication and debug outputs.</p>
548
|library|
Why are the files not being created correctly?
2014-03-02T03:13:06.193
<p>I have been through <a href="http://arduino.cc/en/Hacking/LibraryTutorial" rel="nofollow">http://arduino.cc/en/Hacking/LibraryTutorial</a> but I can't do it. Whenever I create a new sketch and try to save it as <code>.cpp</code> or <code>.h</code> from the <kbd>Save As</kbd> button in the Arduino IDE, it gets saved as <code>_cpp</code> and <code>_h</code>. I am not able to create a library this way. How do I create a new library? What am I missing here?</p>
<p>When you save a file using the <kbd>Save As</kbd> button from the Arduino IDE, it saves the current file as a sketch i.e. as an <code>.ino</code> file.</p> <p>To create a <code>.cpp</code> and <code>.h</code> files for working on a new library, you need to create the files alongside a sketch. For this, you can use the <kbd>Tab</kbd> button on the top right (circled in red).</p> <blockquote> <p><img src="https://i.stack.imgur.com/lya7P.png" alt="enter image description here"></p> </blockquote> <p>Click on it, and select <kbd>New Tab</kbd>. You will get a bar at the bottom of the screen asking for a file name. Enter the name with extension (<code>test.cpp</code>) and press <kbd>Enter</kbd>.</p> <blockquote> <p><img src="https://i.stack.imgur.com/5cIWe.png" alt="enter image description here"></p> </blockquote> <p>Your file has now been added to the current directory.</p> <blockquote> <p><img src="https://i.stack.imgur.com/1Cp0V.png" alt="enter image description here"></p> </blockquote> <p>Similarly, follow the same steps for creating the <code>.h</code> file.</p> <p>Once your library is complete and ready to ship, you can move the <code>.cpp</code> and <code>.h</code> files to a separate directory and then add it under libraries.</p>
574
|arduino-uno|pins|
Should all unused analog input ports be tied to ground for accurate A2D measurements?
2014-03-03T05:07:38.563
<p>I am using the A0 port on my Arduino Uno to read the voltage output from an LM35 temperature sensor. I observed that the reading fluctuates a lot if I leave the remaining analog input ports A1 to A5 floating. Would floating analog inputs affect the accuracy of readings on input ports connected to some signals.</p>
<p>Even if setting the unused pins to OUTPUT/LOW consumes a little bit less power than INPUT with PULLUP enabled, i guess the second option is more save.</p> <p>To quote somebody else:</p> <blockquote> <p>If you accidentally touch a hot wire to an output set low you short-circuit your processor and frie it. If you accidentally touch a ground wire to an output set high you short-circuit your processor and frie it. If you accidentally touch either wire to an input with pull-up you won't even notice.</p> </blockquote>
588
|sensors|arduino-uno-smd|
How can I sense when someone is sleeping with my Arduino?
2014-03-03T23:17:03.163
<h2>Ignore the stalker-like title.</h2> <p>I am thinking about creating a project with Arduino that can sense you sleep habits, when you're asleep, and how much you sleep. It would be convenient to not have to turn it on/off at night; it should know how to do this.</p> <p>Some ideas that I have:</p> <ul> <li>Motion sensor</li> <li>Breathing patterns (if an Arduino microphone could even pick that out... I would be surprised if it could)</li> <li>A RTC clock could assist in deciding <em>It's midnight. Usual, Steve isn't asleep at this time on Fridays. He's probably not sleeping now.</em> It won't always be there to help you, but you might be able to try to get more accurate results this way</li> </ul> <p><strong>How can I accomplish this?</strong> (Extra points for some sort of algorithm that can tell dozing off from a deep sleep.)</p>
<p>I actually did something like this, using a <a href="https://www.sparkfun.com/products/8630">PIR Motion sensor</a>.</p> <p>The motion sensor is good enough to detect a person turning in their sleep, and my simple algorithm just counts movements per minute and when its over a threshold (found by trial and error), it sounds the alarm to wake you up.</p> <p><img src="https://i.stack.imgur.com/pYBe3.png" alt="enter image description here"></p> <p>The image above represents my body movements during a night. The spikes represent a high movements/minute.</p> <blockquote> <p>Here we see after about 30 minutes body motion was minimal. This suggests I was in a deeper stage of sleep during that time.</p> <p>The spike at 250 minutes (around 4:30AM) is when I woke up only to realize I could sleep for couple of hours longer. I recall the time being 4:38 when I looked at my clock and I was already facing it. This means I turned around to face the clock but actually "woke up" 8 minutes later to see the time, and then turned back around (indicated by the shorter spike at 265).</p> <p>The data suggests I was not able to sleep very well (compared to the time period between 30 and 240 minutes) after waking up once and finally got up at 400 minutes (7:00AM), when I shut everything down.</p> </blockquote> <p>Here are a couple of posts from my blog that have a lot more information.</p> <ul> <li><a href="http://blog.sachleen.com/posts/1353217318/body-movement-during-sleep/">Body Movement During Sleep</a></li> <li><a href="http://blog.sachleen.com/posts/1353217790/alarm-clock-hardware/">Intelligent Alarm Clock Hardware</a></li> </ul>
592
|arduino-uno|programming|
Build Infrared Camera Remote
2014-03-04T01:11:20.083
<p>I wish to build a remote for my Camera i.e Sony NEX 5R. It has a built in IR receiver and has several Sony as well as aftermarket remotes provided for it. Due to my interest in Micro controller design I wish to build one myself rather than use an aftermarket one.</p> <p>A friend who did the same for his NEX 5 series camera posted a video of the same on Facebook, which inspired me to build my own. I plan to use an Arduino Uno R3 with the following additional components:</p> <ul> <li><p>IR LED</p></li> <li><p>NPN Transistor(for amplification)</p></li> <li>Schmidt Triggers(for rectification)</li> <li>9 Volt Battery</li> </ul> <p>Ultimately I would like to swap out the Arduino for a standalone ATmega328 or ATtiny2313 but currently I have some issues as of now:</p> <ol> <li>I currently do not have a schematic or a sample code which I can use. I have been trying to search the internet for the same but to no avail.</li> <li>I am unsure of the protocol used by my camera. I have found it difficult to find documentation on the same.</li> <li>How can I replace the 9-Volt battery for something smaller?</li> <li>I would like to use a smaller micro controller but what differences will I encounter when trying to change my code for the smaller micro controller?</li> <li>For such a project, will I need additional hardware?</li> </ol>
<p>Well, for your project you can simply buy/rebuild a TV-B-Gone <a href="https://cornfieldelectronics.com/tvbgone/buy.tvbgkit.php?PHPSESSID=3phhip32unp1ku0di8qe9e6od0" rel="nofollow noreferrer">made by Mitch</a>, which he uses as a basic project to teach soldering all over the world.</p> <p>You can "hack" the TV-B-Gone by adding a <a href="http://www.vishay.com/docs/82459/tsop48.pdf" rel="nofollow noreferrer">TSOP4838</a> that can work as an IR receiver (or use another device as a code recorder).</p> <p><img src="https://i.stack.imgur.com/LezO4.png" alt="TV-B-Gone"></p> <p>And as you can see here the TV B Gone features an ATTiny85. A really small and nice beast.</p> <p>Here you'll find the <a href="https://github.com/adafruit/TV-B-Gone-kit/tree/master/firmware" rel="nofollow noreferrer">source code</a> for the TV B Gone. I'm not sure what format they use for their code database though.</p>