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
3424
|arduino-uno|
How to use two Sonar's
2014-07-24T08:27:01.760
<p>I'm using a single sonar, but I want to use two sonar to know another distance.</p> <p>Here is how I use my single sonar:</p> <pre><code> #include &lt;NewPing.h&gt; #define TRIGGER_PIN 9 #define ECHO_PIN 10 #define MAX_DISTANCE 100 // in CM ... NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); ... delay(100); unsigned int uS = sonar.ping(); int cm = uS / US_ROUNDTRIP_CM; </code></pre> <p>But I Want to use a second one to calculate another distance, how to?</p> <pre><code>#define TRIGGER_PIN_2 11 #define ECHO_PIN_2 12 ... new NewPing sonar(TRIGGER_PIN_2, ECHO_PIN_2, MAX_DISTANCE); ... ??? </code></pre> <p>Thanks in advance</p> <p><strong>EDIT:</strong></p> <p>Maybe this one, I'll try this when I will get my second sonar</p> <pre><code>#define SONAR_NUM 2 #define MAX_DISTANCE 200 ... NewPing sonar[SONAR_NUM] = { NewPing(9, 10, MAX_DISTANCE), NewPing(11, 12, MAX_DISTANCE) }; ... delay(100); unsigned int uS1 = sonar[0].ping(); int cm1 = uS1 / US_ROUNDTRIP_CM; unsigned int uS2 = sonar[1].ping(); int cm2 = uS2 / US_ROUNDTRIP_CM; </code></pre>
<blockquote> <p>Maybe this one, I'll try this when I will get my second sonar</p> </blockquote> <p><em>Ding ding ding!</em> Yeah, this would be one way to do that. That creates an <em>array</em> so you can reference the sonar with <code>sonar[i]</code>, where <code>i</code> is either 0 or 1 for the first or second number.</p> <p>For only two sensors, it might be easier just to do something like this:</p> <pre><code>NewPing sonar1(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); NewPing sonar2(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); </code></pre> <p>Then you can run the other code like this:</p> <pre><code>delay(100); unsigned int uS1 = sonar1.ping(); int cm1 = uS1 / US_ROUNDTRIP_CM; unsigned int uS2 = sonar2.ping(); int cm2 = uS2 / US_ROUNDTRIP_CM; </code></pre> <p>A little less code to read, whichever one you want.</p> <p>The reason you can do this is you can replace the <code>sonar</code> with whatever you wanted (following C++ variable rules like no spaces, etc.). You could call it <code>Arduino_Sonar</code> if you wanted to. </p> <p>The array is basically a simple way of grouping variables together easily. It's not convenient to declare 500 differently name variables; I can just do <code>int numbers[500];</code> to declare them. An array might be more useful if you're expanding your circuit, but either is correct.</p>
3425
|arduino-uno|
Unstable reading from pushbutton on digital pin
2014-07-24T08:34:38.570
<p>I use the Pin 7 to get the status of a push button. I put 10Kohm R on the - .</p> <p>The status is unstable because arduino says thet I push it but it is not true...</p> <pre><code>int button = 7; ... // var for reading pushbutton value int buttonState = 0; ... buttonState = digitalRead(button); if(buttonState == HIGH) { myFunction(); } </code></pre> <p><strong>EDIT :</strong></p> <p>ARDUINO PIN 7 &lt;---> R 10Kohm &lt;--> [switch] &lt;---> VCC</p>
<p>Note that you can also activate the internal pull-up resistor on the pin by first making it an input, then setting it to HIGH.</p> <pre><code>pinMode(pin, INPUT); digitalWrite(pin, HIGH); </code></pre> <h3>EDIT:</h3> <p>Based on info from Craig (in the comments below) it's simpler to use the new pinMode INPUT_PULLUP:</p> <pre><code>pinMode(pin, INPUT_PULLUP); </code></pre> <p>Then wire the switch directly to ground. </p> <p>This is the simplest way to wire a pushbutton to an arduino (no resistor needed) but <strong>do</strong> you need an extra line of code. </p> <p>Also, the pin will read as HIGH when not pressed, and LOW when pressed (which might seem counter-intuitive)</p>
3434
|arduino-leonardo|
Leonardo: disable TX- and RX-LED
2014-07-24T18:20:36.117
<p>I have the (more or less) Leonardo-compatible board Olimexino-32u4. Both, the TX- and RX-LED are permanently on. To reduce power-consumption, I want to disable them <strong>by software</strong>. What is the reliable way to do it?</p>
<p>Reading the answer from Gerben I realised the core of the issue: The TX/RX LED's on the Leonardo are wired PIN-LED-5V(common anode), whereas on the Olimexino-32U4 they are wired PIN-LED-GND(common cathode). So the two boards will need inverse signals for the same visual output.</p> <p>Compare:<br> <a href="http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf" rel="noreferrer">http://arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf</a><br> <a href="https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf" rel="noreferrer">https://www.olimex.com/Products/Duino/AVR/OLIMEXINO-32U4/resources/OLIMEXINO-32U4_rev_A3.pdf</a></p> <hr> <p>The most elegant solution will be to add a new board type (the code below is for IDE 1.0.x):</p> <ul> <li><p>In your sketchbook create a folder 'hardware' and inside that 'olimexino'. In the olimexino folder create a file boards.txt with this content:</p> <pre><code>olimexino32u4.name=Olimexino-32U4 olimexino32u4.upload.protocol=avr109 olimexino32u4.upload.maximum_size=28672 olimexino32u4.upload.speed=57600 olimexino32u4.upload.disable_flushing=true olimexino32u4.bootloader.low_fuses=0xff olimexino32u4.bootloader.high_fuses=0xd8 olimexino32u4.bootloader.extended_fuses=0xcb olimexino32u4.bootloader.path=caterina olimexino32u4.bootloader.file=Caterina-Leonardo.hex olimexino32u4.bootloader.unlock_bits=0x3F olimexino32u4.bootloader.lock_bits=0x2F olimexino32u4.build.mcu=atmega32u4 olimexino32u4.build.f_cpu=16000000L olimexino32u4.build.vid=0x2341 olimexino32u4.build.pid=0x8036 olimexino32u4.build.core=arduino:arduino olimexino32u4.build.variant=olimexino32u4 </code></pre></li> <li><p>Create another folder 'variants' inside the olimexino folder.</p></li> <li>Inside that, create the folder 'olimexino32u4'.</li> <li>Now copy 'arduino/hardware/arduino/variants/leonardo/pins_arduino.h' to that folder</li> <li>Open the copy for editing - the path should be 'sketchbook/hardware/olimexino/variants/olimexino32u4/pins_arduino.h'.</li> <li><p>Change the section that deals with TXLED and RXLED by swapping the macros that end in 1 with those that end in 0. It should look like this:</p> <pre><code>#define TX_RX_LED_INIT DDRD |= (1&lt;&lt;5), DDRB |= (1&lt;&lt;0) #define TXLED1 PORTD |= (1&lt;&lt;5) #define TXLED0 PORTD &amp;= ~(1&lt;&lt;5) #define RXLED1 PORTB |= (1&lt;&lt;0) #define RXLED0 PORTB &amp;= ~(1&lt;&lt;0) </code></pre></li> </ul> <p>I don't own the board so I can't test the solution. I hope that it solves your problem - just choose 'Olimexino-32U4' from the Tools->Board menu.</p>
3440
|arduino-uno|arduino-due|eclipse|
MCU Type ATmega16U2 not avaliable in Eclipse AVR Plugin
2014-07-25T07:31:37.260
<p>I am following <a href="http://horrorcoding.altervista.org/arduino-development-with-eclipse-a-step-by-step-tutorial-to-the-basic-setup/" rel="nofollow">this</a> guide. Now I want to create the Create the "ArduinoCore library". But when I am creating a new project, I can not select ATmega16U2 as MCU type. </p> <p>But my Arduino Due R3-E and UNO SMD R3 both use ATmega16U2. </p> <p>What shall I do O_o??? </p>
<p>The <code>ATmega16U2</code> on those boards isn't intended to be programmable by the end-user. It's only there to help convert from USB to TTL serial, which lets your computer communicate with the board's main microcontroller. It replaces the FTDI chip which was used on some older boards.</p> <p>In the case of the Uno, the main microcontroller is the <code>ATmega328</code>. For the Due, it's the <code>AT91SAM3X8E</code>. If you want to program them from the Arduino IDE, you can usually just select the board by name from the drop-down menu.</p>
3456
|arduino-uno|
MakeyMakey + Arduino
2014-07-26T11:48:04.553
<p>I am trying to use the MakeyMakey with the Arduino (not as an Arduino) and then use a USB to TTL module to send the keys pressed to the Arduino. Is this possible? Do I have to reprogram?</p>
<p>one possibility is to use HOST SHIELD <a href="http://www.circuitsathome.com/products-page/arduino-shields" rel="nofollow">http://www.circuitsathome.com/products-page/arduino-shields</a></p> <p>Arduino is now as host Makey is keyboard</p>
3461
|arduino-uno|c++|
Parsing JSON on the Arduino
2014-07-26T21:10:43.403
<p>I'm using the <a href="https://github.com/bblanchon/ArduinoJson" rel="noreferrer">ArduinoJson</a> library. There is a <a href="https://github.com/bblanchon/ArduinoJson/blob/master/examples/JsonParserExample/JsonParserExample.ino" rel="noreferrer">great example</a> for parsing a single JSON object in the source code. I am attempting to iterate over an array of JSON objects:</p> <pre><code>#include &lt;JsonParser.h&gt; using namespace ArduinoJson::Parser; void setup() { Serial.begin(9600); char json[] = "[{\"sensor\":\"gps\",\"time\":1351824120,\"data\":[48.756080,2.302038]}, \ {\"sensor\":\"gps\",\"time\":1351824140,\"data\":[50.756080,21.302038]}]"; JsonParser&lt;32&gt; parser; JsonArray root = parser.parse(json); if (!root.success()) { Serial.println("JsonParser.parse() failed"); return; } for (JsonArrayIterator item = root.begin(); item != root.end(); ++item) { // unsure of what to do here. Serial.println((*item)["data"]); // results in: // ParseJsonArray:21: error: call of overloaded // 'println(ArduinoJson::Parser::JsonValue)' is ambiguous JsonObject something = JsonObject(*item); Serial.println(something["sensor"]); // results in : // ParseJsonArray:26: error: call of overloaded // 'println(ArduinoJson::Parser::JsonValue)' is ambiguous } } void loop() {} </code></pre> <p>item is of type JsonValue. I would like to treat it as a JsonObject and pull some data out of it.</p>
<p>This is how I would write this loop:</p> <pre><code>for (JsonArrayIterator it = root.begin(); it != root.end(); ++it) { JsonObject row = *it; char* sensor = row["sensor"]; long time = row["time"]; double latitude = row["data"][0]; double longitude = row["data"][1]; Serial.println(sensor); Serial.println(time); Serial.println(latitude, 6); Serial.println(longitude, 6); } </code></pre> <p>And, if C++11 is available (which is not the case with Arduino IDE 1.0.5):</p> <pre><code>for (auto row : root) { char* sensor = row["sensor"]; long time = row["time"]; double latitude = row["data"][0]; double longitude = row["data"][1]; Serial.println(sensor); Serial.println(time); Serial.println(latitude, 6); Serial.println(longitude, 6); } </code></pre>
3470
|serial|power|
Can I use an external power supply and still communicate with my computer over Serial?
2014-07-27T19:17:28.103
<p>I read the following online: If you plug in both USB power (say from a pc) and external power via the 2.1mm jack, the Arduino chooses power source automatically.</p> <p>If the external 2.1mm DC is providing greater than 6.6V, the Arduino will take power from it instead of the USB.</p> <p>Firstly, is this accurate?</p> <p>Secondly, my real question: If I am powering my Arduino via external DC, can I still communicate with my Raspberry Pi using serial via the USB?</p>
<p>Yes you can. It still leaves the data/ground lines intact, it just doesn't bridge the 5V line.</p> <p><a href="http://arduino.cc/en/uploads/Main/Arduino_Uno_Rev3-schematic.pdf" rel="noreferrer">Arduino Uno Schematic v.3</a>:</p> <p><img src="https://i.stack.imgur.com/wVZoy.png" alt=""></p> <p>The <code>USBVCC</code> is directly from the 5V on the USB jack (well, technically there's a fuse there). It then goes through a transistor (<code>T1</code>) that only allows power through when there is no power coming from the 5V regulator (that regulates the VIN voltage).</p> <p><em>The USB jack:</em></p> <p><img src="https://i.stack.imgur.com/Ms8IE.png" alt=""></p> <p>You can see pin 1 of the USB jack (5V) goes through the fuse to <code>USBVCC</code>. The next ones <code>D+</code>/<code>D-</code> are the data lines that go through resistors to the ATMEGA16U (used for USB to UART). The last one just ties into ground.</p>
3472
|serial|programming|arduino-mega|mpu6050|
Sending MPU6050 data over serial to Java/C# Program
2014-07-28T02:04:55.107
<p>I am using a MPU6050 Accelerometer/Gyro breakout (GY-521) to retrieve data and send it to a java program. I have tried several ways, but I couldn't find a way to send the float values calculated from the Arduino over Serial. Could you please let me know a good way of serial communication with Arduino and a Java Program? Thanks in advance. </p> <p><strong><em>UPDATE</em></strong>:</p> <p>Thank you for your comments and replies. What I have tried is the I2Cdev library code. I could work with it without any issue. Code is in this <a href="http://www.i2cdevlib.com/devices/mpu6050#source" rel="nofollow">link</a>. I also could run the processing code to get a visual output. But the problem I have i that I'm not able to send the accelerometer and gyro data to a Java/C# program and process it from there. I tried sending an array of FIFO bytes from the Arduino and convert it from the C# code and processing code, but it didn't give me correct results. Now what i did was, just to send a string of values and receive it from the C# program. But I don't know whether it's good method. I would be glad if you could help me in this. Thanks again. </p> <p><strong>Arduino</strong></p> <pre><code>#ifdef OUTPUT_TEAPOT // display quaternion values in InvenSense Teapot demo format: teapotPacket[2] = fifoBuffer[0]; teapotPacket[3] = fifoBuffer[1]; teapotPacket[4] = fifoBuffer[4]; teapotPacket[5] = fifoBuffer[5]; teapotPacket[6] = fifoBuffer[8]; teapotPacket[7] = fifoBuffer[9]; teapotPacket[8] = fifoBuffer[12]; teapotPacket[9] = fifoBuffer[13]; Serial.write(teapotPacket, 14); //Serial.write(buf, len) teapotPacket[11]++; // packetCount, loops at 0xFF on purpose #endif #ifdef OUTPUT_ACCEL_STR_RAW mpu.getMotion6(&amp;ax, &amp;ay, &amp;az, &amp;gx, &amp;gy, &amp;gz); String accelGyroRaw = "STX,"; accelGyroRaw += ax; accelGyroRaw += ','; accelGyroRaw += ay; accelGyroRaw += ','; accelGyroRaw += az; accelGyroRaw += ','; accelGyroRaw += gx; accelGyroRaw += ','; accelGyroRaw += gy; accelGyroRaw += ','; accelGyroRaw += gz; accelGyroRaw += ','; accelGyroRaw += "ETX"; Serial.println(accelGyroRaw); #endif </code></pre> <p><strong>C# Code</strong></p> <pre><code>class Program { static SerialPort port = new SerialPort("COM7", 115200); //static int serialCount = 0; //static int aligned = 0; //static char[] teapotPacket = new char[14]; //static float[] q = new float[4]; static void Main(string[] args) { Console.WriteLine("****** Serial Console Read ********"); port.Open(); port.DataReceived += port_DataReceived; Console.Read(); } static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { string s = port.ReadLine(); string[] accelGyroVals = s.Split(','); string[] accl = new string[3]; string[] gyro = new string[3]; if (accelGyroVals[0] == "STX" &amp;&amp; accelGyroVals[accelGyroVals.Length - 1] == "ETX\r") { accl[0] = accelGyroVals[1]; accl[1] = accelGyroVals[2]; accl[2] = accelGyroVals[3]; gyro[0] = accelGyroVals[4]; gyro[1] = accelGyroVals[5]; gyro[2] = accelGyroVals[6]; Console.WriteLine("a : " + accl[0] + " , " + accl[1] + " , " + accl[2] + "\t g : " + gyro[0] + " , " + gyro[1] + " , " + gyro[2]); } } static void CurrentDomain_ProcessExit(object sender, EventArgs e) { if (port.IsOpen) { port.Close(); } } } </code></pre> <p>Sorry for this for lengthy code and if my question is unclear. It's my first time to work with an IMU. Thank you. </p>
<p>You may find RXTX java library helpful. </p> <p>You can format the data (float as calculated at Arduino side) in any mannner that you desire. RXTX library will send the data. It will then up to the Java program (non Arduino side, like PC, etc.) how to interpret the data and extract the values. </p> <p><a href="http://playground.arduino.cc/interfacing/java" rel="nofollow">http://playground.arduino.cc/interfacing/java</a></p> <p>Hope this helps</p>
3492
|arduino-due|
Arduino Control over the internet
2014-07-29T09:37:34.300
<p>I am really interested in IoT (enthusiastic noob) and I would like to use the arduino board. Here are the steps according to me, with my queries:</p> <ul> <li>User goes to example.com/arduino_switch</li> <li>Interacts with an HTML form to toggle an action</li> <li>Sends the data over the Internet (This is the part I have problem understanding)</li> <li>Arduino receives the data point (how can we do this? polling a url or can we actively send it)</li> <li>performs the action (easy to do for me)</li> </ul> <p>Any and all help will be appreciated, even if its just pointing me to the right resources.</p>
<p>kiwiron has a great answer, but I have a few things to add:</p> <ul> <li><strong>You don't have to risk security...</strong> you can create a VPN to your network <em>or</em> you could just stay inside local LAN. It's just if you want to access it from outside</li> <li>If you can't get a static IP for your network from your ISP, you can use something like <a href="http://www.noip.com/" rel="nofollow">No-IP</a> to give you a name like <code>example.no-ip.biz</code> that's easier to remember and it will change the IP when your IP changes. I've used them before...</li> <li>A Raspberry Pi might be a good partner in crime to work with the HTTPS connection with a web server like Nginx and with PHP to run a script. I personally like the Arduino better for interfacing with the actual components since it is 5V and has 40 mA per pin, but it's possible that you could use the GPIO pins on a Pi for your server. This might be a little cheaper since you can remove the ethernet shield and replace that with USB.</li> <li>For the approach of polling a web server, it might be better to have the web server send a GET request to the Arduino and then the Arduino can respond ASAP.</li> </ul> <p>For this, you might want to learn the basics of <a href="http://en.wikipedia.org/wiki/List_of_HTTP_header_fields" rel="nofollow">HTTP headers</a> and try to figure out what goes on behind the scenes.</p> <blockquote> <p>(how can we do this? polling a url or can we actively send it)</p> </blockquote> <p>Assuming you're using the Arduino directly, here's roughly what would happen:</p> <ul> <li>The client would request the Arduino for the content for the homepage using HTTP requests</li> <li>The Arduino would send the content and close the connection</li> <li>In the HTML there's a little attribute to the form that tells it to send the data via post to <code>response.php</code>. The client hits "submit" and it sends the data via POST to that URL.</li> <li>The Arduino sees that it's sending data to that URL and reads the data and then process it accordingly. The socket is closed.</li> </ul>
3497
|wifi|android|
Connecting Arduino Android Wirelessy
2014-07-29T10:41:38.140
<p>I am working with Arduino and Android. I am interested in connecting Arduino (Mega 2560 ADK) to my Android tablet (Nexus 7) wirelessly. The chepaest option is via bluetooth but the communication in not reliable. Now I would like to connect it via WiFi. But I don't want to use WiFi shield on my Arduino.</p> <p>As Arduino can send the information to my laptop via serial USB connection will it be possible to put this information on my home WiFi network and get it on my Android device by connecting it to the same WiFi network?</p>
<p>Yes, if the laptop and tablet are on the same network communication will be possible. One way to implement this would be to have a client/server setup that communicates over TCP/IP.</p> <p>The laptop can act as a TCP/IP server and also communicate through the serial interface to your arduino. Many languages will be able to do this, Java, C/C++, Python, whatever you're comfortable with.</p> <p>The android tablet can then connect to the TCP/IP server as a client and send and receive data through your WiFi. Have a look at <a href="http://developer.android.com/reference/java/net/Socket.html" rel="nofollow">the android documentation</a>.</p> <p>This would a simple solution but for a more permanent solution you could also setup a web server on your laptop, look into the apache webserver. Your tablet would be able to communicate with the web server through http requests. The web server can then start further scripts to send data to the arduino or maintain a serial connection depending on your implementation.</p>
3508
|power|voltage-level|electricity|electronics|
Why does arduino work on usb power?
2014-07-30T01:22:05.183
<p>The arduino website states that the operating voltage of an arduino is 7-12V.</p> <p>Why does the arduino work powered on just usb then? As usb only outputs 5V and 500ma.</p> <p>Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?</p>
<blockquote> <p>The arduino website states that the operating voltage of an arduino is 7-12V.</p> </blockquote> <p>That's when it goes through the voltage regulator. It's a <em>linear regulator</em>, meaning it wastes a lot of power as heat. The regulator outputs 5V that's given to the MCU. The USB voltage bypasses the regulator and goes to a fuse before going to the common 5V for the board. If less than 7V is given to the regulator, it will produce less than 5V.</p> <blockquote> <p>Is it preferable to say run the arduino on an external 9V dc power source, or does it make no difference?</p> </blockquote> <p>Usually, yes. A 9V supply would give you more than 500ma, giving you flexibility to add higher current components like motors and lots of LEDs. It will make no difference if you have a single LED connected.</p>
3514
|arduino-uno|
Can anyone tell me the best books for studying UAV?
2014-07-30T06:42:37.403
<p>It's kind of hard to get full guide from the internet. I just wanna buy a book for UAV guide. I gotta make DIY drones. I'd appreciat it if you recommend good books.</p>
<p>Not a book, but try the following course from EdX, the online MOOC: <a href="https://www.edx.org/course/tumx/tumx-autonavx-autonomous-navigation-1658" rel="nofollow">https://www.edx.org/course/tumx/tumx-autonavx-autonomous-navigation-1658</a></p>
3517
|arduino-mega|
Raspberry pi -Arduino bridge
2014-07-30T07:59:50.990
<p>I am building a small wireless controlled robot using the Arduino and the raspberry pi. It works by the user wirelessly connecting through to the raspberry Pi (using vnc or some other form wirelessly) and using the user inputs to send a command to the Arduino which controls the motorised wheels. SO for example if the user presses the up button, a 'W" command is sent from the Raspberry Pi to the Arduino which then reads it and pushes the wheels forward. </p> <p>I was looking to use one of the new Arduino-Raspberry Pi bridges to connect the two to make it easier to use, but I am not too familiar on how they work. Had a few question such as:</p> <p>1) How exactly do they work (connection wise)?</p> <p>2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?</p> <p>3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)</p> <p>Sorry really new to the raspberry pi and need to find a solution soon so any help would be awesome.</p> <p>Cheers</p>
<blockquote> <p>1) How exactly do they work (connection wise)?</p> </blockquote> <p>Physically they all sit on the GPIO sockets of the Pi, sitting on top of the pi. The <a href="http://www.element14.com/community/docs/DOC-64326/l/gertduino-add-on-board-for-raspberry-pi" rel="nofollow">Gertduino</a> and <a href="http://www.makershed.com/products/alamode-for-raspberry-pi" rel="nofollow">AlaMode</a> seem to have the same form factor as the Pi which makes them a little more appealing to me but I guess then is personal choice. </p> <p>Communication appears to differ but it will use <a href="http://www.bitsharr.com/rtxu6LvK" rel="nofollow">Serial</a>, <a href="https://www.google.co.uk/search?q=SPI%20communication%20between%20raspberry%20pi%20and%20arduino" rel="nofollow">SPI</a> or <a href="http://www.adafruit.com/blog/2014/02/21/connecting-an-arduino-to-a-raspberry-pi-using-i2c-raspberry_pi-piday-raspberrypi/" rel="nofollow">I2C</a>. I would imagine that you'd be able to choose an alternate one but not read enough about them to know for sure. Serial appears to be fairly simple, and it would be easy to debug, however you might struggle if you wanted to receive data on the Pi without the communication being initiated by the Pi. I2C would overcome this as you can run it in <a href="http://forum.arduino.cc/index.php/topic,13579.0.html" rel="nofollow">multi-master</a> mode. </p> <blockquote> <p>2) is it possible to write one python code in the raspberry pi that when run can load the specific ino code into arduino?</p> </blockquote> <p>As you can call external programs with python I would say that even if you have to resort to this mechanism then it would be possible. You can turn on the debugging in the Arduino IDE to see what it actually does, then either script it or make the calls from your python program. </p> <blockquote> <p>3) which bridge would be the most suited for my project? (eg: Arduberry, alamode, gertduino, etc?)</p> </blockquote> <p>I'd go for either the gertduino or alamode purely on looks particularly the matched form factor.</p>
3524
|sensors|
What is this component? (range finder)
2014-07-30T12:17:00.790
<p>I've taken apart an <a href="https://plus.google.com/111652317143259686566/posts/75TraxED8bg" rel="nofollow">old range finder (see photo here)</a>. It uses a circular, seemingly gold-plated, two-wire sensor that I'd like to re-use in an Arduino project. I'm looking for a datasheet of the sensor and/or a circuit-diagram. Any help is welcome.</p>
<p>The big circular parts likely is ultrasonic transducer as used in instant camera. </p> <p><a href="http://www.uoxray.uoregon.edu/polamod/" rel="nofollow">http://www.uoxray.uoregon.edu/polamod/</a></p> <p><a href="https://www.google.com/?gws_rd=ssl#q=polaroid+ultrasonic+ranging+module&amp;revid=399558007&amp;safe=off" rel="nofollow">https://www.google.com/?gws_rd=ssl#q=polaroid+ultrasonic+ranging+module&amp;revid=399558007&amp;safe=off</a></p> <p>Working principle is same as modern unit, easily available at a few US dollars. The transducer does NOT work by itself, needs the associate PCB to work.</p>
3539
|arduino-uno|serial|c++|strlen|
Why can't this C++ program read my arduino's Serial.write()?
2014-07-30T23:54:30.127
<p>I made a super simple arduino uno sketch to send a serial byte once every second:</p> <pre><code>void setup(){ Serial.begin(9600); } void loop(){ Serial.write(12); // send a byte with the value 12 delay(1000); } </code></pre> <p>My arduino is hooked up to com 3.</p> <p>On the other end of the line, I have a C++ program with the following read function:</p> <pre><code>int Serial::ReadData(char *buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead; //Use the ClearCommError function to get status info on the Serial port ClearCommError(this-&gt;hSerial, &amp;this-&gt;errors, &amp;this-&gt;status); //Check if there is something to read if(this-&gt;status.cbInQue&gt;0) { //If there is we check if there is enough data to read the required number //of characters, if not we'll read only the available characters to prevent //locking of the application. if(this-&gt;status.cbInQue&gt;nbChar) { toRead = nbChar; } else { toRead = this-&gt;status.cbInQue; } //Try to read the require number of chars, and return the number of read bytes on success if(ReadFile(this-&gt;hSerial, buffer, toRead, &amp;bytesRead, NULL) &amp;&amp; bytesRead != 0) { return bytesRead; } } //If nothing has been read, or that an error was detected return -1 return -1; } </code></pre> <p>This seems to check only one time if data is available, so obviously I have to loop through it until data comes in. I did that in my main program:</p> <pre><code>#include "Serial.h" #include &lt;iostream&gt; using namespace std; int main(void) { Serial serial("COM3"); char* c = ""; int len = strlen(c); while(c == "") { serial.ReadData(c, len); } cout &lt;&lt; "\n\n"; system("PAUSE"); } </code></pre> <p>When I do this, my C++ program gets stuck in an infinite loop waiting for data from the arduino, and I cannot figure out why this is happening. My program never sees the data the arduino is sending.</p> <p>This Serial class works and is configured properly because I can SEND all the data I want to the arduino without any problems. My issues are only with reading back from the arduino.</p> <p>Can someone please help me figure out why this is not working?</p>
<pre><code>char* c = ""; while(c == "") </code></pre> <p>The variable named c is a misnomer, because it is a pointer to a string, not a character. For example c = 0x123456.</p> <p>You should use a more explicit name for your variable.</p> <p>This first line assigns a pointer to an empty string to the c pointer. So, the value stored at address 0x123456 == whatever pointer to a static memory address containing '\0'</p> <p>Note that no memory has been allocated to hold characters. Only a pointer to char has been allocated. Thus you cannot store anything in your string!!</p> <p>You could write something like: <code>char data[2] = "";</code> That would allocate a pointer, and a string to hold 2 characters</p> <hr> <p>The second line, <code>while(c == "")</code> compares a real memory pointer (e.g. 0x123456) with a compiler pointer. <code>""</code> is not a real application pointer, you should not manipulate it.</p> <p>So that second line relies on a compiler behavior.</p> <hr> <p>If I were you I would wrap the multi-char routine into a single-char routine. For example:</p> <pre><code>int ReadChar(char *c) { return ReadData(c, 1); } </code></pre> <p>Then:</p> <pre><code>main() { char c; ReadChar(&amp;c); } </code></pre> <hr> <p>On a different note, I think the compiler should catch such error. The line <code>c == ""</code> would never do anything useful and should be caught.</p>
3546
|avrdude|atmega328|
How to modify Arduino boards.txt to support new MCUs
2014-07-31T06:41:06.220
<p>In <a href="https://arduino.stackexchange.com/questions/3489/arduino-boot-loader-problem">this post</a>, it was mentioned that to get the Arduino IDE to support an ATmega328 (only the ATmega328P is supported):</p> <blockquote> <p>I should mention the Arduino way of doing this, is to create a new boards.txt file with this chip and add (not change) the avrdude.conf file. This will allow programing either from selecting the correct board. but that is another subject.</p> </blockquote> <p>After a great deal of research in the past, and attempted modifications to boards.txt and avrdude.conf, I arrived at the conclusion that the Toolchain doesn't support the ATmega328 therefore the changes will have no effect.</p> <p>Can anyone confirm that they have successfully found a way to make these changes, so we can avoid the need for a work-around?</p>
<p>Please, Note that the Arduino IDE is behind on many of the tools. In this case avrdude and its conf file, along with avr-gcc </p> <p><strong>First:</strong></p> <pre><code>.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf </code></pre> <p>needs to support the m328 in addition to m328p. This can be done by either updating </p> <pre><code>.\arduino-1.5.6-r2\hardware\tools\avr\bin\avrdude.exe </code></pre> <p>to something like <a href="http://download.savannah.gnu.org/releases/avrdude/" rel="nofollow">avrdude-6.1-svn-20131205-mingw32</a>. along with replacing the conf file with the new one</p> <pre><code>.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf </code></pre> <p>file that has both m328 along with the m328p. Note 6.1 supports a parent method, making it easy to duplicate chips with different signatures. Or use existing 5.11 and add to its </p> <pre><code>.\arduino-1.5.6-r2\hardware\tools\avr\etc\avrdude.conf </code></pre> <p>file by duplicating the entire m328p section and renaming the new entry to "m328" along with the correct signature.</p> <p><strong>Second:</strong></p> <p>avr-gcc need to be updated to support compiling both the m328p and m328. Yes, it just a semantic thing. But the next part will send either ATmega328p or ATmega328 to both gcc and dude. which both need to support it. One can simply copy over </p> <pre><code>.\arduino-1.5.6-r2\hardware\tools\avr\ </code></pre> <p>with the new tool chain. I used <a href="http://sourceforge.net/projects/mobilechessboar/files/avr-gcc%20snapshots%20%28Win32%29/" rel="nofollow">avr-gcc-4.8_2013-03-06_mingw32</a></p> <p><strong>Third:</strong></p> <p>replace the following line in boards.txt</p> <pre><code>uno.build.mcu=atmega328p </code></pre> <p>with</p> <pre><code>## Arduino ATmega328P ## --------------------------------------------- uno.menu.cpu.atmega328p=ATmega328P uno.menu.cpu.atmega328p.build.mcu=atmega328p ## Arduino ATmega328 ## --------------------------------------------- uno.menu.cpu.atmega328=ATmega328 uno.menu.cpu.atmega328.build.mcu=atmega328 </code></pre> <p>This will add an option to the IDE when UNO is selected for either chip. And subsequently send the correct MCU to both the compiler and avrdude.</p> <hr> <p><strong>Proof:</strong> </p> <p>Below are the verbose output of the IDE with the above changes. Note the -mmcu and -p for both options. As a real unit is was not connected it yielded the "not in sync" error. Where this shows it all works.</p> <pre><code>C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o ... C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i avrdude: Version 5.11, compiled on Sep 2 2011 at 19:38:36 ... avrdude: stk500_getsync(): not in sync: resp=0x00 avrdude done. Thank you. </code></pre> <hr> <pre><code>C:\projects\Arduino\arduino-1.5.6-r2\hardware\tools\avr\bin\avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -MMD -mmcu=atmega328 -DF_CPU=16000000L -DARDUINO=156 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\cores\arduino -IC:\projects\Arduino\arduino-1.5.6-r2\hardware\arduino\avr\variants\standard C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp -o C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp\sketch_jul31a.cpp.o ... C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex Sketch uses 444 bytes (1%) of program storage space. Maximum is 32,256 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes. C:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/bin/avrdude -CC:\projects\Arduino\arduino-1.5.6-r2/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328 -carduino -PCOM3 -b115200 -D -Uflash:w:C:\Users\mflaga\AppData\Local\Temp\build6597836883576934105.tmp/sketch_jul31a.cpp.hex:i avrdude: Version 5.11, compiled on Sep 2 2011 at 19:38:36 ... avrdude: stk500_getsync(): not in sync: resp=0x00 avrdude done. Thank you. </code></pre>
3562
|programming|led|
Arduino Remote controlled RGB LED strip, having issues with brightness/dimming
2014-08-01T07:31:04.180
<p>I have this sketch:</p> <pre><code>#include &lt;TimerOne.h&gt; #include &lt;IRremote.h&gt; #include &lt;RGBMood.h&gt; int RECV_PIN = 2; // IR-Receiver PIN int led = 13; // Satus-LED PIN int modus; // Modus for Interrupt-Querry int ledr = 11; // RGB LED red PIN int ledg = 12; // RGB LED green PIN int ledb = 13; // RGB LED blue PIN int SerialBuffer = 0; RGBMood m(ledr, ledg, ledb); int timerwert = 20; // Timer time for Interrupt in ms String readString; // Color arrays int black[3] = { 0, 0, 0 }; int white[3] = { 100, 100, 100 }; int red[3] = { 100, 0, 0 }; int green[3] = { 0, 100, 0 }; int blue[3] = { 0, 0, 100 }; int yellow[3] = { 40, 95, 0 }; int dimWhite[3] = { 30, 30, 30 }; int brightness = 0; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by // etc. // Set initial color int redVal = black[0]; int grnVal = black[1]; int bluVal = black[2]; int wait = 10; // 10ms internal crossFade delay; increase for slower fades int hold = 0; // Optional hold when a color is complete, before the next crossFade int DEBUG = 1; // DEBUG counter; if set to 1, will write values back via serial int loopCount = 60; // How often should DEBUG report? int repeat = 3; // How many times should we loop before stopping? (0 for no stop) int j = 0; // Loop counter for repeat // Initialize color variables int prevR = redVal; int prevG = grnVal; int prevB = bluVal; #define ON 0xF4F37A66 #define OFF 0x1363ADB4 #define BRIGHTNESS_UP 0xE6721691 #define BRIGHTNESS_DOWN 0xE9721B48 #define FLASH 0xFFF00F #define STROBE 0xFFE817 #define FADE 0x39ED1255 #define SMOOTH 0xFFC837 #define RED 0x9D561314 #define GREEN 0XCB8E93A5 #define BLUE 0xC88E8EEC #define WHITE 0x16DBBEE3 #define ORANGE 0xFFB04F #define YELLOW_DARK 0xFFA857 #define YELLOW_MEDIUM 0xFF9867 #define YELLOW_LIGHT 0xFF8877 #define GREEN_LIGHT 0XFF30CF #define GREEN_BLUE1 0XFF28D7 #define GREEN_BLUE2 0XFF18E7 #define GREEN_BLUE3 0XFF08F7 #define BLUE_RED 0XFF708F #define PURPLE_DARK 0XFF6897 #define PURPLE_LIGHT 0XFF58A7 #define PINK 0XFF48B7 IRrecv irrecv(RECV_PIN); decode_results results; void setup() { pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output pinMode(led, OUTPUT); // set Status-LED as Output m.setMode(RGBMood::RANDOM_HUE_MODE); // Automatic random fade. m.setHoldingTime(4000); // Keep the same color for 4 seconds before fading again. m.setFadingSteps(150); // Fade with 150 steps. m.setFadingSpeed(50); // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds m.setHSB(random(359), 255, 255); Serial.begin(9600); irrecv.enableIRIn(); // Start of IR-Recive Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt } void leseIR(){ if (irrecv.decode(&amp;results)){ irrecv.resume(); // Receive the next value switch (results.value) { case FADE: // Modus Fade (DIY 4) modus = 1; break; case 0xFF906F: // Modus pcambi (DIY 5) modus = 2; break; case ON: //Power modus = 0; crossFade(white); // RGB LEDs Off break; case OFF: //Power modus = 0; crossFade(black); // RGB LEDs Off break; case BLUE: //Blau 0,0,255 modus = 0; crossFade(blue); break; case RED: //Rot modus = 0; crossFade(red); break; case GREEN://Grün modus = 0; crossFade(green); break; case WHITE: //Weiss modus = 0; crossFade(white); break; case BRIGHTNESS_UP: //DIMMING modus = 0; // fade in from min to max in increments of 5 points: for(int fadeValue = 0 ; fadeValue &lt;= 255; fadeValue +=5) { // sets the value (range from 0 to 255): analogWrite(ledg, fadeValue); } break; case BRIGHTNESS_DOWN: //orange modus = 0; for(int fadeValue = 255 ; fadeValue &gt;= 0; fadeValue -=5) { // sets the value (range from 0 to 255): analogWrite(ledg, fadeValue); } break; case 0xFFAA55://Grün mitrtel modus = 0; break; case 0xFF926D: //blau mittel modus = 0; break; case 0xFF12ED: //rosa modus = 0; break; } // Switch END } } void loop() { if(modus==1){ // Querry pb Modus:1 m.tick(); } Serial.println(results.value, HEX); Serial.println(DEC); Serial.println(DEC); Serial.println(DEC); } int calculateStep(int prevValue, int endValue) { int step = endValue - prevValue; // What's the overall gap? if (step) { // If its non-zero, step = 1020/step; // divide by 1020 } return step; } /* The next function is calculateVal. When the loop value, i, * reaches the step size appropriate for one of the * colors, it increases or decreases the value of that color by 1. * (R, G, and B are each calculated separately.) */ int calculateVal(int step, int val, int i) { if ((step) &amp;&amp; i % step == 0) { // If step is non-zero and its time to change a value, if (step &gt; 0) { // increment the value if step is positive... val += 1; } else if (step &lt; 0) { // ...or decrement it if step is negative val -= 1; } } // Defensive driving: make sure val stays in the range 0-255 if (val &gt; 255) { val = 255; } else if (val &lt; 0) { val = 0; } return val; } /* crossFade() converts the percentage colors to a * 0-255 range, then loops 1020 times, checking to see if * the value needs to be updated each time, then writing * the color values to the correct pins. */ void crossFade(int color[3]) { // Convert to 0-255 int R = (color[0] * 255) / 100; int G = (color[1] * 255) / 100; int B = (color[2] * 255) / 100; int stepR = calculateStep(prevR, R); int stepG = calculateStep(prevG, G); int stepB = calculateStep(prevB, B); for (int i = 0; i &lt;= 1020; i++) { redVal = calculateVal(stepR, redVal, i); grnVal = calculateVal(stepG, grnVal, i); bluVal = calculateVal(stepB, bluVal, i); analogWrite(ledr, redVal); // Write current values to LED pins analogWrite(ledg, grnVal); analogWrite(ledb, bluVal); delay(wait); // Pause for 'wait' milliseconds before resuming the loop } // Update current values for next loop prevR = redVal; prevG = grnVal; prevB = bluVal; delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop } </code></pre> <p>It's working like a charm, the fade operates smoothly using <code>timer1</code>, the colors appear correct on led, but I can't fix the brightness part. <strong>Can someone provide sample code to do this?</strong></p> <p>If anyone else wants to use the code, I'm using an Arduino Mega 2560, please use the same PINs as mine since timers works only on 11,12,13 on this Arduino. (<a href="http://www.pjrc.com/teensy/td_libs_TimerOne.html" rel="nofollow">link with pin info regarding several Arduino boards</a>)</p> <ul> <li><a href="http://forum.arduino.cc/index.php/topic,90160.0.html" rel="nofollow">RGB mood library</a></li> <li><a href="http://github.com/PaulStoffregen/TimerOne" rel="nofollow">TimerOne library</a></li> <li><a href="http://github.com/shirriff/Arduino-IRremote" rel="nofollow">IR Library</a></li> </ul> <p>I'm using a small Xbox 360 IR control (no numbers keypad), some HEX codes are left intact from the original sketch found on internet.</p> <p><a href="http://forum.arduino.cc/index.php?topic=256671" rel="nofollow">original topic</a></p>
<p>I've moved the <code>analogWrite</code> part of the code inside the <code>switch case</code> <code>BRIGHTNESS_UP</code> &amp; <code>BRIGHTNESS_DOWN</code> and it's working. I also removed the <code>crossFade(c);</code> line. </p> <p>Here's the working code:</p> <pre><code>#include &lt;TimerOne.h&gt; #include &lt;IRremote.h&gt; #include &lt;RGBMood.h&gt; int RECV_PIN = 2; // IR-Receiver PIN int led = 13; // Satus-LED PIN int modus; // Modus for Interrupt-Querry int ledr = 11; // RGB LED red PIN int ledg = 12; // RGB LED green PIN int ledb = 13; // RGB LED blue PIN int SerialBuffer = 0; int c[3]; //RGB Pins Array int CH[3] = {11, 12, 13}; int val[3] = {0, 0, 0}; // led brightness 0-255 RGBMood m(ledr, ledg, ledb); int timerwert = 20; // Timer time for Interrupt in ms String readString; // Color arrays int black[3] = { 0, 0, 0 }; int white[3] = { 100, 100, 100 }; int red[3] = { 100, 0, 0 }; int green[3] = { 0, 100, 0 }; int blue[3] = { 0, 0, 100 }; int yellow[3] = { 40, 95, 0 }; int dimWhite[3] = { 30, 30, 30 }; int brightness = 100; // how bright the LED is int fadeAmount = 5; // how many points to fade the LED by // etc. // Set initial color int redVal = black[0]; int grnVal = black[1]; int bluVal = black[2]; int wait = 10; // 10ms internal crossFade delay; increase for slower fades int hold = 0; // Optional hold when a color is complete, before the next crossFade int DEBUG = 1; // DEBUG counter; if set to 1, will write values back via serial int loopCount = 60; // How often should DEBUG report? int repeat = 3; // How many times should we loop before stopping? (0 for no stop) int j = 0; // Loop counter for repeat // Initialize color variables int prevR = redVal; int prevG = grnVal; int prevB = bluVal; #define ON 0xF4F37A66 #define OFF 0x1363ADB4 #define BRIGHTNESS_UP 0xE6721691 #define BRIGHTNESS_DOWN 0xE9721B48 #define FLASH 0xFFF00F #define STROBE 0xFFE817 #define FADE 0x39ED1255 #define SMOOTH 0xFFC837 #define RED 0x9D561314 #define GREEN 0XCB8E93A5 #define BLUE 0xC88E8EEC #define WHITE 0x16DBBEE3 #define ORANGE 0xFFB04F #define YELLOW_DARK 0xFFA857 #define YELLOW_MEDIUM 0xFF9867 #define YELLOW_LIGHT 0xFF8877 #define GREEN_LIGHT 0XFF30CF #define GREEN_BLUE1 0XFF28D7 #define GREEN_BLUE2 0XFF18E7 #define GREEN_BLUE3 0XFF08F7 #define BLUE_RED 0XFF708F #define PURPLE_DARK 0XFF6897 #define PURPLE_LIGHT 0XFF58A7 #define PINK 0XFF48B7 #define MAX 255 IRrecv irrecv(RECV_PIN); decode_results results; void setup() { pinMode(ledr, OUTPUT); // Set RGB LED Pins as Output pinMode(ledg, OUTPUT); // Set RGB LED Pins as Output pinMode(ledb, OUTPUT); // Set RGB LED Pins as Output pinMode(led, OUTPUT); // set Status-LED as Output //initiate rgb pins output for (int i=0; i&lt;3; i++) { pinMode(CH[i], OUTPUT); } m.setMode(RGBMood::RANDOM_HUE_MODE); // Automatic random fade. m.setHoldingTime(4000); // Keep the same color for 4 seconds before fading again. m.setFadingSteps(150); // Fade with 150 steps. m.setFadingSpeed(50); // Each step last 50ms. A complete fade takes 50*150 = 7.5 seconds m.setHSB(random(359), 255, 255); Serial.begin(9600); irrecv.enableIRIn(); // Start of IR-Recive Timer1.initialize(timerwert); // Initialisation of Timer-Interrupts Timer1.attachInterrupt(leseIR); // IR-Read from Interrupt } void leseIR(){ if (irrecv.decode(&amp;results)){ irrecv.resume(); // Receive the next value switch (results.value) { case FADE: // Modus Fade (DIY 4) modus = 1; break; case 0xFF906F: // Modus pcambi (DIY 5) modus = 2; break; case ON: //Power modus = 0; crossFade(white); // RGB LEDs Off break; case OFF: //Power modus = 0; crossFade(black); // RGB LEDs Off break; case BLUE: //Blau 0,0,255 modus = 0; crossFade(blue); break; case RED: //Rot modus = 0; crossFade(red); break; case GREEN://Grün modus = 0; crossFade(green); break; case WHITE: //Weiss modus = 0; crossFade(white); break; case BRIGHTNESS_UP: //DIMMING UP modus = 0; brightness += 5; if (brightness &gt; 255) brightness = 255; c[0] = prevR; c[1] = prevG; c[2] = prevB; analogWrite(ledr, redVal * brightness / 255); // Write current values to LED pins analogWrite(ledg, grnVal * brightness / 255); analogWrite(ledb, bluVal * brightness / 255); break; case BRIGHTNESS_DOWN: //DIMMING DOWN modus = 0; brightness -= 5; if (brightness &lt; 0) brightness = 0; c[0] = prevR; c[1] = prevG; c[2] = prevB; analogWrite(ledr, redVal * brightness / 255); // Write current values to LED pins analogWrite(ledg, grnVal * brightness / 255); analogWrite(ledb, bluVal * brightness / 255); break; case 0xFFAA55://Grün mitrtel modus = 0; break; case 0xFF926D: //blau mittel modus = 0; break; case 0xFF12ED: //rosa modus = 0; break; } // Switch END } } void loop() { if(modus==1){ // Querry pb Modus:1 m.tick(); } if(modus==2){ // Querry pb Modus:1 } Serial.println(prevR); Serial.println(prevG); Serial.println(prevB); // Serial.println(results.value, HEX); // Serial.println(DEC); // Serial.println(DEC); // Serial.println(DEC); // Serial.print("channel 1,2,3 values:"); // sends brightness values to the serial monitor // for(int i=0; i&lt;3; i++){ // every time the remote is pressed // Serial.print(CH[i]); // Serial.print(" "); // } } int calculateStep(int prevValue, int endValue) { int step = endValue - prevValue; // What's the overall gap? if (step) { // If its non-zero, step = 1020/step; // divide by 1020 } return step; } /* The next function is calculateVal. When the loop value, i, * reaches the step size appropriate for one of the * colors, it increases or decreases the value of that color by 1. * (R, G, and B are each calculated separately.) */ int calculateVal(int step, int val, int i) { if ((step) &amp;&amp; i % step == 0) { // If step is non-zero and its time to change a value, if (step &gt; 0) { // increment the value if step is positive... val += 1; } else if (step &lt; 0) { // ...or decrement it if step is negative val -= 1; } } // Defensive driving: make sure val stays in the range 0-255 if (val &gt; 255) { val = 255; } else if (val &lt; 0) { val = 0; } return val; } /* crossFade() converts the percentage colors to a * 0-255 range, then loops 1020 times, checking to see if * the value needs to be updated each time, then writing * the color values to the correct pins. */ void crossFade(int color[3]) { // Convert to 0-255 int R = (color[0] * 255) / 100; int G = (color[1] * 255) / 100; int B = (color[2] * 255) / 100; int stepR = calculateStep(prevR, R); int stepG = calculateStep(prevG, G); int stepB = calculateStep(prevB, B); for (int i = 0; i &lt;= 1020; i++) { redVal = calculateVal(stepR, redVal, i); grnVal = calculateVal(stepG, grnVal, i); bluVal = calculateVal(stepB, bluVal, i); analogWrite(ledr, redVal); // Write current values to LED pins analogWrite(ledg, grnVal); analogWrite(ledb, bluVal); delay(wait); // Pause for 'wait' milliseconds before resuming the loop } // Update current values for next loop prevR = redVal; prevG = grnVal; prevB = bluVal; delay(hold); // Pause for optional 'wait' milliseconds before resuming the loop } </code></pre> <p>thanks geometrikal for your support! You believe it's possible to manipulate the dimming of the fade effect too? It's using the RGBMood class to create a HSB color mix.</p>
3567
|avr|audio|
Using Arduino as USB Device?
2014-08-01T17:32:26.717
<p>I'm trying to get audio data from an ADC connected to an Arduino into a host PC. I've done some digging and found LUFA, which I think Arduino uses under the hood. Is it possible to use the Arduino as a USB device, and if so, are there any examples? Thanks!</p>
<p>LUFA is used for the USB to serial firmware on the separate USB-serial bridge AVR found on Uno and newer Megas. The firmware is compiled using a supplied makefile. Otherwise LUFA isn't used by Arduino.</p> <p>But LUFA is probably the right choice if you want to make a USB audio device. It comes with examples of both input and output audio devices. But you will have to compile using the supplied makefile, unless you are really ninja. On a Linux distro it's easy - don't know about other OS'es.</p> <p>The demo "Audio Input Device Demo" comes with LUFA and is ompatible with the atmega32u4 used on Leonardo. It can be set up to sample analog input and send it to the pc. From the documentation:</p> <blockquote> <p>On start-up the system will automatically enumerate and function as a USB microphone. By default, the demo will produce a square wave test tone when the board button is pressed. If USE_TEST_TONE is not defined in the project makefile, incoming audio from the ADC channel 1 will be sampled and sent to the host computer instead.</p> </blockquote>
3573
|library|
How to avoid odd naming rules for Arduino when writing a library?
2014-08-02T00:11:19.937
<p>I'm building a small library that will be used and production and released open source. I'm paying a lot of attention to the "best practices" to make sure this code is reliable and easy to use. I also would also like to make this easy to edit. I'm having an issue with the naming scheme of the whole project.</p> <p>There are a few Arduino naming quirks. If I have a sketch called <code>mylib</code>:</p> <ul> <li>...I can't create a tab called <code>mylib.cpp</code>. However, I <em>can</em> create a file called <code>mylib.h</code>...</li> <li>...The folder and main sketch file <strong>must</strong> be the same name as the folder it is in</li> <li>...The sketch name (and folder) cannot contain any spaces.</li> </ul> <p><em>Well, why are you creating a sketch for a library?</em> The Arduino IDE won't open a <code>.cpp</code> file unless there's a sketch in that folder (and you have to open the <code>.ino</code>/<code>.pde</code> file in that folder). I'm trying to get this to work with the Arduino IDE so, if users need to edit the library, then can just open the file and go to the correct tab. If they use an external editor, they won't be able to compile it to see if there are any errors.</p> <p>I'd ideally just do this structure:</p> <pre><code>my_lib |- my_lib.ino |- mylib.cpp |- mylib.h </code></pre> <p>However, a user might see that the folder is called <code>my_lib</code> and try including the file <code>my_lib.h</code>.</p> <p>I think this is a major oversight in the Arduino IDE, but I need to have this work with the Arduino IDE. If it was just me working on this code, I might consider making the library directly in a project directory, but that isn't ideal. Is there anything that I can do to bypass this/make it easy for users to edit? Is there any "standard"/"convention" that defines how to do this?</p>
<p>The Arduino IDE's restriction of not allowing you to create a .cpp tab with the same name as the sketch has been removed since the 1.6.12 release. </p> <p>In fact, older IDE versions would happily open and save sketches that contained, e.g., mylib.ino and mylib.cpp. You just needed to create the .cpp file outside of the Arduino IDE.</p> <p>The reason for this restriction in previous IDE versions was that the file in the temporary build folder generated from the preprocessed sketch was named {build.project_name}.cpp, which would be overwritten by the other .cpp "tab" file of the same name. Of course that is not an issue for your desired usage of the Arduino IDE simply to edit library source files. Later, the Arduino developers changed to the much more sensible system of naming the preprocessed file {build.project_name}.ino.cpp. Thus the restriction was no longer necessary.</p>
3576
|current|
Measure low current with variable voltage
2014-08-02T06:21:16.747
<p>I want to make a system that always have the same current (about 1ma) in a water with silver electrode. At start it will be purified water so conductivity will be really low.</p> <p>But with time silver particle will be released in water, raising his conductivity so if I don't lower the voltage the current will raise too (meaning that bigger particle will be released which I don't want too).</p> <p>So, is there any way I can measure low current and adapt voltage with the result (since deducting resistance wouldn't be hard).</p> <p>I know about ASC712 but It seem that he can't be precise enough (steps of 13ma max) to my use.</p> <p>I precise it's not that long I'm trying to get back in electronics with arduino so many school things have been forgotten. </p>
<p>What you want is called a constant current source. You can actually build a simple one using <a href="http://en.wikipedia.org/wiki/Current_source#mediaviewer/File:Const_cur_src_113.svg" rel="nofollow noreferrer">one transistor</a> ; but a better one uses two transistors - as in the left example below - see <a href="http://www.talkingelectronics.com/projects/TheTransistorAmplifier/TheTransistorAmplifier-P2.html" rel="nofollow noreferrer">this page</a> for explanations.</p> <p><img src="https://i.stack.imgur.com/E01sN.gif" alt="Transistor based current source"></p> <p>Here the leds would be your load, R=680 Ohm would give you about 1mA - and you would need to increase the value of the 2k2 resistor to somewhere around 22k.</p> <p>The problem is that, as John Williams noted, forcing 1mA through a high resistance requires high voltage : 1MOhm would need 1kV, 10MOhm needs 10kV etc. That's very dangerous voltages! and quite some power as well : 10kV at 1mA means 10W. </p> <p>I think you need to define your needs first :</p> <ul> <li>What is a tolerable error on the absolute value of current? (Would constant 1.1mA be OK?)</li> <li>What is a tolerable error on the current variations? (Would current varying between 1.19mA and 1.21mA be OK?)</li> <li>Do you absolutely need 1mA right from start? Or can you accept a lower current at start, growing with increased conductivity until 1mA is reached and then being held nicely constant?</li> </ul> <p>If the above examples are fine, a current source as described above would do the job nicely for less than 1USD. </p> <p>If you really need a constant current source right from the start, then be prepared to work with expensive and dangerous pieces of equipment.</p>
3579
|power|interrupt|
External (pin change) interrupt and power consumption
2014-08-02T09:19:12.867
<p>I want to write a lipoly powered arduino device that can be launched from sleep mode by pressing a certain key that is connected to ground. Usually, when no in sleep mode I enable the internal pull-up resistor for a definite level. But when in sleep mode, I assume this would drain to much power and hence I want to avoid it. Is it sufficient to just wait for a pin-change interrupt on the same port pin without the internal or an additional external pull-up resistor?</p>
<p>Tutorial from University of South Florida <a href="https://www.youtube.com/watch?v=HiAbxSO_9nU" rel="nofollow">https://www.youtube.com/watch?v=HiAbxSO_9nU</a></p> <p>Internal pull-up resistor does not drain too much current. Only leakage in nA range. It is correct to use pull up, in your case, as this is what it is designed to do. As Ignacio Vazquez-Abrams, do not leave input pin open.</p> <p>MCU are designed to do the precise action you mentioned, to wake up on pin change as in mass produced wrist watch and TV remote controller. On remote, MCU sleeps until key pressed. On watch, it wake on timer 1 second) and key change. </p>
3587
|arduino-yun|
YUN. How to reset the micro controller from linux?
2014-08-02T16:47:21.120
<p>As the title, I'd like to reset the Arduino sketch from the linux machine. Is it possible? how?</p> <p>One solution could be to save the hex file inside the sd card and then upload it via the lua sketch but I think there is a smarter solution.</p>
<p>Use command <code>reset-mcu</code>: it's a linux script that resets the 32u4 via GPIO</p>
3590
|accelerometer|data-type|
square root of large number
2014-08-02T17:02:06.777
<p>I've got 2 int16_t numbers, say 388 and 10288, which are sensor readings from an accelerometer. I want to estimate the angle of the device on that, but seemingly there are some type overflow issues:</p> <p>My final goal is this: </p> <pre><code>theta = atan(-ax/sqrt((float)ay*ay+az*az)); </code></pre> <p>The problem occurs in the bracket: ay^2 and az^2 are the 2 power of the given numbers. I recalculated with matlab and for the above example I get <code>a^2+b^2 = 388^2+10288^2 = 105993488</code> what I get from the arduino however is <code>152848</code>. To be short: I don't know much about fixed point math or thelike and I couldn't find a sufficient answer to this: How do I calculate the square root term?</p>
<p>You need 2 typecasts. So </p> <pre><code>atan(-ax/sqrt((float)ay*ay+(float)az*az)); </code></pre> <p>Otherwise it will use int16_t for the right side of the addition and overflow.</p> <p>Though for speed you might want to typecast them as <code>long</code> (<code>int32_t</code>), as floats calculations on the arduino are really slow. The <code>sqrt</code> function will covert this double into a float for you.</p>
3598
|sensors|
What is exactly MQ-2 sensor?
2014-08-02T19:58:51.857
<p>What does the <a href="http://linksprite.com/wiki/index.php5?title=MQ2_Smoke_Detector_Shield_for_Arduino" rel="nofollow">MQ-2</a> sensor detect?</p> <p>I know it detects concentrations of flammable gas. But does it detect smoke from fires too? What about smoke from cigarettes, and other things?</p>
<p>Simple answer is no. </p> <p>There are about 10 similar sensors, each detect specific kind of chemicals </p>
3603
|time|
Delay function without using a timer
2014-08-03T10:33:40.753
<p>Is there a delay function available that does not use <code>millis()</code> which itself makes use of a timer? Does not need to be hyper-exact.</p>
<pre><code>delayMicroseconds(1000);// maximum delay is 65535 uS </code></pre> <p>or </p> <pre><code>#include &lt;util/delay.h&gt; _delay_ms(1); </code></pre>
3604
|rfid|
125 kHz RFID reader with Arduino
2014-08-03T10:37:01.740
<p>Why is a toroidal inductor being used in the RFID reader described in <em><a href="http://playground.arduino.cc/Main/DIYRFIDReader" rel="nofollow">DIY FSK RFID Reader</a></em>?</p> <p>I feel that a toroidal inductor wouldn't be very effective in grasping the changes in electromagnetic field changes.</p>
<p>Yes, Chris Stratton is right. A toroidal inductor keeps flux within the core, reduces the external flux to near zero and have near zero ability to grasp/convert external flux/magnetic field into electrical signal. Apparently, the word 'toroidal' was used in loose sense referring to a circularly shaped coil.</p> <p>In an real-life commercial product, a 125&nbsp;kHz coil typically has many turns on a very thin wire on an open-air core (no core).</p> <p>An example profession factory made a 125&nbsp;kHz RFID with a <a href="http://en.wikipedia.org/wiki/GitHub" rel="nofollow">GitHub</a> Arduino library and photos of an antenna coil:</p> <ul> <li><p><em><a href="http://www.seeedstudio.com/depot/125Khz-RFID-module-UART-p-171.html" rel="nofollow">125 kHz RFID module - UART</a></em></p></li> <li><p><em><a href="https://github.com/Seeed-Studio/RFID_Library" rel="nofollow">Seeed-Studio/RFID_Library</a></em></p></li> <li><p><em><a href="http://www.seeedstudio.com/wiki/index.php?title=125Khz_RFID_module_-_UART" rel="nofollow">125Khz RFID module - UART</a></em> (wiki)</p></li> </ul> <p>Also, see <em><a href="http://www.8051projects.net/news-i140-5-building-rfid-card-reader-using-pic-microcontroller.html" rel="nofollow">Building RFID Card Reader using PIC Microcontroller</a></em>.</p> <p>Note, for higher frequency RFID, not shown in above examples, coils have fewer turns than for 125&nbsp;kHz.</p>
3612
|timers|sd-card|virtualwire|tmrpcm|
Using both TMRpcm and VirtualWire libs with ATmega328, despite the conflict on TIMER1
2014-08-04T00:16:42.560
<p>I wanted to use both <a href="https://github.com/TMRh20/TMRpcm" rel="nofollow noreferrer">TMRpcm</a> and <a href="http://www.airspayce.com/mikem/arduino/VirtualWire/" rel="nofollow noreferrer">VirtualWire</a> with ATmega328 in an Arduino-like board I'm making, but both libraries use TIMER1. I wanted to use each lib for the following purposes:</p> <ul> <li>TMRpcm: play a WAV sound from an SD Card;</li> <li>VirtualWire: to receive commands from an RF remote control.</li> </ul> <p><a href="https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features" rel="nofollow noreferrer">TMRpcm Advanced Features Wiki</a> has a section on <a href="https://github.com/TMRh20/TMRpcm/wiki/Advanced-Features#timer2-usage" rel="nofollow noreferrer">how to use TIMER2 instead</a>, but I couldn't get it to work. They also say:</p> <blockquote> <p>Notes:</p> <ol> <li>This is usually not the best solution.</li> </ol> </blockquote> <p>So, before I spend any more time on this, I would like to hear what you guys have to say.</p> <p>So, my question is: <strong>is there a workaround to solve this conflict on the use of TIMER1, so I can use both libs in my project?</strong></p> <p>If not, <strong>what other alternatives do I have?</strong></p> <p>My circuits for reading the SD card and driving the speaker are similar to the schematic in this Instructable: <a href="http://www.instructables.com/id/Playing-Wave-file-using-arduino/" rel="nofollow noreferrer">Playing Wave file using Arduino</a>. And I'm using one of those <a href="http://www.soldafria.com.br/datasheet/RWS-375-6(433_92mhz).pdf" rel="nofollow noreferrer">433MHz Receiver modules</a> for the RF part (standard, working circuit).</p> <p>Both features, the RF receiver and SD card WAV playing, work correctly, when run separately (with separate sketches).</p>
<p>the virtual wire library has been obsoleted, and you should now use the <a href="http://www.airspayce.com/mikem/arduino/RadioHead/" rel="nofollow">RadioHead</a> library. In this RadioHead Library, you can edit the RH_ASK.cpp file, and uncomment the #define RH_ASK_ARDUINO_USE_TIMER2 near the top. </p>
3613
|time|
Shortest time interval that Arduino Uno R3 can read
2014-08-04T01:19:08.970
<p>I am doing a light speed determination experimsmt. Lightspeed is around 3*10^8 m/s. For this, I need to measure time interval between 2 light sensors in nanoseconds, Somewhere about 50ns. Is this possible using the Uno R3? I know the clock is 16MHz only but is the clock irrelevantto the topic? If it is not possible, Some tips would be helpful. Thank you. </p> <p>Sorry for irrelevant tags. No suitable tags found.</p>
<p>At 16MHz, the quickest operation that the cpu can do (a one cycle operation) will take 62.5 nanoseconds (1/(16*10^6) seconds). That means the best resolution you could conceivably have is 62.5 ns chunks. It will take considerably longer than one clock to respond to an outside event though, so making an experiment will be really tough even then.</p> <p>Maybe you could build an experiment like the <a href="https://en.wikipedia.org/wiki/Fizeau-Foucault_apparatus#mediaviewer/File:Fizeau.JPG" rel="nofollow noreferrer">Fizeau apparatus</a> where the arduino measured pulses of light that make it back through the slit? Those would be measured in microseconds. The arduino could change the speed of the grooved wheel and maximize the returning pulse width, reading the rpm then gives you the speed of light.</p> <p>I'll note that since the meter is defined by the speed of light, and the foot defined by the meter, You would not be measuring the speed of light in feet or meters per second; you would be measuring the length of a meter given how long a second is, or vice versa.</p>
3617
|electronics|
What electronics should I study to create something like a fridge temperature monitor?
2014-08-04T22:12:52.627
<p>I would like to be able to design an Arduino circuit for a fridge monitor that would have a temperature sensor, a small speaker to emit a sound when the temperature changes past a threshold and an LCD screen showing the current temperature.</p> <p>I have found a few examples online, but I would like to know why components like capacitors and transistors are used in their circuits so I'd be able to design similar circuits myself.</p> <p>I found this list of electronics topics:</p> <ul> <li>Basic Theory</li> <li>Basic Passive Components</li> <li>Passive Circuits</li> <li>Discrete Active Components</li> <li>Active Circuits</li> <li>Integrated Circuits</li> <li>Digital Logic</li> <li>Analog</li> <li>Signals</li> <li>Outputs</li> <li>Inputs</li> <li>Digital Electronics</li> </ul> <p>Some of these things, like digital logic seem unnecessary in such a project, but obviously some others are useful, but I don't know which. I'd like to know what it would be useful to study so I can understand the reasons for the circuit design of something like a fridge monitor.</p>
<p>A fridge temperature monitor (or any system that talks to world using some data) will include a sensor (temperature sensor like LM35), a controller (to do calculations, arduino ofcourse) and an output (display, like LCD). The topics you should be aware of, are digital electronics, basic passive components (working of resistor, capacitor etc). And a little arduino programming and lots of logic.</p>
3623
|lcd|1-wire|
LCD showing weird characters when using two 1-wire temperature sensors
2014-08-05T10:09:51.127
<p>I have a sketch to display a temperature obtained from 1-wire DS18B20 sensors. The sketch works fine, however when I connect two sensors to my board, the text on the LCD displays gets corrupted (### and other symbols shown instead of a temperature).</p> <p>I have tried plugging each of the two DS18B20 sensors individually and it works with both of them, the problem shows only when I use both at the same time. I am connecting them both with black to ground, red to 5V and white to Dx and to 5V via a 4.7 kOhm pull-up resistor.</p> <p>I have little idea how to check what is wrong - is it some kind of interference, insufficient voltage, or a SW problem?</p>
<p>After some more searching I have found <a href="http://forum.arduino.cc/index.php?PHPSESSID=kpntcnv2f3dq544iuh5inrl404&amp;topic=86731.msg650003#msg650003" rel="nofollow">Arduino forum topic LCD text corrupts after Arduino runs for length of time</a>. I have followed <a href="http://forum.arduino.cc/index.php?PHPSESSID=j4imm6sr0dbrnas4pp1unc8ae5&amp;topic=86731.msg653008#msg653008" rel="nofollow">this advice</a>:</p> <blockquote> <p>In particular, try running the LCD ground wire directly to a ground pin on the Arduino (not to the breadboard) and keep it short.</p> </blockquote> <p>This seemed to solve the issue, therefore it was likely some kind of interference on the ground wiring. (Before this, the ground to the LCD went trought the breadboard power bus).</p>
3625
|arduino-uno|programming|pins|lcd|
Why is my LCD 16*2 is not displaying any characters, although all the wiring is correct?
2014-08-05T11:17:40.777
<p>Recently I have linked up a typical 16*2 LCD (Liquid Crystal Display) display to my Arduino Uno and have linked all the pins up.</p> <p>Here is my connection:(LCD pin first)</p> <p>1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative</p> <pre><code>#include &lt;LiquidCrystal.h&gt; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(12, 11, 5, 4, 3, 2); void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("hello, world!"); } void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): lcd.setCursor(0, 1); // print the number of seconds since reset: lcd.print(millis()/1000); } </code></pre> <p>This is the code that is the default for the LCD, I didn't write it.</p> <p>So I have done all this and when I turn it on the screen is blank and nothing is happening. Could anyone explain what I have done wrong?</p>
<p>Recently I also faced similar problem, with connection as:</p> <p>1=GND, 2=+5v, 4=11, 6=12, 11=5, 12=4, 12=3, 14=2, 15=backlight positive, 16=backlight negative</p> <p>Solution: I just <strong>connected VEE (pin 3) of LCD to Ground (GND)</strong> without use of potentiometer as it worked.</p>
3629
|serial|
How to tap my thermostat's serial line
2014-08-05T15:21:30.417
<p>This is a home heating system hack.</p> <p>I want to add an arduino in-line between my thermostat and air handler; and possibly between the air handler and outdoor compressor. The long-term goal is to post long-term statistics to an RRD web page (run time, power consumption, temp, etc.) and control the blower (without the heat) automatically when we are burning our wood stove.</p> <p>The product is a Nordyne IQDrive (notable in that the equipment comes with 5 separate brand logos to adhere to the equipment: Tappan, Frigidaire, Westinghouse, Nutone, and Broan).</p> <p>At this stage, all I want to attempt to do is to tap the serial links and record the conversations. I would prefer not to shoot myself in the foot.</p> <p>The "System Field Wiring Instructions" describe both links as "serial." The wiring diagrams label the connection points as:</p> <p>air handler interface board --> [description] --> thermostat</p> <pre><code> G --&gt; GND --&gt; C - --&gt; DX- --&gt; B- + --&gt; DX+ --&gt; A+ R --&gt; R --&gt; R </code></pre> <p>Googl'ing these might indicate that this is an RS485 (never heard of it).</p> <p>How do I tap and record the communication?</p>
<p>I does sound like RS-485.</p> <p>You can get cheap RS-485 transceivers from the usual sources. These take the 0..5v TX line and convert it to RS-485 voltages, or RS-485 voltages and convert to the 0..5v RX expected by your Arduino. You would normally enable only one direction at a time - sending RS-485 from the Arduino TX or receiving RS-485 to the Arduino.</p> <p>In your case, you just want to receive, so keep the transmit side (TX to RS-485) disabled, while enabling the receive side (RS-485 to RX).</p> <p>RS-485 is just an electrical standard, and they could be sending any pattern of on and off signals they want, but often they will be sending asynchronous data with one start bit, 7-8 data bits, and one stop bit per character - which the Arduino's Serial port can handle. So it's worth testing to see if that works.</p> <p>The next thing you need to know is the clock rate, or "baud rate", which is how many bits per second (including start and stop bits) it is sending. Often you can figure this out by trying some standard rates like 1200,2400,4800,9600,19200,38400,57600,115200 (there are others) and printing the results to your screen - when you are at the wrong rate you will get nothing, or some odd garbage. When you get the right rate, it will look more reasonable.</p> <p>If no speed works, you may need to reverse A and B.</p> <p>You might temporarily hook up an LED and a resistor (say 2.2K or higher) between the RX from the RS-485 and your 5v power. This will give you an idea of when there are transmissions from or to the thermostat. If it only transmits once a minute, say, you might have to wait a while for each speed test. Or changing the set temperature may trigger a send.</p> <p>You may be able to test the lower speeds at least using Software Serial, and then echo the received data to the hardware serial port which goes to the Serial Terminal in the Arduino IDE.</p> <p>From there, you may need to figure out the protocol - the structure of the data. Protocols vary widely. It may be text or it may be binary; if it's binary you may want to have the arduino convert each character (values 0..255) into hexadecimal (00..FF) for printing.</p> <p>Most protocols for this kind of control send data in a burst, or packet. You will likely be able to detect the start and end by the timing (ie: a long pause between the end and the start of the next). Of course, some protocols might send several packets continuously, but still the first character (or binary value) after a long pause will often be the packet header.</p> <p>Remember that there may be packets from the themostat, and packets to the thermostat, and you will see both without knowing which is which (so long as you are just passively tapping the line).</p> <p>I hope this is enough of a pointer to get you started. Decoding protocols is a more extended subject.</p>
3632
|avr|attiny|
Is it possible to program an Attiny85 with a USB-to-TTL converter?
2014-08-05T21:31:20.613
<p>I currently use my Arduino to program Attiny85. As I have one of these <a href="http://www.ebay.com/itm/New-1PCS-5PIN-PL2303-USB-To-TTL-Auto-Converter-Adapter-Module-unit-For-arduino-/141150349286">USB-to-TTL adapters</a> I am wondering if it is possible to program Attiny85 with it, to free up my Arduino. I know it is possible to program Atmega's with such a thing.</p> <p>If it is in fact possible to use the converter as a simple programmer for Attiny's, how should I connect the converter to the Attiny?</p>
<p>Yes, it is possible.</p> <p>Note that the FTDI chip (assuming that is what you have) can be accessed as either Virtual Com Port <a href="http://www.ftdichip.com/Drivers/VCP.htm" rel="noreferrer">VCP</a> or <a href="http://www.ftdichip.com/Drivers/D2XX.htm" rel="noreferrer">D2XX</a>. Where VCP is the traditional method of using them as Serial Ports with avrdude calling "-c arduino -P COM3 -b115200". However the later D2XX method allows for the pins to be Bit Bang'ed.</p> <p>One can see in this <a href="http://doswa.com/2010/08/24/avrdude-5-10-with-ftdi-bitbang.html" rel="noreferrer">tutorial</a> it is possible to call avrdude with a programmer of "-c ftdi". Assuming that the D2XX drivers are installed.</p> <p>Where I see in the current releases 1.0.5r2 and 1.5.7's avrdude's config files that a programmer of type "avrftdi" is supported, as opposed to the article "ftdi"</p> <p>However, that is not to say the IDE natively supports its. You will have to either call avdude manually. Or add the "avrftdi" to "\arduino-1.5.7\hardware\arduino\avr\programmers.txt" so that the IDE will be aware of it.</p> <hr> <p>That all said I see "Tiny AVR Programmer" that are very in-expensive.</p>
3638
|sensors|power|sketch|flash|temperature-sensor|
Wrong data from DS18B20 temperature sensor after long power off
2014-08-06T07:12:50.567
<p>I have my Arduino Uno connected to the PC via USB when prototyping. I am developing a thermometer with memory, using DS18B20 sensors.</p> <p>When PC is shut down, there is no power on the USB and the Arduino is off. Sometimes, when my PC is turned off for several hours and then, when I turn it on, the Arduino is started, but it behaves "strange" - the program is showing buggy values on the display, looking like if there is some bug in the sketch. However, when I upload the sketch again, it works fine.</p> <p>The buggy values are the averages for the run, computed simply by summing a float and dividing by int. What I see is e.g. instead of seeing something around 23.5 I see 85.1. The current values read from the sensor look OK (show 23.5 as expected), but I cannot tell for sure if perhaps some value read early might be wrong.</p> <p>It is not easy to reproduce, I see it only sometimes, always when powering Arduino on after several hours without power.</p> <p>My first idea is either the sketch got corrupted during the long power down, or variables are initialized wrong, and the sample sum / sample count is not zero.</p> <p>However I though the sketches are uploaded into the Flash RAM, which should be non-volatile <a href="http://arduino.cc/en/Tutorial/Memory" rel="nofollow">according to the docs</a>. Is there something obvious I am missing, some explanation why is the sketch working differently after long power down?</p>
<p>I researched this once when I was getting consistent, exactly 85 degC readings from my sensors. The <a href="https://duckduckgo.com/l/?kh=-1&amp;uddg=http%3A%2F%2Fdatasheets.maximintegrated.com%2Fen%2Fds%2FDS18B20.pdf" rel="nofollow">Maxim DS18b20 data sheet</a> (rev 042208, page 4, in a footnote to Table 1) says: </p> <blockquote> <p>"The power-on reset value of the temperature register is +85°C.</p> </blockquote> <p>Double check that the Arduino code is follows the sensor communication protocol correctly.</p>
3639
|attiny|ir|
Reliably duplicate custom IR remote control with ATTiny85
2014-08-06T07:31:01.310
<p>This is something I'm struggling with for a while and fail to find solid solution. The Arduino IR library provides method for recording arbitrary IR code and re-sending it. This gave me different results every time I recorded the IR remote, so I wrote a little code, based on interrupts, that try to record the IR rise/fall as accurately as possible. I am working with ATTiny85 running at 8Mhz on internal oscillator. </p> <p>Here is the code:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(4,3); const int dataSize = 40; int data[dataSize]; int dataLength[dataSize]; void setup() { pinMode(0, OUTPUT); // 0 is IR receiver pin mySerial.begin(9600); mySerial.println("Start"); attachInterrupt(0,IR_ISR,CHANGE); mySerial.println("Registered"); sei(); } volatile unsigned long prev = micros(); volatile unsigned long curr = -1; volatile unsigned short index = 0; volatile bool rising = true; void IR_ISR() { if (!rising) { dataLength[index] = micros() - curr; rising = !rising; return; } curr = micros(); data[index++] = (int)curr-prev; prev = curr; rising = !rising; } void loop() { delay(5000); for (int i=1; i&lt;dataSize; i++) { mySerial.print(data[i]); mySerial.print("("); mySerial.print(dataLength[i]); mySerial.print(")"); mySerial.print("; "); } mySerial.println(); index = 0; } </code></pre> <p>Problem is that the milliseconds alter on each record of the remote control, here is an example of the output of 3 attempts of clicking at the same button of the remote control (I pasted only the first 5 IR modulations to avoid too much text, total is about 39):</p> <blockquote> <p>Start<br> Registered</p> <p>14104(9496); 1184(672); 1184(616); 1160(656); 1176(672); ...</p> <p>14096(9480); 1184(664); 1208(568); 1136(616); 1184(664); ...</p> <p>14096(9384); 1216(576); 1136(616); 1184(664); 1208(560); ...</p> </blockquote> <p>The format is: [microseconds from previous falling edge](microseconds from rise to fall);</p> <p>As you can see, the results vary. According to the <a href="http://arduino.cc/en/Reference/Micros" rel="nofollow">arduino.cc</a> website, the micros() function has a 8 microseconds resolution on 8Mhz AVR's, but the difference between reads is bigger than that.</p> <p>This is not reliable enough for me to solidly duplicate a remote control, and I'm looking for a resolution that will provide accurate results, as the magnitude of every deviation increases when the voltages are low (for example, with a 3v 2032 coin battery half discharged). </p>
<p>I often see where people have problems with decoding IR signals from time to time, but very few say how they are attempting to do that? The first thing you really need to know is what is the carrier frequency? if you are using a TSOP IR DEMODULATOR, They come in several flavors and if you have the wrong one your results may not be all that rock solid. There are one or two ways to determine this. have a digital storage scope and a fast photo diode (photo transistors are slow) which does no demodulation, just gives you raw IR . Once you determine your carrier frequency, then purchase a IR demodulator TSOP that is closest to your carrier frequency, then your results will be more stable no doubt.</p>
3644
|programming|lcd|
My counting function is not working with the text on my lcd
2014-08-06T12:34:21.570
<p>I want the bottom row of my LCD to display the counting function and include text:</p> <pre><code>lcd.setCursor(0, 1); lcd.print("Launch in"millis()/1000); </code></pre> <p>But it comes out with an error, what part is wrong?</p>
<p>The last line in the code you provided won't compile.</p> <p>The <code>lcd.print()</code> function expects a char, byte, int, long or string (taken from the LiquidCrystal docs) and you're trying to combine a string and an int which the compiler isn't going to understand.</p> <p>The easiest way to print both would be to have two lcd.print statements:</p> <pre><code>lcd.print("launch in "); lcd.print(millis()/1000); </code></pre> <p>Most of this is taken from quickly googling displaying time on an lcd screen. Check out this forum post, it seems similar to what you want to do: <a href="http://forum.arduino.cc/index.php/topic,12003.0.html" rel="nofollow">click me!</a></p>
3651
|arduino-uno|programming|pins|lcd|sketch|
On my lcd my characters collide, how can i remove one(because of the programming)
2014-08-06T14:30:15.640
<p>My code means that when i press a button it displays a word, but by default words are already there and i need to get rid of those default words.</p> <pre><code>#include &lt;LiquidCrystal.h&gt; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(7,8,9,10,11,12); int buttonApin = 4; void setup() { pinMode(buttonApin, INPUT_PULLUP); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. lcd.print("Mission Control "); } void loop() { if (digitalRead(buttonApin) == LOW) { lcd.setCursor(0, 1); lcd.print("Test"); } lcd.setCursor(0, 1); lcd.print("launch in "); lcd.print(millis()/1000); </code></pre>
<p>The HD44780 controller has a 80 bytes (characters) memory, in order to support up to 2x40 character displays. Since you use a 2x16 display, there is an empty space in the memory you can use on your benefit. It's like having two desktops, you are able to show one or the other.</p> <p>Refer to <a href="http://web.alfredstate.edu/weimandn/lcd/lcd_addressing/lcd_addressing_index.html" rel="nofollow noreferrer">LCD Addressing</a> for a visualization of the the memory locations and detailed explanation.</p> <p><img src="https://i.stack.imgur.com/a9SV4.gif" alt="enter image description here"></p> <p>Anything you write in locations <code>setCursor(16, 0)</code> to <code>setCursor(39, 0)</code> and <code>setCursor(16, 1)</code> to <code>setCursor(39, 1)</code> will not be visible until you scroll to the left. Consequently you can have some text already written in the hidden area and then alternate the shown text just by scrolling left and right.</p> <p>Here is an example</p> <pre><code>#include &lt;LiquidCrystal.h&gt; // initialize the library with the numbers of the interface pins LiquidCrystal lcd(7,8,9,10,11,12); int buttonApin = 4; void setup() { // set up the LCD's number of columns and rows: lcd.begin(16, 2); } void loop() { if (digitalRead(buttonApin) == LOW) { // write text to the visible area lcd.setCursor(0, 0); lcd.print("showing 0,0-15,0"); lcd.setCursor(0, 1); lcd.print("showing 1,0-15,1"); // write text to the hidden area lcd.setCursor(16, 0); lcd.print("now 16,0-31,0"); lcd.setCursor(16, 1); lcd.print("now 16,1-31,1"); while (1) { // scroll to the left and back to show different text without writing a single character delay(2000); for(uint8_t i=0;i&lt;16;i++) lcd.scrollDisplayLeft(); delay(2000); for(uint8_t i=0;i&lt;16;i++) lcd.scrollDisplayRight(); } } } </code></pre> <p>The code changes the visible text just by scrolling</p>
3655
|arduino-uno|
USB device not recognised - windows 8.1
2014-08-06T18:56:01.853
<p>I'm a beginner with Arduino and i have acquired the Arduino UNO R3 board. i have followed the instructions on arduino website in order to install the board, however it fails and still remains as an unrecognised device.</p> <p><strong>consequently, arduino IDE reports that COM1 is not found, and the 'ports' menu is grayed out.</strong></p> <p>steps i have tried:</p> <p><strong>1) install the Arduino 1.0.5 IDE</strong> <br/>- the installation failes near the end when installing the arduino board <strong><br/>2) install the Arduino 1.5.7 BETA IDE</strong> <br/>- the installation is successful but arduino device is still unrecognized. <strong><br/>3) i have tried manually installing the drivers by letting windows search in the arduino IDE installation folder/drivers/</strong> <br/>- it reports that the best driver is already installed - "usb unrecognized device" <strong><br/>4) i have tried installing the drivers by manulally loading the <code>.inf</code> files from the IDE installation folders, and installing all the <code>serial converter A/B/C/D</code> in the list</strong> <br/>- all failed to install.</p> <p>i have done all the above for both IDE 1.0.5 and 1.5.7b with windows installer And zipped files, under administrative rights in windows 8.1</p> <p>How do i get this to work?</p>
<p>Right click on devices list from Manager update driver and choose the folder with name "driver" in your arduino IDE app that you use Ok and the card ll be recognized good luck</p>
3658
|arduino-uno|c++|class|
Arduino Servo won't move when using classes
2014-08-06T19:30:41.987
<p>I'm trying to make a class work with Arduino, however it doesn't seem to trigger properly. The <strong>code is compiling</strong> perfectly, and it's supposed to control the <strong>leg of an hexapod</strong>. Also, the example sweep works on this servo, so no problem here. However, the servo is not actually moving. I'm thinking it has something to do with the order of declaring the variables:</p> <pre><code>#include &lt;Servo.h&gt; // Abstract each leg, so only those functions can be accessed class Leg { // Actions that can be triggered from outside public: Leg(int hipPin, int kneePin); void up(); // These should be only available for the leg private: Servo hip; Servo knee; }; Leg::Leg(int hipPin, int kneePin) { hip.attach(hipPin); knee.attach(kneePin); } // Testing the leg: move it up void Leg::up() { for(int pos = 0; pos &lt; 180; pos += 1) { hip.write(pos); delay(15); } } // Initialize the leg Leg topLeft(9, 10); void setup() { } // Test the function up() void loop() { topLeft.up(); } </code></pre> <p>I'm testing only the pin 9 (leaving the 10 empty). It <em>seems in pain</em>, meaning, you can see the servo trembling but not moving really at 0 degrees.</p>
<p>It looks this problem may be due to bad order of initializers calls for global variables.</p> <p>In C++, the order of global variable initialization is unpredictable across different compilation units (i.e. C++ source files, not header files). Initialization order is only respected <strong>inside</strong> one compilation unit.</p> <p>In your program, there are several global variables that, if initialized in the wrong order, will fail your program:</p> <ul> <li><code>Leg topLeft;</code> this is your class instance</li> <li><code>servo_t servos[MAX_SERVOS];</code>, <code>int8_t Channel[_Nbr_16timers ];</code> and <code>uint8_t ServoCount = 0;</code> all defined in <code>Servo.cpp</code></li> </ul> <p>Calling <code>Servo.attach()</code> requires that the 3 variables above have already been initialized, which you cannot be sure of.</p> <p>How can you fix that?</p> <p>By not performing the <code>attach()</code> in <code>Leg</code> constructor but delegating it to some kind of <code>init()</code> method that you can call from <code>setup()</code>:</p> <pre><code>class Leg { // Actions that can be triggered from outside public: void init(int hipPin, int kneePin); void up(); // These should be only available for the leg private: Servo hip; Servo knee; }; Leg::init(int hipPin, int kneePin) { hip.attach(hipPin); knee.attach(kneePin); } // Testing the leg: move it up void Leg::up() { for(int pos = 0; pos &lt; 180; pos += 1) { hip.write(pos); delay(15); } } // Declare the leg Leg topLeft; void setup() { // Initialize the leg topLeft.init(9, 10); } // Test the function up() void loop() { topLeft.up(); } </code></pre>
3667
|arduino-mega|led|attiny|
Attiny13 + Arduino
2014-08-07T09:40:02.750
<p>I started my first try in programming an ATTINY13 with my Arduino 2560.</p> <p>Everything seemed fine, however when I wanted to run the blink example, my LED did not blink, it keeps lighting.</p> <p>I am using 5V as input voltage.</p> <p>I did not change the blink example except for the correct pin number.</p> <p>All the wiring seems correct, when I change the pin number the LED stays dark, so my program is arriving propperly on the ATTINY.</p> <p>If I start playing with the delays (delaymicroseconds) I get the LED to become darker.</p> <p>The documentation of the ATTINY13 (www.atmel.com/images/doc2535.pdf) mentions a maximum clock frequency of 20MHz. When I choose the ATTINY13 from the Arduino IDE board menu it is listed with a 9.6MHz clock.</p> <p>Could this be a reason? How can I adjust or take care of that?</p> <p>----------- Edit:</p> <p>I was starting with the default blink example (<code>delay(1000)</code>).</p> <p>I played with both, the normal <code>delay</code> and the <code>delayMicroseconds</code>.</p> <p>The following codes dimmed the LED:</p> <pre><code>void setup() { pinMode(3, OUTPUT); } void loop() { digitalWrite(3, HIGH); delayMicroseconds(10); digitalWrite(3, LOW); delayMicroseconds(1000); } </code></pre> <p>Which makes me believe the LED is blinking very fast. A similar sketch with normal <code>delay</code> does not make the LED dim:</p> <pre><code>void setup() { pinMode(3, OUTPUT); } void loop() { digitalWrite(3, HIGH); delay(1); digitalWrite(3, LOW); delay(100); } </code></pre> <p>And as mentioned with the default blink sketch the LED nothing happens as well.</p> <p>I also made the delay a ever increasing variable to see if something is happening, no luck. And I have 2 ATTINYs to test, same result for both...</p> <p>--- Edit2:</p> <p>Another try:</p> <pre><code>int led = 3; void setup() { pinMode(led, OUTPUT); digitalWrite(led, HIGH); delayMicroseconds(100); digitalWrite(led, LOW); } void loop() { } </code></pre> <p>Now I moved switching the LED on and off into the setup function. Strangely enough, by changing the delay between 1000 and 100 micro seconds, the LED gets lighter and darker...</p> <p>---- Edit 3:</p> <p>Here is my circuit:</p> <p><img src="https://i.stack.imgur.com/mwhqi.png" alt="enter image description here"></p> <p>And this is the ATTINY specific code I added to the Arduino IDE:</p> <pre><code>attiny13.name=ATtiny13 (internal 9.6 MHz clock) attiny13.bootloader.low_fuses=0x7a attiny13.bootloader.high_fuses=0xff attiny13.upload.maximum_size=1024 attiny13.build.mcu=attiny13 attiny13.build.f_cpu=9600000L attiny13.build.core=arduino:arduino attiny13.build.variant=tiny8 </code></pre>
<p>I switched to a different ATTINY 13 driver and core definition in the Arduino IDE and this made it work.</p> <p>Unfortunately by playing around I lost track of the old driver.</p> <p>I am now using smeezkekitty's core13 which I found here: <a href="http://elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/" rel="nofollow">http://elabz.com/arduino-shrunk-how-to-use-attiny13-with-arduino-ide/</a></p>
3676
|motor|arduino-nano|
little pump isn't working
2014-08-07T17:02:50.550
<p>I'm trying to use a little pump with my arduino nano:</p> <pre><code>void setup () { pinMode(waterPump, OUTPUT); } ... while (val &lt; valueWater) { Serial.println ("in while"); // testing purpose digitalWrite(waterPump, HIGH); delay(1000); // 1 second digitalWrite(waterPump, LOW); val = analogRead(sondeEau); } </code></pre> <p>When I try this one, pump isn't working. When I unplug the waterPump pin, I see "LED3" that run, and when I plut it, LED3 is not running, why?</p> <p>I tried to plug pump directly on 5V on arduino, pump works well...</p> <p>This is the pump I bought: <a href="http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808" rel="nofollow">http://www.dx.com/p/hsyy01-water-pump-motor-w-hose-white-silver-236808</a></p> <p>Thanks in advance to help me!</p>
<p>As Chris says, you should never plug a high current device like a motor directly into a pin on your Arduino. That motor is rated at 800 mA, which is more than you can draw from the entire 5V supply on the Arduino!</p> <p>The digital pins are rated for 40 mA max, if I remember correctly. You tried to draw 20 times that much. There is a decent chance that you burned out the driver for that digital pin. I would try hooking an LED through a 220 ohm resistor and to ground and see if it still lights up when you send it a HIGH logic signal.</p> <p>For a simple DC motor you should be able to use a high current transistor and an external power supply to drive it.</p> <p>Edit: If I were doing this I would use a logic-level MOSFET to drive the pump directly, plus a flyback diode. To use a relay, you will still need a transistor to power the relay coil, AND a flyback diode. Your circuit might look like this:</p> <p><img src="https://i.stack.imgur.com/3TJKg.png" alt="enter image description here"></p> <p>(Note that I made no attempt to pick the RIGHT kind of diode and transistor. Ignore the part numbers shown in the schematic. I just used the defaults.)</p>
3682
|motor|arduino-motor-shield|
Question different ways of connecting L298N motor driver board to arduino and motors and powering them
2014-08-07T20:44:59.103
<p>I read few posts and tutorials on this topic but none of them kind of answered my questions. I bought this L298N motor board and i have two motors that are rated 3V <img src="https://i.stack.imgur.com/T3URN.jpg" alt="enter image description here"></p> <p>Now i am trying to understand how to connect it to arduino and power the motors.<br> For example i have a 12V (8x 1.5v AA batteries) I can connect to VCC and GND then enable ENA with a jumper and connect PWN port from arduino to INA. This way i can control the voltage that is coming out from OUTA and OUTB I can bring down the 12V to 3V.<br> Now the question is can i use the +5 (regulated voltage) on the driver board and connect it to arduino Vin and GND to ground to power the arduino? Is that viable solution. I actually tried it and it works. I am worried that it is not enough voltage to properly power the arduino. It's suggested to connect 7v - 12v to Vin. I am also going to connect a red lab ble shield on top of arduino that is powered by 5v</p> <p>Another question is if i use 12 volts battery and step it down to 3v with PWN is that going to heat up the L298N chip? </p> <p><img src="https://i.stack.imgur.com/n7C3i.png" alt="enter image description here"> Another option is connecting 9V battery to arduino and then using Vin and GND to power the motor shield and the motors. The problem there if motor draws more then 1Amp that wouldn't be good for the arduino. Also if i would switch to 9v+ motors then it wouldn't work.</p> <p>The third option is to have two separate power sources. 9V for arduino and 5v+ for powering the motors. Does it make sense to use two power sources? </p> <p>This project seems like a good way to learn about arduino and electronics</p> <p>Update</p> <p>NEOMART Brand New Original High Quality Chips L298N <a href="http://rads.stackoverflow.com/amzn/click/B00E58EA90" rel="noreferrer">http://www.amazon.com/gp/product/B00E58EA90/ref=oh_aui_detailpage_o04_s00?ie=UTF8&amp;psc=1</a> Product Details 1. driver chip: L298N Dual H-Bridge Motor Driver IC</p> <ol start="2"> <li>drive section terminal supply area Vs: +5V ~ +35V; such as the need to take power within the board, the supply area Vs: +7V ~ +35V</li> <li>drive section peak current Io: 2A</li> <li>logical part of the terminal supply area Vss: +5V ~ +7V(can take power within the board +5V)</li> <li>logical part of the operating current range: 0 ~ 36mA</li> <li>Control signal input voltage range: Low:-0.3V ≤ Vin ≤ 1.5V High: 2.3V ≤ Vin ≤ Vss</li> <li>enable signal input voltage range: Low: -0.3 ≤ Vin ≤ 1.5V (control signal is invalid) High: 2.3V ≤ Vin ≤ Vss (control signal active)</li> <li>Maximum power consumption: 20W (when the temperature T = 75℃)</li> <li>Storage temperature: -25℃ ~ +130℃</li> <li>Driver Board Size: 48mm*43mm*33mm (with fixed copper pillar and the heat sink height)</li> <li>Other Extensions: control of direction indicators, the logic part of the plate to take power interface.</li> </ol> <p><img src="https://i.stack.imgur.com/8XdEy.jpg" alt="enter image description here"></p> <p>Update 2:</p> <p>I wanted to clarify regarding using 12 volt battery and having 2 motors that I think max voltage is 3 volts. If i use PWN and step down the voltage to 3 volts will L298N produce a lot more heat to step the voltage down?<br> Probably in this case would be the best just to get two separate power supplies 9 volts for arduino and 4.5 volts for the motor drive to supply 3 volts for each motor. Unless i get better motors that support 6v - 9v then i can use the 12 volts battery for both arduino and motors. </p> <p>As far as the motor drivers, I thought they are used to prevent the noise and power spikes from motors? I guess you still have to consider it either way. </p> <p>Thanks in advance! </p>
<p>Here is a link to a <a href="http://www.robotoid.com/appnotes/circuits-bridges.html" rel="nofollow noreferrer">robotoid</a> page which describes a way to use it.<br> Here is a link to <a href="http://www.funnyrobotics.com/2011/03/arduino-with-l298n-based-dual-motor.html" rel="nofollow noreferrer">funnyrobotics</a> which explains how to use it.</p> <p>I am confident that you could use a search engine to find more examples.</p> <p>One trick is to use image search. Then look for pictures which look like your photo, and which have extra writing on them. Most people who add labels and writing to the photo are writing to help beginners understand how to use something.</p> <p>Edit: That L298N board claims to have a 5V regulator for powering the Arduino, in which case you could use a single power supply, and let the motor board feed the Arduino.</p> <p>There are two schools of thought on powering the Arduino and motors:</p> <ol> <li>Use two separate power supplies, one for the motor and one for the Arduino.</li> <li>Use one supply for both the motor, and Arduino.</li> </ol> <p>Using one supply is simple overall. One concern is electric motors can create a lot of electrical noise. If this is not adequately filtered, it might get injected into the Arduino and maybe cause the microcontroller to reset, or become temporarily unstable. The single supply advocates say the power supply to the Arduino should be properly filtered using capacitors and a proper voltage regulator usually, and the problem is solved.</p> <p>I agree in principle. However, I have seen situations where the transient failure was so brief it looked 'mysterious'. It took time and effort to track it down. Sometimes it was because the motor power supply was underpowered. When the motor 'stalled', for example when changing direction, taking maximum current, the power supply voltage might dip enough to cause the Arduino supply to dip, and reset the chip. </p> <p>Summary, if you are going to use a single power source for both motor and Arduino, ensure it has plenty of electrical noise filtering, and is a bit over-engineered to cope with the motor stalling. Specifically, it should be able to supply the motors stall current without dipping too low for the Arduino. The 'professional' approach is to have the Arduino monitor the main power supply, and detect that voltage dip. However, that is more complexity, and I suggest you avoid that.</p> <p>Edit: If you are concerned you might have weird, hard to trace problems, using a single supply, try to design the system so that the Arduino can be 'unplugged' and given its own supply. That should be easy to do with that L298N board as the connections are screw terminals.</p> <p>Using two separate power supplies should <em>reduce</em> the chances of electrical noise from the motors getting into the Arduino. In some circumstances is it useful to be able to change the motor power supply, or switch it off, without powering the Arduino off.</p> <p>When the motor voltage is a lot higher than the 5V needed by the arduino, simple techniques to step down the voltage (linear regulators, like the part on that L298N board) convert the excess power to heat, which is quite inefficient. Much above, about, 18V it can generate enough heat to reach quite a high temperature (i.e. 100C) unless it has a good heatsink. </p> <p>In that case, a simple, cheap solution is to use a second small power supply for the Arduino. An Arduino is likely using under 100mA, so a PP3 would be okay for, maybe, a few hours. A longer term approach is to step the motor voltage down efficiently.</p> <p>If you use two power supplies, connect the two 'ground' (i.e. or most negative battery connections) together so that they have a common 'ground' reference. That way the Arduino signals will control the motor driver reliably.</p> <p>Edit: PWM does not step down voltage. It gives the illusion of less power because the full voltage is only applied for a fraction of each millisecond. When it is on, it is providing (very close to) the full 'motor' voltage. If the 'motor voltage' connected to that L298N board is 12V, then the motor will see 12V. </p> <p>However, even if the motor is rated at only 3volts, it is unlikely to break only because 12V is applied across it. A 3V motor is as likely to break because it gets too hot, or spun too fast (e.g. the bearings get damaged). </p> <p>It will likely get too hot under load, or spin too fast if the PWM signal is on for more than, WAG 50% of the time (but there is no warranty with WAG = Wild-A$$-Guess).</p> <p>If, and only if, your software doesn't run PWM more than 50%, then those motors may be okay. That is a risk I might be prepared to take if the motors are cheap, and replacements easy to get.</p> <p>Skimming the datasheet, the L298N needs an absolute <em>minimum</em> motor supply of 2.3V+2.5V = 4.8V.<br> Also, the output switches which control the motor appear to 'drop' a minimum of 1.8volts.<br> So I think it would be okay with 6V or 7.2V (maybe upto 9V) motor voltage.</p> <p>IIRC the arduino will work okay with 7.2V upwards, i.e. 6 x NiMh batteries. A higher voltage is just converted to heat by the on-board voltage regulator. I might be tempted to experiment with the L298N boards 5V output, unless you have seen complaints about it.</p> <p>I am assuming the motors are brushed DC motors (and not steppers or something exotic)</p> <p>The motor driver will handle switching the current that the motor needs. However, each time the current is switched on or off, the motor will draw current, or generate current (remember it is a motor and also a generator). That could cause the power rail to dip, or even feed current into power or ground. There are diodes on the board to prevent those spikes doing anything awful to the chip, but there is still current flowing through wires.</p> <p>Further, every rev of the motor, the brushes will break one connection, and make a different connection with the commutator, typically 6 times. (The commutator is the mechanical system that directs the current to flow the correct way round in the motors spinning electromagnet). That creates electrical noise. In some cases so much that you can hear it on an old fashioned radio receiver or analogue TV.</p> <p>So noise may be a problem. People typically put a 10nF-100nF, relatively high voltage (say 50V), capacitor directly across the motors power connections, at the motor end. </p> <p>If things get bad, I did a quick search and this <a href="http://www.kerrywong.com/2012/01/26/a-short-guide-on-motor-electrical-noise-reduction/" rel="nofollow noreferrer">blog</a> looked okay, it illustrates ways to use capacitors and inductors to reduce motor noise.</p> <p>I wouldn't worry too much. Put 10nF-100nF across the motor wires, and see what happens.</p>
3688
|power|battery|
Arduino powering from 9V battery
2014-08-08T08:13:04.777
<p>Yesterday afternoon I have left my Arduino running on a fresh Alkaline 9V battery (+ connected to Vin, - connected to GND). Today morning (16 hours later) the LCD display was no longer visible, and when I measured the volatage, I saw the battery was depleted to my surprise - its idle voltage was only 7 V.</p> <p>My device is Arduino Uno with LCD 2x16 with LCD backlight and 2 DS18B20 sensors. Is it normal for such device to deplete 9V battery this quick?</p> <p>I have read <a href="https://arduino.stackexchange.com/a/79/3452">an answer to What are (or how do I use) the power saving options of the Arduino to extend battery life? question</a> and I think what I see might be related to this, however I am not sure. If it is, is there some common schematics how to connect Arduino to be powered by a battery efficiently?</p>
<p>Another option is to look for a hardware (Arduino Clone) that has been designed for that, like this board: <a href="https://bitbucket.org/talk2/whisper-node-avr/overview" rel="nofollow">https://bitbucket.org/talk2/whisper-node-avr/overview</a></p> <p>Combining such hardware with power-saving code techniques you should be able to run projects for quite long time on batteries!</p>
3697
|interrupt|
'crash' when using pin change interrupts
2014-08-09T08:09:23.843
<p>I'm noticing a crash when testing out some interrupt code for a project I'm working on. </p> <p>I've returned to the example provided with the library <a href="http://code.google.com/p/arduino-pcimanager/" rel="nofollow">PciManager</a> and I'm still experiencing the same issue. There doesn't appear to be any patten to when the crash appears, and on occasion I've been playing for several minutes and not seen a crash. NOTE I had to add a file (Task.h) from the developers other project (<a href="http://code.google.com/p/arduino-softtimer/" rel="nofollow">SoftTimer</a>) to get it to compile. </p> <p>here is the code: </p> <pre><code>#include &lt;PciManager.h&gt; #include &lt;PciListenerImp.h&gt; #define INPUT_PIN 3 PciListenerImp listener(INPUT_PIN, onPinChange); int i = 0; void setup() { Serial.begin(9600); PciManager.registerListener(INPUT_PIN, &amp;listener); Serial.println("Ready."); } void onPinChange(byte changeKind) { i++; Serial.print("pci : "); Serial.print(i); Serial.print(" : "); Serial.println(changeKind); } void loop() { } </code></pre> <p>I have a wire connected to pin 3 and 3.3v which I'm pulling out and then connecting again. Some times when disconnected it continually interrupts, I was expecting this. Sometimes it doesn't which I found strange, the crash appears to happen more in the latter case. </p> <p>Here is a trace from the serial monitor</p> <pre><code>Ready. pci : 1 : 0 pci : 2 : 1 pci : 3 : 0 pci : 4 : 1 pci : 5 : 0 pci : 6 : 1 pci : 7 : 0 pci : 8 : 1 pci : 9 : 0 pci : 10 : 1 pci : 11 : 0 pci : 12 : 1 pci : 13 : 0 pci : 14 : 1 pci : 15 : 0 pci : 16 : 1 pci : 17 : 0 pci : 18 : 1 pci : 19 : 0 pci : 20 : 1 pci : </code></pre> <p>I've run this on a <a href="http://shrimping.it/blog/shrimp-kit/" rel="nofollow">shrimp</a> and on a freeduino diecimila compatible board both resulting in the same effect. </p> <p>Anyway down to question; is the issue the way I'm interrupting? i.e. not stopping the floating pin? or is it a problem with the library, or is it a fundamental problem with pin change interrupts. </p>
<p>I'm going to include this answer even though I think there's a very little chance that it is the problem because I just wasted ten hours on a project before finding it and it's an easy check so it won't take much time either way. </p> <p>On AVR chips, if you have enabled interrupts and one occurs and you don't have an ISR for it, it will call the default ISR which resets the board. You can test if this is happening by redefining the default ISR by creating a function ISR(BADISR_vect){}; I would put a serial print in there and run it again and see if it's happening. If you don't want to do serial (for obvious reasons) just toggle an LED. </p> <p>I also agree it's probably a bad idea to be doing this on a floating pin. I'd use the internal pull-up resister to keep it high then connect a wire between that pin and ground to simulate a button. </p>
3700
|osx|
Rename device name (ch340 usb to serial) Mac OS
2014-08-09T12:26:29.273
<p>Can't upload sketches to Arduino Nano clone with USB to serial chip ch340.</p> <p>After installing drivers and plugging in, device has the name <code>cu/tty.wch ch341 USB=&gt;RS232 fa130</code> (with spaces), but Arduino can't recognize the full name (only <code>tty.wch</code>).</p> <p>Is it possible to rename device in Mac OS or change device identifier?</p> <p>UPDATE: <code>ch340</code> new driver <a href="http://www.wch.cn/downloads.php?name=pro&amp;proid=178">http://www.wch.cn/downloads.php?name=pro&amp;proid=178</a> </p>
<p>once you have installed the driver, you should be able to use it with any IDE or program</p> <p>but I doubt anyone would prefer the Arduino IDE to codebender</p>
3702
|arduino-uno|hardware|
Controlling Floppy Disk Drive with Arduino
2014-08-09T21:15:58.030
<p>I am having problems controlling a 3.5" Floppy Disk Drive with an Arduino Uno. </p> <p>I have the floppy disk drive powered with a computer power supply that is switched on, and the Arduino powered by my computer's USB. I have cut apart the ribbon of a 34-pin IDC connector to be able to route the pins to my Arduino. I am able to turn the floppy disk motor on and move the read/write head back and forth, but I am never able to read any pulses from the Track-0 or Index pins. </p> <p>I have pins 7, 15, 17, 19, and 25 from the floppy all grounded to my Arduino, and I have pins 8, 16, 18, 20, and 26 from the floppy connected to my arduino as output pins so I can control the drive. </p> <p>I am expecting the Index to pulse when the disk motor makes a rotation, and for Track 0 to change when I am at the outside of the disk, but they are both always LOW. Am I missing something?</p> <p><strong>Here is the spec I found for the back of the floppy disk unit</strong></p> <pre><code> 2 /REDWC Input Density Select 4 n/c N/A Reserved 6 n/c N/A Reserved 8 /INDEX Output Index 10 /MOTEA Input Motor Enable A 12 /DRVSB Input Drive Sel B 14 /DRVSA Input Drive Sel A 16 /MOTEB Input Motor Enable B 18 /DIR Input Direction 20 /STEP Input Step 22 /WDATE Input Write Data 24 /WGATE Input Floppy Write Enable 26 /TRK00 Output Track 0 28 /WPT Output Write Protect 30 /RDATA Output Read Data 32 /SIDE1 Input Head Select 34 /DSKCHG Output Disk Change/Ready </code></pre> <p><strong>Here a schematic of what I have hooked up</strong> <strong><em>(The breadboard in this circuit diagram represents the IDC connector that is plugged into the 3.5" floppy drive.)</em></strong></p> <p><img src="https://i.stack.imgur.com/pEHOT.png" alt="Floppy &amp; Arduino Connections"></p> <p><strong>Here is a photo of the IDC Connector and I labelled which wires are connected to the Arduino.</strong></p> <p><img src="https://i.stack.imgur.com/DdFX0.jpg" alt="Labelled IDC Connector"></p> <p><strong>Here's the code I am running.</strong></p> <pre><code>//constants static const int IN = LOW; static const int OUT = HIGH; static const int pulseDelayTime = 6; //pins int indexPin = 2; //8 on the drive INDEX int track0Pin = 3; //26 on the drive. TRACK 0 int dirPin = 6; //18 on the drive. DIRECTION int stepPin = 7; //20 on the drive. STEP int motorEnableBPin = 9; //16 on the drive. MOTOR ENABLE B unsigned long motorSpinTime = 1000UL; //in ms void setup() { //initial delay delay(3000); //setup serial monitor Serial.begin(9600); //setup pins. pinMode(dirPin, OUTPUT); pinMode(stepPin, OUTPUT); pinMode(motorEnableBPin, OUTPUT); pinMode(indexPin, INPUT); pinMode(track0Pin, INPUT); //turn the motor off initially digitalWrite(motorEnableBPin, HIGH); //print state here. printState("Setup done."); //spin the disk some. printState("Begin to spin motor"); spinMotorForThisManyMs(motorSpinTime); spinMotorForThisManyMs(motorSpinTime); printState("Done spinning motor"); //step read/write head all the way in. stepAllTheWayIn(); //spin the disk some more. printState("Begin to spin motor"); spinMotorForThisManyMs(motorSpinTime); spinMotorForThisManyMs(motorSpinTime); printState("Done spinning motor"); //step read/write head all the way out. stepAllTheWayOut(); //spin the disk even more. printState("Begin to spin motor"); spinMotorForThisManyMs(motorSpinTime); spinMotorForThisManyMs(motorSpinTime); printState("Done spinning motor"); //never completes. waitForIndex(); } void loop() { } //spins the disk motor for a number of ms and prints the state void spinMotorForThisManyMs(unsigned long msToSpin) { //start spinning digitalWrite(motorEnableBPin,LOW); //delay.. keep printing the state unsigned long maxTimeMs = millis() + msToSpin; while(millis() &lt; maxTimeMs ) { printState("Spinning"); } //stop spinning digitalWrite(motorEnableBPin,HIGH); } //step the read/write head all the way to the center void stepAllTheWayIn() { for(int i=0;i&lt;100;i++) { printState("Stepping In"); stepInALittle(); } } //step the read/write head all the way to the outside void stepAllTheWayOut() { for(int i=0;i&lt;100;i++) { printState("Stepping Out"); stepOutALittle(); } } //print the state of the index and track void printState(const char* charPrint) { Serial.print(" Index:"); Serial.print(digitalRead(indexPin)); Serial.print(" Track:"); Serial.print(digitalRead(track0Pin)); Serial.print(" "); Serial.println(charPrint); } //move the head towards the outside a little void stepOutALittle() { digitalWrite(dirPin,HIGH); stepPulse(); } //move the head towards the center a little void stepInALittle() { digitalWrite(dirPin,LOW); stepPulse(); } //pulse the step pin void stepPulse() { digitalWrite(stepPin,LOW); delay(pulseDelayTime); digitalWrite(stepPin,HIGH); } //waits for the index to trigger. this never gets completed. void waitForIndex() { printState("beginning to wait for index pin to pulse"); //start spinning digitalWrite(motorEnableBPin,LOW); //wait for pulse while(digitalRead(indexPin)); //wait for end of pulse 0 while(!digitalRead(indexPin)); printState("end of waiting for index pin to pulse"); //stop spinning digitalWrite(motorEnableBPin,HIGH); } </code></pre> <p><strong>Here is the output I am getting.</strong> </p> <pre><code> Index:0 Track:0 Setup done. Index:0 Track:0 Begin to spin motor Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Done spinning motor Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Stepping In Index:0 Track:0 Begin to spin motor Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Done spinning motor Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Stepping Out Index:0 Track:0 Begin to spin motor Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Spinning Index:0 Track:0 Done spinning motor Index:0 Track:0 beginning to wait for index pin to pulse </code></pre> <p><strong>UPDATE:</strong> I am now receiving my expected results due to geometrikal's answer. While researching this problem I found a few code examples of Arduino to Floppy Drive. I noticed that they were setting their input pins to HIGH, but I never realized why they were doing this. After fixing my problem, I found this in some Arduino documentation (which made me realize the code examples I had were using an older version of the Arduino IDE): </p> <p>"Prior to Arduino 1.0.1, it was possible to configure the internal pull-ups in the following manner:"</p> <pre><code>pinMode(pin, INPUT); // set pin to input digitalWrite(pin, HIGH); // turn on pullup resistors` </code></pre> <p>In Arduino 1.0.1+ you can do it this way.</p> <pre><code>pinMode(pin, INPUT_PULLUP); </code></pre>
<p>According to this (dead link):</p> <p><a href="http://bitsavers.trailing-edge.com/pdf/nec/FD1035_Product_Description_Jul84.pdf" rel="nofollow noreferrer">http://bitsavers.trailing-edge.com/pdf/nec/FD1035_Product_Description_Jul84.pdf</a></p> <blockquote> <p><em>This is an archived copy of the <a href="https://ia801902.us.archive.org/3/items/bitsavers_necFD1035Pl84_876629/FD1035_Product_Description_Jul84.pdf" rel="nofollow noreferrer">FD1035 3.5" Floppy disk drive: Product Description July 1984 - PDF</a>:</em></p> <p><em><a href="https://archive.org/details/bitsavers_necFD1035Pl84_876629" rel="nofollow noreferrer">https://archive.org/details/bitsavers_necFD1035Pl84_876629</a></em></p> </blockquote> <p>The outputs are open-collector, so a pull-up resistor is required. You can instead enable the Arduino internal pull-ups on those pins by</p> <pre><code>pinMode(indexPin, INPUT_PULLUP); pinMode(track0Pin, INPUT_PULLUP); </code></pre>
3708
|serial|gsm|
Connecting a Arduino to FT232
2014-08-10T08:59:47.990
<p>I found this wonderful breakout board based on <a href="https://www.sparkfun.com/products/9716#comment-53e7333cce395f8b068b4567" rel="nofollow">FT232</a>. I wonder if I can use this board for connecting my arduino to a USB dongle for 3g/GPRS connection ?</p> <p>From what I understand this board can be connected to the serial data pins of the arduino board. And if I connect the USB dongle to the FT232 board, I should be able to run AT commands from the arduino board.</p>
<p>Unfortunately, no, as the FT232 would have to act as a USB host device. A <a href="http://www.circuitsathome.com/products-page/arduino-shields/usb-host-shield-2-0-for-arduino">USB host shield</a> might work if someone has written driver code to support 3G modems.</p>
3712
|programming|teensy|
Nested For Loop
2014-08-10T14:18:08.780
<p>I'm not sure if I'm being really really stupid, but why doesn't this work?</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { for (int x; x &lt; 8; x++) { for (int y; y &lt; 8; y++) { Serial.print(x); Serial.println(y); delay(100); } } } </code></pre> <p>When this does:</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { for (int x; x &lt; 8; x++) { Serial.println(x); delay(100); } } </code></pre> <p>The first produces no output over Serial, whereas the second one prints out the numbers 0 to 7 as expected. I'm using a Teensy 3.1.</p>
<p>You are not initializing x and y.</p> <p>When a local variable isn't initialized, it will "inherit" the value contained in the register assigned to the variable by the compiler. The fact that your single loop example worked is pure luck - the assigned register happened to contain 0 at that point in execution.</p> <p>Change your nested loop like this:</p> <pre><code>for (int x = 0; x &lt; 8; x++) { for (int y = 0; y &lt; 8; y++) { Serial.print(x); Serial.println(y); delay(100); } } </code></pre> <p>And it will work.</p> <p>Note: Global variables, on the other hand, are guaranteed by the c++ standard to be initialized to zero. The compiler will make sure to write zeros to those memory addresses before the main program code executes.</p>
3719
|spi|atmega32u4|
Arduino: Hardware SPI hangs, bit-bang does not
2014-08-10T22:13:59.380
<p>I'm using FastLED with a custom board built around the ATMega32u4. When I set it to use Software SPI, everything works fine, but when I use hardware SPI it just hangs whenever it tries to write out the data (FastLED.show()).</p> <p>I originally mocked this up on an Arduino Pro Micro and it worked fine there. That makes me think that it's a hardware issue but, as I mentioned, SPI output <em>does</em> work, but only when bit-banged. Which really doesn't make much sense.</p> <p>I tested this by also just using the built in SPI classes and I get the same thing. No luck with hardware SPI.</p> <p>Anyone else ever see something like this?</p> <p>The schematic of my circuit is below.</p> <p><img src="https://i.stack.imgur.com/4R7AW.png" alt="enter image description here"></p>
<p>According to <a href="http://www.atmel.ch/Images/Atmel-7766-8-bit-AVR-ATmega16U4-32U4_%20Datasheet.pdf">ATmega32u4 datasheet</a>, section 17.2.1 (SPI / SS Pin Functionality / Master Mode:</p> <blockquote> <p><strong>If SS is configured as an input, it must be held high to ensure Master SPI operation.</strong></p> </blockquote> <p>In your circuit, SS pin (#8 on package), also labeled as "<strong>(SS/PCINT0) PB0</strong>", is left unconnected. </p> <p>Is it possible that PB0 is also configured as input somewhere in your program or libraries? In this case, it should be connected to Vcc.</p>
3730
|arduino-uno|
LM386 module not working
2014-08-11T13:26:49.220
<p>I have arduino UNO hooked up with wtv020-sd-16p and it works fine, playing audio files - speaker is connected right to the WTV020's pin #4 and #5. However, volume is rather low. So I have ordered LM386 amplifier module. I have wired it's IN pin with WTV020's pin #2 AUDIO-L. But no sound comes out of speaker. I can hear only some scratches from the speaker while arduino is running. </p> <p>LM386 is pretty easy, only VCC, IN and GND pins, so there is nothing much to screw up. I am wondering, what could be the problem ? </p> <p>Thanks for any help or hints in advance.</p> <p>EDIT: Only to note, when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis ?</p>
<blockquote> <p>when WTV020 is playing sound, speaker goes completely mute. When it doesn't play sound, little scratchy sounds can be heard from speaker. Maybe it could help with analysis</p> </blockquote> <p>Indeed - what you are describing sounds like the DC component of the Arduino's output is outside the workable range of the amplifier, effectively cutting it off. When there is no output, the voltage is within range and little bits of noise are able to be amplified.</p> <p>You should be able to fix the cutoff problem with a series capacitor to block the DC component of the input, allowing only the AC signal through - a common technique for coupling between stages in Audio and RF systems.</p> <p>The value of the capacitor will depend on the impedance of the circuit it is driving. A bare input to many chips could use a quite small value, while a circuit with feedback or a voltage-divider volume control might require a larger or carefully chosen one.</p>
3732
|sensors|led|resistor|
Sensors and leds. This need resistors? and how?
2014-08-11T16:18:26.570
<p>I have a project with leds and sensors, this is my first project in Arduino and I want to know if it need resistors and how and where?</p> <p>I use 16-Bit I/O Expander <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf" rel="nofollow noreferrer">MCP23017</a> for leds and multiplexer <a href="http://pdf.datasheetcatalog.net/datasheets/120/109150_DS.pdf" rel="nofollow noreferrer">CD4051</a> for sensors <a href="http://www.ti.com/lit/ds/symlink/lm35.pdf" rel="nofollow noreferrer">LM35</a> </p> <p><img src="https://i.stack.imgur.com/jUCjl.jpg" alt="My design"></p>
<p>You will definitely need resistors for each LED connected to MCP23017 circuits.</p> <p>This is necessary because without resistor the following is likely to happen:</p> <ul> <li>burn each LED that is lit on as it would be fed too much current</li> <li>burn the MCP23017 because it is rated for 125mA maximum (20mA per output pin)</li> </ul> <p>The resistor to use normally depends on the color of each LED as those LEDs have different electrical charasteristics.</p> <p>Typically one LED (3 or 5mm) needs no more than 20mA to be lit (lower current such as 10mA is generally provides enough light).</p> <p>One other important LED characteristic is its <strong>forward voltage</strong>, which depends on the color.</p> <p><a href="http://led.linear1.org/1led.wiz" rel="nofollow">This link</a> will help you calculate the "ideal" resistor for each LED.</p> <p>For the sensors part, I see no reason to use any resistor to connect them to 4051 circuits.</p> <p>One last important point is related to the use of <strong>I2C</strong> bus by the MCP23017 circuits. <a href="http://en.wikipedia.org/wiki/I%C2%B2C" rel="nofollow">I2C bus</a> is "open drain" and thus requires pullup resistors for both <strong>SCL</strong> and <strong>SDA</strong> lines.</p>
3739
|xbee|
Serial.write displaying repeating output from Xbee communication
2014-08-11T20:33:31.397
<p>I want to use xbee's to communicate between two different arduinos. I'm using <a href="http://youtu.be/mPx3TjzvE9U" rel="nofollow">this tutorial</a> as a guide to setup my xbee's. I've already used XCTU to setup one xbee as a router and another as a coordinator (both in ZIGBEE AT mode). I used XCTU's terminal feature to verify that info was being sent and received properly.</p> <p>Basically, I have both arduinos connected to the same PC via USB cables, but the communication is taking place through the Xbee's. I also made sure to disconnect the TX &amp; RX wires when uploading the sketches to avoid an AVRDUDE error.</p> <p>I wanted to test the communication by sending a "hello world" message once every five seconds, from the router to the coordinator. To do this, I wrote the following code:</p> <pre><code>//Code for Arduino attached to Xbee in Router AT mode void setup(){ Serial.begin(9600); } void loop(){ Serial.println("Hello World!"); delay(5000); } </code></pre> <p>and </p> <pre><code>//Code for Arduino attached to Xbee in Coordinator AT mode void setup(){ Serial.begin(9600); } void loop(){ if (Serial.available()&gt;0){ Serial.write(Serial.read()); } } </code></pre> <p>I checked the serial monitor for the arduino connected to the router, and it does exactly what I expected to see: a new Hello World message once every 5 seconds. However, the serial monitor on the arduino connected to the coordinator does not produce the desired effect: <strong><em>the "hello world" message instantly displays the message over a hundred times per second and repeats without end, each time on a separate, new line</em></strong>. Sometimes, when I turn the serial monitor on, the message instantly appears with a few repetitions before displaying some strange characters and stopping altogether.</p> <p>I'm not sure if the problem is with the serial monitor or with the xbee. Any help with this problem would be greatly appreciated.</p>
<p>Code is correct and it does what it is asked to. The receiver code reads the RX pin of arduino which is connected to the Xbee. The same pin is used by the FT232 interface IC to send data to your computer through USB.</p> <p>The "hello world" you send is received by the Xbee and is send to microcontroller and FT232 at same time as that pin is shared between them. Thus the "hello world" will be seen in serial monitor, first time from Xbee and second time, from <code>Serial.write(Serial.read())</code> of the program.</p> <p>Also check whether the settings are correct from <a href="http://www.ladyada.net/make/xbee/arduino.html" rel="nofollow noreferrer">this tutorial</a>, as Xbee will not be configured as P2P. </p> <p><img src="https://i.stack.imgur.com/4AxOG.png" alt="enter image description here"></p>
3743
|power|arduino-pro-mini|
Externally Powering a 3.3V device (nRL24L01+) with a 5V Arduino Pro Mini?
2014-08-12T03:34:42.763
<p>I have seen several references where the solution to interfacing a 5V Arduino with a 3.3V nRF24L01+ was to power the nRF24L01+ externally.</p> <p>How do I do this? The ground of the nRF24L01+ is connected to the Arduino; can I simply attach 3.3V power between the power and ground pins of the nRF24L01+?</p>
<p>To connect the nRF24L01+ to a 5V Pro Mini you will need external 3.3V power supply to power the nRF24L01+. The ground for the Pro Mini and the ground for the nRF24L01+ should be tied together to ensure a common ground reference.</p> <p>The inputs to the nRF24L01+ are 5V tolerant so you will not need a level shifter to convert the 5V Digital IO on the Pro Mini to 3.3V. Be aware the not all 3.3V devices have 5V tolerant inputs like nRF24L01+.</p> <p>You might want to look into using a <a href="https://www.sparkfun.com/products/11114" rel="nofollow">3.3V Pro Mini</a> with that you should be able to use the regulated 3.3V power on the Pro Mini to power the nRF24L01+. Be aware that the 3.3V Pro Mini only runs at 8MHz instead of 16MHz.</p>
3747
|sensors|arduino-pro-micro|
Strange values from LSM303 Magnetometer
2014-08-12T09:26:32.140
<p>I am having problems with values i get from Pololu MinIMU-9 boards's magnetometer. I am using Arduino-micro and the arduino library from Pololu. The sensor on the board is 3 axis accelero- and magnetometer LSM303. The problem is - the highest value always seems to be in vertical axis, not horisontal, as i would expect.</p> <p>For example, here is the data i got when i put sensor flat on the table and made 360 clockwise turn in horizontal plane: (values are X Y Z)</p> <pre><code>-6 102 -516 -11 103 -515 -11 103 -515 -21 102 -514 -31 109 -515 -40 114 -512 -57 116 -509 -57 116 -509 -77 111 -507 -93 109 -506 -104 106 -507 -104 106 -507 -114 99 -508 -126 88 -504 -131 74 -507 -142 52 -507 -142 52 -507 -151 31 -506 -150 4 -509 -147 -27 -513 -147 -27 -513 -133 -60 -513 -119 -80 -519 -112 -87 -517 -102 -97 -521 -102 -97 -521 -89 -101 -522 -77 -101 -524 -50 -104 -527 -50 -104 -527 -43 -105 -529 -14 -98 -532 2 -92 -535 23 -92 -535 23 -92 -535 36 -81 -534 66 -54 -534 76 -32 -531 76 -32 -531 76 -21 -532 78 -7 -531 85 10 -528 91 39 -524 91 39 -524 94 50 -524 91 63 -524 76 75 -525 76 75 -525 63 82 -526 47 93 -525 44 98 -522 44 98 -522 38 104 -521 26 110 -521 26 112 -518 21 116 -519 21 116 -519 18 116 -518 12 120 -517 11 120 -515 11 120 -515 8 120 -517 5 122 -515 -5 123 -514 </code></pre> <p>Turning the sensor "upside down" and then rotating it in horisontal plane again gives similar results, only Z axis has positive 500+ value.</p> <p>Shouldn't the magnetometer always point in the direction of the magnetic field - in X or Y direction? I have tried this in different rooms and buildings and got the same results. Rotating the sensor on other axes yields the same results - vertical axis has the largest (and constant) value.</p> <p>For reference, here is the code i used to get the values.</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LSM303.h&gt; LSM303 compass; void setup() { Serial.begin(115200); Wire.begin(); compass.init(); compass.enableDefault(); } void loop(){ compass.readMag(); Serial.print(compass.m.x); Serial.print(" "); Serial.print(compass.m.y); Serial.print(" "); Serial.print(compass.m.z); Serial.print("\n"); delay(100); } </code></pre>
<p>The earth's magnetic field is not parallel with the ground. In some locations it can be pointing more down than across. </p> <p>NOAA has a <a href="http://www.ngdc.noaa.gov/geomag-web/#igrfwmm" rel="nofollow noreferrer">magnetic field calculator</a> where you can enter you latitude and longitude. For example, I am located at approx 19deg S 147degE and the field is </p> <pre><code>North Comp East Comp Vertical Comp Total magnitude 32,434.4 nT 4,280.6 nT -36,035.1 nT 48,670.7 nT </code></pre> <p>So the downwards strength is more than the other two combined for my location. I'm guessing the calculator will also show a very strong down component for your location.</p> <p>Some other things to be aware of are that the LSM303DLHC magnetometer can have quite large offsets, up to the equivalent of 2 earth magnetic fields, and therefore requires calibration. Also hard and soft iron distortions can affect the readings.</p> <p>Edit: Please see my answer <a href="https://electronics.stackexchange.com/questions/22144/magnetometer-%E2%88%9E-shaped-calibration/22271#22271">here</a> for methods to calibrate the sensor.</p>
3748
|lcd|pwm|
Arduino LED backlight - should PWM be used with transistor or capacitor?
2014-08-12T09:40:51.090
<p>I have implemented a PWM controlled LED backlight for the LCD in my Arduino Uno design. One LCD backlight pin is connected to +5V, the second to the ground via 220 Ohm resistor and MOSFET controlled from a PWM capable D9 pin.</p> <p>Everything seems to work fine, I do not see any oscillation, but after some reading about PWM I am not sure if I perhaps should connect a 100 uF capacitor to smooth the voltage?</p> <p>Is the MOSFET even necessary? It seems backlight is drawing about 5 mA - can I perhaps drive it directly from the D9 pin, using the resistor? (It seems another user in <a href="https://arduino.stackexchange.com/questions/1805/do-i-need-to-use-a-resistor-if-i-am-using-a-potentiometer-to-control-an-leds-br?rq=1">Do I need to use a resistor if I am using a potentiometer to control an LED&#39;s brightness?</a> is controlling brightness without any of those.)</p>
<p><strong>You don't need the MOSFET, you don't need the capacitor, you <em>do</em> need the resistor.</strong></p> <p>The pins on your Arduino can deliver up to 20mA comfortably, so in this case there is no need for the MOSFET. However, if you were to replace your backlight with a high power LED, your current setup will work just fine.</p> <p>Without a capacitor, your PWM is a nice square wave. The cap will, depending on its capacity and the resistor in your circuit, turn that into a more rounded waveform, or very ripply DC. Whichever is the case, it will not benefit the (dimming of) your LED. With some bad luck it will even introduce flickering instead of preventing it!</p> <p>The reason why you should still use the resistor is to prevent the LED from drawing too much current. Without it, it's simply a game between the LED and the Arduino pin to see who will burn first. Whoever wins, you'll end up with a destroyed backlight or fried Arduino. Adding a component costing a few cents can prevent that.</p>
3753
|arduino-uno|python|
How to send numbers to Arduino UNO via Python 3 and the module serial
2014-08-12T15:01:41.500
<p>I am new to Arduino (and computer programming in general), so I apologize if this question looks silly.</p> <p>Once I set up a basic arduino-LED connection, I have problems sending INTEGERS to arduino through the serial port. I can easily send characters such as 'm', 'o' and so on.. However if I send a number it looks like it simply does not get it.</p> <p>Here is the Arduino code, ideally it should get a value from the usb port through python or the serial monitor and then adjust the brightness of the LED according to the value. (value must be in range [0,255]).</p> <p>NOTE: I am using ARDUINO UNO and PYTHON 3</p> <p>//--------------------------</p> <pre><code>int LED = 10; int number; void setup(){ pinMode(LED,OUTPUT); Serial.begin(9600); } void loop(){ number = Serial.read(); Serial.print(number); Serial.print('\n'); if(number == -1){ number = 0; } else if(number &gt; 255){ number = 255; } else if(number &lt; 0){ number = 0; } analogWrite(LED,number); delay(1000); } </code></pre> <p>However, when I input a value into the Serial port or through Python, for instance 0, it gives me 48 as answer (which, interestingly, is the ASCII code for 0!) and lights up the LED which is not what should happen since at 0 the LED should be off!! I am missing something but I cannot find what... Could you please tell me what is wrong?</p> <p>Here is the code I use in Python:</p> <pre><code>import serial import time try: arduino = serial.Serial(port,speed) time.sleep(2) print("Connection to " + port + " established succesfully!\n") except Exception as e: print(e) #Note: for characters such as 'a' I set data = b'a' to convert the data in bytes #However the same thing does not work with numbers... data = 0 data = arduino.write(valueToWrite) time.sleep(2) arduino.close() </code></pre> <p>what am I doing wrong or misunderstanding? Thank you.</p>
<p>Parsing on the Arduino can be slow and time-consuming (which is bad if you use clock prescaling or have time-critical tasks), so let's do it in Python.</p> <p>The problem is that you're sending the numbers as ASCII whereas you need to be sending them as raw binary. This is where <a href="https://docs.python.org/3/library/struct.html" rel="noreferrer"><code>struct</code></a> comes in.</p> <pre><code>3&gt;&gt; import struct 3&gt;&gt; print(struct.pack('&gt;B', 0)) b'\x00' 3&gt;&gt; print(struct.pack('&gt;B', 255)) b'\xff' 3&gt;&gt; print(struct.pack('&gt;2B', 255, 0)) b'\xff\x00' 3&gt;&gt; print(struct.pack('&gt;H', 9000)) b'#(' </code></pre> <p>So what you really want is:</p> <pre><code>data = arduino.write(struct.pack('&gt;B', valueToWrite)) </code></pre> <p>or something to that effect.</p>
3755
|serial|programming|
How to use readLine from JSSC
2014-08-12T16:14:36.887
<p>When I use JSSC and call <code>serialPort.readLine(event.getEventValue())</code> from <code>public void serialEvent(SerialPortEvent event)</code> I've got fragments, not all string. What I must do to get all string from begin to <code>"\r\n"</code>? What I must do to get all string from my start marker (like <code>"[start]"</code>) to my stop marker (like <code>"[stop]"</code>)? What to modify in this code:</p> <pre><code>private static class PortReader implements SerialPortEventListener { public void serialEvent(SerialPortEvent event) { if(event.isRXCHAR() &amp;&amp; event.getEventValue() &gt; 0){ try { String data = serialPort.readString(event.getEventValue()); serialPort.writeByte((byte) 1); } catch (SerialPortException ex) { System.out.println(ex); } } } } </code></pre>
<p>The event gets fired when a single character is received, not the whole string. You have to build the string up until you get to <code>\r\n</code> and then process it. This is my code for a similar project. It uses a protocol where <code>&gt;</code> signifies the start of a message and <code>\r</code> signifies the end. <code>processMessage</code> is a function to process the entire message and update GUI elements etc. It is invoked using <code>runLater</code> because the serialEvent function will be on a different thread to the GUI thread.</p> <pre><code>StringBuilder message = new StringBuilder(); Boolean receivingMessage = false; public void serialEvent(SerialPortEvent event) { if(event.isRXCHAR() &amp;&amp; event.getEventValue() &gt; 0){ try { byte buffer[] = serialPort.readBytes(); for (byte b: buffer) { if (b == '&gt;') { receivingMessage = true; message.setLength(0); } else if (receivingMessage == true) { if (b == '\r') { receivingMessage = false; String toProcess = message.toString(); Platform.runLater(new Runnable() { @Override public void run() { processMessage(toProcess); } }); } else { message.append((char)b); } } } } catch (SerialPortException ex) { System.out.println(ex); System.out.println("serialEvent"); } } } </code></pre> <p>A simpler version for you might be the following. <code>processMessage</code> is called whenever a <code>\r</code> or <code>\n</code> is received and there are some bytes in the message.</p> <pre><code>StringBuilder message = new StringBuilder(); public void serialEvent(SerialPortEvent event) { if(event.isRXCHAR() &amp;&amp; event.getEventValue() &gt; 0){ try { byte buffer[] = serialPort.readBytes(); for (byte b: buffer) { if ( (b == '\r' || b == '\n') &amp;&amp; message.length() &gt; 0) { String toProcess = message.toString(); Platform.runLater(new Runnable() { @Override public void run() { processMessage(toProcess); } }); message.setLength(0); } else { message.append((char)b); } } } catch (SerialPortException ex) { System.out.println(ex); System.out.println("serialEvent"); } } } </code></pre> <p><strong>Edit:</strong></p> <p>Two things fixed: 1. Using <code>StringBuilder</code> instead of <code>String</code> to save making a lot objects every time the message is incremented. 2. Make a copy of the message string before passing to <code>runLater</code> otherwise when it does run it will use the up to date version of the string, which could have new characters, and thus cause problems.</p> <p><strong>Edt 2:</strong> On Windows I found it needed <code>if(event.isRXCHAR() &amp;&amp; event.getEventValue() &gt; 0)</code> as the event would sometimes be fired with 0 bytes causing a null point exception in <code>for (byte b: buffer)</code></p>
3763
|arduino-uno|programming|
Issues programming Arduino Uno with Sparkfun's MAX3232 breakout board
2014-08-12T21:12:31.553
<p>I'm having an issue programming the Arduino Uno with Sparkfun's MAX3232 breakout board attached. Sometimes the Arduino IDE won't see the Uno plugged in. I'm thinking of connecting a switch to the GND or the 3V - 5.5V pin so I don't have to disconnect the breakout board when programming. Are there any better solutions?</p> <p>Sparkfun link: <a href="https://www.sparkfun.com/products/11189" rel="nofollow">https://www.sparkfun.com/products/11189</a></p>
<p>Switching the power off to the MAX3232 appears to be okay.<br> There are no components connected to the Rx and Tx lines on the breakout board to complicate it.</p> <p>Unfortunately the break out does not give access to pin 1, EN which is "Enable Control", or pin 18 SHDN "Shutdown Control". AFAICT they could have been used to turn off the receiver and transmitters of the MAX3232. That would have been ideal. Maybe contact Sparkfun and suggest the improvement to put them on pads for folks to use, and offer to beta test it :-)</p> <p>The datasheet for the MAX3232 says that it is able to withstand a continuous short on the Tx line, so it sounds pretty tolerant to minor abuse. Also, the diagrams dont show any pull-ups on the MOS/TTL Tx line. So I would expect it t be okay if you shut the power off, but continued to wiggle the Tx Rx pins.</p> <p>An alternative would be to disconnect the Tx pin from the Arduino, so that the MAX3232 wouldn't interfere with the host PC's USB comms. It sounds like the thing on the RS232 connection will ignore data it receive while the Arduino is being programmed. If that is not true, then it would need to be disconnected too.</p> <p>At the moment, switching off power looks like a reasonable approach. Disconnecting Tx and Rx also looks reasonable, and slightly better than powering the MAX3232 off.</p> <p>Do you know how you want to do that?</p> <p>NB: The MAX232 datasheet shows that part should not be driven by a high when the chip is unpowered. However the MAX3232 datasheet does not carry that warning. My preference would be to use the MAX3232 signals 'EN' and 'SHDN'. However those are not available on the breakout. I'd recommend having the part powered, and disconnecting Tx and Rx from the Arduino.</p>
3767
|arduino-uno|
Release power to stepper motor
2014-08-13T03:39:13.373
<p>I'm driving a large stepper motor via a GeckoBoard G213V and arduino UNO and I have that mostly working fine. However, I'd like to 'release' the stepper so it can swing freely.</p> <p>There's two reasons I want to do this:</p> <p>1) (Most important) I want the rotated object to naturally swing back to the 0 position thanks to gravity. 2) The motor gets hot - I'd rather not juice it when it should just be sat at 0.</p> <p>Anybody know how I can do this? I'm using the AccelStepper library so a solution compatible with that would be ideal.</p>
<p>From <a href="http://www.geckodrive.com/g213v-rev-7" rel="nofollow">the documentation</a>:</p> <blockquote> <p><strong>TERMINAL 7 Disable</strong><br> This terminal will force the winding currents to zero when tied to the step and direction controller +5V.</p> <p>The DISABLE input on the G213V is optically isolated and requires logic “1” to DISABLE and logic “0” to ENABLE the drive. Once it is disabled, the motor windings are unergenized[sic] and <strong><em>the motor freewheels.</em></strong> <em>(emphasis mine)</em></p> </blockquote> <p>So, feed the disable input a high.</p>
3771
|power|
Can I use this pinhole camera with arduino?
2014-08-13T18:47:33.097
<p>The pinhole camera is a <a href="http://www.monoprice.com/Product?c_id=110&amp;cp_id=11018&amp;cs_id=1101801&amp;p_id=9285&amp;seq=1&amp;format=2" rel="nofollow">420TVL, 3.7mm Passive Infrared Detector Color Covert Security Camera</a>. Can I use this camera with an arduino creation? </p> <p>Things I don't know to answer the question:</p> <ol> <li>Does the power need something special arduino can't offer?</li> <li>Is the arduino powerful enough to push the video feed/photos to a computer or any other method to video/photos. </li> </ol> <p>Here are some specs from the site:</p> <blockquote> <ul> <li>Sensor 1/3" Sony Super HAD II CCD</li> <li>Picture Elements NTSC 768x494</li> <li>PAL 752x582</li> <li>Horizontal Resolution 420 TVL</li> <li>Minimum Illumination 0.001 Lux</li> <li>S/N Ratio more than 50dB</li> <li>Scanning System 2:1 interlace</li> <li>Synchronous System Internal, Negative sync</li> <li>Auto Electronic Shutter NTSC 1/60s ~ 1/100,000s</li> <li>PAL 1/50s ~ 1/100,000s</li> <li>Gamma Characteristics 0.45</li> <li>Video Output 1 Vpp, 75 ohms</li> <li>Auto Gain Control Auto</li> <li>Power / Current DC 12V (±10%) / 150mA</li> <li>Lens 3.7mm Taper Pinhole Lens</li> </ul> </blockquote> <p>Is it possible? They're on sale but I don't want to throw money away and find out that they don't work with any arduino. Also, I don't have any setup for this to be plugged into. Therefore, I'm not tied down to previous creations the cameras need to fit in.</p>
<p>No, you cannot use this with an Arduino without additional hardware in between, and even with it, not as more than a still camera (or maybe low quality video for one of the ARM- rather than ATmega-based boards).</p> <p>The first problem is that this camera has a high speed analog output called composite video. It is basically what would be fed into a modulator to produce an old-style analog TV signal. Capturing this digitally requires an Analog to Digital converter (ADC) capable of several million measurements per second, while that on the classic ATmega-based Arduino tops out at around ten thousand.</p> <p>But let's say you had an additional Analog-to-digital converter to put in between this and your arduino. The next problem is that the data rate out of the camera will be too high, and the Arduino won't have enough RAM memory to buffer it. </p> <p>In theory, you could get a "frame grabber" consisting of an ADC and its own buffer memory, which would take a still snapshot of the video and allow the arduino to read it out more slowly. But you can buy cameras which already do that with their onboard electronics, and allowing something like an Arduino to read the still image data out over a moderate speed serial interface.</p> <p>Even the ARM-based arduino boards would be taxed to keep up with the output of a video ADC and do much of anything useful with the results - typical digital cameras do not record raw images to SD card, but do JPEG compression within a frame. When cheap digital cameras operate in video mode, they compress each frame of the video before storing it (just as with stills - they do not compress between frames in the manner of real video recorders), and are able to get that processing done in time because the actual computing hardware is optimized for it in a way that none of the Arduinos are.</p> <p>If you want to experiment with a camera on a development platform, there is one with a high speed digital interface sold as an add-on for the Raspberry Pi board. Or you can use a more inexpensive USB webcam with that.</p>
3772
|arduino-uno|
Can tx and rx pins on the uno be used like regular digital pins?
2014-08-13T20:16:19.923
<p>The uno has digital pins marked 0-13. </p> <p>0 is marked as rx and 1 is marked as tx. Can these two pins be used as regular digital pins if i am short of digital pins?</p>
<p>You can, but it will disable the serial port.</p>
3774
|programming|variables|code-optimization|
How can I declare an array of variable size (Globally)
2014-08-13T20:23:08.100
<p>I'd like to make three arrays of the same length. According to the <a href="http://arduino.cc/en/Reference/array">documentation</a>, Arrays must be defined as <code>int myArray[10];</code> where 10 can be substituted for a known length (another integer), or filled with an array <code>{2, 3, 5, 6, 7}</code>.</p> <p>However, when I attempted to declare a value <code>int arrSize = 10;</code> and then an array based on that size <code>int myArray[arrSize];</code>, I get the following: <code>error: array bound is not an integer constant</code>. </p> <p>Is there a way to variably determine array sizes, or do I just need to hardcode them? (I was taught hardcoding is bad and something to avoid at all costs.)</p>
<p>The coderwall explains in Some detail the theory of how best to get the size of an array in C++ <a href="https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c" rel="nofollow noreferrer">https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c</a></p>
3781
|attiny|avrdude|isp|arduinoisp|
When using Arduino Uno as ISP does "Yikes! Invalid device signature" mean a bad connection, bad config, or bad version of avrdude?
2014-08-14T02:52:40.590
<p>I'm using an Arduino UNO to program a pre-compiled hex image to an ATTINY45, using the avrdude in the Arduino IDE directory, on Windows 7. The Uno has the ISP sketch loaded from the examples directory and that works- the heartbeat LED pulses nicely.</p> <p>On the hardware side I have <a href="http://highlowtech.org/?p=1706">this setup</a>, except the ATTINY is surface-mount, soldered to a surfboard with all its pins verified-soldered with a voltmeter. I use a header-pin strip, held by hand to get the pins touching the surfboard, to get the signals from the Uno to the ATTINY.</p> <p>Here are the command lines, which I took from looking at the IDE's debugging output:</p> <pre><code>REM set the fuse for 8MHz, so the ISP programmer can work C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -v -v -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0xe2:m REM load the program C:\Progra~1\Arduino\hardware\tools\avr\bin\avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -Uflash:w:firefly.hex:i REM set fuse for 1MHz, as the project requires C:\Progra~1\Arduino\hardware/tools/avr/bin/avrdude -CC:\Progra~1\Arduino\hardware/tools/avr/etc/avrdude.conf -v -pattiny45 -cstk500v1 -P\\.\COM7 -b19200 -e -Uefuse:w:0xff:m -Uhfuse:w:0xdf:m -Ulfuse:w:0x62:m </code></pre> <p>-I try running those separately, but always get this error:</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>but sometimes the number is ff0000 or ffff00 or ffffff</p> <p>I read that "Arduino uses a slightly modified version of avrdude to upload sketches to the Arduino board. The standard version queries for the board's device signature in a way not understood by the bootloader, resulting in this error." Does this mean that using the Arduino avrdude with a new ATTINY chip, no bootloader on it, would also cause that same error? In other words, is the modified avrdude incapable of querying a non-Arduino-bootloaded AVR chip?</p> <p>Or does that error simply mean I don't have a good contact between all my programmer pins and the ATTINY?</p> <p>And, are the fuse settings truly needed, can the Uno program the flash into an attiny running at 1MHz and thus save me some steps?</p> <p>(I would just buy a "real" programmer, but need to get this code in the next two days, and am in a rural part of Nova Scotia)</p>
<p>I had <em>exactly</em> this problem. If the ATtiny is set for external clock, then the ArduinoISP will not be able to program it without an external crystal. Connected a 16&nbsp;MHz crystal and 2 capacitors and worked perfectly.</p> <p>(I was then able to set ATtiny to internal clock, remove the crystal, and then worked perfectly without the crystal.)</p>
3784
|arduino-uno|avrdude|terminal|
How to upload an arduino sketch from java / processing?
2014-08-14T16:15:13.783
<p>I'm trying to upload a hex file from Java/Processing but running into some issues. Here is my code so far, based on the Arduino IDE's upload verbose output:</p> <pre><code>void setup(){ //C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avrdude -CC:\Program Files (x86)\Arduino/hardware/tools/avr/etc/avrdude.conf -v -v -v -v -patmega328p -carduino -PCOM96 -b115200 -D -Uflash:w:C:\Users\HM\AppData\Local\Temp\build5909267154049588263.tmp/sketch_aug13a.cpp.hex:i String ArduinoPath = "C:\\Program Files (x86)\\Arduino"; String hexPath = "C:\\Users\\HM\\AppData\\Local\\Temp\\build1023547366107161384.tmp/sketch_aug13a.cpp.hex"; String port = "COM96"; runCommand(new String[]{ArduinoPath+"/hardware/tools/avr/bin/avrdude", "-C"+ArduinoPath+"/hardware/tools/avr/etc/avrdude.conf","-v","-v","-v","-v","-patmega328p","-carduino","-P"+port,"-b115200","-D","-Uflash:w:"+hexPath+":i"}); } void runCommand(String[] cmd){ String s = null; try { Process p = Runtime.getRuntime().exec(cmd); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command System.out.println("command out:\n"); while ( (s = stdInput.readLine ()) != null) System.out.println(s); System.out.println("errors (if any):\n"); while ( (s = stdError.readLine ()) != null) System.out.println(s); }catch (IOException e) { System.out.println("something went wrong: \n"); e.printStackTrace(); } } </code></pre> <p>If I run this from command line it uploads without any issues, but from the code above I always get this output:</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\hardw are\tools\avr\etc\avrdude.conf" Using Port : COM96 Using Programmer : arduino Overriding Baud Rate : 115200 avrdude: ser_open(): can't open device "\\.\COM96": Access is denied. avrdude done. Thank you. </code></pre>
<p>I'd first would try to find out the right command when running on command line (<code>cmd.exe</code>).</p> <p>When you launch an external command from Java which generates output, you should/must read the output (<code>p.getInputStream()</code>, <code>p.getErrorStream()</code>) using separate threads. Otherwise your application might hang for no obvious reason.</p>
3792
|sensors|atmega328|
Seeeduino V3.0 (Atmega 328P) and Rotary Angle Sensor Mystery Message
2014-08-14T22:49:00.657
<p>I am attempting to do a simple example with the Rotary Angle Sensor.</p> <p><strong>Here is my development environment:</strong></p> <ul> <li><a href="http://www.visualstudio.com/en-us/products/visual-studio-premium-with-msdn-vs.aspx" rel="nofollow noreferrer">Visual Studio 2013 Premium</a> </li> <li><a href="http://www.visualmicro.com/page/Arduino-Debug-In-Visual-Studio.aspx" rel="nofollow noreferrer">Arduino Debug Tool</a></li> </ul> <p><img src="https://i.stack.imgur.com/oyOS4.png" alt="Visual Studio Solution and Projects"></p> <p><strong>Board setup (Simple as can be single analog input):</strong> <img src="https://i.stack.imgur.com/dBgoO.jpg" alt="Seeeduino V3 Setup"></p> <p><strong>Code:</strong></p> <pre><code>const int ROTARYSENSOR = A0; void setup() { Serial.println("Setup Start..."); Serial.begin(9600); //Set the serial communication frequency at 9600 bits per second pinMode(ROTARYSENSOR, INPUT); Serial.println("Setup End!"); } void loop() { Serial.println("Loop Start..."); int value = analogRead(ROTARYSENSOR); Serial.println(value); //display on serial monitor delay(1000); //wait 1000ms before printing next value Serial.println("Loop End!"); } </code></pre> <p><strong>Issue:</strong></p> <p>I have a single solution with multiple projects as my sensor playground. All other projects I have so far work flawlessly no issues. Although with this project (RotaryAngleSensor) I am getting a strange message.</p> <p>I am not seeing any of the Serial.println() messages. What is printed to the screen after a good 30 seconds is <strong><em>S?</em></strong></p> <p>Does anyone know what could be returning this S? to the standard output?</p>
<p>One problem is that you try to generate serial output <strong>before</strong> you initiate Serial. This could have odd results beyond just making that message fail.</p> <pre><code>Serial.println("Setup Start..."); Serial.begin(9600); </code></pre> <p>Should be</p> <pre><code>Serial.begin(9600); Serial.println("Setup Start..."); </code></pre> <p>And of course your posted code never reads the sensor...</p>
3811
|i2c|arduino-leonardo|
I2C seems to stop working when I attach an AF motor shield
2014-08-16T16:54:12.690
<p>I have a cheap MPU 6050 chip that communicates over 3.3V I2C. I can talk to it just fine on my Leonardo. If I add an additional Adafruit Motor shield (the old one), my MPU 6050 demo sketch hangs somewhere, and I get nothing back.</p> <p>As far as I see, the pins I use for the I2C communication are not used at all by the motor shield.</p> <p>What could be wrong here?</p> <p>I have the MPU6050 connected to SCL, SDA, GND and 3.3V, the motor shield uses almost all other pins.</p> <p>Additional Info: I am using this sketch currently: <a href="https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050" rel="nofollow">https://github.com/jrowberg/i2cdevlib/tree/master/Arduino/MPU6050</a> </p> <p>Update: Lots of "Serial.println"s later, I've narrowed it down a bit. The example sketch above hangs on the statement "Wire.endTransmission();" on line 279 of the I2CDev library.</p> <p>Update: Connecting the motor shield to external power seems to fix my problem. Weird =) I am still interested in the reason for this behavior.</p>
<p>Motors draw large amounts of current, and will either cause your power supply voltage to sag if you draw more current than your power supply can support, or cause blips in the power supply that will cause you all sorts of problems. </p> <p>You need to take steps to isolate the power from the motor shield from the power for the Arduino. </p> <p>How are you powering the motor shield? How are you powering the Arduino?</p> <p>If your power supply has enough current to support both your Arduino and your motors then you can probably solve the problem by adding an isolation capacitor between the Vin port on your Arduino and ground. </p> <p>What that does is to filter out temporary variations in the input voltage that's being fed to the Arduino. Without it, the Vin voltage to the Arduino is probably dropping as your motor draws large pulses of current, and <strong>that</strong> causes the output from the voltage regulator to droop as well.</p> <p>I don't know how to pick the rating of the cap. A trip to the Electrical Engineering stack exchange is probably in order.</p>
3814
|bootloader|atmega328|
How to free up Flash space by removing the bootloader on UNO?
2014-08-17T06:15:35.997
<p>In order to fit <strong>maximum user program</strong> into the chip, how to free up Flash space (0.5 kilo bytes for UNO, 2 KB pro Mini, 8KB for ATMega2560) by <strong>removing the bootloader on Atmega328</strong> (UNO, Pro Mini, or similar)?</p> <p>What <strong>software</strong> development tools needed (like Atmel AVR Studio software or similar)?</p> <p>What <strong>hardware</strong> flash writing / debug tools needed (like JTAG hardware programmer/debugger)?</p> <p>How is the <strong>procedure</strong>? Where can I get <strong>more information</strong>.</p> <p>Many thanks in advance.</p> <p>edit: Update boot loader size for different boards</p>
<p>You'll need to use an ISP programmer with avrdude. Perform a chip erase and then unprogram the <code>BOOTRST</code> fuse in the high fuse byte.</p>
3818
|hardware|
OBD Connector to Arduino
2014-08-17T15:52:11.770
<p>I bought <a href="https://www.sparkfun.com/products/9911" rel="nofollow">an OBD connector</a> from Sparkfun to try to connect to my vehicle via arduino. </p> <p>I'm just beginning and am not sure if I can just connect the connector pics to the arduino directly, or if there is some other required hardware?</p> <p>Does anyone know if I can connect directly and why or why not?</p>
<p>I briefly read up on this subject and I found out this:</p> <p>It seems like there's a protocol called <em>J1850</em>. There's no native support on the Arduino for that, but you might be able to do something bit-banging if you can find the specifications for this protocol. If you do this, I'd advise accessing the registers directly and skipping the <code>digitalRead()</code> command.</p> <p>There are a few protocols in use, so it is hard to know without knowing the car you drive to even tell what the car will send.</p> <p><em><a href="http://pinoutsguide.com/CarElectronics/car_obd2_pinout.shtml" rel="nofollow">More on this topic...</a></em></p> <p>Anyway, it seems like you need a chip to use with this. <a href="https://www.sparkfun.com/products/9555" rel="nofollow">Sparkfun also sells a breakout board for the STN1110 OBD-II to UART chip</a> <em>(<a href="https://learn.sparkfun.com/tutorials/obd-ii-uart-hookup-guide" rel="nofollow">tutorial)</a></em>. I couldn't really find anything else besides <a href="http://arduinodev.com/hardware/obd-kit/" rel="nofollow">this</a>.</p> <p>Anyway, you probably need another chip to do this work. The Arduino isn't meant to do all of these protocols, and the OBD isn't UART-compatible.</p>
3819
|arduino-uno|bootloader|arduino-pro-mini|
Why bootloader sizes differs from 0.5 to 8 kilo bytes for different boards?
2014-08-17T16:29:46.920
<p>According to <a href="http://arduino.cc/en/Main/ArduinoBoardProMini">official web info</a> bootloader sizes are <strong>0.5, 2 and 8 kilo bytes</strong> for UNO, Pro mini and ATMega2560. I believe all three boot loaders do similar job of receiving serial link data and write to Flash memory. </p> <p>UNO and Pro mini use <strong>same/similar</strong> ATMega168/328 chips but boot loader size are 0.5 and 2 KB. </p> <p>ATMega2560 apparent has a more <strong>advanced MCU</strong> which presumably should use similar or even less memory to do the same task, but the size is significantly large at <strong>8 KB</strong>.</p> <p>Why sizes differ? Small difference may be explained by different development teams, but, should be <strong>that much different</strong>, from 0.5 to 8KB. </p>
<p>Generally speaking the chips offer four possible bootloader size configurations. For example, on the Atmega328 you can have 512, 1024, 2048 or 4096 bytes (notice that the sizes increase by a power of 2).</p> <p>The chips with less program memory offer smaller bootloaders because they won't want to use a lot of that memory for something that is only used to upload code. The chips with more memory (like the Atmega2560) offer larger bootloaders, ie. 1k, 2k, 4k, 8k (again it increases by a power of 2).</p> <p>The Uno manages to use a 512 byte bootloader (Optiboot). The Mega, which has more complex instructions (to handle a larger address space) would need larger bootloaders. Also in some cases the bootloader writers add in extra stuff like a debugging console.</p>
3822
|arduino-uno|avrdude|debugging|avr-gcc|
Does ATMega 328/2560 chips support JTAG-type programmer and hardware debugger?
2014-08-17T17:40:14.073
<p>As stated in <a href="http://arduino.cc/en/Main/FAQ" rel="nofollow">www.Arduino.cc FAQ</a>, "Can I use an Arduino board without the Arduino software? Sure. It's just an AVR development board, you can use straight AVR C or C++ (with avr-gcc and avrdude or AVR Studio) to program it."</p> <p>For UNO/Pro Mini(ATMega328) and ATmega2560, does these two chips support JTAG type (some chip manufacturers may use different name) programmer / hardware-based debugger in same manner as the ST-Link/J-Link programmer/debugger where one can <strong>load code</strong> into the MCU and perform <strong>hardware break point</strong> and single stepping? Example as in <a href="http://www.st.com/web/catalog/tools/FM116/SC959/SS1532/PF252419?sc=internet/evalboard/product/252419.jsp" rel="nofollow">STM32 development board with ST-LINK programmer / debugger</a> where the chip has built-in debug circuit that communicate with ST-Link.</p> <p>Many thanks in advance.</p>
<p>The ATmegaXX8 does not support JTAG, but the ATmegaXX0, 'XX1, and 'XX4 do. The 'XX8 (as well as other AVR families) supports debugWIRE, which allows debugging over ISP. You will need one of Atmel's debuggers such as the AVR ONE! or the Atmel-ICE as well as Atmel Studio in order to use it.</p>
3826
|led|resistor|
Can two LEDs attached to different pins share their resistor?
2014-08-17T23:39:20.667
<p>I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram:</p> <p><img src="https://i.stack.imgur.com/jWXVT.png" alt="schematic"></p> <p>Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?</p>
<blockquote> <p><strong>Can</strong> two LEDs attached to different pins share their resistor?</p> </blockquote> <ul> <li><strong>can</strong> : yes</li> <li><strong>should</strong> : probably not</li> </ul> <p>Your resistor act here as a current limiter, say to <em>3mA</em></p> <p>If you light one LED at a time, you give 3mA to <em>that</em> LED If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each) If you light 3 LEDs, you give 3mA for all of them (<em>on average</em> 1mA each) <br><sub>Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other.</sub></p> <p>As "Amps made LED bright", less Amp is less light. On LED light with that setup will give "full light on", and more LED you add, less would bright each one.</p> <hr> <p>As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are <a href="http://en.wikipedia.org/wiki/Multiplexed_display">multiplexing your LEDs</a></p> <p>That is lighting only one at a time, but cycling fast enough from one LED to the next so that the human eye would <em>see</em> them all lit at once.</p>
3828
|arduino-uno|sketch|compile|flash|eeprom|
Is it possible to run a binary from EEPROM?
2014-08-18T01:19:17.093
<p>Say I wrote a compiled sketch to EEPROM then read it. Could I run the program from EEPROM? I guess the question is: Can an Arduino run software not in flash memory in the middle of executing the software in flash?</p>
<p>Short answer: No; From the atmega328's data sheet (though it applies to all AVR's): </p> <blockquote> <p>AVR uses a Harvard architecture – with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory</p> <p>...</p> <p>Program Flash memory space is divided in two sections, the Boot Program section and the Application Program section. Both sections have dedicated Lock bits for write and read/write protection. The SPM instruction that writes into the Application Flash memory section must reside in the Boot Program section</p> </blockquote> <p>It's architecture prevents using external program memory, but you can load anything into program memory at boot. At that point I would venture to say you are just programming AVR and not arduino, since you would need to replace the arduino bootloader and break the arduino IDE's ability to upload programs.</p> <p>Alternately you could also use an emulator or interpreter of some intermediate language; basically code that steps through and runs other code. As a general rule an emulator runs around 8x slower. </p> <p>There are micro-controllers from other brands that do support this functionality, I know a couple different PIC's do.</p>
3833
|arduino-uno|bootloader|arduino-pro-mini|
Is it advisable to reload Pro Mini with the bootloader originally designed for UNO to save 1.5 KB flash space?
2014-08-18T18:16:15.723
<p>In order to allow <strong>bigger user program size</strong>, is it possible and advisable to <strong>reload Pro Mini</strong> with the boot loader originally <strong>designed for UNO</strong>. This will save 1.5 KB flash space (UNO boot loader is 0.5KB, Pro Mini is 2KB). </p> <p>Using a smaller boot loader is an 'intermediate' step to get more space while still enjoy the easy benefit of the Arduino IDE and many library/code example. Of course, ultimate step is to remove all boot loader (only small saving of 0.5KB if above is possible) and switch to ATmel development environment, ATmel studio, which is complex but programmer has full control of everything.</p> <p>Did I miss anything in the followings?</p> <p>I tend to believe that it is possible as </p> <p>a) same ATMega328 chip is used in both board</p> <p>b) Pro Mini is essentially cutting UNO into two halves, the MCU and the USB/Serial converter now use external USB to Serial converter </p> <p>If the Pro Mini board is reloaded with UNO boot loader, how should the boards.txt file be edited to reflect the changes so that the IDE will handle it correctly?</p> <p>Many thanks in advance</p>
<p>You can just flash the newest <a href="https://raw.githubusercontent.com/arduino/Arduino/master/hardware/arduino/bootloaders/optiboot/optiboot_atmega328-Mini.hex" rel="nofollow">optiboot_atmega328-Mini.hex</a>. That one should also be only .5k in size, as it starts writing at the same address (<code>7E00</code>). </p> <p>If you divide <code>7E00</code> by two you get <code>3F00</code> (This is because AVRs use 16-bit words for addressing while .hex files work with bytes (8-bit)). (I figured that one out, just now)</p> <p><code>3F00</code> is exactly the start of the <code>Boot Loader Flash Section</code> when you have selected a 256-words <code>Boot Size</code> (page 291 of the <a href="http://www.atmel.com/Images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf" rel="nofollow">datasheet</a>). 256-words is the 0.5kb you want.</p> <p>Just make sure you have the <code>BOOTSZ1</code>, <code>BOOTSZ0</code> fuses set to <code>1</code></p> <p>As for the <code>boards.txt</code>. I think you only need to change <code>mini328.upload.maximum_size=28672</code> to <code>mini328.upload.maximum_size=32256</code>.</p>
3836
|programming|atmega328|sd-card|
Arduino Custom Function Problem
2014-08-18T20:26:56.780
<p>I am experiencing problems when I put parts of my code into custom functions and then have Arduino Mega 2560 run it. The code works fine when I put it all in the void loop() function, but when I create new functions then call those functions in the loop() function, it doesn't do what I want it to.</p> <p>Here is the code where I put everything in the loop function</p> <pre><code>/* Location.txt: Date/Time , Latitude (deg decimal), Longitude, Altitude (m) Speed.txt: Date/Time, Speed (m/s), Heading (deg) */ #include&lt;TinyGPS.h&gt; #include&lt;SD.h&gt; #include&lt;SPI.h&gt; int CS = 53; long lat,lon; unsigned long time, date; int year,tinseconds; byte month, day, hour, minute, second, hundredths; unsigned long age; char dataString[20]; TinyGPS GPS; struct GPSstruct { String dateTime; int timeseconds; float C_lat; float C_lon; float C_alt; float heading; float speedmps; }; void setup() { Serial.begin(115200); Serial1.begin(38400); pinMode(CS, OUTPUT); if(!SD.begin(CS)) { Serial.println(F("Card Failure")); } } void loop() { if(Serial1.available()){ // check for gps data if(GPS.encode(Serial1.read())){ // encode gps data GPS.crack_datetime(&amp;year, &amp;month, &amp;day, &amp;hour, &amp;minute, &amp;second, &amp;hundredths, &amp;age); GPS.get_position(&amp;lat,&amp;lon); // get latitude and longitude in degree decimals multiplied by 10^5 sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second); tinseconds = second + minute*60 + hour*3600; float C_lat = ((float)lat)/1000000; //to get degree decimals float C_lon = ((float)lon)/1000000; float C_alt = GPS.f_altitude(); float heading = GPS.f_course(); float speedmps = GPS.f_speed_mps(); GPSstruct A = {dataString,tinseconds,C_lat,C_lon,C_alt,heading,speedmps}; //DEBUG Serial.println(); Serial.print(F("Date/Time: "));Serial.println(dataString); Serial.print(F("Time (sec): "));Serial.println(tinseconds); Serial.print(F("Lat: "));Serial.println(C_lat,5); Serial.print(F("Lon: "));Serial.println(C_lon,5); Serial.print(F("Alt: "));Serial.println(C_alt); Serial.print(F("Heading: "));Serial.println(heading); Serial.print(F("Speed: "));Serial.println(speedmps); //END of DEBUG //add the code below makes alt = 1000000 for a long time then it fixes at some ?wierd? number //------// File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt if (dataFile) { dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat,5);dataFile.print(" , ");dataFile.print(A.C_lon,5);dataFile.print(" , ");dataFile.println(A.C_alt); dataFile.close(); } else { Serial.println(F("Location.txt cannot be opened!")); } File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading if (dataFile2) { dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading); dataFile2.close(); } else { Serial.println(F("Speed.txt cannot be opened!")); } //------// } } } </code></pre> <p>Here is the code where I put them into two custom functions and call them in loop()</p> <pre><code>#include&lt;TinyGPS.h&gt; #include&lt;SD.h&gt; #include&lt;SPI.h&gt; int CS = 53; long lat,lon; unsigned long time, date; int year,tinseconds; byte month, day, hour, minute, second, hundredths; unsigned long age; char dataString[20]; TinyGPS GPS; struct GPSstruct { char dateTime[20]; int timeseconds; float C_lat; float C_lon; float C_alt; float heading; float speedmps; }; //Function Prototypes struct GPSstruct GPSdata(void); void SDlogger(struct GPSstruct); void setup() { Serial.begin(115200); Serial1.begin(38400); pinMode(CS, OUTPUT); SD.begin(CS); } //GPS data function: struct GPSstruct GPSdata(void) { static GPSstruct A; if(Serial1.available()){ // check for gps data if(GPS.encode(Serial1.read())){ // encode gps data GPS.crack_datetime(&amp;year, &amp;month, &amp;day, &amp;hour, &amp;minute, &amp;second, &amp;hundredths, &amp;age); GPS.get_position(&amp;lat,&amp;lon); // get latitude and longitude in degree decimals multiplied by 10^5 sprintf(dataString, "%02d/%02d/%02d %02d:%02d:%02d",month,day,year,hour,minute,second); tinseconds = second; float C_lat = ((float)lat)/1000000; //to get degree decimals float C_lon = ((float)lon)/1000000; float C_alt = GPS.f_altitude(); float heading = GPS.f_course(); float speedmps = GPS.f_speed_mps(); strcpy(A.dateTime, dataString); A.C_lat = C_lat; A.C_lon = C_lon; A.C_alt = C_alt; A.heading = heading; A.speedmps = speedmps; //DEBUG Serial.print(F("Date/Time: "));Serial.println(dataString); Serial.print(F("Time (sec): "));Serial.println(tinseconds); Serial.print(F("Lat: "));Serial.println(C_lat); Serial.print(F("Lon: "));Serial.println(C_lon); Serial.print(F("Alt: "));Serial.println(C_alt); Serial.print(F("Heading: "));Serial.println(heading); Serial.print(F("Speed: "));Serial.println(speedmps); Serial.println(); //END of DEBUG } } return A; } //SD data logging funct: void SDlogger(struct GPSstruct A) { File dataFile = SD.open("Location.txt", FILE_WRITE); //Records date/time, lat, lon, alt if (dataFile) { dataFile.print(A.dateTime);dataFile.print(" , ");dataFile.print(A.C_lat);dataFile.print(" , ");dataFile.print(A.C_lon);dataFile.print(" , ");dataFile.println(A.C_alt); dataFile.close(); } else { Serial.println(F("Location.txt cannot be opened!")); } File dataFile2 = SD.open("Speed.txt",FILE_WRITE); //Records date/time, speed, heading if (dataFile2) { dataFile2.print(A.dateTime);dataFile2.print(" , ");dataFile2.print(A.speedmps);dataFile2.print(" , ");dataFile2.println(A.heading); dataFile2.close(); } else { Serial.println(F("Speed.txt cannot be opened!")); } } void loop() { struct GPSstruct Gdata = GPSdata(); SDlogger(Gdata); } </code></pre> <p>The one with all the code in the loop function prints all the serial.println commands and writes data into the micro SD card, but the one with custom functions DOESN'T print serial.println commands in GPSdata function and only prints that "Location.txt/Speed.txt cannot be opened!" and have writes 0 into the mirco SD card.</p> <p>Why is this happening? Is it memory problems? (But the other one works fine)</p> <p>The code here is meant to be a part of a bigger main code that uses these GPS data, so I would prefer it if I can keep the main script clean using custom functions.</p> <p>Thank you.</p>
<p>Admittedly, your code is somewhat hard to read without an actual editor (not your fault), but I think the issue is that in the first code (everything in one loop), the matching bracket from the initial if-statement (<code>if(Serial1.available()) {</code>) is located <em>after</em> the SD logging functions.</p> <p>In the second code (decomposing the code), you have the SD logging done <em>outside</em> the if-statement. My guess is that <code>Serial1.available() = false</code> initially, so in the first piece of code, it skips everything else and loop until <code>Serial1.available() == true</code>. That probably doesn't take long, so you just see everything working. In the second code, you return <code>static GPSstruct A</code> (I'm not sure you want this to be static, but I could be wrong) which has been initialized but contains no useful data (it's uninitialized). The <code>void loop()</code> then takes that empty struct and passes it over to <code>SDlogger(struct GPSstruct)</code>. That function doesn't do any error-checking to make sure that <code>A</code> has useful information.</p> <p>An easy workaround would be to add a field to the <code>GPSstruct</code> for whether or not it contains data. It's a simple <code>boolean</code> value. The code might look something like this:</p> <pre><code>struct GPSstruct { boolean containsData; String dateTime; int timeseconds; float C_lat; float C_lon; float C_alt; float heading; float speedmps; }; ... if(Serial1.available()){ A.containsData = true; ... } else { A.containsData = false; } ... void SDlogger(struct GPSstruct A) { if(A.containsData) { ... } else { return; } </code></pre> <p>Also, as I was typing this, it got migrated...</p>
3840
|android|
How do I view Serial Output on an Android Device?
2014-08-19T00:37:25.707
<p>Within the Arduino IDE Serial.* output can be viewed with Tools / Serial Monitor. How can I view Serial.* output on an Android? As a concrete example, how can I view the output from Examples / Communication / ASCIITable?</p>
<p>These steps will allow your Android device to function as an Arduino Terminal. </p> <ul> <li>Download a Serial Terminal app. I'm using <a href="https://play.google.com/store/apps/details?id=com.passiontech.support.en" rel="nofollow">Android Hyperterminal, English version</a>.</li> <li>Attach an OTG ("On The Go") cable to your Android device.</li> <li>Attach your Arduino to the OTG using your regular USB cable.</li> <li>Make sure the terminal program is set to the same baud rate as your sketch.</li> <li>Run the terminal App and select the USB port.</li> </ul>
3842
|avr-toolchain|
Why are Tone.cpp and IPAddress.cpp getting built for my project?
2014-08-19T03:30:15.010
<p>I'm using <code>avr-size</code> to see the size of library objects to free up some FLASH. Why are <code>Tone.cpp</code> and <code>IPAddress.cpp</code> getting built? e.g.</p> <pre><code>$ cd /var/folders/3j/6wp3hvrj34n0xg3xzq6vjq380000gn/T/build8391693238079360471.tmp/ localhost:build8391693238079360471.tmp $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.o text data bss dec hex filename 0 0 0 0 0 CDC.cpp.o 0 0 0 0 0 HID.cpp.o 1816 0 170 1986 7c2 HardwareSerial.cpp.o 512 0 6 518 206 IPAddress.cpp.o 10186 391 377 10954 2aca MainINOFile.cpp.o 1872 14 0 1886 75e Print.cpp.o 1414 1 0 1415 587 Stream.cpp.o 1365 1 21 1387 56b Tone.cpp.o 0 0 0 0 0 USBCore.cpp.o 288 0 4 292 124 WInterrupts.c.o 306 0 0 306 132 WMath.cpp.o 4796 1 1 4798 12be WString.cpp.o 30 0 0 30 1e main.cpp.o 618 6 0 624 270 malloc.c.o 56 0 0 56 38 new.cpp.o 450 0 0 450 1c2 realloc.c.o 588 0 9 597 255 wiring.c.o 266 1 0 267 10b wiring_analog.c.o 550 0 0 550 226 wiring_digital.c.o 320 0 0 320 140 wiring_pulse.c.o 260 0 0 260 104 wiring_shift.c.o $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size */*.o text data bss dec hex filename 2790 0 0 2790 ae6 DS3231/DS3231.cpp.o 38 0 1 39 27 EEPROM/EEPROM.cpp.o 1444 0 0 1444 5a4 LSM303/lsm303.cpp.o 782 0 0 782 30e Messenger/Messenger.cpp.o 116 0 1 117 75 SPI/SPI.cpp.o 142 0 4 146 92 SdFat/MinimumSerial.cpp.o 2568 0 0 2568 a08 SdFat/Sd2Card.cpp.o 10644 0 4 10648 2998 SdFat/SdBaseFile.cpp.o 1322 2 0 1324 52c SdFat/SdFat.cpp.o 152 0 0 152 98 SdFat/SdFatUtil.cpp.o 233 0 0 233 e9 SdFat/SdFile.cpp.o 736 0 0 736 2e0 SdFat/SdStream.cpp.o 2604 0 523 3127 c37 SdFat/SdVolume.cpp.o 3395 0 0 3395 d43 SdFat/istream.cpp.o 1635 0 0 1635 663 SdFat/ostream.cpp.o 754 0 86 840 348 Wire/Wire.cpp.o $ /Applications/Arduino.app/Contents/Resources/Java/hardware/tools/avr/bin/avr-size *.elf text data bss dec hex filename 29204 442 1279 30925 78cd MainINOFile.cpp.elf </code></pre>
<p>As stated the IDE's equivalent to the make will compile anything everything it can find, in scope. But its linker has eliminate garbage enabled, hence anything not called or not static will not be linked into the EXE.</p> <p>You can "avr-objdump -t" to create a map from your elf. And -d for an assembly listing. As to see exactly what is in the EXE, for your self. You need to enable show verbose output of compilation from the IDE's preferences, to display the temporary directory that contains the elf file. </p> <p>example:</p> <pre><code>C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp&gt;C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -t MP3Shield_Library_Demo.cpp.elf &gt; MP3Shield_Library_Demo_wo_mem.cpp.elf.map C:\DOCUME~1\mflaga\LOCALS~1\Temp\build6395515806682540138.tmp&gt;C:\projects\Arduino\hardware\tools\avr\bin\avr-objdump -d MP3Shield_Library_Demo.cpp.elf &gt; MP3Shield_Library_Demo_wo_mem.cpp.elf.lst </code></pre> <p>I did the above and commented out a call to a function member of my library, between subsequent builds. To see that the code was not linked into the assembly.</p>
3848
|avrdude|mac-os|
ArbotiX-M Problem uploading to the board
2014-08-19T18:38:28.543
<p>I have an ArbotiX-m Arduino board, and have followed the <a href="http://learn.trossenrobotics.com/arbotix/7-arbotix-quick-start-guide" rel="nofollow">setup guide</a> on Trossen robotics all the way to the 5th step. I have a Mac running OS X 10.10 and use Arduino 1.0.5. I installed the necessary drivers and copied the files to the Sketchbook directory. When I try to load the sample ArbotiXBlink program:</p> <pre><code>// Pin 0 maps to the USER LED on the ArbotiX Robocontroller. int led = 0; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led, OUTPUT); } // the loop routine runs over and over again forever: void loop() { digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level) delay(1000); // wait for a second digitalWrite(led, LOW); // turn the LED off by making the voltage LOW delay(1000); // wait for a second } </code></pre> <p>It verifies just fine, but when I click upload, I get:</p> <pre><code>Binary sketch size: 1,088 bytes (of a 65,536 byte maximum) avrdude: stk500_recv(): programmer is not responding </code></pre> <p>Any ideas?</p> <p><strong>EDIT:</strong> The board was trying to get power from the 5V instead of USB</p>
<p>I figured why my board wasn't responding! Apparently, the power pin was connected to the 5V supply instead of usb. Silly me!</p>
3850
|sd-card|reliability|
SD.begin() fails second time
2014-08-19T21:24:02.897
<p>When I remove the SD card and try to open a file, I can detect the error properly.</p> <p>But how do I detect that the card has been replaced after an error? My first thought was to call <code>SD.begin()</code> again but it appears that this function returns true exactly once and false thereafter.</p> <p>Simplified example:</p> <pre><code>void setup() { SD.begin(pin); // called exactly once. Works. } void loop() { // stuff } </code></pre> <p>But this does not:</p> <pre><code>void setup() { SD.begin(pin); // first time calling this function: works. } void loop() { delay(1000); SD.begin(pin); // always fails } </code></pre> <p>I'd rather not reset the microcontroller just for this.</p>
<p>I know this question is relatively old but still, if you wnat to run <code>SD.begin(chipselect);</code> again first call <code>if(root.isOpen()) root.close();</code> I added this to the library. This way <code>SD.begin(chipselect)</code> will return <code>true</code> if a card is present and <code>false</code> when it's not.</p>
3851
|arduino-uno|programming|
Getting a random number for electronic dice
2014-08-19T21:58:41.283
<p>I am making a "Electronic Dice".</p> <p>I have 7 LEDs to form the output, and this works fine.</p> <p>My problem is getting a random result on the output.</p> <pre><code>int die_face = 1; void loop() { if (analogRead(BUTTON_PIN) == HIGH) { paintDieFace((die_face % 6) + 1); } die_face += 1; } </code></pre> <p>The problem is, that roughly 95% of the time I get a 1.<br> Most of the time it's not a 1, it's a 2, or very rarely a 3.</p> <p>I've tried paintDieFace() with millis()%6+1 too, but always get the same result. When it's painted with random(1,7); I get 1, 2 or 3 100% of the time.</p> <p>Is this some sort of timing issue? I just don't get it.</p> <p>Just to clarify - The paintDieFace() function is working perfectly, I'm logging the result to serial too.</p>
<p>First of all, look at this line of code:</p> <pre><code>if (analogRead(BUTTON_PIN) == HIGH) </code></pre> <p>You probably want to use <em><code>digitalRead()</code></em>. Note that it is okay to use digitalRead() on an analog pin, just make sure to use the right pin number (<code>A0</code>, etc.)</p> <p>From the <a href="https://github.com/arduino/Arduino/blob/3a8ad75bcef5932cfc81c4746a87ddbdbd7e6402/hardware/arduino/cores/robot/Arduino.h" rel="nofollow">Arduino Source</a>:</p> <pre><code>#define HIGH 0x1 #define LOW 0x0 </code></pre> <p><em>(Ignore the <code>0x</code>, that is just specifying that it's hexadecimal. However, 0 and 1 are the same in any base)</em></p> <p>So, really, this function is only activated when <code>analogRead()</code> returns 1, which could possibly cause a problem later if it doesn't check at the right time. <strong>Note:</strong> now is a good time to remind you about debouncing...</p> <p>For your actual code, since you want it to be simple, I suggest you forget that code that you wrote. <a href="http://arduino.cc/en/reference/random" rel="nofollow">Arduino has a built in random library</a>, which works unless you have some special need for a random number.</p> <p>Your final code should look like something like this in the end:</p> <pre><code>void loop() { if (analogRead(BUTTON_PIN) == HIGH) { paintDieFace(random(1, 6); } } </code></pre> <p>Note that you should also use this code here in your setup (make sure that analog pin is floating: nothing should be attached to it):</p> <pre><code>randomSeed(analogRead(A1)); </code></pre> <p>It actually isn't random, just <em>pseudo-random</em>. That means it relies on an equation to generate what seem to be random numbers. Because there has to be a default value of where the equation starts (the <em>seed</em>), it will repeat the same numbers <em>every time</em> you run it.</p> <p>If you're wondering how this works, know that the analog pin is affected by a ton of external factors when there is no other electric signal attached.</p>
3855
|power|sleep|
Sleep mode and months of operation on small battery
2014-08-20T04:06:02.270
<p>In context of getting the MCU on Pro Mini and ATMega2560 (chip is ATmega328 and ATMega 2560) to <strong>sleep and power down modes,</strong> so as to run on <strong>one set of battery for months</strong>, appreciate idea and comment.</p> <p>Initially, I looked at web postings and get the following general idea. Did I miss anything?</p> <p>Is sleep mode done via ATMel factory library, Arduino-level user contributed library, or the Arduino IDE? Many web posting are along the line of getting it partially working but only at half expected current reduction, etc. That is, current do reduced, but, not enough. </p> <p>Are there several such library? </p> <p>How are they? </p> <p>Which one is better support and more functions? (no need for easy to use, can do registers programming, when needed)</p> <p>Many thanks in advance </p>
<ul> <li><p>I have a page about saving power with the Atmega328P chips (similar techniques apply to other chips): <a href="http://www.gammon.com.au/power" rel="nofollow">Power saving techniques for microprocessors</a></p></li> <li><p>I made a <a href="http://www.gammon.com.au/forum/?id=12106" rel="nofollow">Temperature and humidity sensor - battery powered</a> - this runs from 3 x AA batteries, and writes to an SD card. From memory it ran for 2 years before I needed to replace the batteries.</p></li> <li><p>Another project flashes an LED every second: <a href="http://www.gammon.com.au/forum/?id=12769" rel="nofollow">Simple project - torch-locator</a>. I made something similar a couple of years ago that is still running from the same button battery.</p></li> </ul> <p>As a rule-of-thumb, you should be able to achieve 100 nA of current consumption, and still be "alive" and able to respond to external events, like button-presses (eg. a calculator or TV remote). To wake periodically (without an external event) takes more current, because you need the watch-dog timer to be active, but that can still be as low as 6 µA.</p>
3856
|power|fuses|
MCU fuses used by Pro Mini and ATMega 2560 and power down
2014-08-20T04:24:21.277
<p>In context of Pro Mini and ATMega2560 </p> <p>Fuses, as documented in chip factory doc are complex topics (I have not really used it before), appreciate pointers and advises, to narrow down those that are <strong>needed for contexted task</strong> and left un-needed in their default modes. </p> <p>Which fuses are used within context of the IDE in <strong>general</strong>, and in specific of software <strong>loading</strong> via bootloader and ISP? </p> <p>Which fuses related to sleep and power down modes, in context that individual chip modules can be set to various power-saving modes via registers. Does fuses play a part in getting the power-saving effect?</p> <p>Many thanks in advance</p>
<p>The data sheets are the ultimate source. However, that may be a bit overwhelming. I find the below great resources very helpful. </p> <p>1) <a href="http://www.engbedded.com/fusecalc/" rel="nofollow">Online Fuse Calculator</a> There are many others.</p> <p>2) <a href="http://translate.google.com/translate?hl=en&amp;sl=ja&amp;u=http://yuki-lab.jp/hw/avrdude-GUI/&amp;prev=/search%3Fq%3Davrdude-GUI%2Byuki-lab.jp%26client%3Dfirefox-a%26hs%3Drmn%26rls%3Dorg.mozilla:en-US:official%26channel%3Dsb%26biw%3D1160%26bih%3D724" rel="nofollow">avrdude-GUI</a> there are many others out there.</p> <p>3) the .\arduino-1.5.7\hardware\arduino\avr\boards.txt</p> <pre><code>uno.bootloader.low_fuses=0xFF uno.bootloader.high_fuses=0xDE uno.bootloader.extended_fuses=0x05 </code></pre> <p>4) I also read the fuses from any device before I stomp over them. And check into what each mean.</p> <p>As for narrowing down the features the Online Calculator very helpful to start with and then read into the data sheet for ones of interest.</p> <p>For the most part there have several questions and answers for low power modes, using interrupts to re-awake. Where there appears to no direct fuses to save power, outside of clock source and speed. Arguably Brown Out detect is a fuse, but that is not directly related to saving power.</p>
3859
|nrf24l01+|
"Hello World" program for nRF24L01+?
2014-08-20T06:17:48.963
<p>Where is a simple program that demonstrates unidirectional data transmission over a pair of nRF24L01+ radios? It should have adequate output so that a beginner can determine that the transmission is working properly.</p>
<p>I found this site to have pretty strait forward instructions:</p> <p><a href="https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/" rel="nofollow noreferrer">https://maniacbug.wordpress.com/2011/11/02/getting-started-rf24/</a></p> <p>Main Library: <a href="https://github.com/maniacbug/RF24/" rel="nofollow noreferrer">https://github.com/maniacbug/RF24/</a></p> <p>Example Sketch: <a href="https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde" rel="nofollow noreferrer">https://github.com/maniacbug/RF24/blob/master/examples/pingpair/pingpair.pde</a></p>
3864
|serial|sensors|arduino-due|
Parse data from sensor without delimeters
2014-08-20T10:58:38.727
<p>Im using a variant of Arduino Due embedded on a ARM (Udoo). And I have connected a Medlab SPO2 Pearl 200 sensor to Serial1.</p> <p>Im just trying to parse input from Serial1 to Serial, in a human-readable format (Hexadecimal).</p> <p>The protocol is described in this image: <img src="https://i.stack.imgur.com/XxZJt.png" alt="Protocol SPo2"></p> <p>And using this Arduino code I reveice two times the "no finger detected line"</p> <pre><code>int lineLength = 16; int spo2read[16]; int readed = 0; if (Serial1.available()) { int inByte = Serial1.read(); if (readed &lt; lineLength) { spo2read[readed] = inByte; } readed++; if (readed == lineLength) { Serial.print("SPO2: "); for (int i = 0; i &lt;= lineLength; i++) { Serial.print(spo2read[i], HEX); Serial.print( delimeter); } Serial.println(""); readed = 0; } } </code></pre> <p>Output with no finger is:</p> <pre><code>SPO2: A,FB,2,F9,0,FA,0,FC,A,FB,2,F9,0,FA,0,FC,0, </code></pre> <p>Buf if I put my finger, all is messed up:</p> <pre><code>SPO2: 7C,74,6B,62,5A,51,4A,42,3B,34,30,2E,2F,30,31,33,0, SPO2: 36,38,3B,3E,3D,3C,3C,3B,3B,38,34,2F,2C,2B,2B,29,0, SPO2: 24,21,1E,1D,1E,1E,1F,20,22,24,26,28,2B,2D,30,32,0, SPO2: 35,37,39,3C,3E,40,42,44,45,4A,4F,53,55,57,59,5C,0, SPO2: 5E,60,61,F9,0,FA,0,FC,1A,FB,0,F8,62,62,62,63,0, </code></pre> <p>Sensor doesn't sends a \n or \r so I don't know exactly how to parse the data</p>
<p>I have used the source code available on the Medlab web, and do some "modifications" to be Arduino compatible. I dont wanna the waveform data, because my final program will do the waveforms acording the data received, so I don't "listen" to the waveform packet</p> <pre><code>boolean startbyte = false; byte buf = 0; while (Serial1.available() &gt; 3) { buf = Serial1.read(); if (buf &gt; 0xfc) { buf = Serial1.read(); } if ((startbyte == true) &amp;&amp; buf &gt; 0xF7) { startbyte = false; } if (buf &gt; 0xf7 &amp;&amp; startbyte == false) { //startbyte = true; if (buf == 0xf8) { startbyte = true; } if (buf &gt; 0xf8) { byte RX = buf; buf = Serial1.read(); if (buf &gt; 0xfc) { buf = Serial1.read(); } if (RX == 0xf9) { //SPO = buf; Serial.print("SV:"); Serial.print(buf, DEC); Serial.println(); } else if (RX == 0xfa) { //Pulse = buf; Serial.print("SPV:"); Serial.print(buf, DEC); Serial.println(); } else if (RX == 0xfb) { //Status = buf; Serial.print("StV:"); Serial.print(buf, DEC); Serial.println(); } else if (RX == 0xfc) { //quality = buf; Serial.print("QV:"); Serial.print(buf, DEC); Serial.println(); Serial.println(); } else { } } } else if (startbyte == true) { //Waveform data } } </code></pre>
3872
|arduino-mega|sd-card|
How do I specify a working directory when saving to SD card?
2014-08-20T23:15:07.613
<p>I'm trying to datalog to a EyeFi SD card by writing to a file with a jpg extension. Here's that portion of my code so far:</p> <pre><code>// see if the directory exists, create it if not. if( !SD.exists("/DCIM/100NIKON") ) { if( SD.mkdir("/DCIM/100NIKON") ) { Serial.print("File directory created: "); } else { error("File directory not created"); } } else { Serial.print("File directory exists: "); } // Test file char filename[] = "DSCN0000.JPG"; if (! SD.exists(filename)) { logfile = SD.open(filename, FILE_WRITE); // only open a new file if it doesn't exist } if (! logfile) { error("Couldnt create file"); } </code></pre> <p>The Arduino creates the directory, but the file is still saved to the root. I would love some help or tips on this.</p>
<p>You're creating a directory, and then <em>not writing the file into it</em>.</p> <p>You need to change the filename to <code>/DCIM/100NIKON/DSCN0000.JPG";</code></p> <p>Note that <code>SD.open()</code> takes the <strong>full filepath to the file</strong>, not just the file*name*.</p> <p>From the <a href="http://arduino.cc/en/Reference/SD" rel="noreferrer">Arduino Docs</a>:</p> <blockquote> <p>The file names passed to the SD library functions can include paths separated by forward-slashes, /, e.g. "directory/filename.txt". Because the <strong>working directory is always the root of the SD card</strong>, a name refers to the same file whether or not it includes a leading slash (e.g. "/file.txt" is equivalent to "file.txt"). As of version 1.0, the library supports opening multiple files.</p> </blockquote> <p>(emphasis mine)</p>
3881
|arduino-uno|timers|
Very long delay() possible?
2014-08-21T12:14:28.757
<p>I'm trying to make an opening and closing little door that should open or close every 12 hours. I was wondering if I could just make a small looping script with a delay() for 12 hours, delay(43 200 000 000); I guess? However, I have no idea if that's possible and/or recommendable. Some feedback/alternatives(if needed) would be nice :)</p>
<p>I just use for loops when I don't want to do stuff in between:</p> <pre><code>for (int Hours = 0; Hours &lt; 12; Hours++) { //Creates 12 hours for (int Minutes = 0; Minutes &lt; 60; Minutes++) { //Creates 1 hour for (int Seconds = 0; Seconds &lt; 60; Seconds++) { //Creates 1 minute delay(1000); //Creates 1 second } } } </code></pre>
3888
|arduino-mega|sd-card|
SD datalogger sometimes skips readings
2014-08-21T22:07:52.453
<p>I'm using the Adafruit SD shield with a Mega board and wrote a simple program to log data. I am outputting a constant stream of data at 115200 baudrate from another Arduino to the Mega. The data output is mostly good, but there are places where some data are skipped. These skipped data usually occurs around a file flush. I've tried playing around with the flush frequency and the soft buffer size, but to no avail. I'm not sure what these hiccups are caused by and would like some help.</p> <pre><code>void loop(void) { while (Serial1.available()) { softBuffer[i] = Serial1.read(); i++; } if (i &gt;= SOFT_BUFFER_SIZE) { for (x = 0; x &lt; SOFT_BUFFER_SIZE; x++) { logfile.print(softBuffer[x]); } logfile.flush(); i = 0; } } </code></pre>
<p>The SD card library works by filling up a 512 byte buffer. Once full, the data is written to disk.</p> <p>The <code>flush</code> command updates the directory listing with the correct size for the file and also updates the file allocation table. It only needs to be done once, just before you pull the card out.</p> <p>While <code>flush</code> is doing its thing, the internal serial buffer of the Arduino is filling up with new bytes. The internal buffer is 64 bytes long so if <code>flush</code> takes too long, the internal buffer fills up and you lose characters. You could edit HardwareSerial.cpp in the Arduino program directory to make it say 256 bytes.</p> <p>Because of this <code>softBuffer</code> is not needed. Simply write straight to the card and let the internal buffer handle the buffering. See <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp" rel="nofollow">https://github.com/arduino/Arduino/blob/master/hardware/arduino/cores/arduino/HardwareSerial.cpp</a> for the Serial code.</p> <pre><code>unsigned long bytesWritten = 0; void loop(void) { while (Serial1.available()) { logfile.write(Serial1.read()); bytesWritten++; if(bytesWritten &gt; BYTES_PER_FLUSH) logfile.flush(); } } </code></pre>
3890
|arduino-pro-mini|isp|arduino-uno-smd|
Programming Arduino Pro mini 328 with Arduino Uno SMD
2014-08-22T10:26:31.200
<p>I apologize in advance, because there is a lot of tutorials out there about programming arduinos with another arduino, however I can't find really simple one I could understand. </p> <p>I have Arduino Uno SMD version and Arduino Pro mini 328. I want to upload sketch to Arduino Pro mini using Arduino Uno in ISP mode (I guess).</p> <p>I want to know EXACTLY which pins need to be connected and if all I need is Arduino IDE to upload my sketch to Pro mini ?</p> <p>Thank you for your help.</p>
<p>Following the tutorial on <a href="http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/" rel="nofollow noreferrer">http://www.instructables.com/id/Arduino-Examples-2-Use-an-Arduino-as-a-FTDI-Progr/</a> I was able to upload the blink sketch to the Pro Mini 5V version with an Arduino Nano. After I tried uploading the sketch that I really wanted to use but got many errors in the IDE I tried a couple more with no luck. I had stumble on another article earlier about using the Arduino Nano to program the Pro Mini <a href="http://www.electronicsmayhem.com/?p=31" rel="nofollow noreferrer">http://www.electronicsmayhem.com/?p=31</a>. I had tried that method but with no luck but using the first tutorial &amp; only changing one thing from it with info from the article i mentioned I was able to upload the sketch without any errors. The only thing I changed was I didn't connect the TX from the Nano to the TXI of the Mini.</p> <pre><code> Arduino Nano Pro Mini 5V GND-------------GND 5V--------------VCC RX--------------RX1 Reset-----------GRN(DTR) </code></pre>
3892
|arduino-motor-shield|nrf24l01+|
Motor shield and wireless transceiver compete for same pins
2014-08-22T17:49:19.980
<p>I would like to use these 2 components with an Arduino Uno:</p> <ul> <li>Arduino Motor Shield R3 </li> <li>nRF24L01 2.4GHz Wireless Transceiver</li> </ul> <p>I use Stepper for the motor shield, and SPI + RF24 for the wireless transceiver.</p> <p>I could write 2 sketches that work perfectly, but how can I combine them together?</p> <p>My issue is that they both require access to pins 11, 12 and 13.</p> <p>Any help is greatly appreciated!</p>
<p>For prototyping, use male to female jumper wires to connect the Arduino Uno to the robot shield. It is a bit of a pain, but it makes it easy to free the conflicting pins for the wireless transceiver.</p> <p>For a more permanent solution, look at Chris K's answer.</p>
3893
|arduino-uno|library|timers|linux|
In Linux, how do I get this Arduino library to work
2014-08-22T18:11:00.023
<p>In Linux Fedora 20 Arduino I want to use the Timer library from <a href="https://github.com/JChristensen/Timer" rel="nofollow">here</a>, from which I have downloaded the folder <code>Timer-master.zip</code>, but, when I try to import it, I get the Arduino message that it cannot be imported because its name includes characters other than plain ACSII letters and numbers. I have tried copying the file to <code>Timermaster.zip</code> and importing that instead, but still got exactly the same failure message.</p> <p>Please, how do I get out of this impasse?</p>
<p>What's causing the problem is that the folder name inside the zip has a hyphen in it, just extract the folder from this zip and rename it to <code>timer</code> instead of <code>timer-master</code>. I just imported it on Fedora 20.</p>
3902
|programming|
Arduino Digitalwrite for while loop set
2014-08-24T00:23:01.767
<p>My question is simple. Does Arduino set the digitalwrite() the moment it is called or at the end of the while loop. E.G.</p> <pre><code>int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() {for(int i=0; i&lt;10; i++){ if(i%2==0){ digitalWrite(ledPin, HIGH); delay(1000);}else{ digitalWrite(ledPin, LOW); delay(1000); } } </code></pre>
<p>A key point of the Arduino 'language' is <em>every</em> statement is completed before the next one can begin. </p> <p>A simple statement has a '<code>;</code>' at the end of it.<br> Or followed by '<code>)</code>' instead of '<code>;</code>' in <code>for (...; ...; statement)</code> loop.</p> <p>So <code>digitalWrite()</code> will set the pin, HIGH or LOW, <em>before</em> it completes and allows the next statement, <code>delay(...)</code> to begin.</p> <p>Side note:<br> Actually <code>digitalWrite()</code> takes a small amount of time to do its work, so it is not <em>exactly</em> 'the moment' it is called. <code>digitalWrite()</code> <em>is</em> pretty quick, a few millionths of a second, which is usually near enough to be practically 'the moment' for most applications. </p>
3906
|bootloader|
How do I write an Arduino program to an AVR chip without the Arduino bootloader?
2014-08-24T04:22:05.830
<p>Is it possible to write an Arduino program to an AVR chip that does not have teh Arduino bootloader installed? What is the process to do so?</p>
<p>If there are no memory restrictions (too large program) which eliminates this option, I'd try to write the Arduino bootloader first and then continue normally. This has the advantage of simple reprogramming if required.</p>
3913
|programming|arduino-mega|c++|
ArrayList implementation fails for string object
2014-08-24T22:45:59.623
<p>I'm using a customised C++ implementation of ArrayList based on the method found in Processing. The original code is by <a href="https://gist.github.com/obedrios/2970053" rel="nofollow">Obed Isai Rios</a>, but I've added a <a href="https://gist.github.com/geotheory/263bef188b7a164bae87" rel="nofollow">version to Github with more explicit file structure</a>. The arraylist is appended to by the <code>add_string_item</code> method, which works ok in the format <code>arraylist-&gt;add_string_item("text string")</code> but fails when the same input is a String variable. The following script illustrates:</p> <pre><code>#include "ArrayList.h" void setup(){ ArrayList *list = new ArrayList("text1"); list-&gt;add_string_item("text2"); String str = "text3"; list-&gt;add_string_item(str); } void loop(){} </code></pre> <p>This fails on the last line with error message:</p> <pre><code>no matching function for call to 'ArrayList::add_string_item(String&amp;)' sketch_aug24b.ino: In function 'void setup()': sketch_aug24b:7: error: no matching function for call to 'ArrayList::add_string_item(String&amp;)' /Users/robinedwards/Documents/Arduino/libraries/ArrayList/ArrayList.h:17: note: candidates are: void ArrayList::add_string_item(char*) </code></pre> <p>I'm not familiar with C++ so can't figure out why this method accepts a string but not when assigned to a String object <code>str</code>. I'm pretty sure it's because I need to coerce to char* but not sure how to do this. I've tried <code>toCharArray</code> without success, although this seems the right direction. Very grateful for any assistance.</p> <p>ArrayList.cpp code:</p> <pre><code>#include "Arduino.h" #include "ArrayList.h" ArrayList::ArrayList(char* init){ stringlist = (char**)malloc(10*sizeof(char*)); stringlist[0] = init; this-&gt;size = 1; } ArrayList::~ArrayList(void) { } void ArrayList::add_string_item(char* item){ char **neulist = (char**)malloc((size+1)*sizeof(char*)); for(int i=0; i&lt;size; i++){ neulist[i] = stringlist[i]; } // neulist[size] = item; stringlist = neulist; size = size + 1; } void ArrayList::set_string_item(char* item, int index){ stringlist[index] = item; } void ArrayList::remove_selected_item(int index){ char **neulist = (char**)malloc((size-1)*sizeof(char*)); //From Begining for(int i=0; i&lt;index; i++){ neulist[i] = stringlist[i]; } //From next Index for(int i=index; i&lt;=size-1; i++){ neulist[i] = stringlist[i+1]; } //free(matrix); stringlist = neulist; size = size - 1; } void ArrayList::empty_list(){ size = 1; char **neulist = (char**)malloc((size)*sizeof(char*)); stringlist = neulist; stringlist[0] = "EMPTY"; } void ArrayList::display_string_list(){ Serial.begin(9600); for(int i=0; i&lt;size; i++){ Serial.println(stringlist[i]); } } char** ArrayList::get_stringlist(){ return this-&gt;stringlist; } char* ArrayList::get_item(int index){ return this-&gt;stringlist[index]; } void ArrayList::set_stringlist(char** stringlist){ this-&gt;stringlist = stringlist; } int ArrayList::get_size(){ return this-&gt;size; } </code></pre>
<p><em>In theory</em>, there's no reason why you shouldn't be able to call it by using <code>toCharArray()</code>. You would need to call it like this:</p> <pre><code>String str = "text3"; char * buf = new char[str.length()+1]; str.toCharArray(buf, str.length()+1); list-&gt;add_string_item(buf); </code></pre> <p>That allocates a <code>char</code> buffer, copies the string data into it, then passes that buffer pointer to the list to be stored. Note that the buffer is one character larger than the string, as it needs to add a null terminator at the end.</p> <p>However, there is a <strong>major</strong> problem with the rest of your code, which could eventually cause your Arduino to crash or do other strange things (depending on how much you use the list object).</p> <p>Unlike Java, C++ is not a garbage-collected language, meaning it won't automatically clean-up memory for you. If you call <code>new</code> or <code>malloc()</code> to allocate heap memory, you have to call <code>delete</code> or <code>free()</code> (respectively) when you're finished with it to deallocate it.</p> <p>Simply overwriting a pointer with another call to <code>malloc()</code> is not enough; it results in a <strong>memory leak</strong>. This means the block of memory it was previously using is lost, and cannot be reused again as long as the program is running. On a platform like Arduino, which has limited memory, you can very quickly run out.</p> <p>Fixing the design of your class is probably beyond the scope of an answer on this site. I would strongly recommend working through some C++ tutorials (of which there are hundreds online).</p> <p>As a side note, you should generally use <code>new</code>/<code>delete</code> instead of <code>malloc()</code>/<code>free()</code>. It doesn't make much difference when you're using arrays of <code>char</code> or <code>char*</code>, but it's important if you want to allocate class instances.</p>
3914
|flash|debugging|fuses|
What is the capability of AVRISP and USBASP on ATMega48, 328, 2560?
2014-08-25T09:45:41.580
<p>For use with ATMega 48 (old Arduino?), 328 (UNO, Pro Mini) and 2560 (Mega2560) chips, what is the capability for the AVRISP and USBASP programmers on:</p> <ol> <li><p>Can it read, write fuse?</p></li> <li><p>Can it read, write Program Flash?</p></li> <li><p>Can it work 3.3 and 5 volts?</p></li> <li><p>What workable clock frequency range on the MCU? </p></li> <li><p>Can it be used under Arduino ISP to write to board so as to erase the bootloader and use the FULL flash space for big user program (eliminate boot loader saves 0.5 to 8KB space on above Arduino boards)?</p></li> <li><p>Can it be used with ATMel factory software development tools (Atmel studio and associated tools) to use MCU on chip hardware based breakpoint (Debug wire, JTag, or other names, as on different MCU)?</p></li> </ol> <p>Many thanks in advance</p>
<ol> <li><p>Yes.</p></li> <li><p>Yes.</p></li> <li><p>Depends on the specific hardware. See the documentation for the <em>exact</em> variant you have.</p></li> <li><p>See 3.</p></li> <li><p>No. They have their own protocol that you must use instead. They are selectable from the <code>Programmer</code> menu in the IDE though. However, you must unprogram the fuse bits outside of the IDE.</p></li> <li><p>No. They are low-cost tools meant to be used for programming only. You will need an Atmel-supplied debugger in order to use Atmel Studio's debugging features.</p></li> </ol>
3916
|wifi|
Control Arduino via Wifi directly?
2014-08-25T12:21:54.420
<p>I want to build an arduino-based RC Tank, which should be controlled with a notebook or smartphone (Android). Bluetooth would be an easy solution, but the range is a bit short for a RC Vehicle, so I want to controll it via WIFI. I found a ton of examples and tutorials on how to do that but all of them reqire a router which both the arduino and the Smartphone are connected to. Any idea on how to directly control an Arduino with an smartphone via WIFI?</p>
<p>If your computer/tablet/phone can act as a WiFi hotspot, you could use that to avoid the router. Many smartphones have that capability, as do many notebooks (as geometrikal mentioned, it's usually referred to as an 'ad-hoc' network on PCs). Create the network (or turn on hotspot capability), and connect to the network you created from your Arduino. </p>
3917
|programming|c++|
Using an array as a queue
2014-08-25T13:16:49.477
<p>I recently created a state machine for my latest Arduino project. It is a simple LED control, but it has many different modes and functions. I created a template for my state machine so I can use it in the future, but I am looking to take it to the next level. Here is a copy of the current template for reference:</p> <pre><code>/*Setup Variables here*/ int nextState; int currState; /*Fill enum with all case names*/ enum cases{ init; idle; case1; case2; leave; }; /*Begin Program*/ void setup(){ Serial.begin(9600); currState = init; } void loop(){ switch(currState){ case init: /*Prepare program here*/ nextState = idle; break; case idle: if (input1){ nextState = case1; }else if (input2){ nextState = case2; }else{ nextState = idle; } case case1: //Code for case1 here break; case case2: //Code for case2 here break; } currState = nextState; } </code></pre> <p>I am trying to make a Queued State Machine (QSM). This means that instead of a single variable nextState, I can add several states to be executed. Is the best way to do this an array? I have not found much in my research about how to add and remove elements easily, so if this is the best way, could you point me towards a good tutorial on these types of array functions?</p> <p>Thanks in advanced for all the help!</p>
<p>Have an array with fixed size, and have <strong>two</strong> indexes. One pointing to the first/current item in the queue, the other to the last item in the queue.</p> <p>(It actually better/easier to have the second index point to where the next item has to be written)</p> <p>To add an item to the queue:</p> <ol> <li>Check that that the queue isn't full (second index is the same as the first)</li> <li>If not write to second index.</li> <li>Increment second index, and modulo array/queue size, so it wraps around.</li> </ol> <p>To read from the queue</p> <ol> <li>Read value at the first index</li> <li>Increment first index, modulo array/queue size</li> </ol>
3920
|uploading|arduino-leonardo|arduino-ide|debugging|
Why is Arduino STINO upload function not working?
2014-08-25T16:08:25.990
<p>I'm using sublime text for editing and modifying my arduino libraries. Sublime text is pretty pretty, useful and embed a very powerfull plugin system. Someone created an Arduino plugin for it. The compilation function works but the upload doesn't.</p> <p>I'm trying to upload on an arduino leonardo using Windows 7 x64.</p> <p>Did anyone tried to fix this problem ?</p>
<p>I finally found it: Problem was solved after commenting those three lines in */Arduino-like IDE/app/uploader.py:</p> <pre><code>if force_to_reset: pre_serial_port = serial_port wait_for_upload_port = self.args.get('upload.wait_for_upload_port', 'true') == 'true' serial_port = resetSerial(pre_serial_port, self.output_console, wait_for_upload_port) # if self.args['cmd'] != 'avrdude': # if serial_port.startswith('/dev/'): # serial_port = serial_port[5:] if serial_port: for cur_command in self.command_list: command_text = cur_command.getCommand() command_text = command_text.replace(pre_serial_port, serial_port) cur_command.setCommand(command_text) </code></pre>
3923
|arduino-mega|sd-card|
File Size Problem with EyeFi SD Card and Arduino Mega
2014-08-25T18:24:50.857
<p>I've been writing to an EyeFi SD card with an Arduino Mega. I've managed to get the files to upload wirelessly, but I noticed that my data gets cut off when the file reaches a size of 24 kb. If I use a normal SD card, the file is able to keep logging past 24 kb. The EyeFi card is able to upload large images, so I'm not sure what is limiting my file size for the EyeFi card. Can I get some advice?</p> <pre><code>/*************** SETUP ***************/ void setup(void) { Serial.begin(115200); // initialize the SD card Serial.print("Initializing SD card..."); pinMode(10, OUTPUT); // make sure that the default chip select pin is set to // see if the card is present and can be initialized: if (!SD.begin(10,11,12,13)) { error("Card failed, or not present"); } Serial.println("Card initialized"); // see if the directory exists, create it if not. if( !SD.exists(directory) &amp;&amp; !SD.mkdir(directory) ) error("File directory not created"); newFile(); Serial1.begin(115200); while (Serial1.peek() != '!' ) Serial1.read(); i = 0; } /*************** MAIN LOOP ***************/ void loop(void) { if (Serial1.available()) { logfile.print( (char)Serial1.read() ); i++; } if (i &gt;= SOFT_BUFFER_SIZE) { logfile.flush(); if( logfile.size() &gt; 20480 &amp;&amp; logfile.size() &lt; (20480 + SOFT_BUFFER_SIZE) ) Serial.println("Minimum File Size Achieved."); i = 0; } } </code></pre>
<p>After some testing and research, I found out that the Eye-Fi SD card starts a transfer once a file reaches 20kb or more and will not upload a file again once it has been transfered already. The solution, as suggested by ChrisStratton, is to log to a temporary file and trigger a transfer once the file is ready.</p> <p>I took advantage of the fact that the Eye-Fi only transferring files in the standard camera folders. In my case, I used the Nikon naming convention: DCIM/100NIKON/DSCNxxxx.JPG (xxxx is the photo number ranging from 0000 to 9999), but there are also others. Check on the Eye-Fi website for compatible cameras. I created a temporary file called TEMP.TMP and stored it to the root folder of the card and logged to it. Once I'm ready to transfer the file, TEMP.TMP gets renamed to "DCIM/100NIKON/DSCNxxxx.JPG" and the whole file is transferred all at once.</p> <p>Here's my code. I'm using the software serial (pins 10, 11, 12, 13) of the Mega:</p> <pre><code>//Running with 256kb serial buffer (modified HardwareSerial.cpp) //Added file time stamps #include "SdFat.h" #include "SdFatConfig.h" #include &lt;Wire.h&gt; #include "RTClib.h" #define SYNC_INTERVAL 1000 // mills between calls to flush() - to write data to the card uint32_t syncTime = 0; // time of last sync() #define ECHO_TO_Serial 1 // echo data to Serial port #define WAIT_TO_START 0 // Wait for Serial input in setup() #define MESSAGE_SIZE 11 // Message size of "!G N +1234" + CR #define SOFT_BUFFER_SIZE 256// 25 Messages of 11 chars each const uint8_t chipSelect = 10; SdFat sd; SdFile logfile; //create log file RTC_DS1307 RTC; DateTime filedate; uint16_t date; uint16_t time; int i = 0; int x = 0; char directory[] = "DCIM/100NIKON"; char filename[] = "DCIM/100NIKON/DSCN0000.JPG"; char tempfile[] = "TEMP.TMP"; /*************** ERROR ***************/ void error(char *str) { Serial.print("error: "); Serial.println(str); while(1); } /*********** TEMP FILE CREATION ***********/ void newFileName() { sd.chdir("/"); //check DCIM/100NIKON directory // create a temp file for (uint16_t i = 0; i &lt; 10000; i++) { filename[18] = i/1000 + '0'; filename[19] = (i/100)%10 + '0'; filename[20] = (i/10)%10 + '0'; filename[21] = i%10 + '0'; if (! sd.exists(filename)) { Serial.print("New file name: "); Serial.println(filename); break; // leave the loop! } } } /****** call back for file timestamps *****/ void dateTime(uint16_t* date, uint16_t* time) { DateTime now = RTC.now(); // return date using FAT_DATE macro to format fields *date = FAT_DATE(now.year(), now.month(), now.day()); // return time using FAT_TIME macro to format fields *time = FAT_TIME(now.hour(), now.minute(), now.second()); } /*************** SETUP ***************/ void setup(void) { Serial.begin(115200); Wire.begin(); RTC.begin(); if(! RTC.isrunning() ) Serial.println("RTC is not running"); // set date time callback function SdFile::dateTimeCallback(dateTime); // initialize the SD card Serial.print("Initializing SD card..."); // see if the card is present and can be initialized: if (! sd.begin(chipSelect, SPI_HALF_SPEED)) error("Card failed, or not present"); Serial.println("Card initialized"); // see if the directory exists, create it if not. sd.chdir("/"); if( !sd.exists(directory) &amp;&amp; !sd.mkdir(directory) ) error("File directory not created"); // create new file name newFileName(); // Scan root folder for temp files sd.chdir("/"); while( logfile.openNext(sd.vwd(), O_READ)){ if( !logfile.isDir() ) { logfile.printName(&amp;Serial); if( logfile.fileSize() &lt; 20480 ){ Serial.print(" file size too small. "); Serial.print(logfile.fileSize()); Serial.println(" bytes."); logfile.remove(); //Delete under sized files }else if( !logfile.rename(sd.vwd(), filename)) error(" could not be renamed."); else{ Serial.print(" renamed to "); Serial.println(filename); } } logfile.close(); } // create temp file sd.chdir("/"); if(!logfile.open(tempfile, O_WRITE | O_CREAT)) // only open a new file if it doesn't exist error("couldnt create temp file"); Serial1.begin(115200); // Rotate the buffer for( int j = 0; j &lt; 256; j++) { Serial1.read(); } // Look for the '!' character while (Serial1.peek() != '!' ) Serial1.read(); Serial.println("Logging..."); Serial.println(); // Reset buffer index to 0 i = 0; } /*************** MAIN LOOP ***************/ void loop(void) { if (Serial1.available()){ logfile.print( (char)Serial1.read() ); i++; } if (i &gt;= SOFT_BUFFER_SIZE) { logfile.sync(); i = 0; } } </code></pre>
3924
|bootloader|
Uploading bootloader on ATmega328P SMT package using Arduino Uno
2014-08-24T16:29:30.187
<p>I have been trying to upload bootloader on ATmega328P SMT package on a custom PCB using Arduino Uno as ISP, I was quite successful. </p> <p>I have Googled a lot and have tried numerous ways, sometimes I was able to successfully upload the bootloader, but I am not able to upload the sketch am getting "avr sync error".</p> <ul> <li><p>What kind of bootloader should I use for this particular package?</p></li> <li><p>How should I upload the sketches into the chip?</p></li> </ul>
<p>I've had success with bootloader of the Arduino IDE. I used to have some trouble uploading sketches, but I solved them by doing this:</p> <ol> <li>If the atmega is already soldered in a pcb and you have a pull up resistor, or something else connected to the reset pin, disconnect it. reset pin must be free.</li> <li>Connect the tx, rx and rst pins of your atmega to your arduino.</li> <li>Press the Upload button in the Arduino IDE and see the leds tx,rx in your arduino, just after the first blink, press the reset button, after that both of the leds should start blinking and in the end your code should be uploaded.</li> </ol>
3931
|arduino-uno|power|led|
What's the best way to control a USB-powered desk light
2014-08-26T14:27:00.367
<p>I recently bought a USB-powered desk light. Is it possible to control (turn on/off) it with the Arduino Uno? The desk light has 3W so needs 600mA.</p> <ol> <li>Should I connect the USB wire with the 5V pin of the Arduino (which can spend up to 800mA) or should I use an external USB power supply ?</li> <li>How to control the light when using an external USB power supply ?</li> </ol>
<p>Use a TIP120 Darlington transistor to switch the current. This webpage has a detailed guide. <a href="http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/" rel="nofollow">http://bildr.org/2011/03/high-power-control-with-arduino-and-tip120/</a> Use the example with the light bulb - no diode is needed in your case.</p>
3944
|software|isp|
What software is available for use with AVRISP and USBASP on ATMega48, 328, 2560?
2014-08-27T14:25:02.967
<p>What software is available for use with AVRISP and USBASP on ATMega328, 2560 for read/write fuse, flash and EEPROM for UNO, Pro Mini and Mega2560 board?</p> <p>(a fact question not opinion) Which software did you use? </p> <p>Did it work straight forward (like the software did all the needed 'auto select')? </p> <p>Does it need human selection for options, etc. on the above 3 boards?</p> <p>Do I need WinAVR installed before able to use the 'ISP software'?</p>
<p>As Ignacio Vazquez-Abrams mentioned, you should look into <a href="http://www.atmel.com/tools/atmelstudio.aspx" rel="nofollow">Atmel Studio</a>. You can use a 3rd party AVR programmer (Arduino w/isp) or one from Atmel. The IDE is awesome and has a lot of features like setting fuse bits.</p>