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
1247
|arduino-due|bootloader|bossa|
Why doesn't the master branch BOSSA work on Arduino Due?
2014-04-22T07:48:37.103
<p>I have downloaded BOSSA for Linux, and have run <code>bossash-&gt;scan</code>. I have also tried erasing and resetting the board before scanning. It does not work. According to the <a href="http://arduino.cc/en/Main/arduinoBoardDue" rel="nofollow">Arduino website</a>, the native USB port is connected directly to the chip. </p> <p>Isn't the master branch BOSSA (Arduino IDE uses it's own modified version of BOSSA) working because of a problem with this specific board, or have Arduino modified something inside the chip which alters the behaviour of the native port?</p>
<p>No Arduino did not alter the chip, custom chips are massively expensive. If they are using their own modified version of BOSSA, then there must be a reason for it, probably the support of Arduino's hardware platform. To find out what the difference is, you have to find the code base used for Due and the original version when the code was forked. Often in such cases a project like Arduino can provide a patch to the BOSSA project, and that patch may or may not be applied to the master tree. Only way to find out is to check the BOSSA project repository / bug reports and documentation.</p>
1251
|sensors|
A waterproof Chlorine Sensor
2014-04-22T16:44:36.173
<p>Does anyone know where I can find a Chlorine Sensor to use with the Arduino? It would need to be water proof. I've googled, but I couldn't find anything.</p> <p><strong>EDIT</strong> Requirements: relatively inexpensive (under $100us), works with Arduino, waterproof and used to detect chlorine in water.</p>
<p>Maybe measure conductivity instead? I think, in freshwater pools, one of the active parts of working chlorine is an OCL ion - which I guess is conductive.</p>
1260
|progmem|memory-usage|
Can I write to Flash Memory using PROGMEM?
2014-04-23T07:48:16.900
<p>On the documentation of Arduino, I quote:</p> <blockquote> <p><a href="http://playground.arduino.cc/Learning/Memory">http://playground.arduino.cc/Learning/Memory</a> Note: Flash (PROGMEM) memory can only be populated at program burn time. You can’t change > the values in the flash after the program has started running.</p> </blockquote> <p>And on the PROGMEM description:</p> <blockquote> <p><a href="http://arduino.cc/en/Reference/PROGMEM">http://arduino.cc/en/Reference/PROGMEM</a> Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board.</p> <p>The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.</p> </blockquote> <p>So can we or can't we? Or it's not the same thing?</p>
<p>The short answer is no: PROGMEM data is read-only.</p> <p><strong>Flash memory limitations</strong><br> The first thing to understand is that Flash memory (where program space lives) is designed for long-term fixed storage. Reading from it is very fast and precise. However, generally speaking, you can't modify it on a byte-by-byte basis (e.g. changing a specific variable). You usually have to erase and re-write it in large blocks. That makes it completely impractical for run-time manipulation, because you'd have to store a lot of redundant information somewhere else while you do the erase and write cycle.</p> <p><strong>What PROGMEM actually does</strong><br> Any literal data specified in your code (such as strings and numbers) always reside in program space at first (i.e. in Flash). However, when your sketch actually wants to use that data at runtime, it normally has to allocate some space for it in SRAM and copy it over. That means you end up with two copies: the fixed original in Flash, and the temporary copy in SRAM.</p> <p>When you use the PROGMEM modifier, you're telling it not to make that second copy in SRAM. Instead, your sketch will simply access the original in Flash. That's very useful if you only ever have to <em>read</em> the data, as it avoids the allocation and copy operations.</p> <p>However, copying it to SRAM is essential if you want to modify the data. Aside from the Flash limitations I mentioned above, it's also a question of code safety.</p> <p>If you're able to modify the <strong>data</strong> stored in program space, then it follows logically that you could also modify the <strong>code</strong> stored in program space. That would mean that a simple mistake (or in theory a malicious attack) could result in your sketch being partially or fully rewritten at run-time. This could have very unpredictable results, ranging from simply ceasing to work, through to damaging/destroying any connected equipment.</p> <p><strong>More information</strong><br> You can learn more about the low-level PROGMEM stuff from here:</p> <ul> <li><a href="http://www.fourwalledcubicle.com/AVRArticles.php">http://www.fourwalledcubicle.com/AVRArticles.php</a></li> </ul> <p>An older version of the same PROGMEM tutorial is available here:</p> <ul> <li><a href="http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=243018">http://www.avrfreaks.net/index.php?name=PNphpBB2&amp;file=viewtopic&amp;p=243018</a></li> </ul>
1261
|arduino-uno|arduino-leonardo|spi|
Arduino Uno and Leonardo SPI clock can't be measured
2014-04-23T09:06:56.640
<p>I want to measure the SPI clock (pin 13) using the Arduino example code for the SPI library (very simple example). Basically independent from the <code>loop</code> function, the clock should be fired continuously.</p> <p>I deployed the Arduino SPI example code on the board and measured pin 13 on an oscilloscope, but nothing was found, always zero volt.</p>
<p>Please note the SPI clock will only be active while it is shifting data. So simply put the spi.transfer in a hard loop</p> <pre><code>#include &lt;SPI.h&gt; void setup() { SPI.begin(); while (1) { SPI.transfer(0x00); } } </code></pre>
1263
|arduino-uno|pins|
Interference at digital input (UNO)
2014-04-23T10:04:37.873
<p>I was trying out a basic button tutorial on my new Arduino UNO. But for some reason, the Arduino was detecting the button as on (pressed) even when it was off (unpressed).</p> <p>After some experimentation, I found that the digital pins were flickering between <code>HIGH</code> and <code>LOW</code>, even if there was just a loose wire plugged in with nothing at the other end. And the state of the button, etc. wasn't making any difference. I tried this with pins 5,6 and 7, and it's happening with all of them, even when the neighbouring pins are connected to the ground. </p> <p><strong>Is this behaviour normal or is there something wrong with my input pins?</strong></p> <p><em>Since I'm new to Arduino, there might also be something wrong with my testing code. Here's what I used...</em></p> <pre><code>const unsigned int LED_PIN = 12; const unsigned int BUTTON_PIN = 7; const unsigned int INDICATOR_PIN = 13; void setup() { pinMode(LED_PIN, OUTPUT); pinMode(LED_PIN, OUTPUT); pinMode(BUTTON_PIN, INPUT); digitalWrite(LED_PIN, LOW); } void loop() { const int BUTTON_STATE = digitalRead(BUTTON_PIN); if (BUTTON_STATE == HIGH) { digitalWrite(LED_PIN, HIGH); digitalWrite(INDICATOR_PIN, LOW); } else if (BUTTON_STATE == LOW) { digitalWrite(LED_PIN, LOW); digitalWrite(INDICATOR_PIN, HIGH); } } </code></pre> <p><em>This code makes the lights always in opposite states: when one is on, the other is off. When I ran the code, both lights seemed on, which meant they were probably flickering, which meant that there was some interference in the input pin.</em></p>
<p>It sounds like you're seeing entirely normal behaviour. If you leave a digital input unconnected (or connected to an open button) then it's 'floating'. That means it can pick up interference from all sorts of things, and may appear to drift between high and low.</p> <p>The usual way to resolve this problem is using a pull-up or pull-down resistor. This is usually a high-ohm resistor (e.g. 10,000 Ohm or more) which will gently pull the pin HIGH or LOW in the absence of any other signal. When another signal comes in (e.g. from a button being pushed), it should have a much stronger effect than the resistor, so that is what the input will see.</p> <p>Your Uno has built-in pull-up resistors which you can use for this, although it will require a couple of changes. In your <code>setup()</code> function, you can enable the pull-up on your input pin like this:</p> <pre><code>pinMode(BUTTON_PIN, INPUT_PULLUP); </code></pre> <p>That will cause the input to appear HIGH when the button is <strong>not</strong> pushed. That means you'll need to wire the other end of your button to ground (negative) instead of the voltage supply (positive). If you've set it up correctly, the input should appear LOW when the button is pushed.</p>
1265
|motor|
Control/count rotations of a DC motor
2014-04-23T14:04:52.393
<p>Using an Arduino and an L293D IC, can I control the number of rotations a DC motor makes? Or can I only control the direction and speed of the motor?</p> <p>I purchased a two-wheeled robot platform to learn Arduino programming and electronics. The platform is here: <a href="http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html">http://www.robotshop.com/en/dfrobot-2wd-mobile-platform-arduino.html</a></p> <p>Each wheel is controlled by a DC motor. I followed Adafruit's tutorial (<a href="https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing">https://learn.adafruit.com/adafruit-arduino-lesson-15-dc-motor-reversing</a>) to control the motors with the help of an L293D IC.</p> <p>Now I realize that I can't directly control the rotations of the motor. I can control the direction, voltage, and time of the rotation. For example: turn forward at 50% voltage for 500 milliseconds. </p> <p>But that's difficult to translate into actual rotations. The speed of the motor varies according to voltage (like if I switch from 2AA batteries to 4AA's) and weight (adding sensors slows the motors down). Every time I change voltage or weight, I have to guess how much voltage/time causes a single rotation.</p> <p>I think I should just buy stepper motors. Before I do that, I'll ask the community: Is there a way to control DC motors by rotations rather than time?</p>
<p>As you've discovered, there are a lot of variables involved, so you need <em>some</em> sort of feedback. A popular way to do this is with an encoder, but depending on your needs, other kinds of sensors can make do. For example, if your problem is keeping the robot going in a straight line, an electronic compass can help. For a line following robot, the line sensors are usually enough. Range sensors can track your distance. You get the idea.</p>
1267
|arduino-uno|
How to control Keyboard inputs using arduino(serial monitor) and python keyboard libraries?
2014-04-23T17:53:55.487
<p>I am able to control my monitor and most other applications by giving serial input to python through arduino. Arduino code:</p> <pre><code>void setup() { pinMode(2, INPUT); pinMode(3, INPUT); pinMode(4, INPUT); pinMode(5, INPUT); pinMode(6, INPUT); pinMode(7, INPUT); Serial.begin(9600); } void loop() { if(digitalRead(2) == HIGH) { delay(5); } else { Serial.println("up"); } if(digitalRead(3) == HIGH) { delay(5); } else { Serial.println("down"); } if(digitalRead(4) == HIGH) { delay(5); } else { Serial.println("left"); } if(digitalRead(5) == HIGH) { delay(5); } else { Serial.println("right"); } if(digitalRead(6)== HIGH) { delay(5); } else { Serial.println("space");//orange } if(digitalRead(7)==HIGH) { delay(5); } else { Serial.println("nitro");//brown } } </code></pre> <p>Python code:</p> <pre><code>import serial from pymouse import PyMouse from pykeyboard import PyKeyboard k = PyKeyboard() ser = serial.Serial('COM7', 9600) #sp.write("AT\r\n".encode('ascii')) while True: p=ser.readline() print p if ('up' in p): k = PyKeyboard() k.tap_key(k.up_key) if ('down' in p): k = PyKeyboard() k.tap_key(k.down_key) if ('right' in p): k = PyKeyboard() k.tap_key(k.right_key) if ('left' in p): k = PyKeyboard() k.tap_key(k.left_key) if ('space' in p): k = PyKeyboard() k.tap_key(k.space_key) if ('nitro' in p): k = PyKeyboard() k.tap_key(k.enter_key) </code></pre> <p>My problem is that..I am not able to play games such as NFS and other similar games using these controls.. What should i do??</p>
<p>I'm later, but, I think you should redesign your python and arduino code, to make messages like &quot;start up&quot;, &quot;end up&quot;, and if message is &quot;start *&quot;, hold that key, if &quot;end *&quot;, release that key. This should work as intended. I will pin python and arduino code later here. (Also sorry for my english, i'm russian)</p>
1272
|c++|data-type|
How can I convert Arduino String to C string type?
2014-04-24T07:26:04.390
<p>I got a <code>String</code> which as I understand is an Arduino object, and got some C++ code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; #include &lt;string.h&gt; LiquidCrystal_I2C lcd(0x20,16,2); boolean borrar = false; String IP; void setup() { lcd.init(); lcd.backlight(); pinMode(13,OUTPUT); Serial.begin(9600); Serial1.begin(9600); } void loop() { while (Serial1.available()) { char caracter = Serial1.read(); //Comprobamos el caracter switch(caracter) { default: if (borrar) { IP = ""; lcd.clear(); } lcd.print(caracter); delay(125); borrar = false; IP.concat(caracter); break; case '\r': case 0x0F: case 0x0A: String res = ""; borrar = true; int num= atoi(IP.c_str()); if (num &lt; 127) res="Clase A"; if (num == 127) res="Direccion reservada"; if (num &gt; 127 &amp;&amp; num &lt; 192) res="Clase B "; if (num &gt;= 192 &amp;&amp; num &lt; 224) res="Clase C "; if (num &gt;= 224 &amp;&amp; num &lt; 240) res="Clase D "; if (num &gt;= 240 &amp;&amp; num &lt; 255) res="Clase E "; break; } //fin switch }//serial disponible }//fin programa </code></pre> <p>However, this won't compile because of this line:</p> <pre><code>int num= atoi(IP.c_str()) </code></pre> <p>As IP is a <strong><code>String</code></strong> and such method works for <strong><code>string</code></strong>. How can I make it compatible (convert it)?</p>
<p>Your code could be improved by removing the use of <code>IP</code> string altogether, and directly calculating its numeric value while characters come in through <code>Serial1</code>:</p> <pre><code>... boolean borrar = false; int IP = 0; ... void loop() { while (Serial1.available()) { char caracter = Serial1.read(); //Comprobamos el caracter switch(caracter) { // NOTE it is better to replace default by the list of all digits... case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': if (borrar) { IP = 0; lcd.clear(); } lcd.print(caracter); delay(125); borrar = false; IP *= 10; IP += (int) (caracter - '0'); break; case '\r': case 0x0F: case 0x0A: String res = ""; borrar = true; int num= IP; if (num &lt; 127) res="Clase A"; if (num == 127) res="Direccion reservada"; if (num &gt; 127 &amp;&amp; num &lt; 192) res="Clase B "; if (num &gt;= 192 &amp;&amp; num &lt; 224) res="Clase C "; if (num &gt;= 224 &amp;&amp; num &lt; 240) res="Clase D "; if (num &gt;= 240 &amp;&amp; num &lt; 255) res="Clase E "; break; } //fin switch }//serial disponible }//fin programa </code></pre> <p>This way would bring you 2 advantages:</p> <ol> <li>a bit faster than working with <code>String</code></li> <li>no dynamic memory allocation/deallocation (<code>String</code> does a lot of these) which might lead your program to <strong><a href="https://arduino.stackexchange.com/questions/763/im-using-too-much-ram-how-can-this-be-measured/787#787">heap fragmentation</a></strong> and eventually crash.</li> </ol> <p>Note that I have not further refactored your code as I guessed it was just a snippet, not the complete code for your program. Otherwise, I would have performed further refinement like:</p> <ul> <li>remove <code>num</code> variable since it is the same as <code>IP</code> now</li> <li>replace <code>res</code> from <code>String</code> to <code>const char*</code> (to further reduce heap fragmentation due to <code>String</code> usage)</li> </ul>
1278
|arduino-uno|serial|pins|interrupt|softwareserial|
Simultanous read and read/write on two serial connections
2014-04-24T16:38:46.137
<p>At the moment I'm using two softserials to connect to a GPS and an GSM module. </p> <p>It seems not possible to have two open software-serials. So I was looking for an solution</p> <p>After the initial-setup, the GPS module is only needed to be read from; while the GSM module needs to be bidirectional. So:</p> <pre><code>GPS &gt; listen only GSM &gt; listen and write </code></pre> <p>Now I came across the <a href="https://github.com/adafruit/Adafruit-GPS-Library" rel="noreferrer">GPS library from Adafruit</a>, which uses an interrupt to receive data. Is this <em>instead</em> of a software serial. Or do I again run into the limitation?</p> <p>An other solution might be to use the D0 and D1 to attach eg the GPS module. But than I won't be able to see the debug messages in my serial monitor. Is that correct?</p> <p>Sorry in advance for these n00b questions. But I'm frustrated the things dont work as I want :)</p> <p><strong>edit</strong> </p> <ul> <li><a href="http://www.adafruit.com/products/746" rel="noreferrer">This is the adafruit GPS board</a>.</li> <li>And the board with whom it is connected: <a href="http://imall.iteadstudio.com/im120411004.html" rel="noreferrer">Gboard</a></li> <li>The Sim900 is connected to D2/D3 and the GPS is connected to A2/A3.</li> <li>D0/D1 are connected to a FTDI breakout board, which is plugged into my USB.</li> </ul>
<p>I've done exactly this. The secret sauce for me was the <a href="http://arduino.cc/en/Reference/SoftwareSerialListen" rel="nofollow">SoftwareSerial.listen()</a>.</p> <p>Before running your GSM commands you have to make sure the GSM module's SoftwareSerial port is "listening". Then when you're done you have to <code>listen()</code> again to the GPS.</p> <p>This is, of course, not terribly efficient, while the GSM port is listening any GPS data will be lost, but at least in my case the impact was negligible.</p> <p>My code is here: <a href="https://github.com/lectroidmarc/gsm-tracker" rel="nofollow">https://github.com/lectroidmarc/gsm-tracker</a></p> <p>As an aside, I have also considered plugging the GPS into the UART and running debug messages to a SoftwareSerial serial port, to be monitored during testing with another Arduino. I'm just not sure the benefit would be there.</p>
1281
|uploading|bootloader|
SeeedDuino/Grove and the story of not being able to upload programs
2014-04-24T19:37:30.180
<p>I am new to the arduino world and wanted to start playing with the micro controllers, I am a .NET developer by trade so not completely new to this kind of world.</p> <p>I purchased a seeedduino v3 and a Grove started kit (No soldering skills here) and can't even get the basics to work.</p> <p>I am setting up a simple button to light up the LED program. I have had it run once or twice but it seems really hit or miss on whether or not the Arduino IDE actually gets the program onto the seeedduino.</p> <p><strong><em>Arduino IDE (1.5.6-r2) set-up:</em></strong> Followed setup instructions found here: <a href="http://www.seeedstudio.com/wiki/Seeeduino_v3.0#How_do_I_configure_the_Arduino_IDE.3F" rel="nofollow">SeeedDuino v3</a></p> <ul> <li>Board: Arduino Duemilanove or Diecimila </li> <li>Processor: ATmega328</li> <li>Port: COM4 [this is what popped up once device was plugged in]</li> <li>Button is installed on D3</li> <li>LED is installed on D7</li> </ul> <p><strong><em>Program:</em></strong></p> <pre><code>int button = 3; int LED = 7; void setup() { pinMode(button, INPUT); //define button on INPUT devices pinMode(LED, OUTPUT); //define LED on OUTPUT device } void loop() { int buttonState = digitalRead(button); //read the status of hte button if(buttonState == HIGH) //also used (buttonState == 1) { digitalWrite(LED, HIGH); //also used digitalWrite(LED, 1) } else { digitalWrite(LED, LOW); //also used digitalWrite(LED, 0) } } </code></pre> <p>Upload Verbose Message:</p> <pre><code>avrdude: verifying ... avrdude: 1070 bytes of flash verified avrdude: Send: Q [51] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude done. Thank you. </code></pre> <p>I have only had the LED from this program turn on twice, then reloading it ruins it.</p> <p><strong><em>SIDE NOTE</em></strong></p> <p>If I try and run Burn BootLoader I get this message-</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:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf" Using Port : usb Using Programmer : stk500v2 avrdude: usbdev_open(): did not find any USB device "usb" </code></pre>
<p>OK mystery solved!</p> <p>I ended up getting <a href="http://www.visualmicro.com/" rel="nofollow">Visual Micro Debugger</a> plug-in for my Visual Studio 2013 since I am native .NET programmer. I could see that the code was indeed loaded onto the board and when I pressed the button it was indeed getting to the line of code for setting the digital LED to HIGH.</p> <p>It was a very unfortunate case of trying different components and learning I actually had 3 dead LEDs and one bad cable. After getting functioning ones it's all good. :) unlucky me just had 4 bad parts in my kit.</p> <p>Output from Visual Studio Debugging:</p> <pre><code>Legend: line 12 = button state check line 16 = button pressed turn on LED line 20 = button not pressed turn off LED =================OUTPUT==================== 14:01:04.372 SeeedDuinoPlayground.ino, line 12 loop() 14:01:04.372 SeeedDuinoPlayground.ino, line 16 loop() 14:01:04.481 SeeedDuinoPlayground.ino, line 10 14:01:04.481 SeeedDuinoPlayground.ino, line 12 loop() 14:01:04.592 SeeedDuinoPlayground.ino, line 16 loop() 14:01:04.592 SeeedDuinoPlayground.ino, line 10 14:01:04.696 SeeedDuinoPlayground.ino, line 12 loop() 14:01:04.697 SeeedDuinoPlayground.ino, line 20 loop() 14:01:04.804 SeeedDuinoPlayground.ino, line 10 14:01:04.804 SeeedDuinoPlayground.ino, line 12 loop() 14:01:04.912 SeeedDuinoPlayground.ino, line 20 loop() </code></pre>
1285
|arduino-uno|serial|uart|
Matching Baud Rates
2014-04-25T01:37:05.237
<p>So I am working on speeding up a nixie tube speedometer, in this question: , but this brought up another question. Would having matching baud rates for multiple external devices speed up processes. </p> <p>In the case of the other question the OBD-II device is running at 38400 where the Nixie Tubes are running at 9600. Since I'm taking the info from the OBD-II connector and doing a little math and sending it to the Nixie Tubes, would it be beneficial to have the same baud rate for both devices?</p> <p>Now... before you down-vote this question for making some sort of "duplicate" this also answers a question about having a "master" serial hub and having communication between different "slave" serial devices.</p>
<p>If you are using different serial ports for each device (eg: using software serial for at least one of them on a Uno, or using separate hardware serial on a Mega2560), then it really doesn't matter whether they use the same baud rate or not. </p> <p>If you are somehow multiplexing the same serial port (eg: input only from one device, output only to the other; or some external multiplexing hardware) then there might be a slight gain in not needing to change the baud rate when switching between devices, but probably not noticable. </p> <p>If either or both devices have some option to communicate faster, that might speed up your system - independent of whether they use the SAME rate.</p>
1288
|sensors|wifi|
Detect and stream if a chair is occupied
2014-04-25T08:05:46.710
<p>I am planning to build a device able to detect and tell a server via Wi-Fi if a chair is occupied. How would you do it? And how cheap do you think the device could be?</p>
<p>conductive foam as sensor. it chg resistance when compressed.</p> <p>or use image from camera to determine if seat is occupied. only one source for all data.</p>
1293
|pins|arduino-mega|motor|
How to test the sleep / enable function of Stepper Driver?
2014-04-25T15:43:04.290
<p>I am currently using an Arduino Mega 2560 to run this stepper motor driver (Big Easy Driver, ROB-11876 from sparkfun) <a href="https://www.sparkfun.com/products/11876" rel="nofollow">https://www.sparkfun.com/products/11876</a>. </p> <p>I am trying to use the sleep or enable function on this chip to decrease the power consumption when I am not using the motor. I have all the rest of the driver working properly (steps, direction etc.) but when I hook up a wire to either the sleep or enable section and send a respective high or low it doesn't appear to do anything. (Chip works as normal, power consumption stays the same). </p> <p>I have tested to see that the Arduino is outputting correctly and it seems to be. But other than this I'm kinda at a loss on what might be wrong.</p> <p>Does anyone have any suggestions on why this might be or other things to test to try to narrow down the problem?</p> <hr> <p>Found my answer from Sparkfun - see below</p>
<p>Just for future reference if anyone needs it I got the following from SparkFun:</p> <p>On the Big Easy Driver Board, the Step, Dir, Sleep, Reset, and the Microstep pins are all >pulled high with 20kΩ resistors, while Enable is pulled low with the same. So sleep is >disabled (until explicitly enabled) and the stepper is enabled (until explicitly disabled).</p> <p>For much of the use of this board, there is no real need to adjust these settings, but If you >want to achieve a low-power state you would pull the sleep pin low. This should disable much >of the internal circuitry on the IC. In order to reduce power, Enable should be pulled high >to disable the output FETs. To test that the sleep function is working on the chip you can just jump it to low (ground). For me it turned out to be an error with the Arduino code rather than the chip. Here is also a good reference about pull-down / pull-up resistors. <a href="http://www.bit-101.com/blog/?p=3813" rel="nofollow">http://www.bit-101.com/blog/?p=3813</a></p>
1298
|shields|
How to use components that don't have a shield?
2014-04-25T21:40:44.983
<p>I recently started messing around with an Arduino and I have made a few "gadgets" using shields. I then wondered how I would go about using things I can't find shields for.</p> <p>One specific thing I want to do is to be able to use the larger e-paper displays from Pervasive Displays (7'' and 10'') but a brief consultation with Google found no Arduino kits or shields. I then looked through the documentation of the timing controller for the 7'' display and found the information required to be able to use it (initiation, sending data to be drawn, opcodes, etc.). I then decided to check the Github repo for the examples for the 2'' displays and they seem to just do what the documentation says to do.</p> <p>Is my observation naive here? Is it really as straightforward as following the documentation? No magic sauce?</p> <p>Note: I don't have a clue how complex using the 7'' display actually is, I just used it as an example because I had just looked it up...</p>
<p>Your observation is correct. Everything breaks down to some number of physical connections and some protocol for communicating with the device. Shields and libraries associated with them do most of the work for you, but not everything comes in a shield.</p> <p>There are some common protocols for interfacing with devices, including <a href="http://en.wikipedia.org/wiki/Serial_Peripheral_Interface_Bus" rel="nofollow">SPI</a> and <a href="http://en.wikipedia.org/wiki/I%C2%B2C" rel="nofollow">I2C</a>. From a quick peek at the <a href="http://www.pervasivedisplays.com/products/2inch" rel="nofollow">driver interface sheet</a>, it looks like they're using SPI. Well, your <a href="http://arduino.cc/en/Reference/SPI" rel="nofollow">Arduino already supports that</a> so you can hit the ground running with this display. You just need to know what commands to send to it, which you can find from the display's datasheet.</p> <p><strong>Note:</strong> It looks like the 2" screen requires 3.3V while the 7" one supports up to 7V.</p>
1304
|programming|arduino-ide|compile|attiny|rf|
Manchester Library Won't Compile for Attiny85
2014-04-26T21:38:54.610
<p>I am creating a wireless sensor using an Attiny85. I want to send the data to an arduino uno, so I purchased the 315mhz rf link kit from spark fun. Since the Attiny85 does not have a TX I decided to use the Manchester library however it won't compile on the Attiny85.</p> <p>I followed the steps from this blog : <a href="http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192">http://mchr3k-arduino.blogspot.mx/2012/01/wireless-sensor-node-part-2.html?showComment=1338749638806#c853067277980266192</a></p> <p>Here is the code I am using:</p> <pre><code> #include &lt;WProgram.h&gt; //otherwise it says it can't find Arduino.h #include &lt;Manchester.h&gt; //include the library to comunicate #define TxPin 2 //the pin that is used to send data int sensorPin = 4; int ledPin = 3; int count = 50; void setup(){ pinMode (ledPin, OUTPUT); man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84 man.setupTransmit(TxPin, MAN_1200); //set transimt pin } void loop(){ if (count == 50){ digitalWrite (ledPin, HIGH); count = 0; } int data = analogRead(sensorPin); man.transmit(data); //transmits and reads the data delay (100); count ++; } </code></pre> <p>Here is the error message:</p> <pre><code>/Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp: In function 'void MANRX_SetupReceive(uint8_t)': /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'TCCR2A' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:366: error: 'WGM21' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'TCCR2B' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:368: error: 'CS21' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:369: error: 'OCR2A' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'TIMSK2' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:379: error: 'OCIE2A' was not declared in this scope /Users/joelsimonoff/Documents/Arduino/libraries/MANCHESTER/Manchester.cpp:380: error: 'TCNT2' was not declared in this scope </code></pre>
<p>Got the same problem using this lib with a 8 MHz Trinket, but managed to solve it by adding <code>#define __AVR_ATtinyX5__</code> to the file hardware/attiny/variants/tiny8/pins_arduino.h. I'm using the Adafruit support package for ATtiny. Perhaps a bit of a hack, but I can still build for the UNO, by selecting board in Arduino IDE 1.0.5.</p>
1309
|robotics|i2c|
Connect Arduino with fischertechnik TX Controller
2014-04-27T10:39:30.683
<p>Is it possible to cinnect the Arduino with a fischertechnik TX Controller? Maybe with I²C, but i want to use I²C for something else on the arduino. So are there multiple I²C Ports on the Arduino (I haven't got one yet)?</p>
<p>As described in the <a href="http://arduino.cc/en/Reference/Wire" rel="nofollow">Wire library</a> that brings supports I²C support to Arduino, except for the <strong>DUE</strong> that has 2 pairs of pins for 2 I²C buses, <strong>other Arduino boards support one I²C connection</strong>.</p> <p>However, this is when you want to use hardware facilities of ATMEL chips that these limitations apply; there is a <a href="http://playground.arduino.cc/Main/SoftwareI2CLibrary" rel="nofollow">software I²C library</a> exists that allows using other pins for I²C. One major drawback, though, is that it is very slow; not sure if this is a problem in your situation.</p> <p>One important thing though: the principle of I²C is to be able to plug several slave devices (more than 100) to one master device. In general, Arduino is the master device, but the Wire library can be used as master or slave. Wouldn't that fit your requirements?</p> <p>In this situation, you could just use the same I²C bus for everything, including connection to Fischertechnik TX controller.</p>
1312
|arduino-uno|avrdude|ide|avr-gcc|
Understanding the compilation/linking/upload process (so I don't have to use the IDE)
2014-04-27T17:35:01.970
<p>I have started to play with and arduino UNO quite recently (without any prior experience with micro-controllers). I would like to use emacs instead of the IDE, and I'd also like to know what the IDE does under the hood, in order to be able to write my own makefile. The tutorials I've found are either outdated, or are presented as a series of steps without any explanation. I'd appreciate it if someone could explain to me how the whole compliation/linking/upload process works using gcc-avr and avr-dude, and how it is used by the IDE.</p>
<p>Here is a high-level overview of Arduino's compilation process, for folks like me who found this post while hunting for one:</p> <p><strong>The compilation process</strong></p> <p>The arduino code is actually just plain old c without all the header part (the includes and all). when you press the 'compile' button, the IDE saves the current file as arduino.c in the 'lib/build' directory then it calls a makefile contained in the 'lib' directory.</p> <p>This makefile copies arduino.c as prog.c into 'lib/tmp' adding 'wiringlite.inc' as the beginning of it. this operation makes the arduino/wiring code into a proper c file (called prog.c).</p> <p>After this, it copies all the files in the 'core' directory into 'lib/tmp'. these files are the implementation of the various arduino/wiring commands adding to these files adds commands to the language</p> <p>The core files are supported by pascal stang's procyon avr-lib that is contained in the 'lib/avrlib' directory</p> <p>At this point the code contained in lib/tmp is ready to be compiled with the c compiler contained in 'tools'. If the make operation is succesfull then you'll have prog.hex ready to be downloaded into the processor.</p> <p><a href="https://www.arduino.cc/en/Main/Documentation" rel="nofollow noreferrer">https://www.arduino.cc/en/Main/Documentation</a></p>
1314
|arduino-uno|shields|motor|arduino-motor-shield|
How can I connect the Tamiya double gearbox to Arduino Uno?
2014-04-27T19:12:11.227
<p>I'm working on building my first robot. this is my first foray into DIY electronics. I already have an Arduino Uno, and I have ordered the <a href="http://www.pololu.com/product/114" rel="nofollow noreferrer">Tamiya double gearbox</a> here. My goal is to control the gearbox to move the robot, but from what I've already read, I need to have something between the Ardiuno and the motors. It seems like people have trouble doing that because the included motors are low voltage, so the Arduino motor shield won't easily work. </p> <p>I'm looking for a clear solution to making this thing run, in the simplest way possible. One thing I'm considering is replacing the motors in the gearbox <a href="https://rads.stackoverflow.com/amzn/click/B00JR6IY4M" rel="nofollow noreferrer">with these motors</a>. If I do that, am I right in thinking I could run them from the Arduino motor shield? </p> <p>If there is a simpler (or cheaper!) way of making it work than being stuck on the Arduino Motor shield, I'm game for that. I've just gravitated to that solution because it seems simpler as an electronics noob. (I haven't bought that shield yet.) But I'm really open to other solutions, so if you can, I'd appreciate the advice! </p>
<p>The FA130 type electric motors in the Tamiya Double Gearbox Kit (No. 70168) are 1.5v-3v DC motors with current ratings of 0.20A (no load), 0.66A (@ max. efficiency) and 2.2A (stall), see <a href="https://www.jameco.com/z/FA-130RA-2270-Mabuchi-Motor-Company-1-5-3V-DC-Motor-6990-RPM_2192755.html" rel="nofollow noreferrer">1.5-3V DC Motor 6990 RPM</a>. They are not high current motors.</p>
1318
|voltage-level|
Level detection of 3.3V from 5V arduino
2014-04-28T02:18:55.963
<p>A quick question about microcontroller digital level on I/O pins. I have a photo interrupter which is powered at 3.3V which is interfaced to Arduino UNO running at 5V.</p> <p>For microcontroller to detect high or low level is determined by signal higher than 5V*(2/3) = 3.33V is high and signal lower than 5V*(1/3) is low. What I don't understand is that arduino is able to detect the level change from the photo interrupter. Doesn't the supply on pins have to be greater than (2/3) or Vcc in order for it to detect logic high? The circuit works and I am able to count pulses from the interrupter but I want to know why that works considering the photo interrupt only gets about 3.23V.</p> <p>Please clarify</p>
<p>The designed threshold of the '328 logic is 45% of Vcc for all supply voltages, except the tolerance reduces from +/-25% of Vcc {&lt;3V} to +/-15% of Vcc{>3} This tolerance is due to temperature and process variation.</p> <p>Keep in mind that the smaller the difference between the "actual" threshold and your input is your immunity to noise and it will work if there is low noise. Thus 45+15% = 60%* 5V=3V is guaranteed. What is not guaranteed, is the accuracy of your 5V regulator which if say 10% high will increase the threshold 10% above 3V or 3.3V. So then 3.1 would not be guaranteed. So ensure accuracy of 5 V is below 5.04 minus your noise immunity requirements.</p>
1321
|arduino-uno|continuous-servo|
Servo won't stop rotating
2014-04-28T05:27:02.187
<p>I have an Arduino Uno R3 board and after some time not in use it seems to have corrupted. My code is below, basically I want to rotate a servo 90 degrees every 12 hours but as soon as I plug it in the servo starts rotating non-stop. Have tried multiple delay steps and shortening and lengthening the write but the same effect happens.</p> <pre><code>#include &lt;Servo.h&gt; Servo myservo; void setup { myservo.attach(10); } void loop() { myservo.write(90); delay(3600000); } </code></pre>
<p>That was useful. I was getting the same rotation thing when I had servos at 90. What I did to stop that was use the detach command. Using the Particle Photon with a continuous servo attached.</p> <pre><code>bool state = LOW; Servo servo1; Servo servo2;// create servo object to control a servo // a maximum of eight servo objects can be created int pos = 90; // variable to store the servo position void setup() { servo1.attach(D0); servo2.attach(D1); Spark.function("test", testFunction); servo1.attach(10); servo1.write(90); servo2.attach(10); servo2.write(90); } void loop() { servo2.detach(), servo1.detach(); delay (25); servo2.attach(D0), servo1.attach(D1); delay (25); servo1.write(0), servo2.write(180); delay (1000); servo2.write(180), servo1.write(0); delay (1000); //I did this to make the servo not move when it is at 90. servo2.detach(), servo1.detach(); delay (25); servo1.write(90), servo2.write(90); delay (1000); //end //You must attach the servos again to make them move again. servo2.attach(D0), servo1.attach(D1); delay (25); //end servo1.write(180), servo2.write(0); delay (1000); servo2.write(180), servo1.write(100); delay (1000); } int testFunction(String args) { return 200; // This is checked in the web app controller for validation } </code></pre>
1329
|rfid|
How do I use RFID-RC522 with an Arduino?
2014-04-28T23:41:49.340
<p>I am working on a project for my local Makerspace, we have limited budget so I was hoping to use the RFID-RC522 el'cheap'o RFID/NFC readers on eBay, I received a couple of SPI based boards, they work, however the code examples for them are limited.</p> <p>I have found several different libraries and settled on this one: <a href="https://github.com/ljos/MFRC522">https://github.com/ljos/MFRC522</a></p> <p>The trouble is that all the code available online seem to spawn from some Chinese guys Python code that people have translated, and hacked into an Arduino library.</p> <p>The code works, but Mifare cards are meant to have 4, 7 or 10 byte UIDs and the example/library is returning a 5 byte serial number.</p> <p>There is no documentation and the <a href="http://www.nxp.com/documents/data_sheet/MFRC500.pdf">NXP datasheet</a> is incomprehensible... Additionally it seems to work with most cards, but it doesn't work with Mastercard PayWave cards which conform to the ISO 14443 standard. The more expensive RDM880 reader which is based on the MFRC500 works fine and has a nice library but the cost makes the implementation impossible.</p> <p>So, can someone help me to get this NXP MFRC522 based unit reading the UID from all ISO 14443 cards.</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;MFRC522.h&gt; #define RFID_SS 10 #define RFID_RST 5 MFRC522 rfid( RFID_SS, RFID_RST ); void setup() { SPI.begin(); Serial.begin(115200); rfid.begin(); } void loop() { byte data[MAX_LEN]; byte uid[5]; if ( rfid.requestTag( MF1_REQIDL, data ) == MI_OK ) { if ( rfid.antiCollision( data ) == MI_OK ) { memcpy( uid, data, 5 ); for ( int i = 0; i &lt; 5; i++ ) { Serial.print( uid[i], HEX ); Serial.print( ' ' ); } Serial.println(); } } } </code></pre>
<p>The fifth byte from the RC522 is just a checksum.</p> <p>For instance, a possible return value (taken from <a href="https://github.com/miguelbalboa/rfid/issues/604#issuecomment-1885042556" rel="nofollow noreferrer">https://github.com/miguelbalboa/rfid/issues/604#issuecomment-1885042556</a> ) is:</p> <p>8B 65 66 B9 31</p> <p>and if you do the binary xor of the first four numbers, you get precisely the fifth:</p> <pre><code>In [1]: hex(int(&quot;8B&quot;, 16)^int(&quot;65&quot;, 16)^int(&quot;66&quot;, 16)^int(&quot;B9&quot;, 16))[2:] Out[1]: '31' </code></pre> <p>(Indeed, if you compare the first four bytes from the RC522 with the four bytes from the other reader, they should coincide)</p>
1332
|programming|variables|
Default value of global variables is not set
2014-04-29T12:16:21.570
<p>I am tracking a bug in the <a href="https://github.com/reprappro/Marlin" rel="nofollow">Marlin</a> source code. </p> <p><strong>Background</strong></p> <p>Just for those who is not familiar with Reprap 3D printer and G-code: Marlin is firmware that controls a <a href="https://en.wikipedia.org/wiki/RepRap_Project" rel="nofollow">RepRap</a> 3D printer. It receives G-code from a host computer (or read from SD card). Here the important thing is that if you send the "M114" command, it would report information about axis positions. Here, I extended this command to make it print some internal variable as well.</p> <p><strong>The Problem</strong> </p> <p>In Marlin.ino file there is a line that says:</p> <pre><code>volatile int extrudemultiply=100; //100-&gt;1 200-&gt;2 </code></pre> <p>However my RepRap keeps extruding (and worse, ejecting back) a huge amount of filament. So I added some debug output for <code>M114</code> command to output this value. It turns out this value is not the default value, 100, but something like 12374.</p> <p>I thought somewhere inside the <code>setup()</code> function this value might be changed. So I defined another variable,</p> <pre><code>volatile int orig_extrudemultiply = 100; </code></pre> <p>And then at the first line of <code>setup()</code> function, I added the following line.</p> <pre><code>orig_extrudemultiply = extrudemultiply; </code></pre> <p>Finally, I output this value for the <code>M114</code> command. Still, it is not 100. So it looks like the default value is not effective.</p> <p><strong>The Question</strong></p> <p>Although I have experience in C programming, I am new to Arduino development. How is a global variable being initialized in Arduino? In my case, what is the proper way to initialize this value?</p> <p><strong>Versioning</strong></p> <p>I originally posted the official <a href="https://github.com/ErikZalm/Marlin" rel="nofollow">Marlin</a> link for the reference. However, the version I actually use is <a href="https://github.com/reprappro/Marlin" rel="nofollow">this fork</a> from the RepRap Pro team. I was just following the <a href="http://reprap.org/wiki/Melzi#Melzi_Arduino_Pin_Numbers" rel="nofollow">Melzi</a> entry of the RepRap wiki, because my board is Melzi. I am not sure whether the latest version of Marlin works for my board.</p> <p><strong>Further details</strong></p> <p>As the commenter said, the first thing I thought of was memory corruption. So I wanted to narrow the problem down. Since that value is configurable through <code>M302 SXXX</code> command, I tested this command, and it works without difficulty. This means there is nothing in the <code>loop</code> function or the <a href="https://en.wikipedia.org/wiki/Interrupt_handler" rel="nofollow">ISRs</a> can affect this value when it is running stably. So I consider the problem must be in the <code>setup</code> function or earlier.</p> <p>Further tests shows that setting this value at the end of <code>setup</code> or even at the beginning of <code>setup</code> still works fine. This means the <code>setup</code> function may not be the problematic one. The test in "The Problem" session was the last step, which, in my opinion, means the course of the problem must being run before entering <code>setup</code>.</p> <p><strong>UPDATE</strong></p> <p>Further examination shows that although it looks like it works when I set the default value in the first line of <code>setup()</code>, but that it is just luckily being 100. So once I add more padding variables it stops working until I move the default setting after the following line in <code>setup()</code>:</p> <pre><code>EEPROM_RetrieveSettings(); // Loads data from EEPROM if available </code></pre> <p>However, since I <code>grep</code>ed for <code>extrudemultiply</code> before any test, and I didn't figure out this function, this function should not change this value. I guess there is some data overflow inside this function, so the value was changed expectationally.</p> <p>I got to figure out what is wrong in this function.</p>
<p>The problem of this version of Marlin can be shown in the following piece of code (which is inside <code>EEPROM_RetrieveSettings</code> function):</p> <pre><code> for (short i=0;i&lt;4;i++) { axis_steps_per_unit[i]=tmp1[i]; max_feedrate[i]=tmp2[i]; max_acceleration_units_per_sq_second[i]=tmp3[i]; max_length[i]=tmp4[i]; } </code></pre> <p>Here <code>max_length</code> is an array of 3 elements, not 4 (the X,Y and Z axes have a max length to avoid hitting the edge, but the extrude axis does not have such a limit - you should be able to extrude as many filament as you can supply), so the last statement in the loop overrides other variable(s).</p> <p>The solution is </p> <pre><code> for (short i=0;i&lt;4;i++) { axis_steps_per_unit[i]=tmp1[i]; max_feedrate[i]=tmp2[i]; max_acceleration_units_per_sq_second[i]=tmp3[i]; if(i&lt;3) max_length[i]=tmp4[i]; } </code></pre> <p>Or</p> <pre><code> for (short i=0;i&lt;4;i++) { axis_steps_per_unit[i]=tmp1[i]; max_feedrate[i]=tmp2[i]; max_acceleration_units_per_sq_second[i]=tmp3[i]; if(i &lt; sizeof(tmp4)/sizeof(tmp4[0])) max_length[i]=tmp4[i]; } </code></pre> <p>Greate thanks to the answer writer and commenter. Without your help I couldn't follow the right track. </p>
1338
|arduino-uno|motor|
Understanding the relationship of Pulse and Stepper RPM
2014-04-29T22:18:31.973
<p>This may be a better question for <a href="https://physics.stackexchange.com/">the Physics StackExchange</a> so tell me if I should move the question.</p> <p>I have a pretty simple script that I'm using to control the RPM of my stepper motor:</p> <pre><code>void loop(){ digitalWrite(PIN, HIGH); delayMicroseconds(wait); digitalWrite(PIN, LOW); } </code></pre> <p>as you can see it's just producing a pretty standard pulse, I have my Arduino connected to a driver that manages the motor. The <code>wait</code> variable comes from a second order equation I derived from measuring the RPM with a Tachometer and tweaking the value.</p> <pre><code>// From data RPM = 31729/x + 17.327 thus x = 31729/(RPM-17.527) wait = M/(RPM-C); </code></pre> <p>It works pretty well, I get readings consistently within only 1 - 2 rotations off. But the slope and intercept seem completely arbitrary to me. Is there a chance it has to do with the clock speed of the Arduino? I'm using an Uno and from playing around with the numbers I can't seem to find a relationship. From what I can tell, the driver looks hardwired so I don't think it has much to do with the equation.</p> <p>Any idea what these values, the slope/intercept mean?</p> <p>Equation: <code>RPM=31729/wait + 17.327</code> M:<code>31729</code> and C:<code>17.327</code></p>
<p>one pulse equals one step of stepper and rpm is how many rotation stepper makes in one minute. Try to understand the stepper.h library and Accelstepper library</p>
1341
|arduino-uno|sensors|xbee|android|map|
Is it possible to transmit Longitude and Latitude via RF433MHz?
2014-04-30T08:43:44.493
<p>I want to make a drone project, and to that I will use arduino as the platform. My plane is to use a Play Station controller to control the Drone in the air. In addition to that I want to connect a GPS-module. My question goes, is it possible to transmit the longitude and latitude from the GPS via the RF 433MHz to the receiver? When received the longitude and latitude how can I transmit them further to the Smartphone and display the data on google maps? I suggest it could be possible through the Xbee, but I am not sure. </p> <p>I would like if someone can confirm my idea, if not bring me a better way to do that.</p> <p>In the image below, you can see the diagram of my design.</p> <p><img src="https://i.stack.imgur.com/qorvn.png" alt="Image"></p>
<p>Your design suffers several redundancies that should be fixed. First of all, you have an Xbee (only one, not a pair) <em>and</em> a a 433 MHz transmitter/receiver combo. <strong>Why not just add another Xbee to the drone and remove the RF combo?</strong> That would save a little battery life for the receiver end, and a lot of your time. You'll also get two way communication with error checking. Although an Xbee would increase your project size a <em>little</em>, if you manually wired the Xbee instead of a shield (3.3V), it would save a lot of space.</p> <p>As some people point out, Bluetooth is a viable option that's fairly small and low cost. However, it would suffer shorter ranges and it would need a special configuration on the host side for a BT stack.</p>
1344
|arduino-mega|interrupt|
Multiple definition of '__vector_36' (intterupts)
2014-04-30T13:20:01.850
<p>I'm having some conflicts between the core <code>HardwareSerial.cpp</code> and an external DMX library.</p> <p>For DMX I'm using the <a href="http://www.deskontrol.net/blog/arduino-four-universes-dmx-512-library/" rel="nofollow">Four Universes DMX 512 Library</a>. Using the library standalone, it all works perfectly. But when combining it with other libraries, I'm getting the error:</p> <pre><code>core.a(HardwareSerial.cpp.o): In function '__vector_36': C:\Program Files (x86)\Arduino\hardware\arduino\cores\arduino/HardwareSerial.cpp:147: multiple definition of '__vector_36' Dmx\lib_dmx.cpp.o:C:\Program Files (x86)\Arduino\libraries\Dmx/lib_dmx.cpp:206: first defined here </code></pre> <p>The DMX library uses the UART hardware to generate the DMX signals. It supports four universes on the Arduino Mega since that has four UART hardware parts. Now, I'd like to only use the second hardware part, so the UART1. In the DMX library this is easily adjusted in the .h-file, by commenting out the non-used serial ports.</p> <p>The line from <code>lib_dmx.cpp</code> that is conflicting is this line:</p> <pre><code>#if defined(USE_UART1) ISR (SIG_USART1_RECV) { ArduinoDmx1.Process_ISR_RX(1); } #endif </code></pre> <p>The line from <code>hardwareSerial.cpp</code> that is conflicting is in the ISR here:</p> <pre><code>#if defined(USART1_RX_vect) void serialEvent1() __attribute__((weak)); void serialEvent1() {} #define serialEvent1_implemented ISR(USART1_RX_vect) { if (bit_is_clear(UCSR1A, UPE1)) { unsigned char c = UDR1; store_char(c, &amp;rx_buffer1); } else { unsigned char c = UDR1; }; } #endif </code></pre> <p>I have been having issues with this for a very long time and don't have a solution at hand yet. It's also a but unclear to me how the interrupts on Arduinos are arranged. I've also included the .ino I'm using currently. I'm also using another Ethernet Library than the default, one that includes multicast UDP (found <a href="https://github.com/aallan/Arduino" rel="nofollow">here</a>).</p> <p><strong>lib_dmx.h</strong></p> <pre><code>&gt; /*************************************************************************** &gt; * &gt; * Title : Arduino DMX512 library. 4 input/output universes. &gt; * Version : v 0.3 beta &gt; * Last updated : 07.07.2012 &gt; * Target : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe) &gt; * Author : Toni Merino - merino.toni at gmail.com &gt; * Web : www.deskontrol.net/blog &gt; * &gt; * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de &gt; &gt; ;***************************************************************************/ &gt; #ifndef __INC_DMX_H &gt; #define __INC_DMX_H &gt; &gt; #include &lt;avr/io.h&gt; &gt; #include &lt;stdint.h&gt; &gt; #include &lt;avr/interrupt.h&gt; &gt; #include &lt;util/delay.h&gt; &gt; #if ARDUINO &gt;= 100 #include "Arduino.h" &gt; #else #include "WProgram.h" &gt; #endif &gt; &gt; //#define USE_INTERBYTE_DELAY // rare cases of equipment &gt; non full DMX-512 compliant, need this &gt; &gt; // *** comment UARTs not used *** //#define USE_UART0 &gt; #define USE_UART1 //#define USE_UART2 //#define USE_UART3 &gt; &gt; // New DMX modes *** EXPERIMENTAL *** &gt; #define DMX512 (0) // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512 &gt; #define DMX1024 (1) // DMX-1024 (500 kbaud - 1024 channels) Completely non standard - TESTED ok &gt; #define DMX2048 (2) // DMX-2048 (1000 kbaud - 2048 channels) called by manufacturers DMX1000K, DMX 4x or DMX 1M ??? &gt; &gt; // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512 &gt; #define IBG_512 (10) // interbyte gap [us] &gt; #define DMX_512 ((F_CPU/(250000*8))-1) // 250 kbaud &gt; #define BREAK_512 ( F_CPU/(100000*8)) // 90.9 kbaud &gt; &gt; // DMX-1024 (500 kbaud - 1024 channels) Completely non standard &gt; #define IBG_1024 (5) // interbyte gap [us] &gt; #define DMX_1024 ((F_CPU/(500000*8))-1) // 500 kbaud &gt; #define BREAK_1024 ( F_CPU/(200000*8)) // 181.8 kbaud &gt; &gt; // DMX-2048 (1000 kbaud - 2048 channels) Non standard, but used by &gt; manufacturers as DMX1000K or DMX-4x or DMX 1M ??? &gt; #define IBG_2048 (2) // interbyte gap [us] + nop's to reach 2.5 uS &gt; #define DMX_2048 ((F_CPU/(1000000*8))-1) // 1000 kbaud &gt; #define BREAK_2048 ( F_CPU/(400000*8)) // 363.6 kbaud &gt; &gt; // Inline assembly: do nothing for one clock cycle. &gt; #define nop() __asm__ __volatile__("nop") &gt; &gt; #ifdef __cplusplus extern "C" { &gt; #endif #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) &gt; #if defined(USE_UART0) &gt; void SIG_USART0_RECV (void) __attribute__((__always_inline__)); &gt; void SIG_USART0_TRANS (void) __attribute__((__always_inline__)); &gt; #endif &gt; #if defined(USE_UART1) &gt; void SIG_USART1_RECV (void) __attribute__((__always_inline__)); &gt; void SIG_USART1_TRANS (void) __attribute__((__always_inline__)); &gt; #endif &gt; #if defined(USE_UART2) &gt; void SIG_USART2_RECV (void) __attribute__((__always_inline__)); &gt; void SIG_USART2_TRANS (void) __attribute__((__always_inline__)); &gt; #endif &gt; #if defined(USE_UART3) &gt; void SIG_USART3_RECV (void) __attribute__((__always_inline__)); &gt; void SIG_USART3_TRANS (void) __attribute__((__always_inline__)); &gt; #endif #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) &gt; #if defined(USE_UART0) &gt; void USART_RX_vect (void) __attribute__((__always_inline__)); &gt; void USART_TX_vect (void) __attribute__((__always_inline__)); &gt; #endif #endif &gt; #ifdef __cplusplus }; &gt; #endif &gt; &gt; class CArduinoDmx { #if defined(__AVR_ATmega1280__) || &gt; defined(__AVR_ATmega2560__) &gt; #if defined(USE_UART0) &gt; friend void SIG_USART0_RECV (void); &gt; friend void SIG_USART0_TRANS (void); &gt; #endif &gt; #if defined(USE_UART1) &gt; friend void SIG_USART1_RECV (void); &gt; friend void SIG_USART1_TRANS (void); &gt; #endif &gt; #if defined(USE_UART2) &gt; friend void SIG_USART2_RECV (void); &gt; friend void SIG_USART2_TRANS (void); &gt; #endif &gt; #if defined(USE_UART3) &gt; friend void SIG_USART3_RECV (void); &gt; friend void SIG_USART3_TRANS (void); &gt; #endif #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) &gt; #if defined(USE_UART0) &gt; friend void USART_RX_vect (void); &gt; friend void USART_TX_vect (void); &gt; #endif #endif public: enum {IDLE, BREAK, STARTB, STARTADR}; // RX DMX states enum {TXBREAK, TXSTARTB, TXDATA}; &gt; // TX DMX states &gt; volatile uint8_t *RxBuffer; // array of RX DMX values volatile uint8_t *TxBuffer; // array of TX DMX &gt; values &gt; &gt; private: uint8_t gRxState; uint8_t *gRxPnt; uint8_t &gt; IndicatorCount; uint8_t USARTstate; uint8_t RxByte; &gt; uint8_t RxState; uint8_t mUART; uint8_t gTxState; &gt; uint16_t RxCount; uint16_t gCurTxCh; uint16_t &gt; rx_channels; // rx channels number uint16_t &gt; tx_channels; // tx channels number uint16_t &gt; rx_address; // rx start address uint16_t &gt; tx_address; // tx start address int8_t &gt; rx_led; // rx indicator led pin int8_t &gt; tx_led; // tx indicator led pin int8_t &gt; control_pin; // max485 input/output selection pin &gt; uint8_t dmx_mode; // Standard USITT DMX512 = &gt; 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) = 2 &gt; uint8_t speed_dmx; uint8_t speed_break; uint16_t &gt; CurTxCh; uint8_t TxState; uint8_t *RxPnt; &gt; &gt; #if defined(USE_INTERBYTE_DELAY) void delay_gap (); &gt; #endif &gt; &gt; public: void stop_dmx (); void set_speed &gt; (uint8_t mode); void set_control_pin (int8_t pin) &gt; { control_pin = pin; } void init_rx &gt; (uint8_t mode); // Standard USITT DMX512 = 0, non standard DMX1024 = &gt; 1, non standard DMX2048 (DMX1000K) = 2 void set_rx_address &gt; (uint16_t address) { rx_address = address; } void &gt; set_rx_channels (uint16_t channels) { rx_channels = channels; &gt; } void init_tx (uint8_t mode); // Standard USITT &gt; DMX512 = 0, non standard DMX1024 = 1, non standard DMX2048 (DMX1000K) &gt; = 2 void set_tx_address (uint16_t address) { tx_address = address; } void set_tx_channels &gt; (uint16_t channels) { tx_channels = channels; } &gt; &gt; void attachTXInterrupt (void (*isr)(uint8_t uart)) { &gt; TXisrCallback = isr; } // register the user TX callback void &gt; attachRXInterrupt (void (*isr)(uint8_t uart)) { RXisrCallback &gt; = isr; } // register the user RX callback &gt; //void Process_ISR_RX(uint8_t rx_isr_number); &gt; &gt; void (*TXisrCallback) (uint8_t uart); void &gt; (*RXisrCallback) (uint8_t uart); &gt; &gt; inline void Process_ISR_RX (uint8_t rx_isr_number); inline &gt; void Process_ISR_TX (uint8_t tx_isr_number); public: &gt; CArduinoDmx (uint8_t uart) { rx_address &gt; = 1; &gt; rx_channels = 8; &gt; tx_address = 1; &gt; tx_channels = 8; &gt; mUART = uart; } }; &gt; &gt; #if defined(USE_UART0) extern CArduinoDmx ArduinoDmx0; &gt; #endif &gt; #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #if defined(USE_UART1) &gt; extern CArduinoDmx ArduinoDmx1; #endif #if defined(USE_UART2) &gt; extern CArduinoDmx ArduinoDmx2; #endif #if defined(USE_UART3) &gt; extern CArduinoDmx ArduinoDmx3; #endif &gt; #endif &gt; &gt; #endif </code></pre> <p><strong>lib_dmx.cpp</strong></p> <pre><code>/*************************************************************************** * * Title : Arduino DMX512 library. 4 input/output universes. * Version : v 0.3 beta * Last updated : 07.07.2012 * Target : Arduino mega 2560, Arduino mega 1280, Arduino nano (1 universe) * Author : Toni Merino - merino.toni at gmail.com * Web : www.deskontrol.net/blog * * Based on ATmega8515 Dmx library written by Hendrik Hoelscher, www.hoelscher-hi.de ;***************************************************************************/ #include "lib_dmx.h" #include &lt;SPI.h&gt; #if defined(USE_UART0) CArduinoDmx ArduinoDmx0(0); #endif #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #if defined(USE_UART1) CArduinoDmx ArduinoDmx1(1); #endif #if defined(USE_UART2) CArduinoDmx ArduinoDmx2(2); #endif #if defined(USE_UART3) CArduinoDmx ArduinoDmx3(3); #endif #endif // *************** DMX Transmision Initialisation **************** void CArduinoDmx::init_tx(uint8_t mode) { cli(); //disable interrupts stop_dmx(); //stop uart dmx_mode = mode; set_speed(dmx_mode); if(control_pin != -1) { pinMode(control_pin,OUTPUT); // max485 I/O control digitalWrite(control_pin, HIGH); // set 485 as output } if(mUART == 0) { pinMode(1, OUTPUT); UBRR0H = 0; UBRR0L = speed_dmx; UCSR0A |= (1&lt;&lt;U2X0); UCSR0C |= (3&lt;&lt;UCSZ00)|(1&lt;&lt;USBS0); UCSR0B |= (1&lt;&lt;TXEN0) |(1&lt;&lt;TXCIE0); UDR0 = 0; //start USART 0 } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) else if(mUART == 1) { pinMode(18, OUTPUT); UBRR1H = 0; UBRR1L = speed_dmx; UCSR1A |= (1&lt;&lt;U2X1); UCSR1C |= (3&lt;&lt;UCSZ10)|(1&lt;&lt;USBS1); UCSR1B |= (1&lt;&lt;TXEN1) |(1&lt;&lt;TXCIE1); UDR1 = 0; //start USART 1 } else if(mUART == 2) { pinMode(16, OUTPUT); UBRR2H = 0; UBRR2L = speed_dmx; UCSR2A |= (1&lt;&lt;U2X2); UCSR2C |= (3&lt;&lt;UCSZ20)|(1&lt;&lt;USBS2); UCSR2B |= (1&lt;&lt;TXEN2) |(1&lt;&lt;TXCIE2); UDR2 = 0; //start USART 2 } else if(mUART == 3) { pinMode(14, OUTPUT); UBRR3H = 0; UBRR3L = speed_dmx; UCSR3A |= (1&lt;&lt;U2X3); UCSR3C |= (3&lt;&lt;UCSZ30)|(1&lt;&lt;USBS3); UCSR3B |= (1&lt;&lt;TXEN3) |(1&lt;&lt;TXCIE3); UDR3 = 0; //start USART 3 } #endif gTxState = BREAK; // start with break TxBuffer = (uint8_t*)malloc(tx_channels); // allocate mem for buffer memset((uint8_t*)TxBuffer, 0, tx_channels); // fill buffer with 0's sei(); //enable interrupts } // ************************ DMX Stop *************************** void CArduinoDmx::stop_dmx() { #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) if(mUART == 0) { UCSR0B &amp;= ~((1&lt;&lt;RXCIE0) | (1&lt;&lt;TXCIE0) | (1&lt;&lt;RXEN0) | (1&lt;&lt;TXEN0)); } else if(mUART == 1) { UCSR1B &amp;= ~((1&lt;&lt;RXCIE1) | (1&lt;&lt;TXCIE1) | (1&lt;&lt;RXEN1) | (1&lt;&lt;TXEN1)); } else if(mUART == 2) { UCSR2B &amp;= ~((1&lt;&lt;RXCIE2) | (1&lt;&lt;TXCIE2) | (1&lt;&lt;RXEN2) | (1&lt;&lt;TXEN2)); } else if(mUART == 3) { UCSR3B &amp;= ~((1&lt;&lt;RXCIE3) | (1&lt;&lt;TXCIE3) | (1&lt;&lt;RXEN3) | (1&lt;&lt;TXEN3)); } #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) if(mUART == 0) { UCSR0B &amp;= ~((1&lt;&lt;RXCIE0) | (1&lt;&lt;TXCIE0) | (1&lt;&lt;RXEN0) | (1&lt;&lt;TXEN0)); } #endif } // *************** DMX Reception Initialisation **************** void CArduinoDmx::init_rx(uint8_t mode) { cli(); //disable interrupts stop_dmx(); dmx_mode = mode; set_speed(dmx_mode); if(control_pin != -1) { pinMode(control_pin,OUTPUT); //max485 I/O control digitalWrite(control_pin, LOW); //set 485 as input } if(mUART == 0) { pinMode(0, INPUT); UBRR0H = 0; UBRR0L = speed_dmx; UCSR0A |= (1&lt;&lt;U2X0); UCSR0C |= (3&lt;&lt;UCSZ00)|(1&lt;&lt;USBS0); UCSR0B |= (1&lt;&lt;RXEN0) |(1&lt;&lt;RXCIE0); } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) else if(mUART == 1) { pinMode(19, INPUT); UBRR1H = 0; UBRR1L = speed_dmx; UCSR1A |= (1&lt;&lt;U2X1); UCSR1C |= (3&lt;&lt;UCSZ10)|(1&lt;&lt;USBS1); UCSR1B |= (1&lt;&lt;RXEN1) |(1&lt;&lt;RXCIE1); } else if(mUART == 2) { pinMode(17, INPUT); UBRR2H = 0; UBRR2L = speed_dmx; UCSR2A |= (1&lt;&lt;U2X2); UCSR2C |= (3&lt;&lt;UCSZ20)|(1&lt;&lt;USBS2); UCSR2B |= (1&lt;&lt;RXEN2) |(1&lt;&lt;RXCIE2); } else if(mUART == 3) { pinMode(15, INPUT); UBRR3H = 0; UBRR3L = speed_dmx; UCSR3A |= (1&lt;&lt;U2X3); UCSR3C |= (3&lt;&lt;UCSZ30)|(1&lt;&lt;USBS3); UCSR3B |= (1&lt;&lt;RXEN3) |(1&lt;&lt;RXCIE3); } #endif gRxState = IDLE; RxBuffer = (uint8_t*)malloc(rx_channels); // allocate mem for buffer memset((uint8_t*)RxBuffer, 0, rx_channels); // fill buffer with 0's sei(); //enable interrupts } // *************** DMX Reception ISR **************** #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #if defined(USE_UART0) ISR (SIG_USART0_RECV) { ArduinoDmx0.Process_ISR_RX(0); } #endif #if defined(USE_UART1) ISR (SIG_USART1_RECV) { ArduinoDmx1.Process_ISR_RX(1); } #endif #if defined(USE_UART2) ISR (SIG_USART2_RECV) { ArduinoDmx2.Process_ISR_RX(2); } #endif #if defined(USE_UART3) ISR (SIG_USART3_RECV) { ArduinoDmx3.Process_ISR_RX(3); } #endif #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) #if defined(USE_UART0) ISR (USART_RX_vect) { ArduinoDmx0.Process_ISR_RX(0); } #endif #endif void CArduinoDmx::Process_ISR_RX(uint8_t rx_isr_number) { if(rx_isr_number == 0) { USARTstate = UCSR0A; //get state RxByte = UDR0; //get data RxState = gRxState; //just get once from SRAM!!! if (USARTstate &amp;(1&lt;&lt;FE0)) //check for break { UCSR0A &amp;= ~(1&lt;&lt;FE0); //reset flag RxCount = rx_address; //reset frame counter gRxState = BREAK; } } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) else if(rx_isr_number == 1) { USARTstate = UCSR1A; //get state RxByte = UDR1; //get data RxState = gRxState; //just get once from SRAM!!! if (USARTstate &amp;(1&lt;&lt;FE1)) //check for break { UCSR1A &amp;= ~(1&lt;&lt;FE1); //reset flag RxCount = rx_address; //reset frame counter gRxState = BREAK; } } else if(rx_isr_number == 2) { USARTstate = UCSR2A; //get state RxByte = UDR2; //get data RxState = gRxState; //just get once from SRAM!!! if (USARTstate &amp;(1&lt;&lt;FE2)) //check for break { UCSR2A &amp;= ~(1&lt;&lt;FE2); //reset flag RxCount = rx_address; //reset frame counter gRxState = BREAK; } } else if(rx_isr_number == 3) { USARTstate = UCSR3A; //get state RxByte = UDR3; //get data RxState = gRxState; //just get once from SRAM!!! if (USARTstate &amp;(1&lt;&lt;FE3)) //check for break { UCSR3A &amp;= ~(1&lt;&lt;FE3); //reset flag RxCount = rx_address; //reset frame counter gRxState = BREAK; } } #endif if (RxState == BREAK) { if (RxByte == 0) { gRxState = STARTB; //normal start code detected gRxPnt = ((uint8_t*)RxBuffer + 1); } else gRxState = IDLE; } else if (RxState == STARTB) { if (--RxCount == 0) //start address reached? { gRxState = STARTADR; RxBuffer[0]= RxByte; } } else if (RxState == STARTADR) { RxPnt = gRxPnt; *RxPnt = RxByte; if (++RxPnt &gt;= (RxBuffer + rx_channels)) //all ch received? { gRxState= IDLE; if (*RXisrCallback) RXisrCallback(mUART); // fire callback for read data } else { gRxPnt = RxPnt; } } } // *************** DMX Transmision ISR **************** #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) #if defined(USE_UART0) ISR(SIG_USART0_TRANS) { ArduinoDmx0.Process_ISR_TX(0); } #endif #if defined(USE_UART1) ISR(SIG_USART1_TRANS) { ArduinoDmx1.Process_ISR_TX(1); } #endif #if defined(USE_UART2) ISR(SIG_USART2_TRANS) { ArduinoDmx2.Process_ISR_TX(2); } #endif #if defined(USE_UART3) ISR(SIG_USART3_TRANS) { ArduinoDmx3.Process_ISR_TX(3); } #endif #elif defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__) #if defined(USE_UART0) ISR(USART_TX_vect) { ArduinoDmx0.Process_ISR_TX(0); } #endif #endif void CArduinoDmx::Process_ISR_TX(uint8_t tx_isr_number) { TxState = gTxState; if(tx_isr_number == 0) { if (TxState == TXBREAK) //BREAK + MAB { UBRR0H = 0; UBRR0L = speed_break; UDR0 = 0; //send break gTxState = TXSTARTB; } else if (TxState == TXSTARTB) { UBRR0H = 0; UBRR0L = speed_dmx; UDR0 = 0; //send start byte gTxState = TXDATA; gCurTxCh = 0; } else { #if defined(USE_INTERBYTE_DELAY) delay_gap(); #endif CurTxCh = gCurTxCh; UDR0 = TxBuffer[CurTxCh++]; //send data if (CurTxCh == tx_channels) { if (*TXisrCallback) TXisrCallback(0); // fire callback for update data gTxState = TXBREAK; // new break if all ch sent } else { gCurTxCh = CurTxCh; } } } #if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) else if(tx_isr_number == 1) { if (TxState == TXBREAK) { UBRR1H = 0; UBRR1L = speed_break; UDR1 = 0; //send break gTxState = TXSTARTB; } else if (TxState == TXSTARTB) { UBRR1H = 0; UBRR1L = speed_dmx; UDR1 = 0; //send start byte gTxState = TXDATA; gCurTxCh = 0; } else { #if defined(USE_INTERBYTE_DELAY) delay_gap(); #endif CurTxCh = gCurTxCh; UDR1 = TxBuffer[CurTxCh++]; //send data if (CurTxCh == tx_channels) { if (*TXisrCallback) TXisrCallback(1); // fire callback for update data gTxState = TXBREAK; // new break if all ch sent } else { gCurTxCh = CurTxCh; } } } else if(tx_isr_number == 2) { if (TxState == TXBREAK) { UBRR2H = 0; UBRR2L = speed_break; UDR2 = 0; //send break gTxState = TXSTARTB; } else if (TxState == TXSTARTB) { UBRR2H = 0; UBRR2L = speed_dmx; UDR2 = 0; //send start byte gTxState = TXDATA; gCurTxCh = 0; } else { #if defined(USE_INTERBYTE_DELAY) delay_gap(); #endif CurTxCh = gCurTxCh; UDR2 = TxBuffer[CurTxCh++]; //send data if (CurTxCh == tx_channels) { if (*TXisrCallback) TXisrCallback(2); // fire callback for update data gTxState = TXBREAK; // new break if all ch sent } else { gCurTxCh = CurTxCh; } } } else if(tx_isr_number == 3) { if (TxState == TXBREAK) { UBRR3H = 0; UBRR3L = speed_break; UDR3 = 0; //send break gTxState = TXSTARTB; } else if (TxState == TXSTARTB) { UBRR3H = 0; UBRR3L = speed_dmx; UDR3 = 0; //send start byte gTxState = TXDATA; gCurTxCh = 0; } else { #if defined(USE_INTERBYTE_DELAY) delay_gap(); #endif CurTxCh = gCurTxCh; UDR3 = TxBuffer[CurTxCh++]; //send data if (CurTxCh == tx_channels) { if (*TXisrCallback) TXisrCallback(3); // fire callback for update data gTxState = TXBREAK; // new break if all ch sent } else { gCurTxCh = CurTxCh; } } } #endif } void CArduinoDmx::set_speed(uint8_t mode) { if(mode == 0) { speed_dmx = DMX_512; // DMX-512 (250 kbaud - 512 channels) Standard USITT DMX-512 speed_break = BREAK_512; } else if(mode == 1) { speed_dmx = DMX_1024; // DMX-1024 (500 kbaud - 1024 channels) Completely non standard, but usefull ;) speed_break = BREAK_1024; } else if(mode == 2) { speed_dmx = DMX_2048; // DMX-2048 (1000 kbaud - 2048 channels) Used by manufacturers as DMX1000K, DMX-4x or DMX-1M ??? speed_break = BREAK_2048; } } #if defined(USE_INTERBYTE_DELAY) void CArduinoDmx::delay_gap() // rare cases of equipment non full DMX-512 compliant, need this { if(dmx_mode == 0) { _delay_us(IBG_512); } else if(dmx_mode == 1) { _delay_us(IBG_1024); } else if(dmx_mode == 2) { _delay_us(IBG_2048); } } #endif </code></pre> <p><strong>myFile.ino</strong></p> <pre><code>/*----------------------------------------------------------------------------- include files ------------------------------------------------------------------------------*/ #include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; #include &lt;EthernetUdp.h&gt; #include &lt;lib_dmx.h&gt; #define DMX512 (0) byte mac[] = { 0xDD, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; IPAddress ip(10,0,0,2); // TODO: assign ip address from DHCP unsigned int multicastPort = 8888; IPAddress multicastIp(239,0,0,57); char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; EthernetUDP Udp; int sensorValue = 0; int ledState = 0; int DMXPin = 0; void setup() { // DMX ArduinoDmx1.set_control_pin(DMXPin); ArduinoDmx1.set_rx_channels(1); ArduinoDmx1.set_tx_channels(5); ArduinoDmx1.init_tx(DMX512); Ethernet.begin(mac,ip); Udp.beginMulti( multicastIp, multicastPort ); Serial.begin(9600); } void loop() { int packetSize = Udp.parsePacket(); if(packetSize){ Serial.print("Received packet of size "); Serial.println(packetSize); Serial.print("From "); IPAddress remote = Udp.remoteIP(); for (int i =0; i &lt; 4; i++){ Serial.print(remote[i], DEC); if (i &lt; 3){ Serial.print("."); } } Serial.print(", port "); Serial.println(Udp.remotePort()); Udp.read(packetBuffer,UDP_TX_PACKET_MAX_SIZE); Serial.println("Contents:"); Serial.println(packetBuffer[0]); ArduinoDmx1.TxBuffer[0] = (int)packetBuffer; } } </code></pre>
<p>You use the Serial.begin(9600) and other Serial functions in your sketch. Therefore the HardwareSerial library is included. Just avoid the Serial stuff in your sketch, it won't work anyway, because the DMX uses the same serial port.</p> <p>Have a look to "Don't use the Arduino Serial implementation" in <a href="http://www.mathertel.de/Arduino/DMXSerial.aspx" rel="nofollow">http://www.mathertel.de/Arduino/DMXSerial.aspx</a> The Four Universes DMX 512 Library works the same way as the DMXSerial library.</p>
1348
|arduino-uno|pins|motor|pwm|servo|
How can the Arduino Uno support up to 12 servos if it only has 6 digital PWM pins?
2014-04-30T21:32:45.820
<p>According to <a href="http://arduino.cc/en/reference/servo">this</a>:</p> <blockquote> <p>The Servo library supports up to 12 motors on most Arduino boards and 48 on the Arduino Mega. On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins. On the Mega, up to 12 servos can be used without interfering with PWM functionality; use of 12 to 23 motors will disable PWM on pins 11 and 12.</p> </blockquote> <p>However, according to <a href="http://arduino.cc/en/Main/ArduinoBoardUno">this</a>:</p> <blockquote> <p>Digital I/O Pins 14 (of which 6 provide PWM output)</p> </blockquote> <p>So how can the Uno control more than 6 servos if it only has 6 digital I/O pins that can provide PWM output?</p>
<p>Although I haven't looked at the source myself, in these types of situations they usually use <a href="http://playground.arduino.cc/Code/Timer1" rel="nofollow noreferrer">interrupt timer 1</a>, which in PWM mode would have been associated with pins 9 and 10. This would explain why you can't use pulse width modulation on those pins. In fact, you can use any of the three timers for PWM <a href="http://arduino.cc/en/Tutorial/SecretsOfArduinoPWM" rel="nofollow noreferrer">on any digital pin, although it's not as good as the built in PWM options</a>.</p> <blockquote> <p><a href="https://i.stack.imgur.com/u3eoJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u3eoJ.png" alt="" /></a><br /> <sub>(source: <a href="http://bansky.net/blog_stuff/images/servo_pulse_width.png" rel="nofollow noreferrer">bansky.net</a>)</sub></p> </blockquote> <p><em>(<a href="http://forum.arduino.cc/index.php/topic,14146.0.html" rel="nofollow noreferrer">Source</a>)</em></p> <p>The above image accurately describes how the signals are sent to the servo motor. Such a waveform is similar to a standard PWM. The servo library can translate a degree to a waveform that the servo's IC will be able to use to adjust the motor's position with it's motor and potentiometer.</p>
1355
|arduino-yun|
Arduino Yún console clear
2014-04-24T17:22:35.997
<p>I'm having a problem. I want to clear the screen on the connected console. And after the clear, I want to rerun my code. But I can't seem to figure out how to do it. Below is some part of the code: </p> <pre><code>#include &lt;motorStyring.h&gt; #include &lt;Bridge.h&gt; #include &lt;YunServer.h&gt; #include &lt;YunClient.h&gt; #define PORT 6666 motorStyring mt; int cm; YunServer server(PORT); const int pingPin = 9; int led = 13; void setup() { Serial.begin(115200); Bridge.begin(); server.noListenOnLocalhost(); server.begin(); } void loop() { long duration, inches, cm; pinMode(pingPin,OUTPUT); digitalWrite(pingPin,LOW); delayMicroseconds(2); digitalWrite(pingPin, HIGH); delayMicroseconds(5); digitalWrite(pingPin,LOW); pinMode(pingPin, INPUT); duration = pulseIn(pingPin,HIGH); cm = microsecondsToCentimeters(duration); h(); } void h() { YunClient client = server.accept(); if (client.connected()) { String question = "What would you like to drink?\nyou have 4 choises:\n1)Juice\n2)Vodca\n3)Soda\n4)Mix\n"; client.write((uint8_t*)&amp;question[0], question.length()); String response; while (client.connected()) { if (client.available()) { char cmd = client.read(); if (cmd == '\n') { break; } else { response += String(cmd); } } } if (response == "juice") { juice(); } else if (response == "vodka") { vodka(); } else if (response == "soda") { soda(); } else if (response == "mix") { mix(); } else { String error = "you didn't select anything that corrospond to an option. \n try agin"; client.write((uint8_t*)&amp;error[0], error.length()); } String awnser = "Here is your " + response; client.write((uint8_t*)&amp;awnser[0], awnser.length()); } delay(1000); } </code></pre> <p><strong>...</strong></p> <p>Is there a way to clear the screen on the console, so that all of the text from the previous code is not disturbing the user?</p>
<p>Perhaps you could count the number of lines in the console and the print out enough carriage returns (<code>"\n"</code>) to fill it with empty whitespace.</p> <p>For example, with a console with 100 lines:</p> <pre><code>for(int iter = 0; iter &lt; 100; iter++) { client.write('\n'); } </code></pre>
1374
|programming|c++|avr-gcc|gcc|
How to write makefile-compatible sketches?
2014-05-02T13:30:23.127
<p>I'd like to write my sketches so that I can either build/upload them using the Arduino IDE, or optionally using GCC and a makefile.</p> <p>I know about including the function declarations at the top, but is there anything else to do in order for my sketch to be considered valid C++ by my compiler?</p> <h3>Update 1</h3> <p>Understanding what the Arduino IDE does to .ino and .pde files is fine, but extraneous to my question, so this is not a duplicate. What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE <strong>and</strong> g++.</p> <p>The official(?) makefile <a href="http://playground.arduino.cc/Learning/CommandLine" rel="nofollow">available here</a> explains what to do if using the makefile <em>instead</em> of the IDE:</p> <pre><code># The Arduino environment does preliminary processing on a sketch before # compiling it. If you're using this makefile instead, you'll need to do # a few things differently: # # - Give your program's file a .cpp extension (e.g. foo.cpp). # # - Put this line at top of your code: #include &lt;WProgram.h&gt; # # - Write prototypes for all your functions (or define them before you # call them). A prototype declares the types of parameters a # function will take and what type of value it will return. This # means that you can have a call to a function before the definition # of the function. A function prototype looks like the first line of # the function, with a semi-colon at the end. For example: # int digitalRead(int pin); </code></pre> <p>...but this doesn't explain how use <em>both</em> the IDE and a makefile.</p> <h3>Update 2</h3> <p>I recently found PlatformIO which doesn't answer this question directly, but does automate a lot of the process (generates Scons files for you) and so far I prefer the workflow over both the Arduino IDE and the source+makefile approach. Good support from the authors as well.</p>
<blockquote> <p>What I want to know is "how do I write a program such that it is considered valid both by the Arduino IDE and g++.</p> </blockquote> <p>See: <a href="http://www.gammon.com.au/forum/?id=12625" rel="nofollow noreferrer">How to avoid the quirks of the IDE sketch file pre-preprocessing</a>.</p> <p>Disregarding for the moment what the Makefile will look like, the simple answer to your question, as discussed in the above link, is to put everything into .cpp and .h tabs in the IDE, and leave the main "sketch" (.ino file) blank. That will still compile under the IDE, and will also therefore be normal C++.</p> <p>Make sure you start your .cpp files with:</p> <pre><code>#include &lt;Arduino.h&gt; </code></pre> <p>If you use libraries (eg, SPI) you must include them in the main sketch file, which triggers the IDE to copy them into the temporary project build file. The Makefile won't care about that, as you will make sure your Makefile includes all the necessary library files.</p> <p>Also see my answer here: <a href="https://arduino.stackexchange.com/questions/13178/classes-and-objects-how-many-and-which-file-types-i-actually-need-to-use-them/13182#13182">Classes and objects: how many and which file types do I actually need to use them?</a></p>
1384
|programming|motor|
Reverse turning of Stepper motor
2014-05-03T12:26:07.773
<p>I have a stepper motor connected to my Arduino like this using the ULN2003A Darlington Array:</p> <p><img src="https://arduino.cc/en/uploads/Reference/unipolar_stepper_four_pins.jpg" alt="Circuit Diagram"><br> <img src="https://static.flickr.com/32/54357295_756c131217.jpg" alt="Image"> (Ignore the potentiometer)</p> <p>And I have programmed it with the following code:</p> <pre><code>#include &lt;Stepper.h&gt; int in1Pin = 22; int in2Pin = 23; int in3Pin = 24; int in4Pin = 25; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); motor.setSpeed(25); } void loop() { int steps = 360; motor.step(steps); delay(500); } </code></pre> <p>At the moment the motor rotates clockwise, how could I have it so it rotates in the opposite direction?</p> <p>My code was copied and edited from <a href="http://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors/arduino-code" rel="nofollow noreferrer">here</a>.</p> <hr> <p>The problem was that I had the two middle wires the wrong way round as said here: <a href="http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&amp;topic=143276.msg" rel="nofollow noreferrer">http://forum.arduino.cc/index.php?PHPSESSID=kvi8dt2b5en5hhk02dlmjrotl5&amp;topic=143276.msg</a>‌​</p>
<p>The answer is simple. Just pass a negative number of steps as an argument to <code>motor.step();</code>.</p> <p>Another note: You forgot a semicolon on your second to last line. IIRC this doesn't matter in C, but <strong>it's just bad practice to do this.</strong> If you add a line of code below that, then it won't work.</p> <p>Example code:</p> <pre><code>#include &lt;Stepper.h&gt; int in1Pin = 22; int in2Pin = 23; int in3Pin = 24; int in4Pin = 25; Stepper motor(512, in1Pin, in2Pin, in3Pin, in4Pin); void setup() { pinMode(in1Pin, OUTPUT); pinMode(in2Pin, OUTPUT); pinMode(in3Pin, OUTPUT); pinMode(in4Pin, OUTPUT); motor.setSpeed(25); } void loop() { int steps = 360; motor.step(steps); delay(100); steps = -360; motor.step(steps); delay(500); //Semicolon added } </code></pre>
1397
|arduino-uno|gsm|web-server|
client.connect() fails except the first time
2014-05-04T10:03:15.157
<p>I am communicating with the Web server's database via Arduino GSM shield + GPRS connectivity</p> <pre><code>void loop() { if (client.connect(server, port)) { ....... } else { Serial.println("Server not found"); } delay(1000); } </code></pre> <p>The first time when the loop() runs in the serial port, the code works perfectly and stores in my server's db. The second time when the loop() runs after some delay, It is unable to connect to the server and results "server not found" . I don't know what is the problem.</p> <p>Please let me know if there is a way to connect continuously. Thank you</p>
<p>If possible, do a check, if it's still connected with the server. Close the connection when work is done. You might also keep using the open connection, just try whatever works best for you. </p> <p>But avoid opening a second connection, when you still have an open one. As an example:</p> <pre><code>void loop() { if(!client.connected()) { if (client.connect(server, port)) { ... client.disconnect(); } else Serial.println("Server not found"); } else client.disconnect(); delay(1000); } </code></pre>
1401
|pins|sd-card|
Playing audio files with sine wave from arduino
2014-05-04T16:03:46.523
<p>So, when searching for a way to play audio files through the Arduino, I came across this site: <a href="http://maxoffsky.com/maxoffsky-blog/how-to-play-wav-audio-files-with-arduino-uno-and-microsd-card/" rel="nofollow">How to play WAV audio files with Arduino Uno and MicroSD card</a></p> <p>This seems like a really good library (although I haven't had the time to really play around with it yet). Has anyone used this before, and, if so, is it a good library to use, or do you know of better ones out there which you would recommend?</p>
<p>I used some time ago the TMRPCM library that the tutorial you linked used and I was very satisfied.</p> <p>It doesn't take too much space and it has some really unique and neat features like the possibility to use two speakers instead of one to reproduce stereo audio (Unfortunately you need a more powerful AVR IC, surely not an UNO board/328 IC for this feature if you don't want to occur in bad reproduction)</p> <p>From <a href="https://github.com/TMRh20/TMRpcm/wiki" rel="nofollow noreferrer">GitHub's wiki</a>:</p> <blockquote> <p>All 328 based boards: Arduino Uno, Nano, Duemilanove, etc</p> <p>Mega Types: 1280, 2560, etc</p> <p>No Due support currently.</p> </blockquote> <p>You can only have WAV files on the SD but they can be very large (other libraries limit you to a specific maximum size/duration) and you need to connect the SD to the arduino via SPI (as far as I know it is the only way to communicate directly with an SD card).</p> <p>Also, you will need to convert the files to 8 bit WAV (so it's faster and easier for the arduino to reproduce the sound) with sample rate from 8 to 32khz, mono audio.</p> <p>Be careful just because you'll need to power the SD with 3.3 volts otherwise you'll fry the entire card.</p> <blockquote> <p>Most of the extra features require more memory, more program space, and in some cases, more processing power for playback Some of them are still being fine tuned. Please keep this in mind when enabling these features.</p> </blockquote> <p>If you want to take a look, <a href="https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features" rel="nofollow noreferrer">go to this page</a> for more informations on the advanced features</p> <p>A last thing that I have to say is that the functions are really straightforward:</p> <pre><code>TMRpcm audio; audio.play(&quot;filename&quot;); plays a file audio.play(&quot;filename&quot;,30); plays a file starting at 30 seconds into the track audio.speakerPin = 11; set to 5,6,11 or 46 for Mega, 9 for Uno, Nano, etc. audio.disable(); disables the timer on output pin and stops the music audio.stopPlayback(); stops the music, but leaves the timer running audio.isPlaying(); returns 1 if music playing, 0 if not audio.pause(); pauses/unpauses playback audio.quality(1); Set 1 for 2x oversampling audio.volume(0); 1(up) or 0(down) to control volume audio.setVolume(0); 0 to 7. Set volume level audio.loop(1); 0 or 1. Can be changed during playback for full control of looping. </code></pre>
1404
|avr|avrdude|
arduino 16u2 stk500v2_command(): command failed
2014-05-05T04:51:03.373
<p>I'm trying to fix arduino uno r3 that was burned-out. I changed m16u2 chip on it. and now I need burn in: <code>Arduino-COMBINED-dfu-usbserial-atmega16u2-Uno-Rev3.hex</code> I'm using stk500v2 and connecting it to isp of arduino. Output log file of avrdude:</p> <pre><code>C:\&gt;avrdude -c stk500v2 -P COM4 -p m16u2 -U flash:w:1.hex -vvvv avrdude: Version 6.1, compiled on Mar 13 2014 at 00:09:49 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is "C:\WinAVR-20100110\bin\avrdude.conf" Using Port : COM4 Using Programmer : stk500v2 avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14] avrdude: Recv: . [1b] avrdude: Recv: . [01] avrdude: Recv: . [00] avrdude: Recv: . [0b] avrdude: Recv: . [0e] avrdude: Recv: . [01] avrdude: Recv: . [00] avrdude: Recv: . [08] avrdude: Recv: A [41] avrdude: Recv: V [56] avrdude: Recv: R [52] avrdude: Recv: I [49] avrdude: Recv: S [53] avrdude: Recv: P [50] avrdude: Recv: _ [5f] avrdude: Recv: 2 [32] avrdude: Recv: t [74] avrdude: stk500v2_getsync(): found AVRISP programmer AVR Part : ATmega16U2 Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PC6 RESET disposition : possible i/o RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- eeprom 65 20 4 0 no 512 4 128 9000 90 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- flash 65 6 128 0 yes 16384 128 128 4500 45 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- lfuse 0 0 0 0 no 1 0 0 9000 90 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- hfuse 0 0 0 0 no 1 0 0 9000 90 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- efuse 0 0 0 0 no 1 0 0 9000 90 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- lock 0 0 0 0 no 1 0 0 9000 90 00 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW Max W ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- --- -- --------- signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : STK500V2 Description : Atmel STK500 Version 2.x firmware Programmer Model: AVRISP avrdude: Send: . [1b] . [02] . [00] . [02] . [0e] . [03] . [90] . [86] avrdude: Recv: . [1b] avrdude: Recv: . [02] avrdude: Recv: . [00] avrdude: Recv: . [03] avrdude: Recv: . [0e] avrdude: Recv: . [03] avrdude: Recv: . [00] avrdude: Recv: . [02] avrdude: Recv: . [15] avrdude: Send: . [1b] . [03] . [00] . [02] . [0e] . [03] . [91] . [86] avrdude: Recv: . [1b] avrdude: Recv: . [03] avrdude: Recv: . [00] avrdude: Recv: . [03] avrdude: Recv: . [0e] avrdude: Recv: . [03] avrdude: Recv: . [00] avrdude: Recv: . [02] avrdude: Recv: . [14] avrdude: Send: . [1b] . [04] . [00] . [02] . [0e] . [03] . [92] . [82] avrdude: Recv: . [1b] avrdude: Recv: . [04] avrdude: Recv: . [00] avrdude: Recv: . [03] avrdude: Recv: . [0e] avrdude: Recv: . [03] avrdude: Recv: . [00] avrdude: Recv: . [0a] avrdude: Recv: . [1b] Hardware Version: 2 Firmware Version Master : 2.10 avrdude: Send: . [1b] . [05] . [00] . [02] . [0e] . [03] . [94] . [85] avrdude: Recv: . [1b] avrdude: Recv: . [05] avrdude: Recv: . [00] avrdude: Recv: . [03] avrdude: Recv: . [0e] avrdude: Recv: . [03] avrdude: Recv: . [00] avrdude: Recv: U [55] avrdude: Recv: E [45] Vtarget : 8.5 V SCK period : 0.1 us avrdude: Send: . [1b] . [06] . [00] . [0c] . [0e] . [10] . [c8] d [64] . [19] [20] . [00] S [53] . [03] . [ac] S [53] . [00] . [00] 5 [35] avrdude: Recv: . [1b] avrdude: Recv: . [06] avrdude: Recv: . [00] avrdude: Recv: . [02] avrdude: Recv: . [0e] avrdude: Recv: . [10] avrdude: Recv: . [c0] avrdude: Recv: . [c1] avrdude: stk500v2_command(): command failed avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check. avrdude: Send: . [1b] . [07] . [00] . [03] . [0e] . [11] . [01] . [01] . [00] avrdude: Recv: . [1b] avrdude: Recv: . [07] avrdude: Recv: . [00] avrdude: Recv: . [02] avrdude: Recv: . [0e] avrdude: Recv: . [11] avrdude: Recv: . [00] avrdude: Recv: . [01] avrdude done. Thank you. </code></pre> <p>My question is what block with error does? can it be I shorted due soldering? or maybe burned chip? any issues? how I can check?</p> <p>ps. programmer works perfect. checked!</p>
<p>Here’s a decoding of the crucial pair of messages exchanged here. Protocol is documented <a href="http://www.atmel.com/Images/doc2591.pdf" rel="nofollow">on Atmel’s site</a>.</p> <p>Your machine sends:</p> <pre><code>[1b] Beginning of message [06] Message sequence number [00] [0c] Message body length (big endian) [0e] Beginning of message body [10] Command: CMD_ENTER_PROGMODE_ISP [c8] [64] [19] [20] [00] Various programming parameters [53] Response value to look for [03] Response index [ac] [53] [00] [00] Enter programming mode command [35] Checksum </code></pre> <p>This causes the programmer to send the 4 bytes <code>0xAC 0x53 0x00 0x00</code> to the MCU, and look for the value <code>0x53</code> in the third of the 4 response bytes, as specified on page 260 of the <a href="http://www.atmel.ch/Images/doc7799.pdf" rel="nofollow">data sheet</a>. However, the programmer answers:</p> <pre><code>[1b] Beginning of message [06] Sequence number (matches message previously sent) [00] [02] Response body length [0e] Beginning of response body [10] Command: CMD_ENTER_PROGMODE_ISP (Matches message) [c0] STATUS_CMD_FAILED (This is the error message) [c1] Checksum </code></pre> <p>That means that tyne very first command sent to the microcontroller “failed” (most likely by not returning the expected answer byte).</p>
1413
|shields|
If I put a shield on an Arduino, can I use the Arduino for anything else?
2014-05-05T20:04:44.733
<p>I did some basic Arduino examples in the recent past, but I have never actually seen a shield for Arduino firsthand.</p> <p>So I wonder: If I put a shield on an Arduino (for example, the Adafruit Motor Shield), does it "block" the entire Arduino, including all input and output pins?</p> <p>Is it possible to use a shield, and still connect additional components that would usually connect directly to the Arduino (say, a potentiometer, or anything similar)? Does this depend on the type of Arduino, or on the type of the shield, or is it not possible at all?</p>
<p>Yes, but sometimes it interferes with the output and the input pin, and most shields use up the CS, MOSI, MISO, SCK pin. Even through on some shields like wireless SD shield you can switch from USB to MICRO, this is going to interfere with your program. Say, when you want to access the info on your SD card to run your Motor Shield.</p>
1430
|arduino-uno|
Is the Sparkfun RedBoard pre-loaded with a blink sketch?
2014-05-06T16:52:23.560
<p>As soon as I plugged my brand new RedBoard (Sparkfun's Uno) into my computer, I saw the onboard LED (for pin 13) blink on and off every 1 second. This was before I even sent the first demo sketch to blink the LED. After I uploaded a sketch to change the blink time, the LED's blink cycle changed as I expected. </p> <p>But why was the LED blinking <em>before</em> I sent my very first sketch? Is the RedBoard pre-loaded with a sketch? </p>
<p>Yes, the RedBoard is preloaded with the blink sketch (or at least the two that I've purchased have been).</p>
1433
|c++|
Arduino sizeof Servo array objects is.. wrong?
2014-05-06T23:29:23.740
<p>After searching <em>for a quite long while</em> over the internet, I have no choice but to try asking someone if they can explain me this apparently strange situation.</p> <p>I'm doing some tests using some servo motors, trying to move them almost together using <code>millis()</code> and <code>Servo</code> object.</p> <p>It is, of course, working either for single Servos and multiple servos.</p> <p>The case, more detailed, is about this:</p> <ol> <li>Move one, two or more servo motors together.</li> <li>Force them to take ALMOST the same time to accomplish any action.</li> <li>Have a dynamic number of servos.</li> </ol> <p>About the first two points I had no problems to solve them, I was easily able to make a function and then make a library to accomplish such a job.</p> <p>However, since I'm NOT that used to C++ and I was wondering if it actually was possible to create an array of Servo objects, like you can actually do, on arduino, with strings:</p> <pre><code>String stringArray[] = {"string1", "string2", "and so on, I love it."}; </code></pre> <p>So, after wondering a while, I've tried this:</p> <pre><code>Servo servObject; Servo servObject_2; Servo servObject_3; Servo servos[] = {servObject, servObject_2, servObject_3}; </code></pre> <p>And you know what's cool? my function is actually working correctly by forcing the amount of elements of the servos array.</p> <p>What I mean by that is that if I force my function to know that it is going to have 3 elements into the array it will, of course, work; However, for some reason, if I use <code>sizeof(servos);</code> the value returned, surprisingly, is <code>2</code>.... Moreover, if I only push two servo objects instead of three into the servo array, its <code>sizeof</code> returns <code>6</code>.</p> <p>By googling, I've found out a couple of discussions about the fact that, for some reasons, in some cases, sizeof returns an incorrect value (if I'm not wrong it was the correct value -1), but in my case it apparently is not following any logic at all.</p> <p>The board I'm using is an Arduino nano w/ ATMEGA 328.</p> <p>Any idea of why it is not returning the correct value? Am I actually going totally wrong because I shouldn't make an array of servo objects?</p> <p>ps: I didn't post the whole code because it would've been useless, since the sizeof is the first function called in the <code>loop()</code></p> <p>Regards,</p> <p>briosheje</p>
<p>What you describe seems to be a common issue that many C or C++ developers can get (or have got) with <code>sizeof</code>.</p> <p>Take a look at the following code:</p> <pre><code>char a[3]; int size(char b[]) { return sizeof b; } void setup() { int size1 = sizeof a; int size2 = size(a); } </code></pre> <p>In that code, <code>size1</code> will be evaluated, by the compiler, to <code>3</code> which is the real size of <code>a</code> variable, whereas <code>size2</code> will be <code>2</code>.</p> <h2>Why so?</h2> <p>This is just because <code>sizeof a</code> is evaluated by the compiler, and the compiler <em>knows</em> that <code>a</code> is an array of 3 <code>char</code>; but when <code>a</code> is passed as an argument to function <code>size()</code>, it is converted to a pointer (to the first element of the array), hence its size is the <strong>size of a pointer</strong>, which is <code>2</code> bytes on AVR ATmega MCU.</p> <p>This subtlety of <code>sizeof</code> may explain strange values as you describe.</p> <h2>How to fix the issue?</h2> <p>Most C functions that take an array as argument will require another argument that tells the size of the array; that's the way (the only one I think) to deal with this problem.</p> <p>Here is a sample code:</p> <pre><code>Servo allServos[] = {...}; #define NUM_SERVOS (sizeof(allServos) / sizeof(Servo)) ... void handleServos(Servo *servos, int numServos) { for (int i = 0; i &lt; numServos; i++) { servos[i].write(...); ... } } void loop() { handleServos(allServos, NUM_SERVOS); } </code></pre> <p>It is common practice in C to <strong>declare an array</strong> and immediately after, <strong>define its size</strong> as above.</p>
1439
|shields|motor|
What is the advantage of using a motor shield if I want to use a stepper motor?
2014-05-07T09:14:34.433
<p>I know that it is possible to connect a stepper motor directly to an arduino (<a href="http://arduino.cc/en/Tutorial/StepperUnipolar">as displayed here</a>). I know that another option is to use a motor shield (for example the <a href="http://arduino.cc/de/Main/ArduinoMotorShieldR3">Arduino Motor Shield</a> or the <a href="http://www.adafruit.com/product/1438">Adafruit Motor Shield</a>).</p> <p>What I would like to know: What are the actual advantages of using a motor shield?</p> <p>Is it just a question of convenience? Or does a motor shield do something that could not easily performed without a shield? Does it allow me to connect more motors than I could connect directly without a shield (power supply comes to mind)?</p>
<p>I'm using a adafruit motorshield v2 for my solar tracker project with two stepper motors atm. i'm quite a new to arduino and coding and i think the shield made it a lot easier for me to get a hang of it - easy to code and nicely stack able on the ardiuno (little soldering to assemble but not too difficult).</p>
1445
|arduino-uno|shields|gsm|
Receive SMS example gives me a garbage values
2014-05-07T15:49:54.260
<p>When I run my <a href="http://arduino.cc/en/Tutorial/GSMExamplesReceiveSMS" rel="nofollow noreferrer">Receive SMS</a> example code, By default every time I get the same thing.I am trying to send sms to my sim card present in the Arduino GSM shield. I don't want this message. How to solve this problem ?</p> <p><img src="https://i.stack.imgur.com/gGZKX.png" alt="enter image description here"></p> <p>I </p>
<p>Most Telecom operators agree for sending advertisements and promotions to their customers for certain business and some money. You can stop these promotion for your mobile by making (Do Not Disturb)DND active. In India, just do the following for DND Activation</p> <pre><code> ( Fully Blocked Category ) Send SMS at START 0 to 1909 or Call at 1909 Partial Blocked Category Send SMS at START 1 to 1909 to block Banking – Insurance – Financial Products – Credit Cards Send SMS at START 2 to 1909 to block Real Estate Send SMS at START 3 to 1909 to block Education Send SMS at START 4 to 1909 to block Health Send SMS at START 5 to 1909 to block Consumer Goods &amp; Automobiles Send SMS at START 6 to 1909 to block Communication – Broadcasting – Entertainment – IT Send SMS at START 7 to 1909 to block Tourism </code></pre> <ul> <li>See more at: <a href="http://www.techsiren.com/how-to-activate-do-not-disturb-india-registration/#sthash.F87Pfj5V.dpuf" rel="nofollow">http://www.techsiren.com/how-to-activate-do-not-disturb-india-registration/#sthash.F87Pfj5V.dpuf</a></li> </ul>
1448
|arduino-uno|
What's the deal with Uno's pin 13 LED?
2014-05-07T19:59:25.817
<p>(I have a Sparkfun RedBoard, but this question seems to apply to R3 Unos and Uno-compatible boards.) As I was building the first circuit in my SIK guidebook (add a resistor, LED, hook it up and make it blink from code), I noticed a blue LED on the board itself did everything that the circuit's LED did - blinking according to the programming. </p> <p>Why is this LED here? What use cases is it for?</p> <p>What kind of circuits will I have to adjust to account for this LED?</p> <p>Is pin 13 traditionally a debug or a troubleshooting pin? Where did this convention come from?</p>
<p>What everyone else said, plus: if you find the digital-13 LED gives you a problem, you can always remove it from the circuit, either by removing the LED, or the series resistor. </p> <p>This might be useful if you are running out of digital I/Os, or you want several contiguous I/O bits and don't want one of them to behave differently from the others. </p>
1454
|programming|pins|power|voltage-level|analogwrite|
Can I turn off a device using the 5V and analog pins?
2014-05-08T10:17:51.620
<p>Could I connect a device that requires minimum 5V 1A from the 5V Pin to the Ground and somehow turn it off inside a sketch? </p> <p>edit: I'm using a Due based boad, the digix <a href="http://digistump.com/wiki/digix/tutorials/basics" rel="nofollow">http://digistump.com/wiki/digix/tutorials/basics</a></p>
<p>Have you try using a digital potentiometer name AD5220, it let you adjust the resistance with using your hand. You can find more info about it at www.analog.com. I would upload an image of the schematic but i just don't know how.</p>
1463
|arduino-uno|motor|voltage-level|current|
digital pin's current limit, ohm's law and DC motor
2014-05-08T18:42:58.920
<p>A digital pin's output voltage on an UNO board is 5V, which is equal to the output from the VCC. I read that the DC current limits of those pins are 40mA and 200mA respectively, and that a higher current could damage the board. Now, since <strong>V=RI</strong>, I expect to get the same current whether I connect a DC motor to the VCC or to a digital pin. But, the motor spins slower when connected to the digital pin. Therefore, I'm not getting the same current, and the only thing I could think of in order to explain this apparent contradiction with ohm's law is that there must be some mechanism to keep the current flowing through a digital pin inferior to 40mA. But I also read somewhere (can't find/remember the source) that there are no such mechanisms (except for a fuse concerning the USB)... So as you see, I can't understand what's going on. It will be really nice if someone could explain that to me... thanks in advance! </p>
<p>The ATmega (or any other processor that could reasonably be used on an Arduino) output pins consist of a <code>Totem Pole</code> driver with a PMOS transistor which can drive the output towards Vdd and an NMOS transistor which can drive it towards ground. Each of these can be modeled as a switch which has a small resistance when "on", and due to device physics the PMOS transistor has a higher resistance than the NMOS.</p> <p>The 40ma figure is an "Absolute Maximum" rating - a limit above which damage could be possible. At some current less than that, it is likely the voltage drop across the PMOS transistor will start to be great enough that the output voltage can only marginally be considered a logic "high" - it <strong>will be notably less than the supply</strong>. </p> <p>Connecting your motor to an ATmega pin is an extreme, <strong>far out of spec</strong>. When you do that, the voltage drop across the PMOS transistor is much larger, making the output voltage quite low. Additionally, the current flowing through the resistance produces heat within the chip, which can (at least as a rule-of-thumb concern) lead to damage. Finally, your motor will produce <code>inductive kickback</code>, "spike" voltage possibly high enough to pierce the gate oxide of the MOS gates in the chip, destroying it. <code>Latchup</code> is another possibility - a <em>sometimes temporary</em> condition where the bulk of the die ends up biased to conduct in the wrong direction and the chip effectively shorts out its power supply, turning it into a <em>miniature space heater</em>.</p> <p><strong>There really are no components on your typical Arduino board designed to directly control a motor.</strong></p> <p>Instead, for unidirectional control you should use a circuit with an <code>NPN</code> bipolar transistor, <code>NMOS FET</code>, magnetic relay, or solid state relay. The latter are commonly available pre-assembled on shields. With a transistor solution driving the motor in only one direction, it is generally advisable to pick an NPN transistor or NFET and place it in the negative lead of the motor, as the N devices work better due to the greater mobility of electrons than electron-holes.</p> <p>For bidirectional control, look for a <code>motor shield</code> based on an <code>H bridge</code> IC such as the <code>TB6612FNG</code> or the less efficient bipolar <code>L298</code> or <code>L293</code>/<code>SN754410</code>. This basically puts a high current <code>Totem Pole</code> driver on each lead of the motor, allowing you to drive them high &amp; low for one direction or low &amp; high for the other.</p>
1471
|serial|bluetooth|arduino-pro-micro|
Arduino Pro Micro, get data out of Tx pin?
2014-05-08T22:08:00.080
<p>I have a <a href="https://www.sparkfun.com/products/12640" rel="nofollow noreferrer">Sparkfun Arduino Pro Micro with an ATmega32u4 on it</a> and a <a href="https://www.sparkfun.com/products/10253" rel="nofollow noreferrer">Roving Networks RN32 Bluetooth Module</a></p> <p>Theoretically, I should be able to solder the Rx of the Bluetooth to the Tx on the arduino and vice versa and I should get serial communication over the Bluetooth. </p> <p>Of course, I do not. However, as a first question: How do I get my Arduino to transmit data over the Tx pin?</p> <p>I uploaded this to the Arduino with no hiccups: </p> <pre class="lang-cpp prettyprint-override"><code>void setup(){ Serial.begin(9600); } void loop(){ Serial.print("HelloWurld"); } </code></pre> <p>However, when I plug up my o-scope, I see no signal over the Tx line. Nada. I see data coming over the USB into the COM port on my computer, but nothing over the Tx pin.</p> <p>How do I get the Arduino to put out serial data on the Tx pin?</p>
<p>So I stumbled upon this thread while having similar problem, but with HC-05 module. So because I have too much free time on my hands during finals (no I don't) I decided to create a small github repo that might help someone sometime. <a href="https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup" rel="nofollow noreferrer">https://github.com/Sackhorn/HC-05-Pro-Micro-Hookup</a> </p> <p>The code is:</p> <pre><code>//Writen for pro micro //These proved to be usefull //http://arduino.stackexchange.com/questions/1471/arduino-pro-micro-get-data-out-of-tx-pin //https://forum.sparkfun.com/viewtopic.php?f=32&amp;t=38889&amp;sid=8178cdb38005ff33cc380a5da34fb583&amp;start=15 void setup() { pinMode(9, OUTPUT); digitalWrite(9, HIGH); Serial.begin(9600); Serial1.begin(38400); } void loop() { //Serial1 is the physical Serial Connections on TX and RX pins if (Serial1.available()) Serial.write(Serial1.read()); // Serial is from my understanding the virtual connection with computer via USB if (Serial.available()) Serial1.write(Serial.read()); } </code></pre> <p><a href="https://i.stack.imgur.com/kNlx7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kNlx7.png" alt="enter image description here"></a></p>
1472
|arduino-mega|uploading|bootloader|
Can I load programs through the RS232 pins?
2014-05-08T22:14:18.870
<p>Can I upload new programs onto a MEGA2560 through a serial port connected to pins 2&amp;3? (through the correct RS232&lt;->TTL level shifters)</p> <p>I know the 16U2 chip acts as a USB->serial converter and it also asserting the reset which starts the bootloader running on the 2650. Does it do anything else? </p> <p>As long as I can time the reset correctly, is there anything else preventing reprogramming directly through the RX/TX pins?</p> <p>And if I do this, will the application program still be able to use the serial channel?</p>
<p>The stock bootloader will accept the load of new programs on PE0(RX input) and PE1(TX output) (of the ATmega2560) just after reset. Note PE0/1 on the Arduino correspond to pins D0 and D1. Not D2 and D3. You could change the Boot loader if desired.</p> <p>There is a 1K series resistor between the 16U2 and 2560's PE0/1. So you can directly connect your external TTL serial port's TX(out) to PE0(D0), without harm. And correspondingly connect PE1(D1) to the TTL Serial port's RX(in). </p> <p>Next you need to synchronize the bootloader. Either by manually synchronizing the Reset of the 2560 with the starting of the download (of AVRdude). Or by connecting the DTR(out) of the TTL Serial Port through a 100nF capacitor to the RESET pin of the Arduino.</p> <p>I would also recommend putting the 16U2 into reset, to get it out of the way. Simply place a jumper between ICSP1's RESET2(pin5) and GND(pin6). </p>
1475
|arduino-uno|firmware|accelerometer|
Setting up the MMA8452 to trigger interrupt
2014-05-09T09:53:56.413
<p>I am working with the MMA8452q accelerometer by Freescale. I am trying to set it up to be in low power mode, to go to sleep when no motion has happened, and to wake up due to motion being detected and trigger the interrupt that corresponds to it. I am using Arduino.</p> <p>I have verified the accelerometer works (i.e. can read off accelerometer data and communicate properly to it via I2C), and I have also verified that the interrupt and handler all work (by manually triggering the interrupt as compared to using the accelerometer). However, after initializing using the code below, my interrupt due to motion is not getting triggered. </p> <p>-The datasheet can be found here: <a href="http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf" rel="nofollow">http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf</a></p> <p>-App note can be found here: <a href="http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf" rel="nofollow">http://cache.freescale.com/files/sensors/doc/app_note/AN4074.pdf</a></p> <p>My code is as follows:</p> <pre><code>void MMA8452::initMMA8452(unsigned char fsr) { //CONFIGURE THE ACCELEROMETER MMA8452Standby(); // Must be in standby to change registers //Set up the full scale range to 2, 4, or 8g. if ((fsr==2)||(fsr==4)||(fsr==8)) writeRegister(XYZ_DATA_CFG, fsr &gt;&gt; 2); else writeRegister(XYZ_DATA_CFG, 0); writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | bmRES1DOT56); //1.56Hz resolution in both wake and sleep mode (lowest power) writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP &lt;&lt; SMODS) | (LP &lt;&lt; MODS) | (1 &lt;&lt; SLPE)); //LOW POWER MODE IN SLEEP &amp; ACTIVE STATES WITH LOWEST SAMPLING writeRegister(CTRL_REG3, (1 &lt;&lt; WAKE_FF_MT)); //ONLY WAKE UP FROM MOTION DETECTION writeRegister(CTRL_REG4, (1 &lt;&lt; INT_EN_ASLP) | (1 &lt;&lt; INT_EN_FF_MT)); //ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) &amp; MOTION INTERRUPT TO KEEP AWAKE writeRegister(ASLP_COUNT, ASLP_TIMEOUT); //162s TIMEOUT BEFORE SLEEPING writeRegister(CTRL_REG5, (1 &lt;&lt; INT_CFG_FF_MT) | (1 &lt;&lt; INT_CFG_ASLP)); //INTERRUPT SLEEP AND FREE FALL TO INT1 PIN OF MMA8452 //SETUP THE MOTION DETECTION writeRegister(FF_MT_CFG, (1 &lt;&lt; ELE) | (1 &lt;&lt; OAE)); //MOTION DETECTION AND LATCH THE RESULT WHEN IT HAPPENS AS OPPOSED TO COMBINATIONAL REAL TIME writeRegister(FF_MT_THS, MOTION_THRESHOLD); //MOTION DETECTION THRESHOLDS writeRegister(FF_MT_COUNT, MOTION_DEBOUNCE_COUNT); //TIME MOTION NEEDS TO BE PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED MMA8452Active(); }; </code></pre>
<p>I played around more with it, and this code works:</p> <pre><code>void MMA8452::initMMA8452(unsigned char fsr, unsigned char dr, unsigned char sr, unsigned char sc, unsigned char mt, unsigned char mdc) { MMA8452Standby(); //Set up the full scale range to 2, 4, or 8g. if ((fsr==2)||(fsr==4)||(fsr==8)) writeRegister(XYZ_DATA_CFG, fsr &gt;&gt; 2); else writeRegister(XYZ_DATA_CFG, 0); writeRegister(CTRL_REG1, readRegister(CTRL_REG1) &amp; ~(0xF8)); if (dr&lt;= 7) writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (dr &lt;&lt; DR0)); if (sr&lt;=3) writeRegister(CTRL_REG1, readRegister(CTRL_REG1) | (sr &lt;&lt; ASLP_RATE0)); writeRegister(CTRL_REG2, readRegister(CTRL_REG2) | (LP &lt;&lt; SMODS) | (LP &lt;&lt; MODS) | (1 &lt;&lt; SLPE)); //LOW POWER MODE IN SLEEP &amp; ACTIVE STATES WITH LOWEST SAMPLING writeRegister(ASLP_COUNT, sc); // Set up interrupt 1 and 2: 1 = wake ups, 2 = data writeRegister(CTRL_REG3, (1 &lt;&lt; WAKE_FF_MT) | (1 &lt;&lt; IPOL)); // Active high, push-pull interrupts, sleep wake up from motion detection writeRegister(CTRL_REG4, (1 &lt;&lt; INT_EN_ASLP) | (1 &lt;&lt; INT_EN_FF_MT) | (1 &lt;&lt; INT_EN_DRDY)); // DRDY ENABLE SLP/AWAKE INTERRUPT (INTERRUPT THROWN WHENEVER IT CHANGES) &amp; MOTION INTERRUPT TO KEEP AWAKE writeRegister(CTRL_REG5, (1 &lt;&lt; INT_CFG_ASLP) | (1 &lt;&lt; INT_CFG_FF_MT)); // DRDY on INT1, ASLP_WAKE INT2, FF INT2 writeRegister(CTRL_REG5, readRegister(CTRL_REG5)); //SETUP THE MOTION DETECTION writeRegister(FF_MT_CFG, 0xF8); /*MOTION DETECTION AND LATCH THE //RESULT WHEN IT HAPPENS AS OPPOSED //TO COMBINATIONAL REAL TIME*/ writeRegister(FF_MT_THS, mt); //MOTION DETECTION THRESHOLDS writeRegister(FF_MT_COUNT, mdc); //TIME MOTION NEEDS TO BE //PRESENT ABOVE THE THRESHOLD BEFORE INTERRUPT CAN BE ASSERTED MMA8452Active(); } </code></pre>
1477
|arduino-uno|software|reset|
Reset an Arduino Uno in code
2014-05-09T11:57:57.010
<p>Is it possible to reset an Arduino (i.e., to reboot it) from code (i.e from the sketch itself)? I know that is possible with a special circuit but is there a chance to make it just with code?</p> <p>Below is my code and the comment <code>//reset</code> is where I want to force a reset.</p> <pre><code>#include &lt;TrueRandom.h&gt; int i; int randSeed; long randNumber; void setup(){ Serial.begin(9600); Serial.println("20 pseudo Zufallszahlen:"); for (i=1;i&lt;=20;i++) Serial.print(random(10)); Serial.println(); Serial.println(); //randomSeed(TrueRandom.random()); randSeed = analogRead (A0); randomSeed(randSeed); Serial.print("Der 'seed' Wert: "); Serial.println(randSeed); Serial.println(); Serial.println("20 Zufallszahlen mit analogem 'seed' Wert:"); for (i=1;i&lt;=20;i++) Serial.print(random(10)); Serial.println(); Serial.println("---------------------------"); Serial.println(); delay(500); //reset } void loop() { } </code></pre> <p>I want to reset the micro-controller at the end of the setup function to show the effect of random numbers with and without a seed.</p>
<p>In case you have the original Arduino bootloader which you want to execute as a part of the reset, you can do a SW reset by jumping to the bootloader reset address (0x7800 on ATmega328p boards)</p> <pre><code>void reset() { asm volatile (&quot;jmp 0x7800&quot;); } </code></pre> <p>The watchdog reset approach will not work because of a bug in the bootloader. Here's a note from ATmega328P Datasheet page 45:</p> <blockquote> <p>Note: If the watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the watchdog timer will stay enabled. If the code is not set up to handle the watchdog, <strong>this might lead to an eternal loop of time-out resets</strong>. To avoid this situation, the application software should always clear the watchdog system reset flag (WDRF) and the WDE control bit in the initialization routine, even if the watchdog is not in use.</p> </blockquote> <p>This is exactly what <a href="https://arduino.stackexchange.com/q/2922/13327">will happen</a> after a watchdog reset on a system with Arduino bootloader.</p>
1481
|arduino-uno|software|
Formula / calculation of the function random() / randomSeed()
2014-05-09T15:23:22.890
<p>In which file can I find the calculation that is called with <code>random()</code>? If it is not too much could you also post the content in your answer? I am using an Arduino Uno and its standard IDE. </p> <p>I found this in the "WMath.cpp" but that is not the final calculation. </p> <pre class="lang-cpp prettyprint-override"><code>void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall &gt;= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } </code></pre>
<p>Read Peter Bloomfield's answer here: <a href="https://arduino.stackexchange.com/a/1482/7727">https://arduino.stackexchange.com/a/1482/7727</a></p> <p>Then read the following:</p> <p>For everyone's reference, <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/WMath.cpp" rel="nofollow noreferrer">Arduino's WMath.cpp is found here.</a></p> <p><a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__stdlib.html#ga114aeb1751119382aaf3340355b22cfd" rel="nofollow noreferrer">Documentation for AVR-Libc's random() function is here.</a></p> <p><a href="http://download.savannah.gnu.org/releases/avr-libc/" rel="nofollow noreferrer">Source code for AVR-Libc is found here</a>, as linked-to from <a href="http://www.nongnu.org/avr-libc/" rel="nofollow noreferrer">here</a>.</p> <p>I downloaded "avr-libc-2.0.0.tar.bz2.sig 08-Feb-2016" and extracted it. Like Peter said, the source code for "random" is in "<strong>avr-libc-2.0.0\libc\stdlib\random.c</strong>"</p> <p>To save you the hassle, here's the source code, with their included copyright and license statement right at the top of it.</p> <pre><code>/*- * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * Posix rand_r function added May 1999 by Wes Peters &lt;wes@softweyr.com&gt;. * * $Id: random.c 1944 2009-04-01 23:12:20Z arcanum $ */ /* * From: static char sccsid[] = "@(#)rand.c 8.1 (Berkeley) 6/14/93"; */ #include &lt;stdlib.h&gt; #include "sectionname.h" ATTRIBUTE_CLIB_SECTION static long do_random(unsigned long *ctx) { /* * Compute x = (7^5 * x) mod (2^31 - 1) * wihout overflowing 31 bits: * (2^31 - 1) = 127773 * (7^5) + 2836 * From "Random number generators: good ones are hard to find", * Park and Miller, Communications of the ACM, vol. 31, no. 10, * October 1988, p. 1195. */ long hi, lo, x; x = *ctx; /* Can't be initialized with 0, so use another value. */ if (x == 0) x = 123459876L; hi = x / 127773L; lo = x % 127773L; x = 16807L * lo - 2836L * hi; if (x &lt; 0) x += 0x7fffffffL; return ((*ctx = x) % ((unsigned long)RANDOM_MAX + 1)); } ATTRIBUTE_CLIB_SECTION long random_r(unsigned long *ctx) { return do_random(ctx); } static unsigned long next = 1; ATTRIBUTE_CLIB_SECTION long random(void) { return do_random(&amp;next); } ATTRIBUTE_CLIB_SECTION void srandom(unsigned long seed) { next = seed; } </code></pre>
1484
|programming|c++|
Allocate object memory statically; intialize it dynamically?
2014-05-09T20:55:08.513
<p>I have an object whose constructor gets passed a parameter. If I know the parameter value at compile time, I can construct the object statically:</p> <p><code>static FOOOBJ foo(3);</code></p> <p>(I understand that it isn't really done statically, i.e. by the compiler, but is actually done during setup).</p> <p>But if I don't know the parameter value at compile time, I'd still like to pre-allocate space for the object but construct the object in that space at run time. Can it be done without a separate <code>.initialize()</code> method? </p>
<p>Using an <code>initialize()</code> method to a class is contrary to the principle of a class constructor, i.e. once a class instance has been <strong>constructed</strong>, it should be "<strong>ready to use</strong>".</p> <p>As suggested by Ignacio's answer, C++ placement syntax is much better for your purpose.</p> <p>However, with Arduino libraries, placement syntax is not supported "out of the box", so you have to implement it yourself; don't fear, that is quite straightforward:</p> <pre><code>void* operator new(size_t size, void* ptr) { return ptr; } </code></pre> <p>Placement syntax can be a complex beast in C++, but for your specific purpose, its usage can be rather simple:</p> <pre><code>static char buffer[sizeof FOOOBJ]; static FOOOBJ* foo; void setup() { ... foo = new (buffer) FOOOBJ(3); ... } </code></pre> <p>The difference with your current code is that <code>foo</code> is now a pointer, hence any method call will use <code>-&gt;</code> instead of <code>.</code>.</p> <p>If you absolutely want to keep using <code>foo</code> as an instance and not a pointer, then you can do it (but I don't advise it as explained later) by using a <strong>reference</strong> instead:</p> <pre><code>static char buffer[sizeof FOOOBJ]; static FOOOBJ&amp; foo = *((FOOOBJ*) buffer); void setup() { ... new (buffer) FOOOBJ(3); ... } </code></pre> <p>The problem with this code, is that you cannot know if <code>foo</code> has already been constructed with a real <code>FOOOBJ</code> instance or not; using a pointer, you can always check if it is <code>0</code> or not.</p> <p>Using placement syntax, you must be aware that you cannot <code>delete</code> the <code>foo</code> instance above. If you want to destroy <code>foo</code> (i.e. ensure that its destructor is called), then you have to explicitly call the destructor:</p> <pre><code>foo-&gt;~FOOOBJ(); </code></pre>
1491
|arduino-uno|
Solar Tracker Code - how to limit steppers to max & min angle?
2014-05-10T14:08:24.387
<p>a couple of friends and i are working on a double axis solar tracker with a Adafruit Motor-shield V2 and 2x Adafruit bipolar stepper motors (200/rev). We got the following code so far but are stuck with getting the steppers to stop at a certain angle (90° for vertical and 180° for horizontal) so that we dont tangle up the wires and avoid unnecessary movement. Any help and sugestions would be much appreciated. </p> <p>Cheers</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_MotorShield.h&gt; #include "utility/Adafruit_PWMServoDriver.h" Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_StepperMotor *stepperh = AFMS.getStepper(200, 1); // declaring horizontal stepper Adafruit_StepperMotor *stepperv = AFMS.getStepper(200, 2); // declaring vertical stepper int ldr1 = A0; // right ldr int ldr2 = A1; // centre ldr int ldr3 = A2; // left ldr int ldr4 = A3; // top ldr int ldr5 = A4; // bottom ldr const int threshold = 550; // limit to stop tracker from moving at night const int tol = 50; // tolerance for ldrs // maybe vertical AND horizontal depending on difference? //int = countv //int = counth //const int maxh = ? // to prevent overturning horizontal (50 steps = 90°) //const int minh = ? // combine with count int's // i.e. if counth &gt; 90 - stop //const int maxv = ? // to prevent overturning vertical //const int minv = ? void setup() { AFMS.begin(); stepperv-&gt;setSpeed(10); stepperh-&gt;setSpeed(10); } void loop() { int right = analogRead(ldr1); int centre = analogRead(ldr2); int left = analogRead(ldr3); int up = analogRead(ldr4); int down = analogRead(ldr5); //STOP MOVEMENT// if ((left &lt; threshold) &amp;&amp; (right &lt; threshold) &amp;&amp; (up &lt; threshold) &amp;&amp; (down &lt; threshold)) {} // stop any movement if sensor values below threshold // at begining to check after every sensor reading //HORIZONTAL MOVEMENT// if((right &gt; centre + tol) &amp;&amp; (left + tol &lt; centre)) // &amp;&amp; (right - ? &gt; tol) { stepperh-&gt;onestep(BACKWARD,DOUBLE); // add +1 to int counth // if (minh &lt; counth &lt; maxh) - move // else - stop // counth=counth++ , counth=counth-- } else if((left &gt; centre + tol) &amp;&amp; (right + tol &lt; centre)) // &amp;&amp; (left - ? &gt; tol) { stepperh-&gt;onestep(FORWARD,DOUBLE); } else {} // do nothing //VERTICAL MOVEMENT// if((up &gt; centre + tol) &amp;&amp; (down + tol &lt; centre)) // &amp;&amp; (up - ? &gt; tol) { stepperv-&gt;onestep(BACKWARD,DOUBLE); } else if((down + tol &gt; centre) &amp;&amp; (up + tol &lt; centre)) // &amp;&amp; (down - ? &gt; tol) { stepperv-&gt;onestep(FORWARD,DOUBLE); } else{} // do nothing } </code></pre>
<p>Stepper motors are nice and all but they actually make less than adequate servos for this purpose. the best way that I can see is with linear actuators that have position sensors in them and feed the Voltage divider outputs from those sensors to the Atmega chip. If you write the code to compare the signals from the light detectors with the voltage from the pos sensors it should be a lot better. Also, limit switches should be used in this arrangement too. They would be as a fail safe. The other benefit is that linear actuators usually hold a lot better without loosing their position due to outside stresses. Steppers can be used for prototyping, but it would still be better to start with small servos with sensors and get the system working first. I myself am trying to get a working system and I am having troubles with the coding also, but I am not good at coding. One other thing, I have looked at a lot of different codes to find something that might help me with my project and I have seen this. Stepper motor systems are written with minimal code which as I see it leaves room for much error. Atmega has plenty of room for code storage and plenty of ports for sensors in this use. Everyone knows that old phrase keep it simple but some times that is not always the best advice. You are working with something that needs to be somewhat complicated, to be less likely to fail. The more engineering you put into something the more likely something is to go wrong but less engineering gives you the same results. So consider all the posibilities and address them. Adding components and sub systems will in the end make your work better. </p>
1493
|power|battery|
Using multiple laptop battery packs to power everything
2014-05-10T16:57:49.153
<p>I'm working on a medium sized robot project with multiple arduinos to control stuff. I've been planning on using a lead-acid battery pack, but then I was given 10 working and identical Asus laptop battery packs rated at 14.8 V 4400 mAh, and one old Asus laptop.</p> <p>I opened up one of the battery packs, because it was bad and it has a 4S2P battery configuration and a protection board.</p> <p>Can I hook all of these battery packs in parallel, or will power leak between the battery packs, and is that be a problem?</p> <p>Is there alternatively some 4S20P or 3S25P battery pack with charger I can purchase to put these batteries in?</p> <p>(I do have a step-down converter that will provide the Arduinos with the right voltage, regardless of input voltage up to 36 V)</p> <p>I tried to ask a similar question on electrical engineering, but ot was deemed off topic for the site.</p>
<p>In case you didn't know it already you can hook any batteries in parallel by adding a diode on every battery to avoid current from any other battery flowing back to it. Like this:</p> <pre><code> battery |+ diode +----||---&gt;|---+ | | | | | | |+ | +----||---&gt;|---+----o V++ | | | _ V GND </code></pre> <p><strong>The drawback</strong> is that you have a small drop of voltage on the diodes and of course a small power loss too. If for example you're drawing 0.5 Amp from the batteries and you're using an 1N4001 diode which has a voltage drop of about 0.7 Volts then expect 0.350 Watts of power loss (0.5A x 0.7V). So choose the diode with the lowest voltage drop that can handle the current you need. There are solutions to lower the power that is wasted but they're more complex.</p>
1501
|arduino-uno|shields|motor|
Adafruit motor shield + Adafruit stepper not working
2014-05-12T01:21:59.547
<p>I have the Adafruit Motor Shield V2 and an <a href="https://www.adafruit.com/product/858" rel="nofollow noreferrer">Adafruit stepper motor</a>. I have not soldered the shield onto the Arduino (which is an Uno) yet because I don't want to make anything permanent yet. I have the Arduino plugged into a DC wall adapter and have the VIN jumper in the shield, and the green power light on the shield is lit. This is how the stepper is connected. <img src="https://i.stack.imgur.com/LPtx3.jpg" alt="setup"></p> <p>As you can see in the picture, all the wires from the stepper are plugged in. The order of the wires is what it says it should be on the <a href="https://www.adafruit.com/product/858" rel="nofollow noreferrer">website</a>, which is <code>orange-pink-red-blue-yellow</code>. My sketch's code is an adapted version of the StepperExample from the Adafruit motor library. Here's the full code</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_MotorShield.h&gt; #include "utility/Adafruit_PWMServoDriver.h" Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_StepperMotor *myMotor = AFMS.getStepper(513, 2); void setup() { Serial.begin(9600); Serial.println("Stepper test!"); AFMS.begin(); myMotor-&gt;setSpeed(5); } void loop() { myMotor-&gt;step(100, FORWARD, SINGLE); } </code></pre> <p>But the stepper still doesn't move. Can anyone point out what I'm doing wrong here?</p>
<p>As far as I know, you have to solder the header pins. Here is a nice video demonstrating the assembly: <a href="http://www.youtube.com/watch?v=yt-SEOZT-hI" rel="nofollow">Motorshield V2 assembly</a></p>
1508
|arduino-uno|programming|string|
Convert a Bitstring into an integer value
2014-05-12T18:31:24.423
<p>I have got a String filled up with 0 and 1 and would like to get an Integer out of it:</p> <pre><code>String bitString = ""; int Number; int tmp; bitString = ""; for (i=1;i&lt;=10;i++) { tmp= analogRead (A0); bitString += tmp % 2; delay(50); } // now bitString contains for example "10100110" // Number = bitstring to int &lt;------------- // In the end I want that the variable Number contains the integer 166 </code></pre>
<p>If you only need the string for printing you can store value in an integer and then use the <a href="http://arduino.cc/en/Serial/Print">Serial.print(number,BIN)</a> function to format the output as a binary value. Appending integers to strings is a potentially costly operation both in performance and memory usage.</p> <pre><code>int Number = 0; int tmp; for (int i=9;i&gt;=0;i--) { tmp = analogRead (A0); Number += (tmp % 2) &lt;&lt; i; delay(50); } Serial.print(Number, BIN); </code></pre>
1513
|arduino-uno|led|resistor|
Use Higher Resistance Than Instructed in a Circuit
2014-05-12T21:03:41.750
<p>I'm following the "Get Started with Arduino" Guidebook, and I'm at the part where pulse width modulation (PWM) is discussed. </p> <p>The instructions say to create a simple circuit with a breadboard, red LED, arduino (connected at pin 9 and ground) and a 270 ohm resistor. My power source will be the usb connection.</p> <p>I have a 510 ohm resistor. </p> <ol> <li>May I use it instead? </li> <li>In general, will using a resistor with a higher resistance than intended in a circuit fry the arduino?</li> </ol> <p>Thanks very much for your help. I'm new to arduino and electronic circuits. I have a Uno R3.</p>
<p>If the resistor is in series w the LED, it'll just be about half as bright when you use 510 vs 270 ohms. I=E/R and all -> half the current. Your PWM will still work, but starting from a lesser brightness on down.</p>
1519
|hardware|
Looking for a protocol, any hints?
2014-05-13T14:39:53.843
<p>I am looking for a multi-purpose wire protocol for Arduino.</p> <p>Requirements:</p> <ol> <li>Range of at least 500ft (200m)</li> <li>No shield required</li> <li>Able to communicate between Arduino and Raspberry Pi</li> <li>Be able to run "point-to-multipoint"</li> </ol>
<p>There is nothing that will work given those constraints.</p> <p>You only have low power 5V signals on the Arduino which won't handle your distance requirements.</p> <p>You could look into <a href="http://en.wikipedia.org/wiki/RS-485" rel="nofollow">RS-485</a> using a <a href="https://www.sparkfun.com/products/11959" rel="nofollow">shield</a> on the arduino side and a <a href="https://www.sparkfun.com/products/10124" rel="nofollow">breakout board</a> on the Raspberry Pi.</p>
1521
|arduino-uno|power|
DC-DC converter with Arduino not working
2014-05-13T15:38:30.957
<p>I've got a program running on the Arduino that is supposed to turn on and off a pump. currently, I am outputting the reads of the components that need to be read and it shows when the port (port 13) is supposed to turn on and when it's supposed to turn off. When I use a multimeter between the port 13 and ground, everything works as expected.</p> <p>When I start the program and the port is off, I get a reading of 0.03v @20v max (to be more precise, I get 14.0 at 200mV) - Shouldn't this be zero? or is there always going to be some electricity flowing?</p> <p>When the port is turned on: <code>digitalWrite(airPump, HIGH);</code> (and yes, airPump is set to 13), the voltage reads between 4.0 and 4.51 with spikes down to 3.65 on my multimeter set at 20v max. is it ever stable? (pictured below) <img src="https://i.stack.imgur.com/Hybdk.jpg" alt="enter image description here"></p> <p>So, the main question is: I'm supposed to be sending the power from port 13 to a DC-DC converter. I tested the converter on a separate bread board just by itself. I used a DC power supply and set it to 4.5v, then ran the power through the vIn, grounded the ground pin and ran the vOut to the multimeter (then to ground with the multimeter) and I got it set to output only 2.5v with a constant 4.5 running into it. (pictured below) <img src="https://i.stack.imgur.com/ekznO.jpg" alt="enter image description here"></p> <p>I also tested whether or not changing the voltage input would change the output at all and it seems it does not, from 1.5-15v, the converter stays steady at 2.5v</p> <p>Now when I do the exact same set up on the arduino with the power from port 13 running into the voltage in on the DC-DC converter, it gives me a reading of 0.01v. Any idea why this is happening? <img src="https://i.stack.imgur.com/rWelz.jpg" alt="enter image description here"></p> <p>I've checked probably over 30 times and rearranged everything just as many, but nothing seems to help. I can't get a stable 2.5V output from the converter with the arduino...</p> <p>UPDATE: Below is a simple wiring diagram: <img src="https://i.stack.imgur.com/rBXeK.png" alt="enter image description here"></p> <p>The image shows what it is supposed to do, but for testing purposes I made it so if the rH is higher than average (I just breath on it) then the pump will turn on.</p>
<p>The arduino output pin cannot provide enough current to drive the pump. The DC-DC converter is not designed for this use.</p> <p>You need external power supply with enough current to drive the motor that you switch on and off with the arduino output pin. </p> <p>Search for "Arduino 3V DC motor control" for examples of how to do this, there are many options.</p>
1523
|battery|software|
Measure LiPo / Li-Ion SOC or the ever standing question of how much juice is remaining in my battery?
2014-05-13T19:09:09.237
<p>So I have a project in which an arduino runs on a two cell LiPo battery and I need a fast, straight forward way to determine remaining battery charge (with an accuracy of 10% so I only have a readout with 10 LEDs on it) without using any major extra components (so using an external battery charge meter IC is cheating :P). How should I go about this?</p> <p>(using arduino mini, LiPo is two cells: 7,4V 150mAh)</p>
<p>If you are using a single cell, then the <a href="https://www.sparkfun.com/products/10617" rel="nofollow">Fuel gauge</a> from Sparkfun would be great. Instead of reading analog values manually it sends the battery level via I2C.</p>
1530
|programming|pins|arduino-leonardo|
portd not writing on digital ports 5 and 7
2014-05-14T07:32:24.333
<p>I try to build a function generator (preferably a sine) with an <a href="http://www.auctoris.co.uk/2011/05/25/arduino-function-generator-part-2/" rel="nofollow">R-2R ladder</a> and a <a href="https://www.indiegogo.com/projects/9-arduino-compatible-starter-kit-anyone-can-learn-electronics" rel="nofollow">Arduino Leonardo by Borderless Electronics</a>.</p> <p>For performance reasons one should use <code>portd</code> instead of <code>digitalWrite</code>. However the signal is not at all what I want (just noise). So upon further investigation I found that the digital pins were never on <code>HIGH</code>. Pin 6 worked flawlessly. Furthermore I have tested the two failing pins with simple test programms and they behaved exactly as I would have expected.</p> <p>Here is the code I use</p> <pre><code> int sine[255]; void setup() { pinMode(0, OUTPUT); pinMode(1, OUTPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, OUTPUT); float x; float y; for(int i=0;i&lt;255;i++) { x=(float)i; y=sin((x/255)*2*PI); sine[i]=int(y*128)+128; } } void loop() { for (int i=0;i&lt;255;i++) { PORTD=sine[i]; delayMicroseconds(10); } } </code></pre> <p>I tested this with two Arduinos of the exactly same type.</p> <p><strong>Question:</strong> Why are pins 5 and 7 never on <code>HIGH</code>?</p> <p><strong>Edit:</strong> I have simplified everything down to one statement in the loop: <code>portd = x;</code></p> <p>I vary x manually</p> <p><strong>expected</strong> findings:</p> <p>x -> #pin that is on high</p> <p>0 -> None</p> <p>1 -> 0</p> <p>2 -> 1</p> <p>4 -> 2</p> <p>8 -> 3</p> <p>...</p> <p>128 -> 7</p> <p><strong>actual</strong> findings</p> <p>x -> #pin that is on high</p> <p>0 -> None</p> <p>1 -> 3</p> <p>2 -> 2</p> <p>4 -> 0</p> <p>8 -> 1</p> <p>16 -> 4</p> <p>32 -> None</p> <p>64 -> None</p> <p>128-> 6</p> <p>I test this by simply connecting an oscilloscope to the output pins. The behaviour is extremely strange since the pins seem to be in random order, some even missing to <code>portd</code>. Furthermore <code>portd = B11111111</code>, according to the manual, is equivalent to <code>portd = 255;</code> and should set all pins on <code>HIGH</code>. But in my case it sets every pin to <code>HIGH</code>, except pins 5 and 7 are on <code>LOW</code>.</p>
<p>As @jfpoilpret points out, Arduino pins are not always mapped to port bits in a straightforward manner, and it’s crucial to understand the mapping for your particular model.</p> <p>In fact, the Arduino Leonardo is designed in a way that <strong>none</strong> of the ports has all 8 bits usable as I/O pins. As far as the microcontroller is concerned, ports B and D each have all 8 bits available, but the Arduino Leonardo/Micro design uses one bit on each port for a LED.</p> <p>I would also recommend that if you’re using a PORTx register directly, instead of going through the Arduino API, that you also use the DDRx register to set pin directions, instead of trying to use <code>pinMode</code>.</p>
1534
|arduino-yun|
How many total digital pin outs does the Arduino Yun have
2014-05-14T10:58:06.223
<p>I have read the details on the products page for Arduino Yun but I have also read, on a Arduino forum, that there are only 18 digital pins because of Tx, and Rx. Is this true? I am not worried about the PWM, or analog capabilities of the pins, just purely digital.</p>
<p>According to the official specification, it has 20 digital IO pins which can be used with <code>digitalRead()</code> and <code>digitalWrite()</code> etc.. As is typical on Arduino boards though, pins 0 and 1 <em>also</em> act as serial Rx and Tx (respectively).</p> <p>You can program it to use them for either purpose.</p> <p>The information you read might be referring to problems with uploading though. If you have something physically connected to pin 0 and/or 1, then you may have to disconnect it while you do an upload, otherwise it can interfere with the communication between your computer and the microcontroller.</p> <p>If you're doing a lot of tinkering, then sometimes it's simply easier to avoid using pins 0 and 1 altogether, meaning you'd only have 18 IO pins left.</p>
1541
|serial|
Connecting Nokia 106 to Arduino
2014-05-15T03:02:07.257
<p>I was wondering if this can be done. I got a Nokia 106 and am trying to make it talk, but the audio jack doesn't seem to cooperate and the Fbus pins are right under the SIM slot, which is right under the battery. Any advice?</p> <p>Added: It seems that it talks AT commands, since it is a GSM model, but I'm not 100% positive.</p>
<p>just trim the actual simcard, so its level with 'microsim insert' back edge. Its what i did on my Nokia 100/GPO 746 project, works fine, wont kill the phone</p>
1542
|arduino-uno|gsm|web-server|
Unable to read text file from server
2014-05-15T11:53:28.683
<p>I saw the <a href="http://arduino.cc/en/Tutorial/GSMExamplesWebClient" rel="nofollow">Web client Example </a> , In the example, the server connection is initialized in <code>setup()</code>. But I want the server to update the text file every time. So, I need the server connection to be in <code>loop()</code>. </p> <p>But, it is not working. Where is the problem in my code.</p> <pre><code>#include &lt;GSM.h&gt; #define PINNUMBER "" // APN data #define GPRS_APN "GPRS_APN" // replace your GPRS APN #define GPRS_LOGIN "login" // replace with your GPRS login #define GPRS_PASSWORD "password" // replace with your GPRS password // initialize the library instance GSMClient client; GPRS gprs; GSM gsmAccess; // URL, path &amp; port (for example: arduino.cc) char server[] = "yourdomain.com"; char path[] = "/current.txt"; int port = 80; // port 80 is the default for HTTP void setup() { // initialize serial communications and wait for port to open: Serial.begin(9600); Serial.println("SMS connected"); // connection state boolean notConnected = true; // After starting the modem with GSM.begin() // attach the shield to the GPRS network with the APN, login and password while(notConnected) { if((gsmAccess.begin(PINNUMBER)==GSM_READY) &amp; (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD)==GPRS_READY)) notConnected = false; else { Serial.println("Not connected"); delay(1000); } } Serial.println("GPRS connected..."); Serial.println(" Connecting to Server "); } void loop() { if (client.connect(server, port)) { client.print("GET /current.txt"); Serial.print("GET /current.txt"); client.println(" HTTP/1.1"); Serial.println(" HTTP/1.1"); client.println("Host: www.yourdomain.com"); Serial.println("Host: www.yourdomain.com"); client.println("User-Agent: Arduino"); Serial.println("User-Agent: Arduino"); client.println("Accept: text/html"); Serial.println("Accept: text/html"); client.println("Connection: close"); Serial.println("Connection: close"); client.println(); Serial.println(); Serial.println("\nCOMPLETE!\n"); //client.stop(); } else { Serial.println("connection failed"); Serial.println("\n FAILED!\n"); } if (client.available()) { char c = client.read(); Serial.print(c); } else { Serial.println(); Serial.println("disconnecting."); client.stop(); } } </code></pre>
<p>Its working as long as the connection doesn't break or the server doesn't stall. We must wait till the response . </p> <pre><code>while (client.connected()) { while(client.available()) { char ch = client.read(); Serial.print(ch); } } client.stop(); </code></pre>
1543
|arduino-uno|serial|
Can a PC connect to an Arduino for serial communication without installing the entire dev kit?
2014-05-15T12:54:20.937
<p>I'd like to send a prototype board to a friend pre-programmed and wired. Ideally they should just need to plug in the USB and connect to it over a serial COM port. </p> <p>With another laptop I used for testing I had to install the full dev kit, sketch editor and all to get it working.</p> <p>Can I somehow send just the portion of the kit that provides the COM drivers and not the rest? Is there a prebuilt install for just that portion?</p>
<p>On Windows in <code>C:\Program Files\Arduino</code> there is a folder called <code>drivers</code>, which contains all the drivers for the Arduino boards. I think that's what you are looking for.</p>
1550
|arduino-mega|
What is the circular gold pad on arduino mega 2560 v2 and above?
2014-05-15T17:20:35.320
<p>Could someone point me to the documentation that describes the gold dot and surrounding gold circle on the front of my arduino mega v2 board. It is right above the ICSP header and reset button, and directly underneath the letter 'U' in the silk screened word 'communication' I've not been able to find any reference to it anywhere. Is is a jumper, a test pad, RF pad??? </p>
<p>To add to Chris's answer: fiducials appear at three levels. First there are fiducials at the panel level, which contains one or more PCBs, depending on their size. Next there are fiducials for the PCB, acting as a position reference for component placement. Sometimes you can see component fiducials close to some fine pitch components, to make sure they are placed with high precision. You'll sometimes see these latter fiducials on opposite corners of QFP (Quad Flat Package) parts. (The AVR controller on the Arduino Mega 2560 is in QFP.)</p>
1556
|arduino-uno|programming|timers|
Timer1 stops firing
2014-05-16T18:39:28.903
<p>I am trying to use interrupts to play notes on a speaker. Timer2 works fine, but after about 15 seconds, Timer1 stops firing for about 5 seconds, and then it comes back on. If I keep running the sketch, it will stop and resume every now and then.</p> <p>Here is my code:</p> <pre><code>#define SPEAKER1 8 #define SPEAKER2 7 volatile bool swap1; volatile bool swap2; ISR(TIMER1_COMPA_vect) { digitalWrite(SPEAKER1, swap1); swap1 = !swap1; } ISR(TIMER2_COMPA_vect) { digitalWrite(SPEAKER2, swap2); swap2 = !swap2; } void playNote1(unsigned note) { //Play a note on Timer1. uint8_t oldSREG = SREG; cli(); bitSet(TCCR1B, CS10); bitSet(TCCR1B, CS12); unsigned ticks = (16000000 / 1024) / (note); ticks /= 2; OCR1A = (ticks &lt;= 65535 ? ticks : 65535); SREG = oldSREG; } void playNote2(unsigned note) { //Play a note on Timer2. uint8_t oldSREG = SREG; cli(); bitSet(TCCR2B, CS20); bitSet(TCCR2B, CS21); bitSet(TCCR2B, CS22); unsigned ticks = (16000000 / 1024) / (note); ticks /= 2; OCR2A = (ticks &lt;= 255 ? ticks : 255); SREG = oldSREG; } void stopNote1() { //Stop playing a note on Timer1. uint8_t oldSREG = SREG; cli(); bitClear(TCCR1B, CS10); bitClear(TCCR1B, CS12); SREG = oldSREG; } void stopNote2() { //Stop playing a note on Timer2. uint8_t oldSREG = SREG; cli(); bitClear(TCCR2B, CS20); bitClear(TCCR2B, CS21); bitClear(TCCR2B, CS22); SREG = oldSREG; } void setup() { pinMode(SPEAKER1, OUTPUT); pinMode(SPEAKER2, OUTPUT); pinMode(13, OUTPUT); // initialize timers cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B // turn on CTC mode: bitSet(TCCR1B, WGM12); bitSet(TIMSK1, OCIE1A); TCCR2A = 0; // set entire TCCR2A register to 0 TCCR2B = 0; // same for TCCR2B // turn on CTC mode: bitSet(TCCR2A, WGM21); bitSet(TIMSK2, OCIE2A); sei(); // enable global interrupts } void loop() { playNote1(523); delay(1000); stopNote1(); delay(500); playNote1(131); delay(2000); stopNote1(); delay(500); } </code></pre>
<p>The problem you have is that <strong>you never reset Timer1 counter (<code>TCNT1</code>) when you stop a note and then play another one</strong>.</p> <p>Also, changing the clock divider selection to "<em>no clock</em>" by clearing bits <strong>CS10</strong> and <strong>CS12</strong> as you do is not the most effective way to stop the timer; in fact, rather than stopping it, you can let it run but just <strong>disable its interrupts</strong>.</p> <p>I have modified your program and this worked correctly:</p> <pre><code>#define SPEAKER1 8 volatile bool swap1; ISR(TIMER1_COMPA_vect) { digitalWrite(SPEAKER1, swap1); swap1 = !swap1; } void playNote1(unsigned note) { //Play a note on Timer1. uint8_t oldSREG = SREG; cli(); unsigned ticks = (16000000 / 1024) / (note); ticks /= 2; OCR1A = (ticks &lt;= 65535 ? ticks : 65535); TCNT1 = 0; bitSet(TIMSK1, OCIE1A); SREG = oldSREG; } void stopNote1() { //Stop playing a note on Timer1. uint8_t oldSREG = SREG; cli(); bitClear(TIMSK1, OCIE1A); SREG = oldSREG; } void setup() { pinMode(SPEAKER1, OUTPUT); pinMode(13, OUTPUT); // initialize timers cli(); // disable global interrupts TCCR1A = 0; // set entire TCCR1A register to 0 TCCR1B = 0; // same for TCCR1B TCCR1C = 0; // same for TCCR1C // Set clock divider bitSet(TCCR1B, CS10); bitSet(TCCR1B, CS12); // turn on CTC mode: bitSet(TCCR1B, WGM12); bitClear(TIMSK1, OCIE1A); sei(); // enable global interrupts } void loop() { playNote1(523); delay(1000); stopNote1(); delay(500); playNote1(131); delay(2000); stopNote1(); delay(500); } </code></pre> <p>Note that I have removed all code for Timer2 as it does not play any role in the initial problem.</p> <p>The important changes are:</p> <ol> <li><code>setup()</code> now performs Timer1 setup completely (CTC mode, clock divider); note that I also included <strong>TCCR1C</strong> to ensure full setup (it is preferrable as Arduino libraries may have initialized it differently before <code>setup()</code> is called); it also ensures Timer1 interrupts are initially disabled.</li> <li><code>playNote1</code> now clears <code>TCNT1</code> <strong>and then</strong> enable Timer1 interrupt for <code>TIMER1_COMPA_vect</code></li> <li><code>stopNote1()</code> just disables Timer1 interrupt for <code>TIMER1_COMPA_vect</code></li> </ol> <p>To be complete, you would also want to limit <strong>useless consumption</strong> on output <strong>pin 8</strong>, thus stopping a note should also force its output level to <code>LOW</code> (or <code>HIGH</code> depending on your actual circuit behind, but <code>LOW</code> is more likely):</p> <pre><code>void stopNote1() { //Stop playing a note on Timer1. uint8_t oldSREG = SREG; cli(); bitClear(TIMSK1, OCIE1A); swap1 = false; SREG = oldSREG; digitalWrite(SPEAKER1, LOW); } </code></pre> <h3>Now what about your code for Timer2, the code is the same, so why does it work?</h3> <p>Actually it doesn't :-)</p> <p>But you can't hear the difference between Timer2 is an 8-bit counter so if you don't reset it, then it won't take long until it reaches 255 and resets to 0, so only the first wave phase will be wrong but your hear won't notice that...</p> <p>So <strong>you should also modify the code for Timer2</strong> to make it correct.</p>
1563
|arduino-uno|pins|
To connect a simple toy circuit and trigger with an arduino?
2014-05-17T04:38:57.007
<p>I have a small circuit from a toy sword that has an LED and a small speaker. It was powered by a couple of small coin cells.</p> <p>I am trying to figure out how to connect it to my Arduino so I can trigger it. If I attached the circuit directly to the GND and +3.3V and press the switch in it I get the sound of a sword and flashing LED as desired.</p> <p>Now I want to somehow get the Arduino to trigger the circuit but am very new to Arduino and quite unsure of how to approach this.</p> <p>Can anyone advise how best to work with an existing low power circuit that can use the Arduino's power rails but needs the switch integrated?</p> <p>Sorry for the noob question.</p>
<p>You'll probably want to use a transistor to switch it on/off. You <em>could</em> just use the Arduino's digital pin but they can only supply a limited amount of current. Transistors can work with larger currents. The Arduino switches the transistor and it powers the external circuit.</p> <p>There are a couple of existing questions that may help you.</p> <ul> <li><a href="https://arduino.stackexchange.com/questions/508/how-to-switch-an-external-circuit-with-arduino">How to switch an external circuit with Arduino?</a></li> <li><a href="https://arduino.stackexchange.com/questions/403/how-can-higher-current-devices-motors-solenoids-lights-etc-be-controlled-b">How can higher current devices (motors, solenoids, lights, etc.) be controlled by an Arduino?</a></li> </ul> <p><a href="https://arduino.stackexchange.com/a/509/11">jippie's answer</a> in the first link shows an example schematic for hooking up a transistor with a bunch of LEDs but you would replace them with your own circuit:</p> <p><img src="https://i.stack.imgur.com/8zae1.png" alt="enter image description here"></p>
1569
|arduino-uno|serial|
What is Serial.begin(9600)?
2014-05-17T20:48:05.950
<p>I know that this is to initialize something:</p> <pre><code>Serial.begin(9600); </code></pre> <p>But I want to know what it really means? </p>
<p>;TLDR; It initializes the serial communication port and sets the baud rate. The device you're communicating with (or Arduino IDE Serial Monitor) have to be set to a matching baud rate. Once you've initialized the port you can begin sending or receiving characters. <a href="https://www.arduino.cc/en/Reference/Serial" rel="nofollow">Arduino Serial Reference</a></p>
1574
|c++|library|led|class|
Initialize a "Matrix" object in my own library?
2014-05-18T17:37:48.883
<p>So, I'm trying to make a custom library to drive a 8x8 Bi-Color LED Matrix from 2 MAX7219's that incorporates two "Matrix" objects from the "Matrix" library and I cannot, for the life of me, figure out how to initialize them in my class. Can someone help me? By the way, I have been programming for 8 years, and consequently have a decent knowledge of the topic! Here is my current code:</p> <p>header file</p> <pre><code>#include "Arduino.h" #include "Matrix.h" #include "Sprite.h" class ZackBiColorMatrix{ public: ZackBiColorMatrix(byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG); Matrix r; Matrix g; void setLED(byte col, byte row, byte val, char color); void writeSprite(byte x, byte y, Sprite sp, char color); private: byte redData; byte redLoad; byte redClock; byte greenData; byte greenLoad; byte greenClock; }; </code></pre> <p>and the .cpp file:</p> <pre><code>#include "Arduino.h" #include "Sprite.h" #include "Matrix.h" #include "ZackBiColorMatrix.h" ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) { redData = dataR; redLoad = loadR; redClock = clockR; greenData = dataG; greenLoad = loadG; greenClock = clockG; r = Matrix (redData, redClock, redLoad); g = Matrix (greenData, greenClock, greenLoad); } void ZackBiColorMatrix::setLED (byte col, byte row, byte val, char color) { if (color == 'g') { g.write (col, row, val); } else if (color == 'r') { r.write (col, row, val); } } void ZackBiColorMatrix::writeSprite (byte x, byte y, Sprite sp, char color) { if (color == 'g') { g.write (x, y, sp); } else if (color == 'r') { r.write (x, y, sp); } } </code></pre> <p>Also, I use the Eclipse Arduino IDE if that matters.</p>
<p>This is a C++ question actually.</p> <p>In C++, you initialize class members in the class constructor definition by using a "<a href="http://en.cppreference.com/w/cpp/language/initializer_list" rel="nofollow">member intialization list</a>" as follows for your example:</p> <pre><code>ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) : r(dataR, clockR, loadR), g(dataG, clockG, loadG) { ... Additional initialization here } </code></pre> <p>This is a special C++ construct (note the colon <code>:</code> after the constructor declaration but before its implementation).</p> <p>Also note that, in your example, I think you don't need to declare <code>redData</code>, <code>redLoad</code>, <code>redClock</code>, <code>greenData</code>, <code>greenLoad</code>, <code>greenClock</code>, sicne they are not being used once your 2 <code>Matrix</code> fields have been initialized.</p> <p>Hence you could simplify your class further, I think.</p>
1579
|arduino-due|
Why does the Arduino Due have a native and USB programming port?
2014-05-18T21:31:16.687
<p>According to the schematics, the Arduino Due has two USB inputs:</p> <ol> <li>Native</li> <li>Programming</li> </ol> <p>Why is this? And when would I use the different ports?</p>
<p>Either port can be used for programming, but the native USB port lets you do other things:</p> <blockquote> <p>It also enables the Due to emulate a USB mouse or keyboard to an attached computer. To use these features, see the <a href="http://arduino.cc/en/Reference/MouseKeyboard">Mouse and Keyboard library reference pages</a>.</p> <p>The Native USB port can also act as a USB host for connected peripherals such as mice, keyboards, and smartphones. To use these features, see the <a href="http://arduino.cc/en/Reference/USBHost">USBHost reference pages</a>. <sub><a href="http://arduino.cc/en/Main/arduinoBoardDue">http://arduino.cc/en/Main/arduinoBoardDue</a></sub></p> </blockquote> <p>So you can use the Due to interface with USB devices or connect it to your computer and have it act like a USB device.</p>
1589
|serial|
arduino EM408 GPS problem
2014-05-19T18:36:09.847
<p>I have written this little snippet of code to interface with EM408 GPS.</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial GPS = SoftwareSerial(2,3); //rx,tx void setup() { GPS.begin(4800); Serial.begin(9600); } void loop() { //Serial.print(GPS.read(), BYTE); Serial.write(byte(GPS.read())); //as of Arduino 1.0 } </code></pre> <p>Hardware side i have these connections: <br> ENABLE: 3.3V <br> Vcc : 3.3V <br> Ground: Ground <br> Rx, Tx correctly connected to arduino and correctly initialized with SoftwareSerial</p> <p>However, the values i get are just junk data</p> <pre><code>ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ </code></pre> <p>I get these without ending... I experimenting with changing the baud rate, still the same thing goes on. Any ideas?</p> <p>EDIT:<br> I used to get random junk data before with the EM406 gps module, but i solved it by casting everything to BYTE. I have tried both approaches here, but the results are the same...</p>
<p>The problem you get is that <code>read()</code> does not wait for a byte to be available, it just returns <code>-1</code> if there is no byte available; converted as an unsigned byte that becomes <code>255</code>.</p> <p>In <strong>ISO-8859-1</strong>, which I guess is the encoding that your serial monitor is using, <code>255</code> translates to <code>ÿ</code>, so this is exactly what you observe.</p> <p>Fixing this problem is straightforward, just check that a byte is available on <code>SoftwareSerial</code> before reading it:</p> <pre><code>void loop() { if (GPS.available()) { Serial.write(byte(GPS.read())); //as of Arduino 1.0 } } </code></pre>
1595
|motor|arduino-leonardo|
Power small hobby motor using Vin pin on Arduino and 9V battery, safe?
2014-05-20T06:00:34.627
<p>I want to power a small motor with a 9V battery and control it with PWM using an Arduino Leonardo. I know I can power the motor separately, but this introduces the problem of needing a battery to power the motor (9V battery) and another power source to power the Arduino (another 9V battery?)</p> <p><strong>Would it be safe</strong> to simply power the Arduino with a 9V battery and use the Vin pin on the board (which is unregulated and outputs directly the power source powering the Arduino) to drive the motor? That way, I power everything from the 9V battery, and use a transistor to drive the motor.</p> <p>Thanks a lot!</p> <p>Steve.</p>
<p>The arduino has its on voltage regulator, so feeing 9v to the arduino is not a problem. But the arduino will not drive the motor directly. You need to use a transistor big enough to hundle the amperage of your motor (e.g.tip120). The diagram above is a good indication of how to connect it. Yet the diagram is missing a diode (1n4001 or 1n4004) from the GnD to Vcc, as to avoid back voltage from the motor, which may damage your arduino.</p>
1612
|networking|system-design|remote-control|
Is it possible to transmit using an NRF24L01+ without an Arduino?
2014-05-21T11:26:20.363
<p>I have two <a href="http://www.elecfreaks.com/wiki/index.php?title=2.4G_Wireless_nRF24L01p" rel="noreferrer">NRF24L01+ modules</a> which are transceivers, but for my project I would like to send a very simple signal from one of these modules to the be read by the other.</p> <p>That would've been very simple if I had an Arduino on each side but due to power consumption constraints as well as size, cost and practicality, the transmitting side won't have one. Would it still be possible to do this?</p> <p>To clarify, the message itself is not important and can be set in stone, it will never change. I really just want to detect on the receiving side (which will have an Arduino) that the transmitter is in fact transmitting. Transmission will be triggered by a push-button.</p> <p>Ideally I would have a way of identifying my particular transmitter from others on similar frequencies but I am not too precious about that.</p>
<p>Note, there is also the NRF24LE1 SoC which has its own ULP MCU - good for transmitting simple data such as sensor readings. If used to Arduino, ARduino Pro Mini 3.3v and the NRF24L01+ is easier and better way to go. (Mod the Arduino to be ULP)</p>
1615
|programming|c++|analogread|
How to loop over analog pins?
2014-05-21T15:51:17.457
<p>I want to do something along the lines of</p> <pre><code>for (int i = 0; i &lt; 4; i++) { analogRead(i); } </code></pre> <p>Which appears to work, but the following does not:</p> <pre><code>for (int i = 0; i &lt; 4; i++) { pinMode(i, INPUT); pinMode(i + 4, OUTPUT); // should make Analog Pin (i + 4) into an output digitalWrite(i + 4, LOW); analogRead(i); } </code></pre> <p>Instead, it appears to treat the pin addressed by <code>digitalWrite(i + 4, LOW);</code> as one of the digital pins.</p> <p>Do I really have to explicitly specify A0, A1, A2, ... anytime I want to loop over the analog pins?</p>
<p>Assuming pin numbers are consecutives you can iterate them:</p> <pre class="lang-cpp prettyprint-override"><code>int acc = 0; for (int Ai = A0; Ai &lt; A0 + NUM_ANALOG_INPUTS; Ai++) { acc += analogRead(Ai); } Serial.println(acc); </code></pre>
1621
|serial|
Arduino reading serial data non-blocking
2014-05-21T19:36:48.447
<p>I have an Arduino reading serial data and responding to other inputs as well, I'm trying to read incoming serial data without using the while, if at all possible. the incoming serial data will be formatted in a specific manner each time and will be CSV; It will look like such:</p> <pre class="lang-C++ prettyprint-override"><code>19,1400700083, 1-0,1-10,and other values delimited with a new line character "/n". </code></pre> <p>The first value will tell how many bytes are coming in so the serial receive function wont parse data until it gets all the bytes,second value is a Unix time-stamp, the third value (1-0) is the "get" or set" value; which will tell the Arduino to return a value or to set a value. The fourth (1-10) value will correspond to what variable to get or set. and the other values will be integers as well but are dependent on the other values. </p> <p>My code is as follows: </p> <pre class="lang-C++ prettyprint-override"><code>void CheckSerialData() { // begin function if(Serial.available() &gt;= 2) { // begin one, first line will be how many bytes incoming. int NumberOfIncomingBytes = Serial.parseInt(); if(Serial.available() &gt;= NumberOfIncomingBytes) { //begin two int IncomingTime = Serial.parseInt(); setTime(IncomingTime); //time is always incoming with serial values int GetOrSetValue = Serial.parseInt(); //this value should be 1 or 0 for "getting values(1)" or "setting values(0)" if(GetOrSetValue == 1) { //BEGIN THREE int ValueToGet = Serial.parseInt(); switch(ValueToGet) {// BEGIN SWITCH case 0: Serial.print(GetTemp()); Serial.print("/n"); break; case 1: //serialwrite yaw pitch roll break; case 2: Serial.print(GetVoltage()); Serial.print("/n"); break; case 3: //append all RGB final values together and serial print it break; case 4: //print out accel values break; case 5: //print alarm alarmed status break; case 6: //print out last time alarm set off break; case 7: //print out time allowed lights to turn on break; case 8: //print out arduino time break; case 9: //print out system summary, (time,voltage,temp,yaw,pitch,roll,accel break; }//END SWITCH }//END THREE else { //BEGIN TWO B //SET VALUES int ValueToGet = Serial.parseInt(); switch(ValueToGet) {// BEGIN SWITCH case 0: //set global rgb value set LEFT break; case 1: //set global rgb value set RIGHT break; case 2: //set global alarm value break; case 3: //set global angle to start flashing emergency led's break; case 4: //set turn signal RGB value break; case 5: //set time that lights are ok to turn on break; case 6: //set light override value break; case 7: //set pattern enable break; } //END SWITCH }//END TWO B } }//end two }//end one }//end function //**********************END SERIAL FUNCTION************************** </code></pre> <p>I would like to know if this looks like it can work, or am I going about this all wrong? </p> <p>(I don't have access to my Arduino currently to test the code)</p>
<p>Unfortunately your code could end up dropping data quite easily, or parsing it incorrectly.</p> <p>Let's say your code has successfully read the first couple of bytes into <code>NumberOfIncomingBytes</code>. However, when it reaches <code>begin two</code>, let's imagine the sender hasn't finished sending all the data yet.</p> <p>Your code will drop through to <code>end two</code>, discarding the <code>NumberOfIncomingBytes</code> value it just read. Next time round, it will start all over again from scratch, and attempt to read <code>NumberOfIncomingBytes</code> again. However, that data isn't there anymore. The next data waiting on serial will actually be the timestamp from the previous message.</p> <p>From there, it could end up parsing arbitrary data with unpredictable results, getting completely out-of-sync with the sender.</p> <p>A way to fix it would be to store the <code>NumberOfIncomingBytes</code> value outside the function (e.g. as a global variable), along with a flag indicating if you're still waiting for the rest of the data to arrive. At the start of <code>CheckSerialData()</code>, the code should check that flag. If it's true, then it should skip trying to read <code>NumberOfIncomingBytes</code>. Instead, go straight on to <code>begin two</code>.</p> <p>An alternative approach would be to avoid using <code>NumberOfIncomingBytes</code> at all. Each call to <code>CheckSerialData()</code> would read whatever serial data is available, and accumulate it in a buffer. As soon as it hits a newline character, it will stop reading, and parse the data it's accumulated. If it runs out of serial data before it hits a newline, it should stop and carry on from there next time it's called.</p>
1628
|arduino-mega|i2c|spi|
Arduino to Raspberry Pi wired communication
2014-05-22T15:05:13.280
<p>I am new to Raspberry Pi (just brought mine before writing this post), and I am looking to see what is the most ideal way for two way communication between an Arduino and a Raspberry Pi (USB, SPI or I2C).</p> <p>The reason I am asking is because I need to build a small, semi-autonomous robot and plan on using both the Arduino and Pi to control it, using the pins of the Arduino for the motor control and sensors and the Pi for video processing and autonomous part. Both will be on the robot itself. I am pretty good with the Arduino but never used a Raspberry Pi before. </p> <p>So my biggest question is what would be the best form of communication for the two boards taking into account speed and safety (there is a voltage difference between the Pi and the Arduino).</p>
<p>Firsr of all, When you say "there is a voltage difference", I assume you are referring to the raspberry pi being a 3.3v device vs the arduino's 5v, and not to some kind of ground potential difference. If theres a ground potential difference(which there shouldn't be in a robot), neither i2c or spi or usb will work without extra circuitry.</p> <p>My short answer would be USB all the way because its easy and built into the arduino and pi. The only issue is that if anything mechanically bumps the usb enough to lose connection, sometimes linux is a little unpredictable with regards to naming serial ports, and when it reconnects it might give the arduino a different serial port name. But this isnt an issue if your cable isnt a cheap worn out one with a flaky connection like the one that bothered me for a hour today.</p> <p>USB does have about a millisecond of latency because devices are usually polled at 1khz iirc. Using the raspberry pi hardware serial might be a good idea if milliseconds count which I doubt they do.</p> <p>But on the software side, raspi hardware serial and USB serial are the same. So there should be no problem switching between them if you need to.</p> <p>I wouldnt bother with i2c or spi. Why fuss around when serial works so well?</p>
1633
|i2c|wire-library|
Arduino Master-Slave Pins
2014-05-22T23:04:15.293
<p>Can I change the pins on the communication for a Master-Slave arduino Wire transmission? I want to communicate between 2 arduinos, but on one of them A4&amp;A5 are taken</p>
<p>To complete Ignacio's answer, there's indeed no other hardware I2C on AVR Arduinos.</p> <p>The only options you have to use other pins is:</p> <ul> <li>to use bitbang i2c, which is way slower ; </li> <li>or you can switch to the Arduino Due which features two TWI ports ; </li> <li>or you can use an SPI to I2C serial bridge such has <a href="http://www.silabs.com/products/interface/spitoi2c/Pages/default.aspx" rel="nofollow">that one</a>.</li> </ul>
1641
|arduino-uno|
help with input in a Simon arduino uno game
2014-05-23T02:42:16.987
<p>I' making a Simon game with the arduino uno.</p> <p>I know something is wrong with the inputs but i don't know why or how to fix it.</p> <p>The problem is the program takes an input and says it is correct no matter what it is or the length</p> <pre><code>#define NOTES int tones[] = {NOTE_E5, NOTE_E6, NOTE_CS6, NOTE_A6}; String sequence; void setup() { pinMode(13, OUTPUT); //green pinMode(12, OUTPUT); //yellow pinMode(11, OUTPUT); //blue pinMode(10, OUTPUT); //red pinMode(7, INPUT); //green pinMode(6, INPUT); //yellow pinMode(5, INPUT); //blue pinMode(4, INPUT); //red Serial.begin(9600); } void loop() { while(true) { delay(1000); randomSeed(random(random(1000000000))); sequence = String(random(4)); boolean run = true; while(run) { for(int i = 0; i &lt; sequence.length(); i++) { simonOut(sequence.charAt(i) - '0'); delay(500); simonClear(); delay(100); } for(int i = 0; i &lt; sequence.length(); i++) { int input = simonIn(); while(input &lt; 0 || input &gt; 3) { delay(50); input = simonIn(); } if(sequence.charAt(i) - '0' == input) { flash(0); run = false; goto reset; } else if(i = sequence.length() - 1) flash(3); } sequence += random(4); } reset:; } } void boolOut(long pin, boolean val) { digitalWrite(pin,val ? HIGH : LOW); } void simonOut(long num) { boolOut(num + 10, true); tone(2, tones[num]); } void flash(int led) { delay(300); for(int i = 0; i &lt; 5; i++) { simonOut(led); delay(100); simonClear(); delay(100); } } void simonClear() { for(int i = 0; i &lt; 4; i++){ boolOut(i + 10, false); } noTone(2); } int simonIn() { int ret = -1; for(int i = 0; i &lt; 4; i++) { if(simonIn(i)){ ret = i; } } if(ret != -1) { simonOut(ret); delay(500); simonClear(); delay(100); } } boolean simonIn(long num) { return digitalRead(num + 4) == HIGH; } </code></pre>
<p>The problem in your code is there:</p> <pre><code>int simonIn() { int ret = -1; for(int i = 0; i &lt; 4; i++) { if(simonIn(i)){ ret = i; } } if(ret != -1) { simonOut(ret); delay(500); simonClear(); delay(100); } } </code></pre> <p>This method never returns any value, so that means the caller will just tke whatever is in the stack at that time:</p> <pre><code> int input = simonIn(); while(input &lt; 0 || input &gt; 3) { delay(50); input = simonIn(); } </code></pre> <p><code>input</code> could be anything there.</p> <p>So the fix should be easy:</p> <pre><code>int simonIn() { int ret = -1; for(int i = 0; i &lt; 4; i++) { if(simonIn(i)){ ret = i; } } if(ret != -1) { simonOut(ret); delay(500); simonClear(); delay(100); } return ret; } </code></pre> <p>It's surprising you did not get a <strong>warning from the compiler</strong> on that one, which IDE do you use?</p> <p>Finally, regarding your code, I would also advise you the following improvements:</p> <ul> <li>break down the <code>loop()</code> code further into functions that do <strong>ONE</strong> thing, e.g. <code>showSequence(sequence)</code>, <code>checkInput(seuquence)</code>, <code>readSimonInput()</code> (this last function would only return a value between 0 and 3 included. That would make your code much clearer.</li> <li>use the right types for your variables: I see you abuse usage of <code>long</code> where <code>int</code> or <code>byte</code>, or you mix different types for the same data, thus forcing the compiler to cast data on some function calls.</li> <li>avoid hardcoding constants in your code, e.g. you could define the number of buttons, the first pin of buttons, the first pin of LEDs, the various delays.</li> </ul>
1649
|wires|
How to improve wiring a breadboard?
2014-05-23T12:15:52.510
<p>just saw this tweet and was interested what wires are used there:</p> <p><a href="https://twitter.com/EngineersGarage/status/448014811280842752/photo/1" rel="nofollow noreferrer">https://twitter.com/EngineersGarage/status/448014811280842752/photo/1</a></p> <p><img src="https://i.stack.imgur.com/2fssl.jpg" alt="enter image description here"></p> <p>The wiring Looks cleaner than the setup I currently have with "normal" wires.</p> <p>Thanks!</p>
<p>Using good wires helps to build clean breadboard setups. I also found that it greatly helps to wire vertically only and to use the breadboard for horizontal connections. If you look at my picture, wires are always vertical. This is easy to achieve when you work with buses like I²C. As you can see, I also used horizontal lines from another breadboard as you can use these like Lego bricks, though you need to cut the adhesive tape in the back. For the wires, I used standard Solderless Breadboard Jumper Cable Wire that you can buy almost everywhere online.</p> <p>You can also check other pictures on my blog: <a href="http://ouilogique.com/horloge_cycles_ultradiens/" rel="nofollow noreferrer">http://ouilogique.com/horloge_cycles_ultradiens/</a></p> <p><a href="https://i.stack.imgur.com/MuBVh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MuBVh.jpg" alt="enter image description here"></a></p>
1651
|pins|resistor|
Setting a Pin to HIGH to simulate a button with a "pull up" resistor
2014-05-23T15:28:21.017
<p>in the below Fritzing diagram, I have a button that has a pull-up resistor, which when pressed, sets the GPIO Pin 23 to HIGH. On the Raspberry Pi, when the button is released, the GPIO goes LOW. The Raspberry Pi detects when the button is released and pressed. This is my desired behavior. </p> <p>However, in my current configuration, I have PIN 13 connected to the Base of a NPN transistor to try to simulate the same behavior as the button with a pull-up resistor. When pin 13 is set to high, it sets the GPIO 22 Pin to high. When I set the Arduino Pin 13 to low, The GPIO Pin goes low but the Raspberry PI does not detect that GPIO 22 pin went low. Is there a way to simulate the same behavior as a button with a pull-up resistor with an OUTPUT pin from the arduino?</p> <p><img src="https://i.stack.imgur.com/bejPK.png" alt="enter image description here"></p>
<p>So the solution to this was to remove the transistor all together and connect the Arduino pin directly to the Pi. However, I need to change my Arduino sketch. The approach was to set the pin HIGH and go LOW when selected. I had it backwards.</p>
1658
|wifi|
Decimals missing when using radio.write(); with Arduino
2014-05-23T16:12:59.897
<p>I'm adapting a sketch I found to send sensor data over a wifi chip (Nrf2401), and although I get the message through, the value I send contains decimals (e.g. 24.59), but the received message will only be 24.</p> <p>I'm sure there's something wrong on the transmitter part of the code, but I can't see what.</p> <p>Here's my code:</p> <pre><code>#include &lt;RF24.h&gt; #include &lt;RF24_config.h&gt; #include &lt;SPI.h&gt; #include &lt;OneWire.h&gt; #include &lt;DallasTemperature.h&gt; OneWire oneWire(4); DallasTemperature sensors(&amp;oneWire); // ce,csn pins RF24 radio(8,7); // init data buffer to hold a sensor type byte and one uint16_t sensor data unsigned char data[3] = { 0}; unsigned long count=0; void setup(void) { sensors.begin(); Serial.begin(57600); Serial.println("**************V1 Send Sensor Data***********"); radio.begin(); radio.setPALevel(RF24_PA_LOW); radio.setChannel(0x4c); // open pipe for writing radio.openWritingPipe(0xF0F0F0F0E1LL); radio.enableDynamicPayloads(); radio.setAutoAck(true); radio.powerUp(); Serial.println("...Sending"); } void loop(void) { sensors.requestTemperatures(); float currentTemp; currentTemp = sensors.getTempCByIndex(0); //assign 'T' to represent a Temperature reading data[0] = 'T'; data[1] = currentTemp; count++; sprintf(data, "T %5.2f\n", currentTemp); // build command in data[] radio.txMode(strlen(data)); // set # bytes to xmit radio.write(data); // send bytes // print and increment the counter Serial.print("Temperature sent: "); Serial.println(currentTemp); // pause a second delay(500); } </code></pre> <p>In this example, when I print currentTemp, it will display the decimals, but if I print data[1], it won't. </p> <p>What am I missing?</p> <p><strong>EDIT:</strong></p> <p>I've modified the code to include the answer from JRobert (updated code above), but it comes back the following error:</p> <pre><code>nrf24SendSensorDataV1_ino.cpp: In function 'void loop()': nrf24SendSensorDataV1_ino:56: error: invalid conversion from 'unsigned char*' to 'char*' nrf24SendSensorDataV1_ino:56: error: initializing argument 1 of 'int sprintf(char*, const char*, ...)' nrf24SendSensorDataV1_ino:57: error: 'class RF24' has no member named 'txMode' nrf24SendSensorDataV1_ino:57: error: invalid conversion from 'unsigned char*' to 'const char*' nrf24SendSensorDataV1_ino:57: error: initializing argument 1 of 'size_t strlen(const char*)' nrf24SendSensorDataV1_ino:58: error: no matching function for call to 'RF24::write(unsigned char [3])' C:\Users\Zuh\Downloads\arduino-1.0.1\libraries\RF24L01/RF24.h:281: note: candidates are: bool RF24::write(const void*, uint8_t) </code></pre> <p>Any thoughts?</p> <p><strong>EDIT 2</strong></p> <p>I've made a dirty fix that will solve the issue.</p> <p>In the transmitter code I've added:</p> <pre><code>uint16_t sensorValue = currentTemp*100; //do the bit shift to put uint16 into uint8 array data[1] = sensorValue &gt;&gt; 8; data[2] = sensorValue; // print and increment the counter radio.write(data, sizeof(uint16_t)+1); </code></pre> <p>This will send the (temperature value)*100</p> <p>On the receiver end, I just convert the uint16_t to a float element and divide it by 100.</p> <pre><code>uint16_t sensorValue = data[2] | data[1] &lt;&lt; 8; float temp = (float) sensorValue/100; Serial.print("T: "); Serial.println(temp); </code></pre> <p>Dirty, but effective!</p> <p>Many thanks guys for the help, it really pointed me and my lousy programming skills to the right direction.</p>
<p>From the Arduino playground <a href="http://playground.arduino.cc/InterfacingWithHardware/Nrf2401" rel="nofollow">documentation</a> for the Nrf2401 library, the .write method accepts either: a byte to transmit, a pointer to your <code>unsigned char</code> buffer; or a void argument meaning use the library's internal buffer. You must have called the .txmode() method first.</p> <p>Since you're trying to use your own buffer, you'll need to make it long enough to contain the message you want to transmit (plus one byte for the terminating NUL). You'll need a character representation of the value you want to send, not the binary number itself. At a quick read of the library doc I didn't see the message format the library wants, but assuming it's something like: <code>T&lt;space&gt;12.34&lt;newline&gt;</code>, you'll need something like this (untested, it may need tweaking)</p> <pre><code>sprintf(data, "T %5.2f\n", currentTemp); // build command in data[] radio.txMode(strlen(data)); // set # bytes to xmit radio.write(data); // send bytes </code></pre>
1661
|serial|python|
Why does serial port stop sending data?
2014-05-23T19:37:45.530
<p>I'm using an Arduino Leonardo to interface with two pressure sensors and Python on my laptop, a MackBook Pro. </p> <p>I'm using arduino IDE V. 1.5.4, Python V. 2.7.6, and OSX 10.8.5.</p> <p>One pressure sensor is digital, using the Wire lib, and the other is analog. </p> <p>My sketch compiles, runs, and works until I try to get the data in Python using pyserial. </p> <p>If I try to grab a bunch of data using the readlines method in the scrip it will only return blank data or hang, depending on the serial object timeout settings. My python code sometimes works from the repl when I initialize the serial object and wait before reading from it. If I don't wait the serial object will only partially fill a list and then any future reads will return an empty string. This continues even after closing the serial object and reopening it in Python, or closing the serial object in Python and then opening the Serial Monitor in the Arduino IDE. Once the serial port stops sending, I have to reset the Leonardo in order to read new data.</p> <p>I could be running into some kind of buffering problem, but if that were the case I would expect future calls to return data. Another option is that the Wire protocol is getting stuck and halting the program.</p> <p>Here's my sketch</p> <pre><code>#include &lt;Wire.h&gt; int ADDRESS = 0x28;//I2C address of sensor int REQUEST = 4;//# of bytes to request from sensor int BAUD = 19200;//serial rate int PRESSURE_PIN = 1; void setup() { pinMode(A1, INPUT); Wire.begin(); // join i2c bus (address optional for master) Serial.begin(BAUD); // start serial for output } void loop() { Wire.requestFrom(ADDRESS, REQUEST); // request 6 bytes from slave device #2 Serial.print(analogRead(PRESSURE_PIN)); Serial.print(','); while(Wire.available()) // slave may send less than requested { Serial.print(((unsigned int)Wire.read() &lt;&lt; 8) + Wire.read()); Serial.print(','); Serial.println(((unsigned int)Wire.read()) &lt;&lt; 3) + (Wire.read() &gt;&gt; 5); } delay(10); } </code></pre> <p>and here is how I read it from python </p> <pre><code>import serial serial_port = '/dev/tty.usbmodem1a1221' ser = serial.Serial(serial_port, 19200, timeout=0) vals = [val.split(',')[0:2] for val in ser.readlines(1001*14)] </code></pre>
<p>My eventual workaround for the Leonardo was to set up a call-response loop on the Leonardo. Here's the code: </p> <pre><code>#include &lt;Wire.h&gt; int ADDRESS = 0x28;//I2C address of sensor int REQUEST = 4;//# of bytes to request from sensor int BAUD = 19200;//serial rate void setup() { pinMode(A1, INPUT); Wire.begin(); // join i2c bus (address optional for master) Serial.begin(BAUD); // start serial for output } void loop() { if (Serial.available() &gt; 0) { Serial.read(); Wire.requestFrom(ADDRESS, REQUEST); // request 4 bytes from slave device at 0x28 while(Wire.available()) // slave may send less than requested { Serial.print(((unsigned int)Wire.read() &lt;&lt; 8) + Wire.read()); Serial.print(','); Serial.println(((unsigned int)Wire.read()) &lt;&lt; 3) + (Wire.read() &gt;&gt; 5); } } } </code></pre> <p>I was able to simplify a little.</p> <p>There are two things to note:</p> <ul> <li><p>There is no built in delay and requests made too quickly will result in either an empty response or old data from the sensor. Have to take into account in requesting program.</p></li> <li><p>The sketch will respond a number of times equal to the number of bits sent. Use a single ASCII character for one response, 2 characters for 2 responses, etc... This is important if you use an API similiar to a write() and writeln() as the second sends extra characters.</p></li> </ul>
1667
|arduino-uno|
Significance of the numbers used in the manual
2014-05-24T08:57:55.190
<p>i just bought the starter kit and am currently working my way through the examples in the book when i came across some numbers used in the manual that seems a little too specific.</p> <p>For example, in project #3,the love-o-meter, i had to divide the sensor value by 1024.0, and the explanation for it was never given in the manual.</p> <p>Furthermore, in project #4(which i'm currently at), the book states that i have to convert sensor readings from 0 - 1023, to a value between 0 to 255.Is the number 1024/1023 simply an arbitrary number/limit set by the sensor's manufacturers? Also, is they any significance or reason that analogueWrite only accepts positive values up to 255?</p> <p>Thanks!</p>
<p>To clarify, analogRead() has a 10 bit range due to the arduino's Analog to Digital Converter, or ADC. 10 bits can store 1024 (2^10) different values; counting zero as a value gives the range 0-1023. </p> <p>In arduino 0 is the reading when a pin is grounded, 1023 is the reading when an analog pin is connected to Vref, or 5v if there is nothing wired to Vref. The sensors provide a voltage somewhere between these values, but not the actual numbers your code gets.</p> <p>analogWrite() accepts 8 bit numbers. That is 2^8 or 256 different values, called 0-255. It only simulates an analog voltage by pulsing a pin rapidly.</p> <p>In short, the numbers are not arbitrary, but express the limits of the arduino chip's IO. They look random because they were written in decimal, but in binary they are very simple. If you are interested, you could look into replacing the decimal numbers in the code with hexadecimal numbers, which make their binary representations very obvious by way of 16 being 2^4.</p>
1669
|sensors|arduino-due|i2c|
Reading CMPS10 raw values
2014-05-24T11:31:06.060
<p>I've got a cmps10 compass module hooked up to my arduino due through a logic level converter. I am writing code to convert the raw magnetometer readings into a bearing that I can use but have run into a huge problem. My bearings are all funky for some reason. They are totally unrelated to the actual bearing of the robot. I know the sensor is fine because I am able to get the tilt compensated reading from it and it works great. One thing I noticed is that the magnetometer reading on the X-axis is always positive could this be the problem? The X-axis high byte generally between 0x00 and 0x03. My code is below (i2cBus = &amp;Wire)</p> <pre><code>i2cBus-&gt;beginTransmission(I2C_Address); i2cBus-&gt;write(byte(10)); i2cBus-&gt;endTransmission(); i2cBus-&gt;requestFrom(I2C_Address, 4); xMagHighByte = i2cBus-&gt;read(); xMagLowByte = i2cBus-&gt;read(); yMagHighByte = i2cBus-&gt;read(); yMagLowByte = i2cBus-&gt;read(); xMag = short(xMagHighByte&lt;&lt;8); xMag |= xMagLowByte; yMag = short(yMagHighByte&lt;&lt;8); yMag |= yMagLowByte; if(yMag!=0){ magBearing = (atan2(xMag,yMag)*180.0)/3.141592654; } else if(xMag&gt;0) magBearing=0.0; else if(xMag&lt;0) magBearing=180.0; else magBearing = 1000; if(magBearing &lt; 0) magBearing+=360; magBearing=360-magBearing; return magBearing; </code></pre>
<p>Compass modules are highly susceptible to interference from ferrous deposits underground and metals in or around your robot. To correct for them, you need to shift and scale both axis.</p> <p>But first, test if the sensor's X axis is working by watching the value while moving a small magnet around the sensor. If should overpower any stationary field and bias in the sensor, if it can't then there may be a problem with the sensor. </p> <p>To calibrate the compass, first find the min and max value for each axis. Do this by reading all the outputs of an axis when moving the sensor in a complete circle in the environment you will be using it in. Making the robot drive in a circle when first turned on to calibrate itself is not a bad idea. Anyway, the shift is the negative average and the scale is half the difference between maximums. what really matters is that this "distance" is the same on both axis, but normalizing both is easier. For example, </p> <pre><code>float Scale, Shift, Value; Scale = (max-min)/2; Shift = -(max+min)/2; Value = float(raw+Shift)/Scale; </code></pre> <p>Once both axis are corrected the atan2() function can work properly. If you were to plot the x and y points on a graph, they should trace a unit circle at the origin.</p>
1672
|arduino-uno|atmega328|avrdude|
Reset fuses on atmega328p using Arduino
2014-05-24T14:17:18.997
<p>I bought a few atmega328p chips but unfortunately they came with the Arduino bootloader and they are set to use the external clock. I want to reset their fuses using avrdude so I can use the internal 8mhz clock but it's not working. How can I (if even possible) reset their fuses using the Arduino? I have no other programmer and here are the arguments I use for avrdude as well as the response:</p> <pre><code>avrdude -C .\avrdude.conf -p m328p -c arduino -P \\.\COM12 -b 115200 -U lfuse:w:0x62:m -U hfuse:w:0xd9:m -U efuse:w:0xff:m </code></pre> <p>Response:</p> <pre><code>avrdude.exe: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.00s avrdude.exe: Device signature = 0x1e950f avrdude.exe: reading input file "0x62" avrdude.exe: writing lfuse (1 bytes): Writing | ***failed; ################################################## | 100% 0.06s avrdude.exe: 1 bytes of lfuse written avrdude.exe: verifying lfuse memory against 0x62: avrdude.exe: load data lfuse data from input file 0x62: avrdude.exe: input file 0x62 contains 1 bytes avrdude.exe: reading on-chip lfuse data: Reading | ################################################## | 100% 0.00s avrdude.exe: verifying ... avrdude.exe: verification error, first mismatch at byte 0x0000 0x62 != 0x00 avrdude.exe: verification error; content mismatch avrdude.exe: safemode: lfuse changed! Was 62, and is now 0 Would you like this fuse to be changed back? [y/n] </code></pre>
<p>You cannot set the fuses using the Arduino bootloader, since they cannot be self-programmed. You must use either serial or parallel programming via ArduinoISP or an external programmer to set them. Since the chip is configured to use an external crystal you must either connect a crystal up to the chip appropriately (see sections 9.3 or 9.4 of the datasheet) or use parallel programming. You will then be able to use the <code>lfuse</code>, <code>hfuse</code>, and <code>efuse</code> memory types to read and write the fuse bytes.</p>
1673
|avr|isp|
Using ArduinoISP on an Arduino Uno to program an ATmega328
2014-05-24T14:37:57.790
<p>I have an Arduino Uno R3 and would like to use it to program a blank ATmega328 on a breadboard. I've followed the instructions for the 8 MHz version on <a href="http://arduino.cc/en/Tutorial/ArduinoToBreadboard" rel="nofollow">http://arduino.cc/en/Tutorial/ArduinoToBreadboard</a> with an added 10K pullup resistor on the <code>RESET</code> pin of the ATmega328 on the breadboard; and I've uploaded the <code>ArduinoISP</code> sketch from the Arduino 1.0.5 distribution to my Uno. </p> <p>I've also added the metadata for my setup: the following is the contents of <code>~/sketchbook/hardware/breadboard/boards.txt</code>:</p> <pre><code>atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock) atmega328bb.upload.protocol=stk500v1 atmega328bb.upload.maximum_size=30720 atmega328bb.upload.speed=57600 atmega328bb.bootloader.low_fuses=0xE2 atmega328bb.bootloader.high_fuses=0xDA atmega328bb.bootloader.extended_fuses=0x05 atmega328bb.bootloader.path=arduino:atmega atmega328bb.bootloader.file=ATmegaBOOT_168_atmega328_pro_8MHz.hex atmega328bb.bootloader.unlock_bits=0x3F atmega328bb.bootloader.lock_bits=0x0F atmega328bb.build.mcu=atmega328 atmega328bb.build.f_cpu=8000000L atmega328bb.build.core=arduino:arduino atmega328bb.build.variant=arduino:standard </code></pre> <p>I've also added the following section to my <code>~/.avrduderc</code> file:</p> <pre><code>part id = "m328"; desc = "ATMEGA328"; has_debugwire = yes; flash_instr = 0xB6, 0x01, 0x11; eeprom_instr = 0xBD, 0xF2, 0xBD, 0xE1, 0xBB, 0xCF, 0xB4, 0x00, 0xBE, 0x01, 0xB6, 0x01, 0xBC, 0x00, 0xBB, 0xBF, 0x99, 0xF9, 0xBB, 0xAF; stk500_devcode = 0x86; # avr910_devcode = 0x; signature = 0x1e 0x95 0x14; pagel = 0xd7; bs2 = 0xc2; chip_erase_delay = 9000; pgm_enable = "1 0 1 0 1 1 0 0 0 1 0 1 0 0 1 1", "x x x x x x x x x x x x x x x x"; chip_erase = "1 0 1 0 1 1 0 0 1 0 0 x x x x x", "x x x x x x x x x x x x x x x x"; timeout = 200; stabdelay = 100; cmdexedelay = 25; synchloops = 32; bytedelay = 0; pollindex = 3; pollvalue = 0x53; predelay = 1; postdelay = 1; pollmethod = 1; pp_controlstack = 0x0E, 0x1E, 0x0F, 0x1F, 0x2E, 0x3E, 0x2F, 0x3F, 0x4E, 0x5E, 0x4F, 0x5F, 0x6E, 0x7E, 0x6F, 0x7F, 0x66, 0x76, 0x67, 0x77, 0x6A, 0x7A, 0x6B, 0x7B, 0xBE, 0xFD, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00; hventerstabdelay = 100; progmodedelay = 0; latchcycles = 5; togglevtg = 1; poweroffdelay = 15; resetdelayms = 1; resetdelayus = 0; hvleavestabdelay = 15; resetdelay = 15; chiperasepulsewidth = 0; chiperasepolltimeout = 10; programfusepulsewidth = 0; programfusepolltimeout = 5; programlockpulsewidth = 0; programlockpolltimeout = 5; memory "eeprom" paged = no; page_size = 4; size = 1024; min_write_delay = 3600; max_write_delay = 3600; readback_p1 = 0xff; readback_p2 = 0xff; read = " 1 0 1 0 0 0 0 0", " 0 0 0 x x x a9 a8", " a7 a6 a5 a4 a3 a2 a1 a0", " o o o o o o o o"; write = " 1 1 0 0 0 0 0 0", " 0 0 0 x x x a9 a8", " a7 a6 a5 a4 a3 a2 a1 a0", " i i i i i i i i"; loadpage_lo = " 1 1 0 0 0 0 0 1", " 0 0 0 0 0 0 0 0", " 0 0 0 0 0 0 a1 a0", " i i i i i i i i"; writepage = " 1 1 0 0 0 0 1 0", " 0 0 x x x x a9 a8", " a7 a6 a5 a4 a3 a2 0 0", " x x x x x x x x"; mode = 0x41; delay = 20; blocksize = 4; readsize = 256; ; memory "flash" paged = yes; size = 32768; page_size = 128; num_pages = 256; min_write_delay = 4500; max_write_delay = 4500; readback_p1 = 0xff; readback_p2 = 0xff; read_lo = " 0 0 1 0 0 0 0 0", " 0 0 a13 a12 a11 a10 a9 a8", " a7 a6 a5 a4 a3 a2 a1 a0", " o o o o o o o o"; read_hi = " 0 0 1 0 1 0 0 0", " 0 0 a13 a12 a11 a10 a9 a8", " a7 a6 a5 a4 a3 a2 a1 a0", " o o o o o o o o"; loadpage_lo = " 0 1 0 0 0 0 0 0", " 0 0 0 x x x x x", " x x a5 a4 a3 a2 a1 a0", " i i i i i i i i"; loadpage_hi = " 0 1 0 0 1 0 0 0", " 0 0 0 x x x x x", " x x a5 a4 a3 a2 a1 a0", " i i i i i i i i"; writepage = " 0 1 0 0 1 1 0 0", " 0 0 a13 a12 a11 a10 a9 a8", " a7 a6 x x x x x x", " x x x x x x x x"; mode = 0x41; delay = 6; blocksize = 128; readsize = 256; ; memory "lfuse" size = 1; min_write_delay = 4500; max_write_delay = 4500; read = "0 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0", "x x x x x x x x o o o o o o o o"; write = "1 0 1 0 1 1 0 0 1 0 1 0 0 0 0 0", "x x x x x x x x i i i i i i i i"; ; memory "hfuse" size = 1; min_write_delay = 4500; max_write_delay = 4500; read = "0 1 0 1 1 0 0 0 0 0 0 0 1 0 0 0", "x x x x x x x x o o o o o o o o"; write = "1 0 1 0 1 1 0 0 1 0 1 0 1 0 0 0", "x x x x x x x x i i i i i i i i"; ; memory "efuse" size = 1; min_write_delay = 4500; max_write_delay = 4500; read = "0 1 0 1 0 0 0 0 0 0 0 0 1 0 0 0", "x x x x x x x x x x x x x o o o"; write = "1 0 1 0 1 1 0 0 1 0 1 0 0 1 0 0", "x x x x x x x x x x x x x i i i"; ; memory "lock" size = 1; min_write_delay = 4500; max_write_delay = 4500; read = "0 1 0 1 1 0 0 0 0 0 0 0 0 0 0 0", "x x x x x x x x x x o o o o o o"; write = "1 0 1 0 1 1 0 0 1 1 1 x x x x x", "x x x x x x x x 1 1 i i i i i i"; ; memory "calibration" size = 1; read = "0 0 1 1 1 0 0 0 0 0 0 x x x x x", "0 0 0 0 0 0 0 0 o o o o o o o o"; ; memory "signature" size = 3; read = "0 0 1 1 0 0 0 0 0 0 0 x x x x x", "x x x x x x a1 a0 o o o o o o o o"; ; ; </code></pre> <p>So I thought I'd be good to go: I've set the programmer type to <code>ArduinoISP</code> and the board type to <code>ATmega328 on a breadboard (8 MHz internal clock)</code> in the IDE.</p> <p>However, when I try to either upload the Arduino bootloader, or use the <code>Upload using programmer</code> feature on the <code>Blink</code> example, I get this:</p> <pre><code>avrdude: Device signature = 0x000000 avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check. </code></pre> <p>Full output:</p> <pre><code>/usr/share/arduino/hardware/tools/avrdude -C/usr/share/arduino/hardware/tools/avrdude.conf -v -v -v -v -patmega328 -cstk500v1 -P/dev/ttyACM0 -b19200 -Uflash:w:/tmp/build6008715511691559175.tmp/Blink.cpp.hex:i avrdude: Version 5.11.1, compiled on Apr 28 2013 at 18:46:46 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2009 Joerg Wunsch System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf" User configuration file is "/home/cactus/.avrduderc" Using Port : /dev/ttyACM0 Using Programmer : stk500v1 Overriding Baud Rate : 19200 avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Send: 0 [30] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] AVR Part : ATMEGA328 Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PC2 RESET disposition : dedicated RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- eeprom 65 20 4 0 no 1024 4 0 3600 3600 0xff 0xff Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- flash 65 6 128 0 yes 32768 128 256 4500 4500 0xff 0xff Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- lfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- hfuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- efuse 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- lock 0 0 0 0 no 1 0 0 4500 4500 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : STK500 Description : Atmel STK500 Version 1.x firmware avrdude: Send: A [41] . [80] [20] avrdude: Recv: . [14] avrdude: Recv: . [02] avrdude: Recv: . [10] avrdude: Send: A [41] . [81] [20] avrdude: Recv: . [14] avrdude: Recv: . [01] avrdude: Recv: . [10] avrdude: Send: A [41] . [82] [20] avrdude: Recv: . [14] avrdude: Recv: . [12] avrdude: Recv: . [10] avrdude: Send: A [41] . [98] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] Hardware Version: 2 Firmware Version: 1.18 Topcard : Unknown avrdude: Send: A [41] . [84] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [85] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [86] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [87] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: A [41] . [89] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] Vtarget : 0.0 V Varef : 0.0 V Oscillator : Off SCK period : 0.1 us avrdude: Send: A [41] . [81] [20] avrdude: Recv: . [14] avrdude: Recv: . [01] avrdude: Recv: . [10] avrdude: Send: A [41] . [82] [20] avrdude: Recv: . [14] avrdude: Recv: . [12] avrdude: Recv: . [10] avrdude: Send: B [42] . [86] . [00] . [00] . [01] . [01] . [01] . [01] . [03] . [ff] . [ff] . [ff] . [ff] . [00] . [80] . [04] . [00] . [00] . [00] . [80] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: E [45] . [05] . [04] . [d7] . [c2] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: Send: P [50] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude: AVR device initialized and ready to accept instructions Reading | avrdude: Send: V [56] 0 [30] . [00] . [00] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] avrdude: Send: V [56] 0 [30] . [00] . [01] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] ################avrdude: Send: V [56] 0 [30] . [00] . [02] . [00] [20] avrdude: Recv: . [14] avrdude: Recv: . [00] avrdude: Recv: . [10] ################################## | 100% 0.06s avrdude: Device signature = 0x000000 avrdude: Yikes! Invalid device signature. Double check connections and try again, or use -F to override this check. avrdude: Send: Q [51] [20] avrdude: Recv: . [14] avrdude: Recv: . [10] avrdude done. Thank you. </code></pre> <p>I've double-checked and triple-checked, I've rebuilt the whole circuit on another breadboard with another ATmega328, I've even checked the jumper cables one by one, they all work.</p> <p>How do I use my Arduino Uno as an ISP to upload code to this blank ATmega328?</p>
<p>Feeling really stupid about it in retrospect...</p> <p>One last thing I tried was taking the ATmega328P out from the Arduino Uno and plugging the blank ATmega328 in its place, thinking I could use the Uno programmer as such to burn the bootloader on the chip. That didn't work and I don't know if it's supposed to work.</p> <p>However, to plug the new chip into the DIL on the Uno, I had to bend the DIP legs inwards slightly to give it a smaller straddle. After seeing that it didn't work, I plugged the ATmega328P back into the Uno and plugged the ATmega328 back into the breadboard. However, this time, because of the smaller straddle, it slipped in deeper into the breadboard, the plastic package actually touching the board. And with this setup, wiring it up again via the Arduino and using the <code>ArduinoISP</code> I was able to burn both the bootloader and (via the 'Upload with programmer' functionality) test programs to it.</p> <p>TL;DR: I didn't have the blank ATmega328 properly plugged into the breadboard...</p>
1683
|spi|
util/delay.h from arduino _delay_ms not delaying in accurate time with my hardware configuration
2014-05-24T11:38:22.843
<p>I have configured my arduino as a flash programmer and i'm sending data to an atmega328P. It is actually working and the data is send to my atmega328. But what is strange that the _delay_ms from from the Arduino library is not delaying in accurate seconds.</p> <p>_delay_ms(1000) who should wait from 1s, is actually more 8 seconds from my atmega328P hardware point of view. </p> <p>My question is what could possibly turn the program wrong. I'm strongly assuming that this a misconfigured clock cycle from my Atmega, but this is my newbie guess, it can be something else, that's why I'm posting my question here. Can someone can hint me what's wrong with my configuration?</p> <p>Here's the sample code, a dumb toggle pin on / off:</p> <pre><code>#include &lt;util/delay.h&gt; // from arduino library /* */ DDRB |= 0b0000001; while (1) { PORTB = 0b00000001; _delay_ms(1000); // it should be 1 second, but on my hardware it is more ~8 seconds PORTB = 0b00000000; _delay_ms(1000); } </code></pre> <p>And my configuration is (from arduino IDE) </p> <p><em>Arduino Pro / pro Mini (3,3v 8 Mhz) / Atmega 328</em></p> <p>I have tried with </p> <p><em>Arduino Pro / pro Mini (5v 16 Mhz) / Atmega 328</em> </p> <p>expecting that more power will affect speed, but the result is actually the same.</p>
<p>At a 30000 ft. level, it's because the defined <code>F_CPU</code> value doesn't match your hardware. This can happen because the incorrect device is chosen in the IDE or because the device is misconfigured in boards.txt, or because the hardware is somehow different from what is expected.</p> <p>Given that you are using a bare ATmega328P, assuming that you've selected the correct crystal, and that the apparent time scale is 8x, it is likely that the CKDIV8 fuse is set. This means that the chip is running at 1/8 the crystal speed. You will need to unprogram (set to 1) bit 7 of the low fuse byte in order to reset it. Use <a href="https://learn.adafruit.com/arduino-tips-tricks-and-techniques/arduinoisp#bonus-using-with-avrdude">AVRdude from the command line</a> to read the low fuse byte (<code>-U lfuse:r:-:h</code>), set the bit (lfuse | 0x80), and then write it back (<code>-U lfuse:w:0xnn:m</code>).</p>
1717
|arduino-uno|sensors|library|
Why does increasing resistance make a capacitive sensor more sensitive?
2014-05-26T16:02:22.130
<p>From the <a href="http://playground.arduino.cc/Main/CapacitiveSensor?from=Main.CapSense" rel="noreferrer">Capacitive Sensor Page</a> on the Arduino website, it states the following:</p> <blockquote> <p>The capacitiveSensor method toggles a microcontroller send pin to a new state and then waits for the receive pin to change to the same state as the send pin. A variable is incremented inside a while loop to time the receive pin's state change. The method then reports the variable's value, which is in arbitrary units.</p> </blockquote> <p>AND</p> <blockquote> <p>Use a 1 megohm resistor (or less maybe) for absolute touch to activate. With a 10 megohm resistor the sensor will start to respond 4-6 inches away. With a 40 megohm resistor the sensor will start to respond 12-24 inches away (dependent on the foil size)...</p> </blockquote> <p>However, as mentioned above, what I'm measuring is the time taken to change state, and I understand that more resistance = more time taken = higher value, how exactly does increasing the resistance make the sensor more sensitive, allowing it to respond without even touching it (i.e., inches away)?</p> <p>Am I not simply increasing the time taken to change state by increasing resistance? How would that make it more sensitive?!?</p>
<p>A capacitor is created from two conductors with a dielectric between them. The capacitance of the capacitor is determined by the surface area of the conductors and the distance between them. The larger the conductive surface, the higher the capacitance. <strong>The further apart the conductors, the smaller the capacitance. Using a higher resistance means that you can use a smaller capacitance, i.e. be further away from the sensor</strong>, to get the same results.</p>
1719
|sensors|shields|system-design|
How do I know if a board fits my requirements?
2014-05-26T17:22:25.927
<p>I'm new to Arduino and I saw on their website that there are many different kinds of boards. What are the differences, or to be more specific, how would I know which board meets my requirements? I understand that the shields can be connected to the board, but are some boards that do not support certain shields?</p> <p>Another thing, is it possible to connect external sensors to an Arduino board or there are special sensors that can communicate with the board? I want to use weight sensors.</p>
<p>There are some good answers already, but here are a some secondary considerations</p> <ol> <li>Many Arduino boards use a ceramic resonator rather than a crystal as their timing source. This rules out using them in critical timing applications. For instance you might need to add a real time clock board if you need to keep track of time of day.</li> <li>The boards based on the Atmega328 chip only have three timers, and one of these (Timer 0) is used by the delay() function, which is in turn used by other libraries. Timer 1 and timer 2 get used if you include the PWM and tone libraries. The boards based on the 2560 chip have 6 timers, which is a lot more generous.</li> <li>If you want to count external inputs at speed (i.e. up to 4MHz), you need to access the Tn pin of the appropriate timer counter(s). On the UNO, only T0 is exposed to the outside world, and the timer is already in use. Even the Mega2560 boards only seem to expose T0 and T5.</li> </ol>
1726
|serial|
How does the Arduino handle serial buffer overflow?
2014-05-24T16:19:58.203
<p>How does the Arduino handle serial buffer overflow? Does it throw away the newest incoming data or the oldest? How many bytes can the buffer hold? </p>
<h2>Receiving</h2> <p>You can see from the source of HardwareSerial that if an incoming byte finds the ring buffer full it is discarded:</p> <pre class="lang-C++ prettyprint-override"><code>inline void store_char(unsigned char c, ring_buffer *buffer) { int i = (unsigned int)(buffer-&gt;head + 1) % SERIAL_BUFFER_SIZE; // if we should be storing the received character into the location // just before the tail (meaning that the head would advance to the // current location of the tail), we're about to overflow the buffer // and so we don't write the character or advance the head. if (i != buffer-&gt;tail) { buffer-&gt;buffer[buffer-&gt;head] = c; buffer-&gt;head = i; } } </code></pre> <blockquote> <p>I get the impression that if I transmit data to the Arduino and don't have an active "puller" of data on the Arduino side then if more data arrives than can fit in the buffer, it will be discarded. Can you confirm that? </p> </blockquote> <p>Yes it will be discarded. There is no software or hardware flow control, unless you implement your own.</p> <p>However with a 64-byte buffer, and receiving data at (say) 9600 baud, you get one byte every 1.04 ms, and thus it takes 66.6 ms to fill up the buffer. On a 16 MHz processor you should be able to check the buffer often enough that it doesn't fill up. All you really have to do is move the data from the HardwareSerial buffer to your own, if you don't want to process it right now.</p> <p>You can see from the <code>#if (RAMEND &lt; 1000)</code> check that the processors with 1000+ bytes of RAM get the 64-byte buffer, the ones will less RAM get the 16-byte buffer.</p> <hr> <h2>Sending</h2> <p>Data that you write is placed in a same-sized buffer (16 or 64 bytes). In the case of sending if the buffer fills up the code "blocks" waiting for an interrupt to send the next byte out the serial port. </p> <p>If interrupts are turned off this will never happen, thus you do <strong>not</strong> do Serial prints inside an Interrupt Service Routine.</p>
1752
|arduino-mega|wifi|
What is the cheapest way to add wifi to Arduino?
2014-05-29T08:10:51.407
<p>I am trying to find some sort of wifi adapter for Arduino, it needs to be as small as possible (not a shield) and as cheap as possible. </p> <p>So far I can only seem to find shields that cost about £10+ but I figured that if you can get a replacement wifi adapter for a laptop for next to nothing that I should be able to get a wifi adapter for Arduino much cheaper than this.</p> <p>It's possible I just don't know what to search for.</p>
<p><a href="https://www.forward.com.au/pfod/CheapWifiShield/index.html" rel="nofollow noreferrer">https://www.forward.com.au/pfod/CheapWifiShield/index.html</a> provides a very inexpensive wifi addon for Arduino</p> <p><a href="https://i.stack.imgur.com/OjJAA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OjJAA.jpg" alt="Completed Shield" /></a></p> <p>The WiFi Shield needs just two parts, 4 bits of wire and some soldering equipment. Parts List:-</p> <p>Adafruit HUZZAH ESP8266 Breakout US$9.95 + shipping<br /> Uno Protoshield US$1.88 + shipping<br /> Total US$11.83 (as of June 2015)<br /> For an even cheaper version ~US7 see <a href="https://www.forward.com.au/pfod/CheapWifiShield/ESP2866_01_WiFi_Shield/index.html" rel="nofollow noreferrer">https://www.forward.com.au/pfod/CheapWifiShield/ESP2866_01_WiFi_Shield/index.html</a><br /> Both of these need a US10 USB to TTL cable to program them</p> <p>After you have installed the <a href="https://www.forward.com.au/pfod/pfodParserLibraries/pfodESP8266BufferedClient.zip" rel="nofollow noreferrer">pfodESP8266BufferedClient library</a>, open the Arduino IDE and copy this sketch, <a href="https://www.forward.com.au/pfod/CheapWifiShield/ESP8266_WifiShield.ino.txt" rel="nofollow noreferrer">ESP8266_WifiShield.ino</a>, into the IDE. That provides this setup webpage. <a href="https://i.stack.imgur.com/nYvAK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nYvAK.png" alt="Config webpage" /></a></p>
1758
|time|analogread|
What's the most accurate way to time-stamp analogRead data?
2014-05-29T16:30:12.650
<p>I want to sample an Analog sensor as fast as possible, and time-stamp each sample that I take as accurately as possible. </p> <p>Currently, I'm doing the following:</p> <pre><code>val = analogRead(SENSOR_PIN); clocktime = micros(); writeData(val, clocktime); // writes the values to an SD card </code></pre> <p>I'm wondering if there is a more-accurate way of time-stamping the data from the analogRead call. Put another way, I would like to record the exact time that the analogRead data was collected. My guess is that this is basically impossible on an Arduino, so what technique will let me get as close as possible?</p>
<p>For "as fast as possible", I'd</p> <ol> <li>Rewrite your sampling code in assembly language (just those two statements, not the whole program); and</li> <li>Buffer the raw data pairs in memory if you have enough of it, then store it to the card after the measurement burst. If you need more data space, consider that the timing of a tight assembly loop will be consistent (and fast!) and can be measured. You may not need to read the clock at all. Note that you can get the same timing consistency using C/C++ if you read the analog and clock ports directly, and maybe as fast. It's just that with assembly language, WYWIWYG (what you write is what you get); the compilers' code-generators and optimizers won't mess with it.</li> </ol> <p>A possible issue with your code as you've written it is that writeData probably buffers the data on most calls, but whenever a call results in a full buffer, writes the whole buffer to the card, introducing jitter into your sampling.</p> <p>Addressing your edit of June 3, 2014, "I would like to record the exact time that the analogRead data was collected":</p> <p>Since you proposed using micros() (as opposed to a real-time clock), I assume you are satisfied with the relative time. Once you know your data collection code is completely predictable, then the offset from reading data to reading time is constant, and since we're using relative time anyway, can be discounted, or at least, corrected for.</p> <p>It isn't <em>completely</em> predictable of course, since in this case, you're using an interrupt-maintained clock, and can expect that sometimes the interrupt will occur between the data read and the clock read, stretching the offset for that tuple. To get even more accurate, you'd need to keep interrupts off, read the timer yourself in an invariant way. f/ex, you might run the timer at such a rate that you could expect to take two or more samples between overflows of the low-order byte, read and store only the low order byte as your time sample, and post process the time data to reconstruct the high order byte by detecting wrap-around in the low-order.</p> <p>With no interrupts running, and once you know the rate at which you can sample data without reading the clock, you could read and save the clock once immediately prior to taking the first sample, and infer the times of each subsequent sample based on the known sample rate.</p>
1759
|arduino-uno|
How do I avoid this error trying to connect arduino to pc with linux fedora 20
2014-05-29T18:12:55.957
<p>I used Arduino successfully on my old Linux Fedora 12 system. Now I have a brand new PC with Fedora 20, and have today installed Arduino on it. In my first attempt to use it I typed Arduino as follows at the root prompt, after the "yum install arduino" gave me "Complete!", as follows:</p> <pre><code>Complete! [1344][root@localhost:/home/Harry]# arduino WARNING: RXTX Version mismatch Jar version = RXTX-2.2 native lib Version = RXTX-2.2pre2 </code></pre> <p>Subsequently I have loaded the "Blink" sketch, and that is running nicely, whether I start the IDE from the command line, which still gives me the same WARNING, or from the desktop icon, which does not give it.</p> <p>So my question is: please, does this WARNING matter? If so, what should I do about it?</p>
<p>The warning, as I'm sure you can tell, is about a mismatch in version of RXTX arduino is expecting, and what is installed on your system. If everything is functioning, I would not worry about it at all. The versions seem to only be slightly different, maybe just a few bug fixes are missing from the older one. </p> <p>RXTX is a library for java to communicate with serial devices, but it is not under development anymore and only available from mirrors, not the original developer site. Arduino has moved on to a library called jSSC, which is currently being maintained, and a much better library IMHO. The change to jSSC is still only in the arduino beta version, 1.5.6r2 at time of writing, but it works very well. Anyway, if RXTX ever actually gives you trouble, you can download the beta version of arduino and not have to deal with it. </p>
1764
|uploading|networking|
How do I remotely acquire data from Arduino based portable device?
2014-05-29T23:40:56.367
<p>I am making a device which will have an Arduino board and a sensor attached to it. The sensor will acquire data every 10 minutes and the data will be uploaded to my server. The size of every upload is about 200 characters. I'd like this device to work anywhere in my city (US).</p> <p>What are my options for uploading data to my server? Keep in mind that it will work without human intervention. FYI... this is NOT for reconnaissance device! ;)</p>
<p>I can't guarantee <em>anywhere</em> in your city, but this hack will work pretty much wherever there is cell coverage for the carrier you choose.</p> <p>You'll want the <strong><a href="http://arduino.cc/en/Main/ArduinoGSMShield" rel="nofollow noreferrer">GSM shield</a></strong>.</p> <blockquote> <p><img src="https://i.stack.imgur.com/294KE.jpg" alt=""></p> </blockquote> <p><em>Picture from Arduino</em></p> <p>Anyway, it uses pins 2, 3, and 7 on it. It also has the ability to solder (on the bottom of it) a microphone and speaker connection. You'll need to buy a SIM card and a contract to connect your shield to a network. I don't know how often you would use this, but I've seen a pay-as-you-go plan that charges you $2 for unlimited talk/text/internet per day. If you're going to use this once a month, that would be the way to go. I didn't look to see if they supported the GSM shield (it was on TMobile's site). You would want to contact them for more details. Also, depending on where you live, I don't know if you would get good coverage. This goes with any cell phone provider, but make <em>sure</em> that you get coverage where you want to go (and don't always trust the maps they provide).</p>
1773
|timers|pwm|millis|
Does millis() conflict with the PWM pins associated with timer 0?
2014-05-30T18:00:41.717
<p>I've read that the <code>millis()</code> function uses the same timer as a couple of PWM pins. </p> <p>If you're using those PWM pins, will <code>millis()</code> still return the correct value?</p>
<p>Just to add to @Ignacio's answer which has directly answered your question. The "conflict" you speak of is in relation to <code>Timer0</code>'s prescaler. </p> <p>For the most part, you can use those pins (incidentally pins 5 and 6 on the UNO) with PWM without an issue, and read the correct value of <code>millis()</code> (as well as get the expected delay from <code>delay</code>)</p> <p>Where you run into problems is if you want to change the prescaler (usually to modify the frequency of the PWM signal). If you change this, then you directly affect the calculation and reporting of <code>millis()</code> and the length of <code>delay(x)</code>. </p>
1787
|arduino-pro-mini|temperature-sensor|
1 Wire temperature sensor
2014-05-31T12:58:15.603
<p>I bought a waterproof temperature sensor from Ebay, I am fairly new to this and not sure what I need or need to do in order to get the sensor to output the current temperature to the serial monitor.</p> <p>Does anyone have any information on where I can get some information on how to wire this? I have looked at various videos online but they are all for a dallas temp sensor and use the dallas library.</p> <p><a href="http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK%3aMEWNX%3aIT&amp;_trksid=p3984.m1439.l2649" rel="nofollow">http://www.ebay.co.uk/itm/181393039374?ssPageName=STRK:MEWNX:IT&amp;_trksid=p3984.m1439.l2649</a></p>
<p>This probe has the Dallas (now Maxim) DS18b20 sensor in it so you're already on the right track. Search for DS18b20 at <a href="http://www.arduino.cc/" rel="nofollow">arduino.cc</a>. You'll find libraries and lots of forum discussions about using these sensors. Also see page 6 of the <a href="http://datasheets.maximintegrated.com/en/ds/DS18B20.pdf" rel="nofollow">DS18b20 datasheet</a>; there are two schematics for wiring the device.</p> <p>I'm using the parasitic mode (Figure 4 on that page) except I eliminated the transistor switch and connected the MCU pin for the strong-pullup directly to the one-wire bus.</p>
1788
|voltage-level|pwm|current|
Does the square-wave nature of PWM dictate how much resistance you need?
2014-05-31T16:52:14.733
<p>I think the answer is yes, but I wanted to ask the question anyway for future common reference. And to check my understanding.</p> <p>Say I want to power 10 LEDs with PWM with my Mega 2560. I have a bunch of 200 ohm resistors.</p> <p>I know the Mega and most other Arduinos can safely provide a maximum of 200mA total current. 200mA / 10 is 20mA per LED maximum.</p> <p>Using my 200 ohm resistors I can calculate how much voltage will supply 20 mA of current:</p> <pre><code>V = 200 ohms * 20mA V = 4V </code></pre> <p>So I just need to make sure to analogWrite less than or equal to 4V to each of the ten LEDs and I won't cross the 200mA threshold. That's if PWM was true analog.</p> <p>However, PWM is not true analog, and if I analogWrite 4V to each pin, they're going to spend most of the time at 5V and some of the time at 0V.</p> <p>When every pin is at 5V the board has to supply</p> <pre><code>(5V / 200 ohms) * 10 = 250mA </code></pre> <p>Which is over the spec, so I am in danger of damaging my board. Right?</p> <p>So if I want to calculate the maximum current draw of the 10 LEDS being powered simultaneously with PWM, I have to assume that they are all getting 5V regardless of what I analogWrite to them. I do not actually have control over the voltage, I only have control over the resistance.</p> <p>Thus in order to be safe I need to get some new resistors with resistance:</p> <pre><code>5V / 20mA = 250 ohms </code></pre> <p>Is this all correct?</p>
<p>Note that PWM does not actually drop the output voltage. It generates variable length pulses of 5V at different "duty cycles" (percent on vs percent off).</p> <p>For an LED you might get away with using PWM to vary the power that passes through the LED since it can probably tolerate over-current for brief intervals. </p> <p>What you should really do is calculate resistor value based on LED voltage drop and maximum current:</p> <p>Say you have a red LED with a 1.8V voltage drop.</p> <p>5V supply - 1.8 LED voltage drop = 3.2 V If the LED can handle a max of 15 mA, that would be 3.2/.015 ≈ 213Ω. Round up to the nearest 10% resistor value, 220Ω. That would give you about 14.8mA through the LED, slightly less than it's max.</p> <p>If you then power the LED through a PWM pin, running the analog output at max will drive the LED at max brightness, and lower analog output levels will make the LED <em>appear</em> dimmer. Note that the LED will actually be rapidly flashing between full intensity (limited by your current limiting resistor, assuming you have one) and off. Our eyes average out that flashing light and see it as being a dimmer, constant light. </p>
1793
|analogwrite|
Non-blocking strobing code?
2014-06-01T17:52:51.633
<p>I'm trying to figure out how to create some non-blocking code to strobe some RGB leds with analogwrite 7 times a second; I'm really not to sure how to go about this. If anybody could give me some help that'd be great! :)</p>
<p>Timers are the best way to go, (much) less overhead and you don't have to worry about it elsewhere in your code (other than managing variable use between your main loop and your ISRs). </p> <p>But I do have a habit of doing things the hard way in code first and then move to timers once I've got it the way I'd like. </p> <p>Here is sample code to flash the on board LED X times per second, I have calculated it to mean, ON 7 times per second and OFF 7 times as well (meaning, there is a change of state 14 times per second). </p> <p>This code isn't efficient, it doesn't take into consideration that the value is already set or not, it just writes the value that it should be right now. </p> <p>Finally, to go to analogWrite and use PWM, just change:</p> <pre><code>digitalWrite(LED, HIGH); </code></pre> <p>to </p> <pre><code>analogWrite(NEW_PIN, PWM_VALUE); </code></pre> <p>code:</p> <pre><code>#define LED 13 #define TIMES_PER_SECOND 7 const int M1 = 1000 / TIMES_PER_SECOND; const int M2 = 1000 / TIMES_PER_SECOND / 2; void setup(){ pinMode(LED,OUTPUT); } void loop(){ if(millis()%M1&lt;M2){ digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } } </code></pre> <p>Remember there is overhead with digital (and analog) writes, so (as I mentioned) you could check to see if the value is set already or not and skip the write.</p>
1794
|arduino-uno|battery|analogread|
Arduino ADC Reference Voltage if it is Battery Powered
2014-06-01T21:34:03.997
<p>I am looking to possibly monitor battery power to the Arduino using its ADC. This is fairly straight forward and simple (especially if using the Arduino API); however, if the battery is powering the Arduino and is unregulated externally, won't the ADC reference voltage constantly be dropping with the battery? In other words, wouldn't the ADC value would constantly read the same value (the max value) even though the battery would actually be decreasing in voltage?</p> <p>If this is the case, it would be both inefficient and pointless to measure the battery voltage.</p>
<p>@ryeager's link to <a href="http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/#comment-71836" rel="nofollow">http://provideyourown.com/2012/secret-arduino-voltmeter-measure-battery-voltage/#comment-71836</a> has this code for reading the Arduino's battery voltage:</p> <pre><code>long readVcc() { // Read 1.1V reference against AVcc // set the reference to Vcc and the measurement to the internal 1.1V reference #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) ADMUX = _BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) ADMUX = _BV(MUX5) | _BV(MUX0); #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) ADMUX = _BV(MUX3) | _BV(MUX2); #else ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1); #endif delay(2); // Wait for Vref to settle ADCSRA |= _BV(ADSC); // Start conversion while (bit_is_set(ADCSRA,ADSC)); // measuring uint8_t low = ADCL; // must read ADCL first - it then locks ADCH uint8_t high = ADCH; // unlocks both long result = (high&lt;&lt;8) | low; result = 1125300L / result; // Calculate Vcc (in mV); 1125300 = 1.1*1023*1000 return result; // Vcc in millivolts } </code></pre> <p>The trick here is that it measures its internal reference of 1.1V using the battery voltage, and then inverts it to calculate the unknown reference voltage.</p> <p>The ADMUX magic in this code can enable other interesting ADC readings, such as differential measurements, and differential ADC measurements with gain, depending on the component and datasheet.</p>
1798
|led|
Executing multiple functions/commands on Arduino
2014-06-02T05:03:38.993
<p>I am using an <a href="http://www.rfduino.com/" rel="nofollow">RFduino</a> and an iOS application to control some RGB LEDs.</p> <p>This is how I'm sending a string command to the module:</p> <pre><code>- (IBAction)fadeButtonPressed:(id)sender { [rfduino send:[@"fade" dataUsingEncoding:NSUTF8StringEncoding]]; } </code></pre> <p>These command(s) are coming back just fine on the RFduino side:</p> <pre><code>void RFduinoBLE_onReceive(char *data, int len) { if (strncmp(data, "fade", 4) == 0) { // begin fading chosen LED colour } } </code></pre> <p>Is there a better way of executing multiple functions on Arduino? It seems to me that there should be a better way of doing what I'm trying to do.</p> <p>Originally for example I was getting an issue where the "fade" string was coming back as "fadek" so I used <code>strncmp(data, "fade", 4)</code> instead of <code>strcmp(data, "fade")</code> and this fixed the issue.</p> <p>I guess I'd like a way of cleaning up my code and perhaps make it easier to introduce new bits of functionality depending on which strings are coming back.</p> <p>The functions I would like to be able to do would be controlling of the RGB colours and then <em>Fading</em> or <em>Blinking</em> that particular chosen colour.</p> <p>What if I wanted to introduce faster blinking? Rather than setting another command integer and adding another condition is there a cleaner approach?</p> <p>The selection of the colours is set by selection of a color wheel within my iOS application. This is working fine. The problem is that the Blinking and Fading does not blink/fade the selected colour (<code>command 0</code>).</p> <p>Here is my entire sketch so far:</p> <pre><code>#include &lt;RFduinoBLE.h&gt; // Pin 2 on the RGB LED. int rgb2_pin = 2; // red int rgb3_pin = 3; // green int rgb4_pin = 4; // blue int brightness = 0; int fadeAmount = 5; // Command properties. int command = 0; void setup() { // debug output at 9600 baud Serial.begin(9600); // Setup the LEDs for output. pinMode(rgb2_pin, OUTPUT); pinMode(rgb3_pin, OUTPUT); pinMode(rgb4_pin, OUTPUT); // This is the data we want to appear in the advertisement // (the deviceName length plus the advertisement length must be &lt;= 18 bytes. RFduinoBLE.advertisementData = "rgb"; // Start the BLE stack. RFduinoBLE.begin(); } void loop() { if (command == 1) { // Fade in/out chosen colour. analogWrite(rgb2_pin, brightness); analogWrite(rgb3_pin, brightness); analogWrite(rgb4_pin, brightness); // Change the brightness for next time through the loop: brightness = brightness + fadeAmount; // Reverse the direction of the fading at the ends of the fade: if (brightness == 0 || brightness == 255) { fadeAmount = -fadeAmount ; } // Wait for 30 milliseconds to see the dimming effect delay(30); } else if (command == 2) { // Blink digitalWrite(rgb2_pin, HIGH); digitalWrite(rgb3_pin, HIGH); digitalWrite(rgb4_pin, HIGH); delay(200); digitalWrite(rgb2_pin, LOW); digitalWrite(rgb3_pin, LOW); digitalWrite(rgb4_pin, LOW); delay(200); } } void RFduinoBLE_onConnect() {} void RFduinoBLE_onDisconnect() {} void RFduinoBLE_onReceive(char *data, int len) { Serial.println(data); // Each transmission should contain an RGB triple. if (strncmp(data, "fade", 4) == 0) { command = 1; } else if (strncmp(data, "blink", 5) == 0) { command = 2; } else { // Change colour. // Reset other functions. command = 0; if (len &gt;= 3) { // Get the RGB values. uint8_t red = data[0]; uint8_t green = data[1]; uint8_t blue = data[2]; // Set PWM for each LED. analogWrite(rgb2_pin, red); analogWrite(rgb3_pin, green); analogWrite(rgb4_pin, blue); } } Serial.println(command); } </code></pre>
<p>Ended up going with something <a href="https://stackoverflow.com/questions/24005992/arduino-state-machine">like this</a>:</p> <pre><code>#include &lt;RFduinoBLE.h&gt; // State properties. int state = 1; char command; String hexstring; // RGB pins. int redPin = 2; int grnPin = 3; int bluPin = 4; // Setup function to set RGB pins to OUTPUT pins. void setup () { pinMode(redPin, OUTPUT); pinMode(grnPin, OUTPUT); pinMode(bluPin, OUTPUT); // This is the data we want to appear in the advertisement // (the deviceName length plus the advertisement length must be &lt;= 18 bytes. RFduinoBLE.deviceName = "iOS"; RFduinoBLE.advertisementInterval = MILLISECONDS(300); RFduinoBLE.txPowerLevel = -20; RFduinoBLE.advertisementData = "rgb"; // Start the BLE stack. RFduinoBLE.begin(); } void loop () { switch (command) { case 1: // Blink. break; case 2: // Fade. break; } //RFduino_ULPDelay(INFINITE); } // Converts HEX as a String to actual HEX values. // This is needed to properly convert the ASCII value to the hex // value of each character. byte getVal (char c) { if (c &gt;= '0' &amp;&amp; c &lt;= '9') return (byte)(c - '0'); else return (byte)(c - 'a' + 10); } // Process each function/command. void processCommand (int command, String hex) { switch (command) { case 'b': command = 1; // Set blink mode. break; case 'f': command = 2; // Set fade mode. break; case 'c': // We put together 2 characters as is // done with HEX notation and set the color. byte red = getVal(hex.charAt(1)) + (getVal(hex.charAt(0)) &lt;&lt; 4); byte green = getVal(hex.charAt(3)) + (getVal(hex.charAt(2)) &lt;&lt; 4); byte blue = getVal(hex.charAt(5)) + (getVal(hex.charAt(4)) &lt;&lt; 4); // Set the color. setColor (red, green, blue); break; } } // Sets the color of each RGB pin. void setColor (byte red, byte green, byte blue) { analogWrite(redPin, red); analogWrite(grnPin, green); analogWrite(bluPin, blue); delay(200); } // This function returns data from the radio. void RFduinoBLE_onReceive (char *data, int len) { for (int i = 0; i &lt; len; i++) { stateMachine(data[i]); } } // Main state machine function, which processes // data depending on the bytes received. void stateMachine (char data) { switch (state) { case 1: if (data == 1) { state = 2; } break; case 2: if (data == 'b' || data == 'f' || data == 'c') { command = data; hexstring = ""; state = 3; } else if (data != 1) { // Stay in state 2 if we received another 0x01. state = 1; } break; case 3: if ((data &gt;= 'a' &amp;&amp; data &lt;= 'z') || (data &gt;= '0' &amp;&amp; data &lt;= '9')) { hexstring = hexstring + data; if (hexstring.length() == 6) { state = 4; } } else if (data == 1) { state = 2; } else { state = 1; } break; case 4: if (data == 3) { processCommand(command, hexstring); state = 1; } else if (data == 1) { state = 2; } else { state = 1; } break; } } </code></pre>
1799
|serial|i2c|python|
Best way to interact arduino and python
2014-06-02T05:57:28.000
<p>So, i've worked with the pySerial module for python, where I communicated with my arduino via serial. However, this module only works for 32bits and I would like to make my project work on both architectures (I know the person could just install the 32-bits version on the 64-bits architecture). Also, the connection fails a lot of times and I wasn't able to correct it. <p>I think I can use the true USB power of the arduino Leonardo to connect to the python in a different way, but I don't know where to start. But I think this approach will be more professional. <p>Im really intersted in learning, so if you guys could at least indicate documents so I can understand how to make this connection between Leonardo and Python, I'll be happy. I've read the arduino page about the CDC but couldn't find useful information.</p> <p><p>Thank you so much. </p> <p>Update:</p> <p>When i used serial, I had problems with messages getting acumulated at the buffer, and then after some seconds i was reading 10s delayed messages. Also, when I sent a string like: "12345678", it was really easy to get one number less, like: "1345678". This happened frequently to me. So I think I need to implement a protocol to deal with these problems.</p>
<p>I did some work in Java using USB some years ago and I can share some experiences:</p> <ul> <li>Things are not neary as straightforward as using serial.</li> <li>Your code will probably be platform specific, windows being a bit more weird about handling usb. (unless using something to abstract that away, like <a href="http://pyusb.sourceforge.net/docs/1.0/tutorial.html" rel="nofollow" title="PyUSB">PyUSB</a> which wraps libUSB or openUSB, this however does not guarantee platform independency because these libraries also have their weirdnesses).</li> <li>If you drop down to USB level programming, things can get very messy (again, this can be abstracted away). USB is (at least in my opinion) a complicated protocol, especially for beginners. </li> </ul> <p>So unless you really need something that only USB can provide, a nice and dandy serial communication will give you much less headaches. Thats why serial did not die until now.</p> <p>As for debugging why your communication is not reliable I would try several things:</p> <ul> <li>See if your application might send something that is interpreted as a control character</li> <li>Drop your baud rate to something lower and see if it still loses data. If so, you might overflow the buffer of your receiver (and you would need <a href="http://tldp.org/HOWTO/Text-Terminal-HOWTO-11.html" rel="nofollow">flow control</a> in this case)</li> <li>Check your hardware! I've had bad wires or solders on numerous occasions</li> </ul>
1801
|interrupt|timers|isr|
Is volatile needed when variable is accessed from > 1 ISRs, but not shared outside ISRs?
2014-06-02T10:35:22.667
<p>It's <a href="http://arduino.cc/en/Reference/attachInterrupt">clearly documented</a> that when global data is shared with an ISR and the main program, the data needs to be declared <code>volatile</code> in order to guarantee memory visibility (and that only suffices for 1-byte data; anything bigger needs special arrangements to guarantee also atomicity). <a href="http://www.gammon.com.au/forum/?id=11488">Here</a> we have good rules:</p> <ul> <li>Variables only used outside an ISR should not be volatile.</li> <li>Variables only used inside an ISR should not be volatile.</li> <li>Variables used both inside and outside an ISR should be volatile.</li> </ul> <p>But is <code>volatile</code> needed when the variable is accessed from > 1 ISRs, but not shared outside ISRs? For example, I have a function that maintains internal state using a <code>static</code> variable:</p> <pre><code>void func() { static volatile long counter; // volatile or not? // Do stuff with counter etc. } </code></pre> <p>That function is called in two ways: from pin interrupt, and from <a href="http://playground.arduino.cc/Code/Timer1">TimerOne library</a>:</p> <ol> <li><code>attachInterrupt(0, func, CHANGE);</code></li> <li><code>Timer1.attachInterrupt(func);</code></li> </ol> <p>There are no atomicity problems, since <a href="http://www.gammon.com.au/forum/?id=11488">when an ISR is entered, interrupts are automatically disabled</a>, but this <code>volatile</code> is more of a compiler question: what is cached and what is not.</p> <p>Better safe than sorry, of course...</p>
<p><code>volatile</code> only informs the compiler's code generator that the variable may be modified by something other than the code being generated, so not to assume any copy of it remains accurate.</p> <p>ISR code must be written/generated under the assumption that it has no context at entry, and preserve the CPU's context around its (ISR's) own operation. So, as with the indivisbility of non-atomic operations, volatility depends, <em>in this case*</em>, on whether or not interrupts are allowed to nest. If non-nesting is guaranteed, the shared variable can not change by other than this ISR during its own execution. If your ISR might someday be used in an environment where interrupts are allowed to nest, then that constraint will no longer hold.</p> <p>* <em>in this case</em>: <br>I'm assuming a software-maintained variable here. If we're talking about a variable that can be updated by a hardware event, a timer register for example, all bets are off: the variable is volatile no matter what.</p>
1802
|interrupt|timers|isr|pointer|
Are function pointer assignments atomic in Arduino?
2014-06-02T11:19:43.883
<p>The following snippets are from <a href="https://code.google.com/p/arduino-timerone/source/browse/#svn%2Ftrunk">TimerOne library source code</a>:</p> <pre><code>// TimerOne.h: void (*isrCallback)(); // TimerOne.cpp: ISR(TIMER1_OVF_vect) // interrupt service routine that wraps a user defined function supplied by attachInterrupt { Timer1.isrCallback(); } // TimerOne.cpp: void TimerOne::attachInterrupt(void (*isr)(), long microseconds) { if(microseconds &gt; 0) setPeriod(microseconds); isrCallback = isr; // register the user's callback with the real ISR TIMSK1 = _BV(TOIE1); // sets the timer overflow interrupt enable bit resume(); } </code></pre> <p>The question: if the timer is already running, and the main program calls <code>attachInterrupt()</code>, could the timer interrupt occur there <em>during</em> the function pointer assignment <code>isrCallback = isr;</code>? Then, with lucky timing, <code>Timer1.isrCallback();</code> function pointer would consist partly of the old and partly of the new address, causing the ISR jump to a bogus location?</p> <p>I suppose this might be the case, since function pointers are certainly wider than 1 byte, and accessing > 1 byte data isn't atomic. Possible workarounds could be:</p> <ul> <li>Always call <code>detachInterrupt()</code> to make sure the timer isn't running, before calling <code>attachInterrupt()</code>, i.e. clarify Timer1 docs.</li> <li>Or, modify Timer1, disabling timer overflow interrupts temporarily just before <code>isrCallback = isr;</code></li> </ul> <p>Does this make sense, or is there something in <code>Timer1</code> sources or function pointer assignments that I've missed?</p>
<p>It looks like you have a point. The logical thing to do would be to disable interrupts in such a way that you don't re-enable them if they were disabled in the first place. For example:</p> <pre class="lang-c++ prettyprint-override"><code> uint8_t oldSREG = SREG; // remember if interrupts are on cli(); // make the next line interruptible isrCallback = isr; // register the user's callback with the real ISR SREG = oldSREG; // turn interrupts back on, if they were on before </code></pre> <hr> <blockquote> <p>"When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example"</p> </blockquote> <p>The intention of this is to let you write code like this:</p> <pre><code> sei (); // enable interrupts sleep_cpu (); // sleep </code></pre> <p>Without that provision you might get an interrupt between those two lines, and thus sleep indefinitely (because the interrupt which was going to wake you has occurred <em>before</em> you slept). The provision in the processor that the next instruction, after interrupts become enabled if they were not enabled before, is always executed, guards against this.</p>
1805
|arduino-uno|pwm|current|
Do I need to use a resistor if I am using a potentiometer to control an LED's brightness?
2014-06-02T16:14:59.037
<p>I am currently tinkering with an arduino, and am using a potentiometer to change the brightness of an LED.</p> <p>I understand that usually, a resistor is added to the circuit to limit the current flowing through the circuit in order to prevent the LED from burning out.</p> <p>However, as I am currently using a potentiometer to adjust the LED's brightness, <strong>AND</strong> as a potentiometer is basically a variable resistor, would I still need a resistor to prevent the LED from burning out? Currently, I do not see a difference between using a 220 ohm resistor and not using it, as the LED seems unaffected.</p> <p>My code:</p> <pre><code>const int pot=A0; const int led=11; int potValue; void setup(){ Serial.begin(9600); pinMode(pot,INPUT); pinMode(led,OUTPUT); analogWrite(led,100); } void loop(){ potValue = analogRead(pot); potValue=map(potValue,0,1023,0,255); analogWrite(led,potValue); Serial.println(potValue); } </code></pre> <p>PS: My LED is hooked up to the arduino's PWM pin, and connected to ground on a breadboard.</p>
<p>Without a good quality picture of your setup or some schematics, it's hard to tell what's going on, but from your description, what you're doing is <strong>potentially harmful for the LED and the output pin D11</strong>.</p> <p>Yes, LEDs almost always need series resistors to limit their current. They don't limit currents and will burn if you don't do it for them. </p> <p>If you had the pot in series with the LED, which seems to be what you think is going on, you'd still need a series resistance so that when the pot is all the way to one side, effectively behaving like a 0&Omega; resistor or a short, you'd still be limiting the current with the 2nd resistor. One would usually use Ohm's Law to calculate that 2nd resistance so that it lets the maximum current the LED can take when the pot is at 0&Omega; position, usually 20mA for common LEDs.</p> <p><strong>But that's not how your circuit seems to be wired</strong>. The pot is indirectly controlling the LED through an analog input and a PWM output via MCU. So it's not limiting the LED current, in the traditional sense. The pot seems to be wired between 5V and GND with the middle lead (the cursor) hooked up to the analog input A0. That's a variable voltage divider configuration that let's you select a continuous voltage between 0 and 5V that is in turn converted to a value between 0 and 1023 by the MCU ADC (Analog to Digital Converter) - that's the result of the <code>analogRead()</code> call. </p> <p>That value is then fed to a PWM analog output, through the <code>analogWrite()</code> call, that will output a square wave to the LED. The relative position of the pot will determine the duty cycle of the PWM, i.e., how long the square wave is HIGH or LOW. The problem here is that this circuit where the LED is wired should have its own series current limiting resistance.</p> <p>To me, if you didn't burn the LED or the D11 pin yet, is pure luck. If you were to turn the pot all the way to maximum brightness (<strong>don't do it</strong>), the PWM output would act like a digital output put in HIGH level (5V continuously), and without a current limiting resistor, the D11 pin would exceed it's 40mA absolute maximum source current and burn. Unless there's another factor limiting the current that I don't know of, that is.</p> <p>There are some exceptional cases in which you can control the LED voltage closely so you don't need to limit the current (multiplexing, constant-current supply etc.), but these are really advanced configurations for us newbies. So, from know on, do it like I do it: ALWAYS put a series resistor, until you become familiar with these advanced configurations.</p> <p>Finally, below are some links that you may find helpful about the topic:</p> <ul> <li><p><a href="https://www.sparkfun.com/tutorials/219" rel="nofollow">SparkFun Tutorial on LED Current Limiting Resistors</a></p></li> <li><p><a href="http://en.wikipedia.org/wiki/LED_circuit#Series_resistor" rel="nofollow">WikiPedia Article about LED series resistors</a></p></li> </ul>
1808
|i2c|wires|
Connect two Arduinos using I²C (wiring)
2014-06-02T21:37:34.777
<p>Altough having found a lot of documentation concerning wiring of I²C buses, I'm still not sure about the following question:</p> <p>If both devices use separate power sources, is it a good idea to connect VCC/GND of those two devices?</p> <p>I have two lines for SCL and SDA, connected to SCL/SDA pins on both devices A and B. The master device's VCC is connected to both lines using a pull-up resistor. Now as far as I understood, VCC/GND of the two devices should not be disconnected but I'm afraid I'd damage something if I'd connect them. As two separate power sources will never provide exactly the same voltage that would result in high currents, won't it? Or should I just connect them using some resistor to avoid high currents but provide the same voltage level?</p>
<p>Here's what you need to do:</p> <ul> <li>Leave the VINs disconnected. I'm not sure that it's a bad idea, but it is pretty much pointless. Like sburlappp said, the resistors lower the voltage between them (and reduce the current). With a resistor, it wouldn't <em>hurt it</em>, but there's really no need.</li> <li>Connect the grounds <em>directly</em>. Here's the problem: voltage is relative; it is measured very much like gravitational potential energy. It's the difference between the amount of electricity in both parts that determines the voltage. I'm pretty sure that if you don't, with the extra power, it could <em>fry</em> a component. That would happen when there is a lower concentration of electrons in "ground" on one of the boards than the other. That could result in many volts being passed along to the board. I haven't had this happen to me, nor have I really heard about this happening, but I guess it is a possibility.</li> </ul>