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
18103
|bootloader|
Problem in Uploading a Bootloader to Atmega8A
2015-11-25T12:39:28.197
<p>I am getting an error while Uploading the Bootloader to Atmega8A I am selecting..</p> <pre><code> Board -&gt; Arduino NG and Older Processor -&gt; Atmega8A Programmer -&gt; USBasp </code></pre> <p>and sketch code is ArduinoISP, After selecting port then I do "Burn Bootloader"</p> <p>But getting an error of...</p> <pre><code> "efuse" memory type not defined for part "ATmega8" Error while burning bootloader. </code></pre> <p>Please tell me what to do. Any help will be appreciated.</p> <p>Thank you</p>
<p>I used Programmer "AVRUPro+" for Uploading Program. I downloaded its Software "Progisp" Then I did some few steps....</p> <p>1) After downloading it, Run the Progisp.exe file.<br> 2) Then went to Command tab, and clicked “Program Fuse”, It just did my fuse set.<br> 3)Then I just did the simple process of burning the bootloader to my Atmega Controller.<br> 4)After this I was able to upload my program to my new Atmega Controller.</p> <p>Thank you</p>
18120
|programming|arduino-mega|avr|input|
How to check if a pin is set from bank?
2015-11-25T22:02:15.030
<p>How would you go about checking if an input pin has been set using the entire bank? I am thinking that I need to use bit twiddling with a bit mask but I have not used this enough to figure out how to do what I want.</p> <p>Basically I have the following code:</p> <pre><code>void setup() { DDRA = 0x00; PORTA = 0xff; } void loop(){ //Check if any pin from Port A has been pressed if (PINA &amp; 0xff){ //do stuff } } </code></pre> <p>But the code above is not working how I expected it to. Has anyone tried to use this approach before? Am I going about this the wrong way? I figured since I was using all 8 pins from one bank, it would be better to check if any of the pins on that bank have been set instead of checking each individual pin. My thinking on this was to prevent any user input from being skipped in case a button press was initiated while the program was running other code. This way I only check if anything in the bank has been set saving time (I think).</p>
<p>The problem is here:</p> <blockquote> <pre><code>//Check if any pin from Port A has been pressed if (PINA &amp; 0xff){ </code></pre> </blockquote> <p>Since the pullups are enabled, the default state of the pins is high. To detect a "press", they have to be pulled to ground. This changes the test to:</p> <pre><code>//Check if any pin from Port A has been pressed if (~PINA) { </code></pre> <p>And for individual pins:</p> <pre><code>//Check if PA3 has been pressed if (!(PINA &amp; _BV(PA3))) { </code></pre>
18126
|ethernet|
Is there something I can use to control Arduinos easily over Ethernet with .NET?
2015-11-26T00:12:11.157
<p>I'm wondering if there's anything out there that maybe works pretty similarly to Firmata, runs on Unos or Megas, and can be controlled over Ethernet. I am writing a home automation system with .NET, and I see some options for supporting Firmata with .NET, but I want to be able to connect my devices over Ethernet.</p>
<p>I don't use .net but I have done this using php website to control a door lock over ethernet.</p> <p>My solution was to use the ethernet to recieve commands and be able to use them on the arduino through http calls. And when it was done send a http call back to the server with some data. I was doing a door lock program for example. Please ignore anything talking about doors, locking, unlocking, or other requirements to certain calls, I am just providing examples about how it COULD be used, not that you need to include my door lock code in your project to get it to work.</p> <p>As far as how that works out with .net that's up to you, however I can give you a hand getting your messages back and forth.</p> <p>first you want to create the ethernet connection to your router. put this in your header section.</p> <pre><code>#include &lt;UIPEthernet.h&gt; // assign a MAC address for the ethernet controller. // fill in your address here: byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // fill in an available IP address on your network here, // for manual configuration: IPAddress ip(127, 0, 0, 1); // initialize the library instance: EthernetClient client; char server[] = "www.example.com"; //IPAddress server(127,0,0,1); // numeric IP for www.example.com (no DNS) int waitTime = 3L; unsigned long lastConnectionTime = 0; // last time you connected to the server, in milliseconds const unsigned long postingInterval = waitTime * 1000L; // delay between updates, in milliseconds // the "L" is needed to use long type numbers </code></pre> <p>throw this in your main loop so it doesn't constantly make http requests spamming a server.</p> <pre><code>// if ten seconds have passed since your last connection, // then connect again and send data: if (millis() - lastConnectionTime &gt; postingInterval || buttonState == 0) { httpRequest(); } </code></pre> <p>Create a method to handle httpRequest because shoving everything under the main is kinda sloppy.</p> <p>Alright so there will be quite a bit here because http headers are kinda lengthy.</p> <pre><code>// this method makes a HTTP connection to the server: void httpRequest() { // close any connection before send a new request. // This will free the socket on the WiFi shield client.stop(); // if there's a successful connection: if (client.connect(server, 80)) { Serial.println("connecting..."); // send the HTTP PUT request: Serial.println("String is " + readString); if(readString == "Ready" || readString == ""){ client.println("GET /command.txt HTTP/1.1"); where = "web"; waitTime = 5L; } else{ // here is the basic format of sending a get command //this specific request is so that I can tell where the command came from. I had a web client / mobile app that could control the door AND you could also control it from a physical buttom. The door would have to reply either way to the web server (READ: .net application) in order to have the correct status always show up on the web end. client.print("GET /update.php?where=Arduino&amp;command=Ready&amp;status="); if(readString == "Reset"){ client.print("Reset"); } else if(isLocked){ client.print("Locked"); } else{ client.print("Unlocked"); } client.println(" HTTP/1.1"); waitTime = 1L; } client.println("Host: www.example.com"); client.println("User-Agent: arduino-ethernet"); client.println("Connection: close"); client.println(); // note the time that the connection was made: lastConnectionTime = millis(); } else { // if you couldn't make a connection: Serial.println("connection failed"); } } </code></pre> <p>TL;DR if you wanna use ethernet you need to use all of ethernet. Start by creating your connection to the router statically (watch for conflicts).</p> <p>Then create a method of watching for incoming data or waiting for a command if there isn't one. (server call).</p> <p>Then create A FULL HTTP REQUEST in order to pass your request through. Shorting any parts of this last part and you will either end up with bad request errors or will simply fail.</p> <p>Let me know if you need anything else or if this was useful to you!</p>
18138
|arduino-uno|
Updated Arduino IDE and Arduino not working
2015-11-25T23:02:21.080
<p>I've had the 1.0.5 IDE on my PC, which worked great. Now I've just decided to update to 1.6.6. After some stupid Java errors and trial and error, I got it to work.</p> <p>I recompiled my project. Massive errors. Fixed the errors and compiled again.</p> <p>It stated "Uploading..." That took much longer than before, but I saw the "This takes xxx memory and xxx bytes on the device" yadi yadi ya.</p> <p>I decided to unplug the Arduino, swap some jumpers and reconnect it (as I've always done). Only this time - I hear 3 beeps from my PC (the sound you hear with broken USB devices). The COM port is no longer recognized.</p> <p>How do I fix this? Did that IDE upgrade just brick my Arduino?</p>
<p>Allright, seems to be fixed. After a 3rd reinstall it seems like its fixed. I reinstalled the whole package, including the drivers, and now it seems to recognize the device again.</p> <p>Also the compiling now stops properly when done and shows "upload complete".</p>
18141
|arduino-ide|
Documentation for creating a Board Manager profile for the Arduino IDE
2015-11-26T11:19:06.770
<p>I'd like to write a Board Manager profile for some Arduino boards that I have. So far I've struck out on finding the documentation on the format and contents of the files. Does anybody know where I can find it?</p>
<p>Arduino has provided comprehensive official documentation. You may not have found it because, since this is developer documentation rather than something the average Arduino user needs, it is published in the wiki of the Arduino IDE GitHub repository rather than with the standard documentation on <a href="https://www.arduino.cc/" rel="nofollow noreferrer">arduino.cc</a>.</p> <h3>Hardware Package</h3> <p><a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification" rel="nofollow noreferrer">https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5-3rd-party-Hardware-specification</a></p> <h3>Boards Manager Support Files</h3> <ul> <li><p>JSON Index File: <a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification" rel="nofollow noreferrer">https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification</a></p></li> <li><p>Boards Manager installation archive: <a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#installation-archive-structure" rel="nofollow noreferrer">https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.6.x-package_index.json-format-specification#installation-archive-structure</a></p></li> </ul>
18147
|programming|arduino-mega|library|lcd|u8glib|
Problems with Draw Loop using u8glib
2015-11-26T17:55:51.770
<p>I am using an Arduino Mega and a 12864ZW LCD with the u8glib library and the following code to draw to the LCD:</p> <pre><code>U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE); void loop(){ Draw(); } void Draw(){ Display.firstPage(); do{ Display.setPrintPos(10, 10); Display.print("This is a test"); }while(Display.nextPage()); } </code></pre> <p>The problem is that the display is constantly redrawing itself. When I used LCD displays in the past, they usually only required to write to the LCD once unless you wipe the display. When I adjusted the code to:</p> <pre><code>U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE); bool needsUpdate = true; void loop(){ Draw(); } void Draw(){ if (needsUpdate){ Display.firstPage(); do{ Display.setPrintPos(10, 10); Display.print("This is a test"); }while(Display.nextPage()); needsUpdate = false; } } </code></pre> <p>I do not get anything drawn on the LCD. Is there a parameter that needs to be set so I only have to redraw the LCD if something changes? Am I using an outdated library? Is there a better library I should be using?</p> <p><strong>EDIT</strong></p> <p>I think the main problem I have with using this library is does the Draw loop need to be executed continuously to display on the LCD or is there a way to only draw the screen once until it is needed to be drawn again?</p>
<p>Much thanks to jwpat7 for getting me on the right track with this. So I found out how this LCD should really be setup. I am not sure why the examples I was able to find online and even on the u8glib wiki showed the usage like my question but I was able to get this library functioning right. </p> <p>First thing is the .firstPage() and .nextPage() functions. The .firstPage() function actually clears the screen and the .nextPage() function displays what is waiting in the queue (thanks jwpat7). When the .nextPage() finishes there is no need to write to the LCD again until you need a refresh. I put together a very simple code example that uses a input to change the text without having to continuously update the LCD.</p> <pre><code>U8GLIB_ST7920_128X64 Display(LCD_E_PIN, LCD_RW_PIN, LCD_RS_PIN, U8G_PIN_NONE); bool redraw = true; String strOut = "This is a test..."; void loop() { if (redraw){ Display.firstPage(); //Clear the LCD //Main Difference while the LCD needs drawing will return 1 while(Display.nextPage()){ Display.setFont(u8g_font_04b_03b); Display.setPrintPos(20, 20); Display.print(strOut); } redraw = false; //Clear flag to redraw } //check if any of the pins in PINA have been pressed if (~PINA &amp; 0xff){ strOut = "Of the emergency broadcast ..."; redraw = true; //Set flag to redraw the screen } } </code></pre>
18154
|arduino-mega|relay|
How does this eBay relay board connect to the Arduino
2015-11-26T19:57:41.183
<p>I bought a <a href="http://www.ebay.com/itm/5V-10A-one-1-Channel-Relay-Module-With-optocoupler-For-PIC-AVR-DSP-ARM-Arduino-/310636242802" rel="nofollow noreferrer">single channel relay</a> on eBay and besides the NC/COM/NO, it has six pins and a jumper.</p> <p><a href="https://i.stack.imgur.com/PicO1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PicO1.jpg" alt="relay"></a></p> <p>It is not possible to see the labels on the image, but the labels are:</p> <pre><code>X X--X X X X VCC -IN+ GND </code></pre> <p>The default jumper position is shown above with a <code>-</code> mark.</p> <p>Which pins should I use for VCC, GND and ARDUINO? Is the jumper on the correct position?</p>
<p>You should do a bit of testing. The Vcc and GND pins will go to power and ground respectively. They are powering the circuitry on the board that protects the Arduino from the relay coil. Then it looks like the IN pins allow you to operate the relay either from an active high or an active low signal.</p> <p>If you have a DMM check the connections of the pins (see if any of them are common). The thing that is puzzling to me is the jumper, but it may be set up so that you can use only two wires to control the relay by using the IN terminal to also supply either Vcc or ground.</p> <p>So start out by hooking up to power and ground, and then test by jumping the IN pins to ground and power in turn. I would expect the relay to operate when the IN+ goes to Vcc or when the IN- goes to GND.</p>
18163
|attiny|nrf24l01+|temperature-sensor|
Using ATtiny85, NRF24L01+, DHT2: can't get data from DHT22
2015-11-26T21:37:09.903
<p>I am trying to make a sensor that gets temperature and humidity values from a DHT22 and send it through NRF24L01+ to a Raspberry Pi 2 Model B.</p> <p>To connect NRF24L01+ to ATtiny85 and to free two pins for the DHT22, I used <a href="http://hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2" rel="nofollow noreferrer">this link</a>.</p> <p>There is a scheme of my sensor: <a href="https://i.stack.imgur.com/Ip0Y4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ip0Y4.png" alt="enter image description here"></a></p> <p>There is a photo of the test board with the sensor (sorry, it is very untidy, because I remade it many times before to fix the problem): <a href="https://i.stack.imgur.com/52X6K.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/52X6K.jpg" alt="enter image description here"></a></p> <p>I program the ATtiny85 with Arduino IDE (with 8 MHz clock).</p> <p>I used <a href="http://github.com/TMRh20/RF24" rel="nofollow noreferrer">this library</a> and radio communication is working perfectly (it can't be an error during the radio transmission).</p> <p>Here is the code of my ATtiny85:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;DHT.h&gt; #include &lt;RF24.h&gt; byte currentNodeAddr[6] = "1Node"; // Address of this node // Struct for sending measured data struct Data { uint16_t temp; // Temperature value uint16_t hum; // Humidity value int status; // DHT22 module status } data; RF24 radio(2,2); // Create instance of RF24 radio object DHT dht; // Create instance of DHT22 module object void setup() { // Set up the radio radio.begin(); radio.openWritingPipe(currentNodeAddr); radio.stopListening(); dht.setup(3); // Set up the sensor on PB3 pin } void loop() { // This DHT library can calculate the delay but it may be 2+ sec delay(dht.getMinimumSamplingPeriod()); // Get values from DHT22 data.temp = dht.getTemperature(); data.hum = dht.getHumidity(); radio.write(&amp;data, sizeof(Data)); // Send data to the Raspberry } </code></pre> <p>But I can't the get temperature and humidity values from the DHT22. I used a lot of different libraries for DHT22 (for example, <em>github.com/ringerc/Arduino-DHT22, github.com/nethoncho/Arduino-DHT22, github.com/jscrane/DHT22</em>, etc.) and none of them works (they return zeros, NAN, or, generally, timeout error). And it seems that the connection with the DHT22 is correct (there were connection errors and I fixed them). I tried to use a lot of DHT22 modules, so the problem can't be a defective module.</p> <p>Yes, I put a 2 second (and more) delay in between read requests. Yes, I added a 10k resistor between pin 1 and 2 of the DHT22.</p> <p>Now I am thinking that the libraries work fine, but may be free pins (PB3 or PB4) of ATtiny85 can't receive data for some reason.</p> <p>Tell me please where may be an error or a bug? Thank you in advance! And also many thanks to authors of all links and repositories that I have mentioned here!</p> <p><strong>EDIT (in accordance with frarugi87's answer):</strong></p> <p>At first I have grounded 3 and 4 pins of the DHT22.</p> <p>When I program ATtiny at the <strong>1 MHz</strong>, values are sent every 2 seconds (as it should be), but when I program ATtiny at <strong>8 MHz</strong>, values are sent every 16 seconds (is it correct?).</p> <p>I used the suggested code to check the radio library and it seems it works pretty well (values are being incremented and sent): <a href="https://i.stack.imgur.com/m8oH8.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/m8oH8.png" alt="Test radio library"></a></p> <p>After that I used the suggested library (<a href="https://github.com/RobTillaart/Arduino" rel="nofollow noreferrer">RobTillaart/Arduino</a> v. 0.1.21) and at first time it returned some strange values (humidity and the status were 0 and temperature was MAX_INT value), but when I have tried to get only status value as string, the library also has returned -2 (DHTLIB_ERROR_TIMEOUT). This time I program ATTiny at 8 MHz: <a href="https://i.stack.imgur.com/XnmDS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XnmDS.png" alt="enter image description here"></a></p> <p>Also I tried to get values without NRF24L01+ through I2C connection between the ATtiny85 and the Raspberry Pi. Result was the same (DHTLIB_ERROR_TIMEOUT): <a href="https://i.stack.imgur.com/RcpKr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RcpKr.png" alt="enter image description here"></a></p> <p>Maybe the problem is in timings of ATtiny85 or in the program process? I used these links (<a href="http://spellfoundry.com/sleepy-pi/setting-arduino-ide-raspbian/" rel="nofollow noreferrer">1</a>, <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=42&amp;t=76639" rel="nofollow noreferrer">2</a>, <a href="https://projects.drogon.net/raspberry-pi/gertboard/arduino-ide-installation-isp/" rel="nofollow noreferrer">3</a>) to set up Arduino IDE on Raspbian.</p> <p><strong>Here is list of useful links for this project which I found to implement it (I hope the authors will not mind that I posted their links here)</strong>:</p> <p>Arduino/AVR DHT projects and libraries:</p> <ul> <li><a href="http://www.instructables.com/id/Arduino-Wireless-Weather-Station/" rel="nofollow noreferrer">Arduino Wireless Weather Station</a></li> <li><a href="http://www.instructables.com/id/Mini-weather-station-with-Attiny85/" rel="nofollow noreferrer">Mini weather station with Attiny85</a></li> <li><a href="http://www.instructables.com/id/Esay-IoT-Weather-Station-With-Multiple-Sensors/" rel="nofollow noreferrer">Easy IoT weather station with multiple sensors</a></li> <li><a href="https://github.com/nathanchantrell/TinyTX" rel="nofollow noreferrer">ATtiny84 &amp; RFM12B wireless sensor node</a></li> <li><a href="http://www.uugear.com/portfolio/dht11-humidity-temperature-sensor-module/" rel="nofollow noreferrer">DHT11 HUMIDITY &amp; TEMPERATURE SENSOR MODULE</a></li> <li><a href="http://forum.arduino.cc/index.php?topic=269216.0" rel="nofollow noreferrer">DHT22 running @ 8MHZ</a></li> <li><a href="http://forum.arduino.cc/index.php?topic=97915.0" rel="nofollow noreferrer">DHT22 not working with 8mhz clockspeed?</a></li> <li><a href="http://forum.arduino.cc/index.php?topic=124457" rel="nofollow noreferrer">Adafruit DHT Library and ATtiny85</a></li> <li><a href="http://playground.arduino.cc/Main/DHTLib" rel="nofollow noreferrer">Class for DHTxx sensors</a></li> <li><a href="https://github.com/markruys/arduino-DHT" rel="nofollow noreferrer">An Arduino library for reading the DHT family of temperature and humidity sensors</a></li> <li><a href="http://blog.ringerc.id.au/2012/01/using-rht03-aliases-rht-22.html" rel="nofollow noreferrer">Using a RHT03 (aliases: RHT-22, DHT22, AM2302) temperature/humidity sensor from Arduino</a></li> <li><a href="https://github.com/amperka/dht" rel="nofollow noreferrer">Arduino-library for DHT11/DHT22 sensors reading</a></li> <li><a href="https://github.com/markruys/arduino-DHT" rel="nofollow noreferrer">Efficient DHT library for Arduino</a></li> <li><a href="http://www.pgollor.de/cms/?page_id=1013" rel="nofollow noreferrer">Feuchtesensor AM2302/DHT22</a></li> <li><a href="http://www.instructables.com/id/7-Segment-Digital-Thermometer-using-ATtiny-85/?ALLSTEPS" rel="nofollow noreferrer">7 Segment Digital Thermometer using ATtiny 85</a></li> <li><a href="https://learn.adafruit.com/dht-humidity-sensing-on-raspberry-pi-with-gdocs-logging/wiring" rel="nofollow noreferrer">Wiring up DHT humidity sensors</a></li> <li><a href="http://www.instructables.com/id/Attiny85-RF-Transmitter-to-Arduino-Uno-Receiver-Ma/" rel="nofollow noreferrer">Attiny85 RF Transmitter to Arduino Uno Receiver</a></li> <li><a href="https://github.com/nethoncho/Arduino-DHT22" rel="nofollow noreferrer">Arduino library for the DHT22 humidity and temperature sensor</a></li> <li><a href="https://github.com/adafruit/DHT-sensor-library" rel="nofollow noreferrer">Arduino library for DHT11DHT22, etc Temp &amp; Humidity Sensors</a></li> <li><a href="https://github.com/adafruit/TinyDHT" rel="nofollow noreferrer">A simplified DHT11/DHT22/AM2302 library for use with the Trinket/Gemma</a></li> <li><a href="https://github.com/nathanchantrell/Arduino-DHT22" rel="nofollow noreferrer">Arduino library for the DHT22 humidity and temperature sensor </a></li> <li><a href="https://github.com/ringerc/scrapcode/blob/master/arduino_avr/RHT03_DHT22_humidity_temp_sensor.c" rel="nofollow noreferrer">Arduino sketch code for reading RHT03 (also known as DHT22, RHT22, and AM2302) temperature/humidity sensor</a></li> </ul> <p>Arduino/AVR nRF24L01 projects and libraries:</p> <ul> <li><a href="https://github.com/TMRh20/RF24" rel="nofollow noreferrer">Optimized fork of nRF24L01 for Arduino and Raspberry</a></li> <li><a href="https://github.com/TMRh20/RF24Network" rel="nofollow noreferrer">Optimized Network Layer for nRF24L01(+) Radios on Arduino and Raspberry Pi</a></li> <li><a href="http://nerdralph.blogspot.ru/2014/01/nrf24l01-control-with-3-attiny85-pins.html" rel="nofollow noreferrer">nrf24l01+ control with 3 ATtiny85 pins</a></li> <li><a href="https://hallard.me/nrf24l01-real-life-range-test/" rel="nofollow noreferrer">NRF24L01 real life range test</a></li> <li><a href="https://github.com/edoardoo/RF24" rel="nofollow noreferrer">Optimized fork of nRF24L01 for Arduino and Raspberry Pi</a></li> <li><a href="https://www.itead.cc/blog/nrf24l01-six-channels-to-one-receiver" rel="nofollow noreferrer">NRF24L01 SIX CHANNELS TO ONE RECEIVER</a></li> <li><a href="https://github.com/stanleyseow/attiny-nRF24L01" rel="nofollow noreferrer">Arduino attiny support files for nRF24L01 RF modules</a></li> <li><a href="http://hack.lenotta.com/arduino-raspberry-pi-switching-light-with-nrf24l01/" rel="nofollow noreferrer">ARDUINO + RASPBERRY PI Switching light with NRF24l01+</a></li> </ul> <p>Programming the ATtiny85 from Raspberry-Pi:</p> <ul> <li><a href="http://www.instructables.com/id/Programming-the-ATtiny85-from-Raspberry-Pi/?ALLSTEPS" rel="nofollow noreferrer">Programming the ATtiny85 from Raspberry Pi</a></li> <li><a href="https://projects.drogon.net/raspberry-pi/gertboard/arduino-ide-installation-isp/" rel="nofollow noreferrer">Arduino IDE Installation</a></li> <li><a href="http://playground.arduino.cc/Main/ArduinoOnOtherAtmelChips" rel="nofollow noreferrer">Arduino for other Chips</a></li> <li><a href="https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/attiny85-use-hints" rel="nofollow noreferrer">Tiny AVR Programmer Hookup Guide</a></li> <li><a href="https://www.raspberrypi.org/forums/viewtopic.php?f=42&amp;t=76639" rel="nofollow noreferrer">ATtiny85 with Arduino IDE and Gertboard</a></li> <li><a href="http://spellfoundry.com/sleepy-pi/setting-arduino-ide-raspbian/" rel="nofollow noreferrer">Setting up the Arduino IDE on Raspbian</a></li> </ul> <p>Arduino/AVR FR433 libraries:</p> <ul> <li><a href="https://github.com/ninjablocks/433Utils" rel="nofollow noreferrer">433Kit is a collection of code and documentation designed to assist you in the connection and usage of RF 433MHz transmit and receive modules to/with your Arduino and Rapberry Pi</a></li> <li><a href="https://learn.sparkfun.com/tutorials/tiny-avr-programmer-hookup-guide/attiny85-use-hints" rel="nofollow noreferrer">Tiny AVR Programmer Hookup Guide</a></li> </ul> <p>Troubleshooting:</p> <ul> <li><a href="https://community.particle.io/t/wrong-reading-value-for-dh22-get-stuck-after-running-for-a-while/11271" rel="nofollow noreferrer">Wrong reading value for DH22 &amp; get stuck after running for a while</a></li> <li><a href="http://forum.arduino.cc/index.php?topic=91569.0" rel="nofollow noreferrer">DHT22 Sensor - sync timeout</a></li> </ul>
<p>Thanks to Rob Tillaart, the autor of the Arduino DHT <a href="https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib" rel="nofollow">library</a> suggested by @frarugi87 (also thank him), the problem has been solved (see <strong><a href="https://github.com/RobTillaart/Arduino/issues/30" rel="nofollow">this issue</a></strong> for more information).</p> <p>In my case <strong>to fix the problem</strong> there is only needed to to set a specific value of <code>DHTLIB_TIMEOUT</code> by leaving the definition <code>#define DHTLIB_TIMEOUT 1000</code> in the <code>dht.h</code> file of this library and commenting other definitions written next to it:</p> <pre><code>// #ifndef F_CPU #define DHTLIB_TIMEOUT 1000 // should be approx. clock/40000 // #else // #define DHTLIB_TIMEOUT (F_CPU/40000) // #endif </code></pre> <p>The ATtiny is programmed on 8 MHz. The DHT22 is working at a voltage of 3.3V with a <strong>3K3</strong> resistor.</p> <p>The cause of the problem may be the way I program the ATtiny85 with old version of Arduino IDE installed in the Raspberry Pi (see comments to the @frarugi87's answer). </p> <p>Libraries used:</p> <ul> <li><a href="https://github.com/RobTillaart/Arduino/tree/master/libraries/DHTlib" rel="nofollow">RobTillaart/Arduino DHT11, 21, 22, 33 library</a></li> <li><a href="https://github.com/maniacbug/RF24" rel="nofollow">Arduino driver for nRF24L01 http://maniacbug.github.com/RF24</a></li> </ul> <p>Here is the final code of the ATtiny85 transmitter and the Raspberry Pi reseiver respectively (<strong>I took the most part of the code from different examples of RF24 libraries and DHT libraries! Excuse me, if the code is not tidy.</strong>).</p> <p><strong>NRF24Transmitter.ino:</strong></p> <pre><code>#include &lt;dht.h&gt; #include &lt;RF24.h&gt; #define DHT22_PIN 3 #define LONG_DELAY_MS 900000 byte currentNodeAddr[6] = "1Node"; // Address of this node // Struct for sending measured data struct Data { float temp; // Temperature value float hum; // Humidity value int status; // DHT22 module status } data; RF24 radio(2,2); // Create instance of RF24 radio object dht DHT; // Create instance of DHT22 module object void setup() { // Set up the radio radio.begin(); radio.openWritingPipe(currentNodeAddr); radio.stopListening(); } void loop() { unsigned long startMillis = millis(); while (millis() - startMillis &lt; LONG_DELAY_MS); do { data.status = DHT.read22(DHT22_PIN); data.temp = DHT.temperature; data.hum = DHT.humidity; if (data.status != DHTLIB_OK) { delay(1000); } } while(data.status != DHTLIB_OK); radio.write(&amp;data, sizeof(Data)); // Send data to the Raspberry } </code></pre> <p><strong>Receiver.cpp:</strong></p> <pre><code>#include &lt;cstdlib&gt; #include &lt;iostream&gt; #include &lt;sstream&gt; #include &lt;string&gt; #include &lt;unistd.h&gt; #include &lt;RF24/RF24.h&gt; using namespace std; uint8_t addresses[][6] = {"1Node", "2Node", "3Node", "4Node", "5Node"}; // Struct for sending measured data struct Data { float temp; // Temperature value float hum; // Humidity value int status; // DHT22 module status } data; RF24 radio(RPI_V2_GPIO_P1_22, RPI_V2_GPIO_P1_24, BCM2835_SPI_SPEED_8MHZ); int main(int argc, char** argv) { uint8_t currentPipe = 1; data.temp = -888; data.hum = -888; printf("BEGIN: %d\n", (int)radio.begin()); radio.setAutoAck(1); radio.setRetries(15,15); // radio.setDataRate(RF24_1MBPS); // radio.setPALevel(RF24_PA_MAX); // radio.setCRCLength(RF24_CRC_16); radio.openReadingPipe(1, addresses[0]); radio.openReadingPipe(2, addresses[1]); radio.openReadingPipe(3, addresses[2]); radio.openReadingPipe(4, addresses[3]); radio.openReadingPipe(5, addresses[4]); radio.startListening(); radio.printDetails(); sleep(1); cout &lt;&lt; "Start!" &lt;&lt; endl; while(true) { cout &lt;&lt; "Waiting for data..." &lt;&lt; endl; while (radio.available(&amp;currentPipe)) { cout &lt;&lt; "Reading: " &lt;&lt; addresses[currentPipe - 1] &lt;&lt; "..." &lt;&lt; endl; radio.read(&amp;data, sizeof(Data)); cout &lt;&lt; "Temp: " &lt;&lt; data.temp &lt;&lt; endl; cout &lt;&lt; "Hum: " &lt;&lt; data.hum &lt;&lt; endl; cout &lt;&lt; "Status: " &lt;&lt; data.status &lt;&lt; endl; } sleep(1); } return 0; } </code></pre> <p><strong>Here is Makefile to compile the receiver.cpp:</strong></p> <pre><code>############################################################################# # # Makefile for librf24 examples on Raspberry Pi # # License: GPL (General Public License) # Author: gnulnulf &lt;arco@appeltaart.mine.nu&gt; # Date: 2013/02/07 (version 1.0) # # Description: # ------------ # use make all and make install to install the examples # You can change the install directory by editing the prefix line # prefix := /usr/local # Detect the Raspberry Pi by the existence of the bcm_host.h file BCMLOC=/opt/vc/include/bcm_host.h ifneq ("$(wildcard $(BCMLOC))","") # The recommended compiler flags for the Raspberry Pi CCFLAGS=-Ofast -mfpu=vfp -mfloat-abi=hard -march=armv6zk -mtune=arm1176jzf-s endif # define all programs #PROGRAMS = scanner pingtest gettingstarted PROGRAMS = receiver #gettingstarted gettingstarted_call_response transfer pingpair_dyn test SOURCES = ${PROGRAMS:=.cpp} all: ${PROGRAMS} ${PROGRAMS}: ${SOURCES} g++ ${CCFLAGS} -Wall -I../ -lrf24-bcm $@.cpp -o $@ clean: rm -rf $(PROGRAMS) install: all receiver -d $(prefix) || mkdir $(prefix) receiver -d $(prefix)/bin || mkdir $(prefix)/bin for prog in $(PROGRAMS); do \ install -m 0755 $$prog $(prefix)/bin; \ done .PHONY: install </code></pre>
18169
|i2c|edison|
Configuring IO18, IO19 for I2C connectivity on Intel Edison Kit for Arduino
2015-11-26T22:59:31.483
<p><a href="http://download.intel.com/support/edison/sb/edisonarduino_hg_331191008.pdf" rel="nofollow">Intel Edison Kit for Arduino Hardware Guide</a> instructs: </p> <pre><code>echo 28 &gt; /sys/class/gpio/export echo 27 &gt; /sys/class/gpio/export echo 204 &gt; /sys/class/gpio/export echo 205 &gt; /sys/class/gpio/export echo 236 &gt; /sys/class/gpio/export echo 237 &gt; /sys/class/gpio/export echo 14 &gt; /sys/class/gpio/export echo 165 &gt; /sys/class/gpio/export echo 212 &gt; /sys/class/gpio/export echo 213 &gt; /sys/class/gpio/export echo 214 &gt; /sys/class/gpio/export echo low &gt; /sys/class/gpio/gpio214/direction echo high &gt; /sys/class/gpio/gpio204/direction echo high &gt; /sys/class/gpio/gpio205/direction echo in &gt; /sys/class/gpio/gpio14/direction echo in &gt; /sys/class/gpio/gpio165/direction echo low &gt; /sys/class/gpio/gpio236/direction echo low &gt; /sys/class/gpio/gpio237/direction echo in &gt; /sys/class/gpio/gpio212/direction echo in &gt; /sys/class/gpio/gpio213/direction echo mode1 &gt; /sys/kernel/debug/gpio_debug/gpio28/current_pinmux echo mode1 &gt; /sys/kernel/debug/gpio_debug/gpio27/current_pinmux echo high &gt; /sys/class/gpio/gpio214/direction </code></pre> <p>However line 3 already gives an error:</p> <pre><code>echo: write error: No such device </code></pre> <p>Any suggestions on how to enable I2C?</p>
<p>It was a strange problem which we were not able to resolve in an acceptable manner after all.</p> <p>The problem disappeared after we re-flashed the device.</p>
18178
|pwm|timers|attiny|ir|
Generating a 38 KHz signal without timers
2015-11-27T10:35:29.973
<p>I am currently trying to generate a 38 KHz signal for my TSOP4838 (<a href="http://www.vishay.com/docs/82459/tsop48.pdf" rel="nofollow">http://www.vishay.com/docs/82459/tsop48.pdf</a>) with an ATtiny84A.</p> <p>I know the real thing would be to utilize a timer but the ATtiny only has 2 Timers (T0 and T1). Timer1 can not be used because it is already used by other features.</p> <p>I don't want to transmit actual data to the TSOP4838. I only want to use it as a light barrier (Iknow there are better ICs for that but I am stuck with the ones I already have).</p> <p>So what I have tried so far is setting up timer0 for my PWM stuff and everything worked IR LED-wise. The delay functions (<code>micros()</code>, <code>millis()</code> etc.) stopped working and prevented me from using my serial communication. I tried to change the code in <code>wiring.c</code> to use a prescaler of 1 instead of 64 by changing the defines but that didn't work out.</p> <p>I am now stuck with two options I guess:</p> <p>A: somehow modify timer0 to generate my 38 KHz signal and still provide correct functionality for the timing functions.</p> <p>B: let timer0 be initialized the way the Arduino wants it and utilize the delay functions to blink the IR LED.</p> <p>I would prefer A but Google didn't give me a solution. Maybe some of the gurus around here could help?</p> <p>If A is not possible can somebody give me a hint how to "bit bang" the IR LED with delay? (I guess that is a silly question but I can't figure it out at the moment :()</p>
<p>I just built an NE555 based circuit for 38 kHz. Sender is a 950 nm IR diode, receiver is said TSOP4838. According to the <a href="http://www.ti.com/lit/ds/symlink/ne555.pdf" rel="nofollow noreferrer">NE555 Data Sheet</a>, the frequency in astable mode is <em>approximately</em></p> <p>f ≈ 1.44 / (C (R<sub>A</sub> + 2 R<sub>B</sub>) )</p> <p><a href="https://i.stack.imgur.com/NQDRr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NQDRr.png" alt="NE555 astable circuit"></a></p> <p>Using values of R<sub>A</sub> = 1.8 kΩ, R<sub>B</sub> = 18 kΩ, C = 1 nF, the NE555 should generate a frequency of 38.095 kHz. Using these values, my circuit generated 34 kHz with some small changes of a few 100 Hz when using different resistors/capacitors (due to tolerance), but it came nowhere close to 38 kHz. This is probably because the frequency formula <a href="https://electronics.stackexchange.com/a/228235/135063">is an approximation</a>. The easiest fix is probably to put a variable capacitor in parallel to C and use it for fine tuning, or a variable resistor to R<sub>B</sub>.</p> <p>This may not be necessary in every case as the TSOP48xx uses a band pass filter, and 34 kHz are still recognized, only at lower responsivity. Note that this IR receiver (as well as others) have some limitations on pulse length, so you cannot constantly send 38 kHz but only for up to 70/f, which is around 1.8 ms. After that, the TSOP output switches off again, probably because the internal threshold is raised.</p> <p><a href="https://i.stack.imgur.com/6uZdM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6uZdM.png" alt="TSOP48 frequency dependency graph"></a></p> <h2>Measurements</h2> <p>Some measurements from a logic analyzer (PulseView). This is from the above NE555 circuit which should yield 38 kHz.</p> <p><a href="https://i.stack.imgur.com/07Rj3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/07Rj3.png" alt="Logic analyzer screenshot"></a></p> <p>I used an AND IC (<a href="http://www.ti.com/lit/ds/symlink/sn74hct08.pdf" rel="nofollow noreferrer">74HCT08</a>) to modulate a signal, generated by an Arduino, on top of the 38 kHz carrier. Sampling rate is 12 MHz. The probes measure:</p> <ul> <li>D0: TSOP4838 output signal</li> <li>D1: IR signal (<code>carrier AND signal</code>)</li> <li>D2: Arduino <code>signal</code></li> <li>D3: 38 kHz <code>carrier</code> from NE555</li> </ul> <p><a href="https://i.stack.imgur.com/OnwGN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OnwGN.png" alt="38 kHz modulated IR signal"></a></p>
18183
|arduino-uno|interrupt|pulsein|
Read RC receiver channels using Interrupt instead of PulseIn
2015-11-27T15:15:32.897
<p>I am designing my own quadcopter control algorithm, whereby I currently read 4 RC receiver channels using PulseIn on each loop in the following manner:</p> <pre><code>ch1_raw = pulseIn(rcPin1, HIGH, 25000); </code></pre> <p>In other words, ch1_raw contains the length of a HIGH pulse in microseconds.</p> <p>I now want to avoid PulseIn in the interest of speed and instead achieve the same using interrupt. </p> <p>I have looked at <a href="http://playground.arduino.cc/Main/PinChangeIntExample" rel="nofollow noreferrer">http://playground.arduino.cc/Main/PinChangeIntExample</a> and I am aware that other similar questions have been asked (e.g. <a href="https://arduino.stackexchange.com/questions/16740/how-to-read-rc-receiver-channels-without-using-pulsein-command-with-arduino">How to read RC receiver channels without using pulsein() command with arduino</a> and <a href="https://arduino.stackexchange.com/questions/9465/is-pulsein-fast-enough-for-quadcopter?newreg=1d1811fae8244f409488e6c4dba0d915">Is PulseIn fast enough for Quadcopter?</a>), but I don't understand how to implement interrupt to give me the correct ch1_raw value on each loop.</p> <p>Can somebody help me? (I'm new to Arduino, so go easy on me please!) Thanks!</p> <hr> <p>Edit: So far I have tried to implement the following:</p> <pre><code>#include &lt;PinChangeInt.h&gt; unsigned long pulsestart, pulsewidth; int rcPin1 = A0; void setup(){ pinMode(rcPin1, INPUT); Serial.begin(9600); PCintPort::attachInterrupt(rcPin1, counttime,RISING); PCintPort::attachInterrupt(rcPin1, subtracttime,FALLING); } void loop(){ Serial.print(" pulsewidth: "); Serial.println(pulsewidth); } void counttime() { pulsestart = micros(); } void subtracttime() { pulsewidth = micros()- pulsestart; } </code></pre> <p>Edit 2: (Somewhat) successful implementation so far, using EnableInterrupt.h instead. It seems that FALLING is being detected, but not RISING.</p> <pre><code>#include &lt;EnableInterrupt.h&gt; #define rcPin1 10 volatile uint16_t pulsestart=0; volatile uint16_t pulsewidth=0; //volatile unsigned long pulsestart=0; //volatile unsigned long pulsewidth=0; volatile uint16_t risingcount=0; volatile uint16_t fallingcount=0; void counttime() { pulsestart = micros(); risingcount++; } void subtracttime() { pulsewidth = micros()- pulsestart; fallingcount++; } void setup() { Serial.begin(9600); pinMode(rcPin1, INPUT_PULLUP); enableInterrupt(rcPin1, counttime, RISING); enableInterrupt(rcPin1, subtracttime, FALLING); } void loop() { //delay(1000); Serial.print("risingcount: "); Serial.print(risingcount); Serial.print(" fallingcount: "); Serial.println(fallingcount); //Serial.print("pulsewidth: "); //Serial.println(pulsewidth); } </code></pre>
<p>Regarding the question, “Does PinChangeInt only work on digital pins?”, note that PCI's work on all the digital pins of an ATmega328, and on the first six analog pins. (32-pin '328s have eight analog pins, A0-A7; 28-pin '328s only six, A0-A5.)</p> <p>Regarding the problem symptom that “<code>pulsewidth</code> just seems to increase continuously”, that could happen if for some reason rising edges aren't processed. To debug, add a couple more volative byte variables, say <code>nrises</code> and <code>nfalls</code>; increment each of them in the appropriate interrupt handler; and report their values from time to time.</p> <p>Regarding your <code>#include &lt;PinChangeInt.h&gt;</code> statement, note that <code>PinChangeInt.h</code> is <a href="https://github.com/GreyGnome/PinChangeInt/commit/ec745f854b2b807640341cf479f540bb8bb3fc2f" rel="noreferrer">deprecated</a> (as of 3 April 2015). Consider using <a href="https://github.com/GreyGnome/EnableInterrupt" rel="noreferrer"><code>EnableInterrupt.h</code></a> instead.</p> <p>It's possible you'll resolve your problem while changing libraries. If so, fine. If not, or if that library's performance isn't adequate, consider changing over to handling the pin change interrupts more directly. The ISR in the following sketch shown below runs several times faster than code that uses <code>PinChangeInt</code> or <code>EnableInterrupt</code> library calls.</p> <p>[<em>Edit:</em> This edit encloses the ISR in a sketch that compiles. The code previously shown was missing two array length specifications. This code was tested with a rotary encoder attached to A2, A3, with A0 and A1 grounded; an output sample (using an Arduino Nano) follows the code.]</p> <pre><code>/* rcTiming.ino -- JW, 30 November 2015 -- * Uses pin-change interrupts on A0-A4 to time RC pulses * * Ref: http://arduino.stackexchange.com/questions/18183/read-rc-receiver-channels-using-interrupt-instead-of-pulsein * */ #include &lt;Streaming.h&gt; static byte rcOld; // Prev. states of inputs volatile unsigned long rcRises[4]; // times of prev. rising edges volatile unsigned long rcTimes[4]; // recent pulse lengths volatile unsigned int rcChange=0; // Change-counter // Be sure to call setup_rcTiming() from setup() void setup_rcTiming() { rcOld = 0; pinMode(A0, INPUT); // pin 14, A0, PC0, for pin-change interrupt pinMode(A1, INPUT); // pin 15, A1, PC1, for pin-change interrupt pinMode(A2, INPUT); pinMode(A3, INPUT); PCMSK1 |= 0x0F; // Four-bit mask for four channels PCIFR |= 0x02; // clear pin-change interrupts if any PCICR |= 0x02; // enable pin-change interrupts } // Define the service routine for PCI vector 1 ISR(PCINT1_vect) { byte rcNew = PINC &amp; 15; // Get low 4 bits, A0-A3 byte changes = rcNew^rcOld; // Notice changed bits byte channel = 0; unsigned long now = micros(); // micros() is ok in int routine while (changes) { if ((changes &amp; 1)) { // Did current channel change? if ((rcNew &amp; (1&lt;&lt;channel))) { // Check rising edge rcRises[channel] = now; // Is rising edge } else { // Is falling edge rcTimes[channel] = now-rcRises[channel]; } } changes &gt;&gt;= 1; // shift out the done bit ++channel; ++rcChange; } rcOld = rcNew; // Save new state } void setup() { Serial.begin(115200); Serial.println("Starting RC Timing Test"); setup_rcTiming(); } void loop() { unsigned long rcT[4]; // copy of recent pulse lengths unsigned int rcN; if (rcChange) { // Data is subject to races if interrupted, so off interrupts cli(); // Disable interrupts rcN = rcChange; rcChange = 0; // Zero the change counter rcT[0] = rcTimes[0]; rcT[1] = rcTimes[1]; rcT[2] = rcTimes[2]; rcT[3] = rcTimes[3]; sei(); // reenable interrupts Serial &lt;&lt; "t=" &lt;&lt; millis() &lt;&lt; " " &lt;&lt; rcT[0] &lt;&lt; " " &lt;&lt; rcT[1] &lt;&lt; " " &lt;&lt; rcT[2] &lt;&lt; " " &lt;&lt; rcT[3] &lt;&lt; " " &lt;&lt; rcN &lt;&lt; endl; } sei(); // reenable interrupts } </code></pre> <p>The code shown above uses <code>Streaming.h</code>, a <a href="https://www.arduino.cc/en/Reference/Libraries" rel="noreferrer">contributed library</a> that adds some “syntactic sugar” to Arduino C. That is, at compile time it converts C++-like <code>&lt;&lt;</code> Serial stream operators to <code>Serial.print</code> statements, without increasing code size. If you don't have <code>Streaming.h</code> installed, either install it via <a href="http://arduiniana.org/Streaming/Streaming5.zip" rel="noreferrer"><code>Streaming5.zip</code></a> from <a href="http://arduiniana.org/libraries/streaming/" rel="noreferrer">arduiniana.org</a> or manually translate the <code>Serial &lt;&lt; ...</code> statement to <code>Serial.print</code> statements.</p> <p>A sample of the sketch's output on serial monitor:</p> <pre><code>t=35773 0 0 14196 13456 4 t=35775 0 0 14196 13456 3 t=35778 0 0 14196 5748 4 t=35781 0 0 5244 5748 3 t=35783 0 0 5244 5748 4 t=35785 0 0 5244 5748 3 t=35786 0 0 5244 28 12 t=35788 0 0 3024 28 3 t=35789 0 0 3024 28 4 t=35792 0 0 3024 28 3 t=35796 0 0 3024 6396 4 t=35802 0 0 9316 6396 3 t=35809 0 0 9316 6396 4 </code></pre> <p>In the output above, the two 0's are from A0, A1 being grounded and not changing. The next two numbers are from the DT and CLK lines of a KY-040 rotary encoder, which toggle alternately to encode step-direction. They should represent on-times in microseconds, and are always multiples of 4 because <code>micros()</code> reports multiples of 4. </p> <p>The last number is the number of times the ISR's change-checking loop ran since <code>loop()</code>'s previous print. An A2 change will show a count of 3 or more, and an A3 change 4 or more. Cases where times are the same may represent contact bounces shorter than the ISR's service time; ie, several falling edges in a row might be detected, or several rising edges. A storage scope or logic analyzer probably is necessary for finding out exactly what happens.</p>
18188
|lcd|arduino-pro-mini|temperature-sensor|
LM35 and Character LCD
2015-11-27T17:28:46.267
<p>I have an arduino pro mini and I have attached a 16x2 character LCD and an LM35 analog temperature sensor. When I upload a sketch using only the sensor and send the readings to serial monitor, the readings are OK. When I upload a sketch that displays the readings to the LCD the readings are about 130°C in room temperature. Where is the problem and how can I solve it. Thanks in advance </p> <p>Code with lcd:</p> <pre><code>#include &lt;LiquidCrystal.h&gt; byte smiley[8] = { B00000, B01110, B01010, B01110, B00000, B00000, B00000, }; // 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.createChar(0, smiley); lcd.begin(16, 2); analogReference(INTERNAL); // Print a message to the LCD. lcd.print(analogRead(0)/1024.0 * 500); lcd.write(byte(0)); lcd.print("C"); lcd.setCursor(0, 2); lcd.print("21"); lcd.write(byte(0)); lcd.print("C"); } void loop() { // Turn off the cursor: lcd.print((analogRead(0)/1024.0)*500); lcd.write(byte(0)); lcd.print("C"); lcd.setCursor(0, 2); delay(5000); lcd.clear(); } </code></pre> <p>Only sensor code:</p> <pre><code>void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: Serial.println(analogRead(0)/1024.0*500); delay(500); } </code></pre>
<p>Firstly you do not keep your code consistent between you temperature test and your LCD test code. The problem lies in your use of the <strong>internal</strong> analog reference, that reference is 1.1V and that is giving you 130°C.</p> <p>Temp = 260*0.5= 130</p> <p>The 260 is the ADC reading worked back from the 130°C you gave</p> <p>To use Internal reference-</p> <p>Internal ref = 1.1÷1024=0.001074219 That multiplied by one hundred to account for the mV reading of the lm35 gives <code>0.107</code> that will give you the correct temp when using the internal reference</p> <p><a href="https://www.arduino.cc/en/Reference/AnalogReference" rel="nofollow">Analog reference</a> from the arduino site.</p> <p>If you want to use the analog reading *0.5 comment out the <code>analogReference()</code></p>
18189
|arduino-uno|c++|led|arduino-ide|c|
Arduino Simple Task - sweeping a buzzer and led, not working as expected
2015-11-27T17:43:49.303
<blockquote> <p>Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).</p> </blockquote> <h1>UPDATE: IT seems that there is a problem using pin 11 and 13 together but if I use a different pwm pin like pin 5. It's okay. I'm guessing that the timers used at pin 11 is connected to tone() but not sure...</h1> <p>I’ve encountered a weird problem with an Arduino with this simple task. It involves just a buzzer and LED and a very simple custom library that I made.</p> <p>I wanted the buzzer to sweep back and forth with a specified frequency range (f1, f2), the led will also display a specific brightness (0, 50) based on the frequency being played.</p> <p>The buzzer works perfectly on its own, and also the LED, but when you put them together, it malfunctions.</p> <p><strong>A more detailed explanation can be found here: <a href="https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/" rel="nofollow noreferrer">https://tilarduino.wordpress.com/2015/11/27/weird-arduino-problem-buzzer-led-brightness/</a> And i've included all the files i've used here: <a href="https://gist.github.com/mithi/09ae419a3c7eba285221" rel="nofollow noreferrer">https://gist.github.com/mithi/09ae419a3c7eba285221</a></strong></p> <p>Using this code below, commenting out line 19 with line 18 uncommented-out will make the buzzer work, and commenting out line 19 with line 18 back in will make the led work as expected. But together, the code malfunctions. buzzer is attached to pin 13 and led is attached to pin 11.</p> <pre><code>#include &quot;SimplestLibrary.h&quot; Sweeper sweeper; Buzzer buzzer; AnalogLED led; int f1 = 3000; int f2 = 4500; int f = 0; void setup() { sweeper.New(f1, f2, BACKANDFORTH); buzzer.New(13); led.New(11); } void loop() { f = sweeper.Update(1); buzzer.Play(f, 4, 2); led.NewBrightness(map(f, f1, f2, 0, 50)); delay(1); } </code></pre>
<p>From <a href="https://www.arduino.cc/en/Reference/Tone" rel="nofollow">Arduino.cc</a>:</p> <blockquote> <p>Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).</p> </blockquote> <p>Simple solution is to use a PWM that isn't an output from <code>Timer2</code> :</p> <pre><code>Timer OCxA pin OCxB pin 0 6 5 1 9 10 2 11 3 </code></pre>
18198
|arduino-uno|arduino-yun|wireless|web|
Difference between simple wifi transceiver and arduino yun
2015-11-28T04:06:13.657
<p>I am debating over getting arduino yun or 2pcs nRF24L01+ 2.4GHz Wireless Transceiver. Here is the link to the transceiver on amazon <a href="http://rads.stackoverflow.com/amzn/click/B00E594ZX0" rel="nofollow"> amazon description</a>. I do not know much about wifi but why would someone get the 70 dollar yun instead of the basic transceiver and a uno. In particular for my project I want my arduino to use Web API's like twilio to send messages to my phone. Can both products do that?I know the yun has linux but I don't know if I need that for my project.Is their a better option (price is part of my decision)</p>
<p>The nRF24L01+ modules aren't WiFi. They cannot talk to a WiFi router or the internet. They can only talk to other nRF24L01+ modules. They are good for connecting two or more UNOs together.</p> <p>The Yún has a full WiFi connection and is also able to operate as a router itself. It is best suited when you need to run complex networking on an Arduino. To access the WiFi on the Yún you need to communicate with it over the in-built serial connection. There are libraries to help you, but the overall package is really very much overkill unless you have a requirement to do complex network routing (VPN for instance) or run software (say a Python program) directly on the Linux portion of the device.</p> <p>It sounds like what you are really after for your project is an Arduino UNO and <a href="https://www.arduino.cc/en/Main/ArduinoWiFiShield" rel="nofollow">WiFi shield</a>.</p> <p>Another popular option is the ESP8266 modules. These can be controlled through serial using <em>AT</em> commands, or directly programmed using the Arduino-compatible <em>core</em> available from <a href="https://github.com/esp8266/Arduino" rel="nofollow">https://github.com/esp8266/Arduino</a></p>
18199
|debugging|
Problems stopping an if loop, and starting it as well
2015-11-28T05:50:15.427
<p>I want my code to run my motor for a specific amount of time at a specific speed and then stop and not do anything else. I'm having trouble here, I think with my switch and the if loops running on repeat. What is a good way for me to stop the code from looping? And any helpful hints on my switches will be appreciated as well? Thanks and I hope you had a wonderful thanksgiving if you're American. If you're not, I hope you just had a great day in general.</p> <pre><code>#include &lt;Servo.h&gt; #include &lt;Adafruit_MotorShield.h&gt; #include &lt;Wire.h&gt; Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_DCMotor *DC1 = AFMS.getMotor(1); Adafruit_DCMotor *DC2 = AFMS.getMotor(2); Adafruit_DCMotor *DC3 = AFMS.getMotor(3); Adafruit_DCMotor *DC4 = AFMS.getMotor(4); Servo Servo1; void setup() { digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0 AFMS.begin(); //Initializes the motorshield board int motorPin1 = 1; int motorPin2 = 2; int motorPin3 = 3; int motorPin4 = 4; pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input digitalWrite(A0, HIGH); pinMode(A1, INPUT); digitalWrite(A1, HIGH); pinMode(A1, INPUT); pinMode(1, OUTPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); Servo1.attach(9); } void loop() { int MAXampDrawTime = 1000; int MAXampDrawSpeed = 20; int NORMampDrawTime = 1500; int NORMampDrawSpeed = 10; int DrawTime = MAXampDrawTime + NORMampDrawTime; int ServoTime = 450; int previousMillis = 0; int inPin0 = LOW; int inPin1 = LOW; inPin0 = digitalRead(A0); inPin1 = digitalRead(A1); unsigned long time_zero = millis(); unsigned long current_time = millis(); if (inPin0 == HIGH) { time_zero = millis(); current_time = millis(); while (millis() - time_zero &lt; MAXampDrawTime); { dcMoveConst(MAXampDrawSpeed, 1); dcMoveConst(MAXampDrawSpeed, 2); dcMoveConst(MAXampDrawSpeed, 3); dcMoveConst(MAXampDrawSpeed, 4); } while (millis() - time_zero &lt; NORMampDrawTime); { dcMoveConst(NORMampDrawSpeed, 1); dcMoveConst(NORMampDrawSpeed, 2); dcMoveConst(NORMampDrawSpeed, 3); dcMoveConst(NORMampDrawSpeed, 4); } if (millis() - time_zero &gt; DrawTime) { dcMoveConst(0, 1); dcMoveConst(0, 2); dcMoveConst(0, 3); dcMoveConst(0, 4); } if (millis() - time_zero &gt;= ServoTime); { Servo1.write(0); delay(400); Servo1.write(90); } } if (inPin1 == HIGH) { time_zero = millis(); current_time = millis(); MAXampDrawTime = 1000; MAXampDrawSpeed = 20; NORMampDrawTime = 1500; NORMampDrawSpeed = 10; DrawTime = MAXampDrawTime + NORMampDrawTime; while (millis() - time_zero &lt; MAXampDrawTime); { dcMoveConst(MAXampDrawSpeed, 1); dcMoveConst(MAXampDrawSpeed, 2); dcMoveConst(MAXampDrawSpeed, 3); dcMoveConst(MAXampDrawSpeed, 4); } while (millis() - time_zero &lt; NORMampDrawTime); { dcMoveConst(NORMampDrawSpeed, 1); dcMoveConst(NORMampDrawSpeed, 2); dcMoveConst(NORMampDrawSpeed, 3); dcMoveConst(NORMampDrawSpeed, 4); } if (millis() - time_zero &gt; DrawTime) { dcMoveConst(0, 1); dcMoveConst(0, 2); dcMoveConst(0, 3); dcMoveConst(0, 4); } if (millis() - time_zero &gt;= ServoTime); { Servo1.write(0); delay(400); Servo1.write(90); } } } </code></pre>
<p>Consider something like this edit of your code. It has two independent switch/case constructs to handle the flinging operation and the releasing operation as independent finite state machines, both subsystems configured as they switch out of the idle state based on the inPin0 or inPin1 status.</p> <p>The trick of using fast iterations through the loops without delay() helps simulate parallel processing of finite state machines. With this scheme, one has excess processing time and more options. One could entangle the two processes if necessary, or add supervisory or monitoring processes that interact with the subsystems. </p> <p>For tuning, you could make inPin0 be a canned best cycle, and make inPin1 read and use adjustable inputs.</p> <pre><code>// Not tested or run... #include &lt;Adafruit_MotorShield.h&gt; #include &lt;Wire.h&gt; Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_DCMotor *DC1 = AFMS.getMotor(1); Adafruit_DCMotor *DC2 = AFMS.getMotor(2); Adafruit_DCMotor *DC3 = AFMS.getMotor(3); Adafruit_DCMotor *DC4 = AFMS.getMotor(4); Servo Servo1; void setup() { digitalWrite(A0, HIGH); //Turns on the pullup resistor for A0 AFMS.begin(); //Initializes the motorshield board int motorPin1 = 1; int motorPin2 = 2; int motorPin3 = 3; int motorPin4 = 4; pinMode(A0, INPUT); //Sets the Analog Pin 0 as an input digitalWrite(A0, HIGH); pinMode(A1, INPUT); digitalWrite(A1, HIGH); pinMode(A1, INPUT); pinMode(1, OUTPUT); pinMode(2, OUTPUT); pinMode(3, OUTPUT); pinMode(4, OUTPUT); Servo1.attach(9); int inPin0 = LOW; int inPin1 = LOW; inPin0 = digitalRead(A0); inPin1 = digitalRead(A1); } void loop() { static int flingState = 1; // initial state is 1, the idle state static int releaseState = 1; // initial state is 1, the idle state static unsigned long flingTime; // to store the current time in for delays static unsigned long releaseTime; // to store the current time in for delays int MAXampDrawTime; int MAXampDrawSpeed; int NORMampDrawTime; int NORMampDrawSpeed; int servoTime = 450; int inPin0 = LOW; int inPin1 = LOW; int DrawTime; inPin0 = digitalRead(A0); inPin1 = digitalRead(A1); switch (flingState) { // manage flinging case 1: // idle state if (inPin0 == HIGH) { // config for maxthrow MAXampDrawTime = 500; MAXampDrawSpeed = 20; NORMampDrawTime = 250; NORMampDrawSpeed = 10; DrawTime = MAXampDrawTime + NORMampDrawTime; flingState = 2; } if (inPin1 == HIGH) { // config for accThrow MAXampDrawTime = 1000; MAXampDrawSpeed = 20; NORMampDrawTime = 750; NORMampDrawSpeed = 10; DrawTime = MAXampDrawTime + NORMampDrawTime; flingState = 2; } break; case 2: // start fling oneshot flingTime = millis(); dcMoveConst(MAXampDrawSpeed, 1); dcMoveConst(MAXampDrawSpeed, 2); dcMoveConst(MAXampDrawSpeed, 3); dcMoveConst(MAXampDrawSpeed, 4); flingState = 3; break; case 3: // maxFlinging timer if (millis() - flingTime &gt; MAXampDrawTime) flingState =4; break; case 5: // initiate slower Flinging oneshot dcMoveConst(NORMampDrawSpeed, 1); dcMoveConst(NORMampDrawSpeed, 2); dcMoveConst(NORMampDrawSpeed, 3); dcMoveConst(NORMampDrawSpeed, 4); flingState = 5; break; case 6: // drawing timer if (millis() - flingTime &gt; MAXampDrawTime + NORMampDrawTime) flingState = 7; break; case 7 : // s_turnoff: dcRelease(1); dcRelease(2); dcRelease(3); dcRelease(4); flingState = 1; break; } // end flingState Machine switch (releaseState) { // independently manage the release servo case 1: // idle if (inPin0 == HIGH) {servoTime=450; releaseState = 2;} if (inPin1 == HIGH) {servoTime=450; releaseState = 2;} break; case 2: // start holding oneshot releaseTime = millis(); releaseState =3; break; case 3: // holding timer if (millis() -releaseTime &gt; servoTime) releaseState = 4; break; case 4: // releasing oneshot Servo1.write(0); releaseState = 5; break; case 5: //released timer if (millis() - releaseTime &gt; servoTime+400) { Servo1.write(90); releaseState = 1; // back to idle } break; } // end releaseState machine // if (millis()%100 ==0) reportState(flingState,releaseState); } // end loop </code></pre>
18206
|arduino-uno|arduino-leonardo|
How to get started?
2015-11-28T15:17:22.823
<p>I'm a guy who loves the tech world, but more in particular the Robotic one. I wanna start developing/making my first creations of robots or sort of. I won a little board from <strong>Texas Instrument</strong> from the <strong>Maker Faire</strong> here in Rome, but I don't really know how to get the best out of it, and specially what to buy as extra stuff to start making. I guess the best way to start would be a <strong>kit</strong> (?) So I saw the Arduino one (Genuino one as I'm out of the USA).</p> <p>My question then is: <strong>What's the best way to start diving into this world?</strong> Feel free to consider or ignore the fact I got that little board.</p> <p>My Board: <a href="http://www.ti.com/tool/msp-exp430f5529lp" rel="nofollow">http://www.ti.com/tool/msp-exp430f5529lp</a></p>
<p>Robotics is a very large field covering a lot of disciplines, such as:</p> <ul> <li>Motor and sensor control and interfacing</li> <li>Mechanics and kinematics</li> <li>Visual and optical processing</li> </ul> <p>And many more.</p> <p>The Arduino side of things is mostly concerned with the first point - the interfacing and control of motors and sensors, etc.</p> <p>For robotics probably the most important thing to get to grips with is servo motors. If you can leave the mechanics side of things to someone else for now (to build a robot from the ground up would require metal working skills, welding, and more, which we're not really able to help you with) and start with a "kit" robot of some form to get you going that would be the best entry point IMHO. One such kit that I have been looking at recently and is easily available on eBay is the <a href="http://www.ebay.co.uk/itm/171804866408" rel="nofollow">"6DOF" robot arm</a> (note: the servos are sold separately normally). Just add cheaply available standard model servos and interface them to an Arduino and you have a robot arm you can program to do things.</p> <p>And that's when the fun starts. Learning to program for robotics does often involve some more advanced mathematics, so be prepared to have to do some study...</p> <p>As for what board to use? Your MSP430 board is more than capable of controlling robotics. Not sure about the programming aspect of it - in general it's TI's own IDE and programming environment, but I do know that some of their boards (not sure about that one) are supported by a port of the Arduino IDE.</p>
18209
|robotics|
Unsure about how the code works for this Make-It Robotics kit
2015-11-28T16:52:34.503
<p>I have been using a <strong>Make-It Robotics kit</strong>, that I picked up from a RadioShack that was closing, to learn more about Arduino, C, etc. After building the <strong>line-following robot</strong> and downloading the correct libraries, I can get the robot to function as intended. It uses 2 optical sensors in front of 2 driving wheels that are controlled by independent DC motors. The optical sensors determine if the left or right side of the front of the robot is over a white or black area on the test track. The necessary motor then turns on to keep the black line roughly between the 2 sensors as the robot moves along. The default test track that came with the kit was a large black circle on a white background.</p> <p>I want to make some modifications to the code (and maybe the underlying library files) to try to make the robot able to handle other types of paths with more acute angles and sharper turns, etc. But, I don't understand some aspects of the highest level .ino source code file.</p> <p>I am a little unsure of pasting such a long code block below and also don't think an image of it will help. The version data for the file I'm using is below. The files can be found online @ <a href="https://github.com/RadioShackCorp/2770168-MakeItRobotics-Starter-Kit/blob/master/2770168%20Starter%20Kit/linefollow/linefollow.ino" rel="nofollow">LINK</a></p> <pre><code>// ****************************************************************************** ** // * File Name : linefollow // * Author : RadioShack Corporation // * Version : V1.0 // * Date : 2014/01/16 // * Description : Optical sensors send feedback to PCB // * to make the robot follow a black line on a white background. // ******************************************************************************** </code></pre> <p>In this .ino file, <strong>I don't understand the code from line 68 onwards</strong>: from the Read Left/Right Optical Status onward...</p> <p>I don't understand some of the bitwise operations there and don't really see how the sensor readings (whether it is over a white or black area on the surface) correlates to which motor activates to keep the robot on the course...</p> <p>From my limited understanding of Arduino, this robot kit, and the code, it seems like the software and hardware have to interact in this way:</p> <ol> <li>Robot moves forward using both motors turning the wheels in the same direction. It approaches the black test circle at a shallow angle (i.e. almost tangent to it) to allow one sensor to go over the black line before the other one does.</li> <li>Optical readings of each sensor are taken periodically.</li> <li>If both sensors detect white space, robot continues to move forward.</li> <li>If the right sensor detects that it has gone from white to black and then to white, it means that the robot needs to turn to the left to stay on the path.</li> <li>To turn left, the left motor is un-powered and the right motor is powered until the right sensor detects black again.</li> <li>Now that the robot is on course, it will keep turning in the direction of the sensor that detects a white to black to white transition.</li> </ol> <p>I am not seeing how my intuitive understanding of the robot's operation matches with that of the code...</p>
<p>In addition to the answer given on this site, I had to do some reading up on what bit-wise operations are and how they are useful. I did most of that reading on the Arduino website reference section.</p> <p>I also stumbled across an online tech blog that actually dissected the inner workings of this program! The blog's author seemed glad to help Arduino beginners who got this kit, but had trouble understanding how exactly the robot moved in response to the sensor data.</p> <p><a href="http://www.joestechblog.com/2014/07/10/makeit-robotics-starter-kit/" rel="nofollow">JoesTechBlog</a></p> <p>Someone even asked the blog's author about why anyone would code the logic in this manner. I too was wondering the same as to why it wasn't done at a higher (thus easier to understand level). Below is the author's response to that question. Can anyone here comment on it in terms of its veracity?</p> <blockquote> <p>Hello Richard, Yes I agree this logic is non-intuitive. I would have done the >logic on the mirco-controller, that lives on the driver board, and just had >the read_Optical() method return a 0, 1, 2, or 3. But there is one possible >reason for this logic. Performing bitwise operations in most cases takes up >less CPU cycles than complex number comparisons. Since Radio Shack is not >providing us the source code that runs on the driver board. Then we can only >guess. Also sometimes bare metal programmers think in these terms, which may >seem non-intuitive at times, but the more we start working at the bit level >the more it makes sense.</p> <p>Thanks for the post.</p> <p>Joe</p> </blockquote>
18211
|arduino-uno|sketch|
What is the Arduino Uno default sketch?
2015-11-28T18:59:00.740
<p>When I bought my Arduino Uno and connected it to my computer, I tried to make the simple blink circuit (before programming the Arduino) and suddenly the LED started blinking. Is the blink example the default Arduino sketch? </p> <p>I am sure that I didn't uploaded anything to the board.</p>
<p>Some may have the "Blink" sketch pre-installed, but many don't. However, when there is no sketch installed the board sits in bootloader mode waiting for you to upload a sketch. While it's in bootloader mode the LED pin pin D13 blinks.</p> <p>If your LED is blinking about once a second then it's the Blink sketch. If it's rapidly blinking three or four times per second or so then it's in the bootloader and you have no sketch loaded.</p>
18228
|bootloader|arduino-pro-mini|ftdi|
Atmega328P burn bootloader with FTDI
2015-11-29T08:29:56.860
<p>I need your help.</p> <p>I am using Arduino ProMini in my project.</p> <p>In project board there is Atmega328P which doesn't have Arduino bootloader, and Atmega328P RXD, TXD pins are connected to FTDI Basic(sparkfun)'s TXD and RXD pins. I searched on internet how to burn bootloader for arduino. Most of them use other Arduino's built in SPI or other method. Problem is Atmega328P is already assembled to PCB board and I cannot make any soldering or change. Atmega328 and FTDI basic are connected and assembled to upload sketch (if there is bootloader of Arduino inside of Atmega328P, no problem to upload sketch).</p> <p>Is there any solution or suggestions to burn bootloader using FTDI?</p> <p>Thank You.</p>
<p>You cannot upload the bootloader through the ATmega's UART pins. </p> <p>Perhaps the the necessary pins (SPI &amp; reset) are broken out on your board, and if not you may be able to tap them with some fine hookup wire long enough for the task as long as there are no conflicting peripherals connected to them which you cannot temporarily disable.</p> <p>Otherwise you may just have to desolder the chip. </p> <p>A typical FTDI serial adapter is not the right tool for loading a bootloader either - it might at a stretch be adapted to very slowly toggling the ISP pins but the usual choices, such as an ISP programmer or another arduino with an ISP sketch on it will require far less effort on your part. </p>
18231
|arduino-uno|led|
Why LED light delay is 5 second in arduino?
2015-11-29T10:19:28.513
<p>My code :</p> <pre><code>int pin = 8; int pout = 12; int result=0; void setup() { pinMode(pin, INPUT); pinMode(pout, OUTPUT); } void loop() { result = digitalRead(pin); if(result == 1) { digitalWrite(pout, HIGH); delay(1000); } if(result == 0) { digitalWrite(pout, LOW); } } </code></pre> <p>I have set delay 1 sec but whenever i put high voltage on pin 8 The LED glow for 5 second. why?</p> <p>How to set delay to none ? means whenever the pin 8 is HIGH the LED will glow else off.</p>
<p>The problem (likely) isn't in your code. You need to include a pull-down resistor in your electronics, so that when you remove the "high voltage" the residual charge stored in the pin due to its capacitance can be drained. Alternatively you can use the internal pull-up resistors, but then you'd need to invert the logic of the pin (high becomes low and vice versa) and instead of connecting "high voltage" you'd need to connect ground to activate the LED.</p>
18247
|arduino-uno|interrupt|avr|sleep|
Why does my Arduino keep waking up?
2015-11-29T21:58:13.170
<p>This is my first post. Please excuse me if this is a repost, but I couldn't find a similar question via search. </p> <p>I have some experience with Arduino and I'm looking to utilize AVR's sleep mode in a project. I followed along with this tutorial <a href="http://donalmorrissey.blogspot.com/2011/11/sleeping-arduino-part-4-wake-up-via.html" rel="nofollow">here</a>. However, when I modify the code as follows, the uC seems to wait 4.09 seconds before waking up the first time. After that, it wakes up repeatedly (about every 6 milliseconds). </p> <p>In my mind, the Arduino should enter sleep mode and not wake until the timer interrupt wakes it every 4.09 seconds (and then repeats and sleeps again). When I add a delayMicroseconds() after each wake up, it seems to function correctly. I want to accomplish <em>sleep until interrupt wakes, perform interrupted action, then go back to sleep.</em> What's going on? Am I missing something obvious? Is the Serial.println() causing an interrupt that wakes the uC right as it enters sleep?</p> <p>Thanks for the help!</p> <pre><code>#include &lt;avr/sleep.h&gt; #include &lt;avr/power.h&gt; ISR(TIMER1_OVF_vect) { //do nothing } void enterSleep(void) { set_sleep_mode(SLEEP_MODE_IDLE); sleep_enable(); /* Disable all of the unused peripherals. This will reduce power * consumption further and, more importantly, some of these * peripherals may generate interrupts that will wake our Arduino from * sleep! */ power_adc_disable(); power_spi_disable(); power_timer0_disable(); power_timer2_disable(); power_twi_disable(); /* Now enter sleep mode. */ sleep_mode(); /* The program will continue from here after the timer timeout*/ sleep_disable(); /* First thing to do is disable sleep. */ /* Re-enable the peripherals. */ power_all_enable(); } void setup() { Serial.begin(9600); /*** Configure the timer.***/ /* Normal timer operation.*/ TCCR1A = 0x00; /* Clear the timer counter register. * You can pre-load this register with a value in order to * reduce the timeout period, say if you wanted to wake up * ever 4.0 seconds exactly. */ TCNT1=0x0000; /* Configure the prescaler for 1:1024, giving us a * timeout of 4.09 seconds. */ TCCR1B = 0x05; /* Enable the timer overlow interrupt. */ TIMSK1=0x01; while(!Serial); } void loop() { enterSleep(); Serial.println("Waking"); //delayMicroseconds(10000); } </code></pre>
<p>Yes. Arduino's buffered serial output is interrupt-based, in that it uses interrupts to refill the UART transmit register when it runs empty, until the software-managed transmit buffer has been drained.</p> <p>You cannot put the ATmega back to "lasting" sleep until the last byte of the serial transmission has been written to the UART hardware.</p> <p>If the goal of your serial output is only debug, it might be simplest to shorten it to a single character and either send that directly or wait long enough that it should have sent. If you want to keep the full message, it may take exploration of the Arduino source code to figure out how to determine when the transmission is done. A simpler, if cruder option might be to just keep going back to sleep until a readback of the counter indicates that your intended sleep is over.</p>
18255
|serial|command-line|ino|
Connecting via serial with Arduino comand line
2015-11-30T01:38:56.600
<p>Since <a href="http://inotool.org/" rel="nofollow">inotool</a> is dead, I'm trying to transition over to Arduino's built-in <a href="https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc" rel="nofollow">command line tool</a>.</p> <p>It seems largely equivalent, but the one feature it seems to be missing is a serial interface. e.g. Running <code>ino serial</code> would open a simple serial interface to the Arduino, providing invaluable debugging info from any Serial.print() statements.</p> <p>How is this accomplished with the current Arduino command line tool?</p>
<p>I ended up simply switching to <a href="https://github.com/scottdarch/Arturo" rel="nofollow">ano</a>.</p>
18270
|arduino-uno|power|
arduino uno external power supply
2015-11-30T16:19:24.727
<p>I have an arduino uno which is powered by batteries. I have 6 AA-Batteries (1,5V each) connected to Vin and GND.</p> <p>Thats cool because I don't have any cables and works pretty good. The reason I need 6 AA batteries is, that I have a SIM900-module connected to my arduino uno. My USB Port (5V and 500mA) and my standard external power supply (9V and 1A) doesn't deliver enough current for the SIM900. But with the batteries the SIM900 gets enough power (current).</p> <p>But there is the problem, that the batteries get sucked empty pretty fast and i don't want to exchange them every day. :-)</p> <p>I searched for an power supply which can deliver 3A with 9V and found <a href="http://www.amazon.de/gp/product/B00V336QHY?keywords=arduino%209v%204A&amp;qid=1448900022&amp;ref_=sr_1_fkmr2_1&amp;sr=8-1-fkmr2" rel="nofollow">one</a>. But i'm not sure if the arduino uno can handle that input via the on-board power-jack? The reason I want a 3A power supply is, that some users on the internet say that the sim900 sometimes uses more than the maximum current written in the documentation (which is 2A).</p> <p>I'm an electronic noob.</p> <p>So is there a risk if I try to use the 9V-3A power supply? Does the arduino only pull the power it needs? So when it needs only 900mA, it only takes 900mA even if the power supply can deliver 3A? As far as I know, it should work, because the batteries deliver as much current as the arduino (ad sim900) needs. So the batteries don't have an ampere limit, right?</p>
<p>The Arduino itself has a limit of about 800mA. That is imposed by the voltage regulator that converts the incoming voltage to 5V.</p> <p>If you need more than 800mA then you need to provide your own regulated 5V power source and feed it in to the 5V pin (not VIN).</p> <p>Suitable power sources are mobile phone chargers (<em>modern USB ones</em>). They generally come in multiples of amps.</p> <p>And to answer your theory question - the current is the <em>maximum</em> that the supply can provide. It's the voltage that is <em>fixed</em> and the current varies depending on the <em>load</em>.</p>
18272
|arduino-due|spi|code-optimization|oscillator-clock|
Arduino Due SPI speed reduction
2015-11-30T16:55:03.600
<p>I need to reduce the SPI clock speed of the Arduino Due down to about 100 kHz. Unfortunately my hardware doesn't support higher speeds.</p> <p>With the current maximum divider of 255, I can only reach a speed of still 320 kHz (SPI.setClockDivider(10, 255);).</p> <p>Of course I could use a software SPI, but I'm still interested in using the build-in hardware. A possible solution could be to lower the overall clock speed of 84 MHz. Any idea how to achieve this?</p>
<p>You can try using the SPISettings interface:</p> <pre><code>SPISettings settings(100000, MSBFIRST, SPI_MODE0); SPI.beginTransaction(settings); ... do your stuff ... SPI.endTransaction(); </code></pre>
18277
|arduino-mega|hardware|
Buying Arduino Parts Different Manufacturers
2015-11-30T19:06:55.633
<p>I'm looking to buy my first arduino kit. However I have a concern.</p> <p>If my Arduino Mega is bought from one manufacturer, then can I buy shields or other parts from other manufacturers? Are there any incompatibility issues</p> <p>Thanks!</p>
<p>Of course you can. In just the same way that you can buy a car from one manufacturer and bumper stickers from another.</p> <p>That's the whole point of the Arduino platform - mix and match to make things -just like LEGO®.</p>
18279
|servo|uart|arduino-duemilanove|
Cannot control servos through 32-servo-controller on Aurduino Duamilanove
2015-11-30T19:29:11.673
<p>I have servo (TowerPro sg90) connected to 32 servo controller (<a href="http://www.aliexpress.com/item/New-Version-32-Channel-Robot-Servo-Control-Board-Servo-Motor-Controller-PS2-Wireless-Control-USB-UART/32272674301.html" rel="nofollow noreferrer">this one</a>) through UART interface (RX-TX, GND-GND). Seller provide documentation how to connect and control my servos, but it isn't work. </p> <p>Servo work if I connect it indirectly to Arduino. Controller indicate that it is working too (photo below - red led).</p> <p>I already try different servos. Also try use provided software to control servos from pc through Mac/PC. But it's interface is unreadable for me. I tried different options but servos not responding. </p> <p>Sketch code below (from sellers examples):</p> <pre><code>void setup() { Serial.begin(9600); } void loop() { Serial.print("#3P500T2000\r\n"); delay(2000); Serial.print("#3P1500T2000\r\n"); delay(3000); Serial.print("#3P2500T2000\r\n"); delay(2000); Serial.print("#3P1500T2000\r\n"); delay(2000); } </code></pre> <p>Photo of my connections: </p> <p><a href="https://i.stack.imgur.com/Verqy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Verqy.jpg" alt="arduino-duamilanovo+32-servo-controller+servo"></a></p> <p>Sorry if it post duplicate some, but I cannot google this problem.</p>
<p>There is one connection missing - the one that powers the servo and board.</p> <p>At the moment your servo board is getting a small amount of power through the RX pin - <strong>disconnect it immediately, you are damaging it</strong>.</p> <p>You need to provide +5V to the +5V terminal block, and also a suitable voltage (+5V should do) to the VCC on the terminal block.</p>
18284
|serial|rs485|
Serial: What is different between Gammon's RS485 (blocking) and RS485 "non blocking" libraries?
2015-11-30T21:30:14.120
<p>The RS485 master-slave communication library on Nick Gammon's page <a href="http://www.gammon.com.au/Arduino/RS485_protocol.zip" rel="nofollow">http://www.gammon.com.au/Arduino/RS485_protocol.zip</a> is working for me OK, but on the same hardware wiring is not working for the non-blocking library <a href="http://www.gammon.com.au/Arduino/RS485_non_blocking.zip" rel="nofollow">http://www.gammon.com.au/Arduino/RS485_non_blocking.zip</a>.</p> <p>I can not find information about the connection of MAX485 on Arduino for non-block version. Is MAX485/RS485 from HW serial (ie Rx=0 and Tx=1)?</p> <p>If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor? Thank you for the explanation. </p> <p>When I added the SoftwareSerial library into Nick's example for non-blocking, so it works, but is it still a non-blocking?</p> <pre><code>//Master: #include &lt;RS485_non_blocking.h&gt; #include &lt;SoftwareSerial.h&gt; const byte ENABLE_PIN = 4; SoftwareSerial mySerial(2,3); //RX = 2 TX = 3 size_t fWrite (const byte what) { return mySerial.write (what); } RS485 myChannel (NULL, NULL, fWrite, 0); void setup () { Serial.begin (9600); mySerial.begin (28800); myChannel.begin (); pinMode (ENABLE_PIN, OUTPUT); // driver output enable } // end of setup const byte msg [] = "Hello world"; void loop () { digitalWrite (ENABLE_PIN, HIGH); // enable sending myChannel.sendMsg (msg, sizeof (msg)); digitalWrite (ENABLE_PIN, LOW); // disable sending delay (1000); } // end of loop //Slave: #include &lt;RS485_non_blocking.h&gt; #include &lt;SoftwareSerial.h&gt; const byte ENABLE_PIN = 4; SoftwareSerial mySerial(2,3); //RX = 2 TX = 3 int fAvailable () { return mySerial.available (); } int fRead() { return mySerial.read (); } RS485 myChannel (fRead, fAvailable, NULL, 20); void setup() { Serial.begin(9600); mySerial.begin(28800); myChannel.begin(); pinMode (ENABLE_PIN, OUTPUT); // driver output enable } // end of setup void loop() { if (myChannel.update()) { Serial.write (myChannel.getData(), myChannel.getLength()); Serial.println(); } } // end of loop </code></pre> <p>Regards, Vava (Sorry for my English... :-)</p>
<p>Reference page: <a href="http://www.gammon.com.au/forum/?id=11428" rel="nofollow">http://www.gammon.com.au/forum/?id=11428</a></p> <hr> <p>The blocking library is intended where you want to wait for incoming data, and are prepared to do nothing else while it arrives. There is also a timeout parameter which lets the code proceed if nothing happens for a specified number of milliseconds.</p> <p>The non-blocking library is intended for where you need to do other things (like control motors, or read switches) at the same time you are receiving data. For that situation you call an <code>update</code> function periodically which assembles the incoming packet, byte-by-byte if necessary.</p> <p>When the data is fully received the <code>update</code> returns true, and you can process the packet.</p> <hr> <blockquote> <p>If so, how can a slave on the same line at the same time receive from master the message "hello world" and print it to the serial monitor?</p> </blockquote> <p>As I stated above in neither case do you receive and print "at the same time", however the non-blocking one does not simply wait until all the data has arrived.</p> <hr> <p>Example code from the linked page:</p> <pre class="lang-C++ prettyprint-override"><code>void loop () { if (myChannel.update ()) // returns true when packet fully received { Serial.write (myChannel.getData (), myChannel.getLength ()); Serial.println (); } // do other things while waiting } // end of loop </code></pre> <hr> <blockquote> <p>If in example for non-blocking libraries is the same wiring as in the example of blocking library, where is (in non-blocking example) definition of RX(=2) and TX(=3) pins?</p> </blockquote> <p>The hardware is the same.</p> <hr> <blockquote> <p>there is limitation for use - only pins which supports change interrupts.</p> </blockquote> <p>Of course. If the underlying protocol is SoftwareSerial then the usual limitations apply (that is for the Rx pin).</p>
18293
|arduino-uno|power|adafruit|
Looking at Adafruit's website I'm confused which wallcharger I should get
2015-12-01T04:16:12.413
<p>As the title says there are many different wall chargers to choose from.</p> <p>12v, 9v, 5v, with different mA amounts...</p> <p>The starter kit on Adafruit's website mentions to get the 9V 1000mA switching power adapter, so I'm curious if that's what we should get?</p> <p>here is the link to all of them.</p> <p>There are regular wall adapters, and these big power supplies...</p> <p><a href="http://www.adafruit.com/search?q=switching+power+adapter&amp;b=1" rel="nofollow">http://www.adafruit.com/search?q=switching+power+adapter&amp;b=1</a></p> <p>I'm just looking to run some LED Strip lights from the arduino and power some joystick buttons, some rotary encoder/knobs, and a keypad to work the LED lights</p> <p>Thoughts?</p> <p>Thanks!</p>
<p>Your Arduino Uno will use 35 to 50 mA at 5V. The “joystick buttons, some rotary encoder/knobs, and a keypad” will draw a small amount of current, probably between 1 and 10 mA. Thus, power for the Uno and your controls will be well under 100 mA and can be supplied via USB without any problem. (Also see: <em><a href="https://electronics.stackexchange.com/q/5498">How to get more than 100mA from a USB port</a></em>.)</p> <p>If your Uno enumerates and negotiates to get 500 mA via USB, you might have 450 mA available out of the +5V pin. However, in some cases if you need more than a few dozen mA to power other devices, it will make sense to get a separate 5V supply for them. (Eg, if the devices drag down the +5V and cause the Uno to reset, or if the devices are electrically noisy, like motors, RC servos, relays, solenoids.) Also, note that <a href="http://forum.arduino.cc/index.php?topic=70450.0" rel="nofollow noreferrer">thread #70450</a> at forum.arduino.cc says you can draw 650 mA (or 3.25 W of power) when the Uno is powered via its DC power jack.</p> <p>If your LED string has up to 6 or 7 WS2812B equivalents, you can power it from the Uno's 5V. Here is the all-lights-on, full-brightness calculation for six of them: 6 WS2812Bs x 3 LEDs per WS8211 x 21 mA per LED = 378 mA. For seven: 7 x 3 x 21 mA = 441 mA, which is out there on the edge.</p> <p>For longer LED strings, figure on a little over 3 W of power for every 10 WS2812B equivalents. (Calculation: 5 volts x 10 WS2812Bs x 3 LEDs per WS2812B x 21 max mA per LED = 3150 mW = 3.15 W.) For example, get a 10 W (2 A x 5 V) or greater 5V power supply for a meter of 30- WS2812B-per-meter LED strip, etc. This power supply will connect directly to the LED strip's power connectors. The ground from the LED strip will connect to the Uno's ground, to establish a signal reference point.</p> <p>Note, the absolute max voltage rating for a WS2812B, according to its datasheet, is 5.3 V, so use a supply whose voltage does not exceed 5.3 V. The absolute min voltage rating is 3.5 V; they will work ok on 3.7 V LIPO batteries, but 3V3 power is out of spec for a WS2812B.</p> <p>As mentioned in a previous question, if your LED strip is being installed inside a desktop PC, the PC's power supply will have lots of 5 V power available, and you can hook on to one of the red +5V wires and black Gnd wires from its supply to power the LEDs, either while powering the Uno itself from USB power or while using the same +5V to power the Uno as the LEDs.</p>
18300
|arduino-uno|serial|
Leostick Receiving message from Uno using USB jumpers cables
2015-12-01T06:52:10.163
<p>I have a Arduino Uno which is looping over Serial.println("$testmessage"). Connected to this is a USB cable that i have cut and soldered male jumper leads to . I need to receive this message ("$testmessage") from the Uno using this USB cable without using the leosticks usb connector. After receiving the correct messgae from the Uno i plan to use Serial to send data from the leostick to my pc.</p> <p>I'm stuck trying to figure out how to receive this message from the Uno. </p> <p>Currently the the USB 5v and ground is connected to the leosticks 5V, GND pins. The Uno powers on and the the tx led is flashing every 100 milliseconds. </p> <p>Can i just plug the green and white wires from the USB cable into D0&amp;D1 and except it to work?</p> <p>(Uno plugs into usb cable in the image) <a href="https://i.stack.imgur.com/M0kbb.jpg" rel="nofollow noreferrer">https://i.stack.imgur.com/M0kbb.jpg</a></p>
<p>While USB <em>is</em> a serial protocol, it's a completely different serial protocol than the RS-232-style logic-level serial protocol that the Serial library supports. So the approach mentioned in the question has no logical chance of working.</p> <p>Also, the USB electrical signal is differential (double-ended, or line-to-line, rather than single-ended, or line-to-ground). So the mentioned approach has no electrical chance of working.</p> <p>What may work is to wire from Tx on the Uno to Rxd1 on the Leostick, and from Rx to Txd1, unless that conflicts with the Leostick's USB-Serial link.</p>
18311
|arduino-uno|serial|programming|i2c|
I2C connection with MT9D111 camera module, strange results after writing registers via i2C
2015-12-01T14:26:44.363
<p>I am currently working on a camera platform based on the MT9D111 module from Micron. The first thing to do is to write the configuration to the numerous registers of the chip which is done via an i2C connection.</p> <p>I adapted the code from <a href="https://hackaday.io/project/6386-usensecam/log/20618-checking-mt9d111-communication" rel="nofollow noreferrer">here</a> for testing this with an Arduino Uno. 3.3V supply and 8MHz clock are also provided by the Arduino.</p> <p>Everything seems to work fine, but there are some odds which I don't know the reason for.</p> <p>So here is the code (I just added the soft reset sequence according to the Developers Guide):</p> <pre><code>const int freqOutputPin = 9; // OC1A output pin for ATmega328 boards #define TMR1 0 #include &lt;Wire.h&gt; #include &lt;avr/io.h&gt; #include &lt;util/delay.h&gt; //#include &lt;TimerOne.h&gt; #include &lt;avr/interrupt.h&gt; void setup() { pinMode(freqOutputPin, OUTPUT); Serial.begin(9600); TCCR1B |= (1 &lt;&lt; CS10); //selecting prescaler 0b001 (Tclk/1) TCCR1B &amp;= ~((1 &lt;&lt; CS12) | (1 &lt;&lt; CS11)); // turn off CS12 and CS11 bits TCCR1A |= ((1 &lt;&lt; WGM11) | (1 &lt;&lt; WGM10)); //Configure timer 1 for TOP mode (with TOP = OCR1A) TCCR1B |= ((1 &lt;&lt; WGM13) | (1 &lt;&lt; WGM12)); TCCR1A |= (1 &lt;&lt; COM1A0); // Enable timer 1 Compare Output channel A in toggle mode TCCR1A &amp;= ~(1 &lt;&lt; COM1A1); TCNT1 = 0; OCR1A = TMR1; delay(500); //Initial delay Wire.begin(); // join i2c bus as master Serial.begin(9600); Serial.println("MT9D111 Camera Module + Arduino"); Serial.println("Read and Write 16-bit register value example"); Serial.println("* Read expected value = 0x1519 from Register 0x00"); Serial.println("* Write value = 0xA5F0 to Register 0x20:1"); Serial.println(); init1(); //execute code just 1 time } void loop() { } void init1() { int16_t a; delay(500); //wait until start Serial.print("Soft reset first"); Serial.println(); soft_reset();//do a soft reset at startup //***************Configuration here!****************// Serial.print("Read result from register 0x00"); a = read_reg(0); Serial.println(); Serial.print("0x"); Serial.println(a, HEX); //print result Serial.println(); Serial.print("Read original data from register 0x0a, should be 11"); Serial.println(); a = read_reg(10); Serial.print("0x"); Serial.println(a, HEX); //print result Serial.println(); //Enable this part for writing register //Some example reads and writes follow Serial.print("Writing 0xA5F0 in register 0x20:1"); Serial.println(); write_reg(32, 1, 165, 240); Serial.print("Read new value from register 0x20:1"); Serial.println(); a = read_reg(32); Serial.print("0x"); Serial.println(a, HEX); //print result Serial.println(); Serial.print("Writing 0xA1F3 in register 0x20:1"); Serial.println(); write_reg(32, 1, 161, 243); Serial.print("Read new value from register 0x20:1"); Serial.println(); a = read_reg(32); Serial.print("0x"); Serial.println(a, HEX); //print result Serial.println(); } //Write 2Byte register void write_reg(int reg_address, int page, int data_msb, int data_lsb) { delay(5); //5ms Wire.beginTransmission(93); // transmit to device 93, Camera Module Wire.write(240); //page register address Wire.write(0); Wire.write(page); //select page 0/1/2 Wire.endTransmission(1); // stop transmitting Wire.beginTransmission(93); // transmit to device 93, Camera Module Wire.write(reg_address); //register address 8bit, decimal Wire.write(data_msb); //msbyte Wire.write(data_lsb); //lsbyte Wire.endTransmission(1); // stop transmitting } //read 2Byte register //be careful about selected register page int16_t read_reg(int reg_address) { int16_t err; delay(5); //5ms Wire.beginTransmission(93); // transmit to device 93, Camera Module Wire.write(reg_address); //register address 8bit, decimal err = Wire.endTransmission(1); // stop transmitting Serial.println(err); Wire.requestFrom(93, 2, 1); //request value form device 93, 2 bytes with stop bit int16_t result = ((Wire.read() &lt;&lt; 8) | Wire.read()); //read 16 bits return result; } //Perform Soft reset, required at startup void soft_reset(){ write_reg(101, 0, 160, 0);//write registers according to dev guide write_reg(195, 1, 5, 1); write_reg(13, 0, 0, 33); delay(5); write_reg(13, 0, 0, 0); delay(5);//wait for i2c to be ready again } </code></pre> <p>Running this code gives me the following result on the serial monitor:</p> <p><a href="https://i.stack.imgur.com/8j3Tr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8j3Tr.png" alt="Serial Monitor"></a></p> <p>So here are the questions:</p> <ol> <li>Do you have any ideas why I get an extra FFFF when reading a register after writing it? (underlined in blue)</li> <li>Why are there some extra zeros in the output? (marked in yellow)</li> </ol>
<p>The <code>0</code> comes from your code:</p> <pre><code>Serial.println(err); </code></pre> <p>It's printing the error code. 0, hence no error.</p> <p>As for the extra <code>FFFF</code> I'd say it's because you are using signed integers. Change your <code>a</code> declaration to <code>uint16_t</code> and see if that fixes it.</p>
18312
|arduino-uno|rtc|
Arduino RTC - getting the time from RTC after the power is cut off
2015-12-01T14:33:35.060
<p>I have a new DS1307 (original, not a Chinese rip off), with a new battery. It is working great, but when I turn the Arduino off (it is currently connected to laptop) and then turn it back on, it resets the time.</p> <p>The line that sets the time is (in setup part of code):</p> <pre><code>setDS1307time(30, 42, 21, 4, 26, 11, 14); </code></pre> <p>So, when the Arduino gets the power back it runs the program again and it overrides the correct current time.</p> <p>How can I avoid this?</p>
<p>If setup() runs, it is because the system has been restarted. It could becuase the reset button was pushed, or it could be due to a power-cycle. But either way, the code will start over completely. So you could</p> <ol> <li><p>Deal with restart issues in setup() as it will only be called once per session (unless you call it in your own code); or</p></li> <li><p>Make a variable <code>static boolean PowerCycled = true;</code> and clear it once your code has dealt with its re-start issues. After a restart, the initialzed data will get reloaded, including <code>PowerCycled</code> with it's initial value of <code>true</code> restored.</p></li> </ol>
18320
|teensy|midi|
Teensy MIDI Show Control
2015-12-01T21:50:01.197
<p>I'd like to use my Teensy 3.1 to send MIDI Show Control messages using USB MIDI in order to control an ETC Nomad system. These are different from standard NoteOn, NoteOff, ProgramChange, etc. commands, but as far as I can tell they are not supported by the standard library.</p> <p>Is there any way I can send these messages directly (using lower level commands), as seen <a href="http://www.mymidiremotes.com/home/?page_id=46" rel="nofollow">here</a>, or does anyone know of a library that supports this? Google has, unusually, not been much help.</p>
<p>According to the <a href="https://www.pjrc.com/teensy/td_midi.html" rel="noreferrer">documentation</a>, SysEx messages are sent like any other messages:</p> <pre class="lang-c prettyprint-override"><code>array[0] = 0xf0; array[1] = 0x7f; array[2] = 0x7f; array[3] = 0x02; array[4] = 0x7f; array[5] = 0x01; array[6] = 0xf7; usbMIDI.sendSysEx(7, array); </code></pre>
18321
|wire-library|
Using a class instance with Wire.onReceive
2015-12-01T23:30:45.827
<p>Is it possible to register a class instance member function with Arduino's <a href="https://www.arduino.cc/en/Reference/WireOnReceive" rel="nofollow">Wire.OnReceive</a>?</p> <p>I'm trying to make my code object-oriented, and want a specific non-static class function to handle I2C data, but if I'm reading <a href="http://forum.arduino.cc/index.php?topic=116685.0" rel="nofollow">this thread</a> correctly, <code>onReceive</code> is incompatible with classes since it only accepts a function pointer, which won't store context.</p>
<p>A non-static class member function has an implicit <code>ClassName *this</code> parameter inserted as the first parameter in the parameter list.</p> <p>Because the function prototype required for <code>Wire.onReceive()</code> does not have that parameter specified in its parameter list a non-static member function is not compatible with it.</p> <p>The same goes for <code>attachInterrupt()</code> and anything else that takes a function pointer.</p>
18333
|arduino-micro|isp|
multiple connection with ISP Pin at Arduino Micro
2015-12-02T08:14:50.923
<p>Actually I'm not good at English ;-) trying to ask to you. please understand me :)</p> <p>I needed connect SD card Shield and TFT LCD Screen to Arduino Micro.</p> <p>successfully finished compile at source code but when i connect MISO together </p> <p>it doesn't work. only SS pin is connected separate Pin's to Micro</p> <p>How can i make it work together to Micro.. </p> <p>i've checked each device perfectly work at Micro</p> <p>Plese Help me!!</p> <p>Regards and Thanks</p>
<p>Each SPI device must have a separate device/slave select pin. The device must disconnect (high impedance state) when not selected. The SD shield will have a level shifter. It may not correctly disconnect from MISO. </p> <p>Depending on what libraries you are using you might also need to check that they set the SPI hardware attributes correctly (clock, mode, etc). </p> <p>For more help please post code and references to the shields and libraries.</p> <p>Cheers!</p>
18339
|arduino-uno|memory-usage|progmem|
How to correctly pack an unsigned long from 3 unsigned chars?
2015-12-02T12:41:45.073
<p>I would like to use 652 unsigned long values on an Arduino Uno, but it doesn't look like there's enough memory. I thought about the splitting unsigned long values to 3 unsigned chars to store in PROGMEM which I can letter recall and join as unsigned long as needed.</p> <p>I'm not super experienced with byte manipulations and I got myself stuck when trying to merge the data. When I try with one variable at a time, I get the expected output. The part I'm confused about is why do I get different values when using a variable as an array index for each value ? How can I fix this ?</p> <p>Here's my test code so far:</p> <pre><code>#include &lt;avr/pgmspace.h&gt; #include "flashData.h" void setup() { Serial.begin(115200); unsigned long fromPROGMEM = (onsets1[0] &lt;&lt; 16) | (onsets2[0] &lt;&lt; 8) | onsets3[0]; Serial.println(fromPROGMEM); unsigned long fromValues = (0x00 &lt;&lt; 16) | (0x01 &lt;&lt; 8) | 0xF3; Serial.println(fromValues); byte b1 = 0x00; byte b2 = 0x01; byte b3 = 0xF3; unsigned long fromBytes = (b1 &lt;&lt; 16) | (b2 &lt;&lt; 8) | b3; Serial.println(fromBytes); delay(2000); unsigned char c1,c2,c3; unsigned long value; Serial.println("data using same index:"); for(int i = 0 ; i &lt; 10; i++){ c1 = onsets1[3]; c2 = onsets2[3]; c3 = onsets3[3]; value = (c1 &lt;&lt; 16) | (c2 &lt;&lt; 8) | c3; Serial.print("index: "); Serial.print(i); Serial.print("\tvalue:"); Serial.println (value); delay(10); } Serial.println("data using counter:"); for(int i = 0 ; i &lt; 10; i++){ c1 = onsets1[i]; c2 = onsets2[i]; c3 = onsets3[i]; value = (c1 &lt;&lt; 16) | (c2 &lt;&lt; 8) | c3; Serial.print("index: "); Serial.print(i); Serial.print("\tvalue:"); Serial.println (value); delay(10); } } void loop() { } </code></pre> <p>and flashData.h:</p> <pre><code>#ifndef _flashData_h_ #define _flashData_h_ static PROGMEM const unsigned char onsets1[652] = {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x01,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x02,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03,0x03}; static PROGMEM const unsigned char onsets2[652] = {0x01,0x04,0x05,0x06,0x07,0x08,0x09,0x0A,0x0D,0x0E,0x0F,0x10,0x11,0x12,0x14,0x15,0x16,0x17,0x18,0x19,0x1A,0x1B,0x1D,0x1E,0x1F,0x20,0x21,0x22,0x23,0x25,0x26,0x28,0x29,0x2A,0x2B,0x2C,0x2E,0x2F,0x30,0x31,0x32,0x33,0x34,0x35,0x38,0x39,0x3A,0x3B,0x3C,0x3F,0x40,0x41,0x42,0x43,0x44,0x45,0x46,0x48,0x49,0x4A,0x4C,0x4D,0x4E,0x51,0x52,0x53,0x54,0x55,0x56,0x57,0x59,0x5A,0x5B,0x5C,0x5E,0x5F,0x61,0x63,0x64,0x65,0x67,0x6A,0x6B,0x6C,0x6D,0x6E,0x70,0x71,0x73,0x75,0x76,0x77,0x79,0x7C,0x7E,0x7F,0x80,0x82,0x84,0x85,0x86,0x87,0x88,0x89,0x8A,0x8C,0x8D,0x8E,0x8F,0x90,0x91,0x92,0x95,0x96,0x97,0x98,0x99,0x9A,0x9B,0x9C,0x9E,0x9F,0xA0,0xA1,0xA2,0xA3,0xA4,0xA7,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAF,0xB0,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB9,0xBA,0xBB,0xBC,0xBD,0xBE,0xC0,0xC2,0xC4,0xC6,0xC9,0xCB,0xCD,0xCF,0xD2,0xD4,0xD6,0xD8,0xDA,0xDB,0xDD,0xDF,0xE0,0xE2,0xE4,0xE6,0xE7,0xE8,0xE9,0xEB,0xEC,0xED,0xEE,0xEF,0xF0,0xF1,0xF2,0xF4,0xF6,0xF7,0xF8,0xF9,0xFA,0xFD,0xFE,0xFF,0x00,0x01,0x02,0x03,0x06,0x07,0x08,0x0A,0x0D,0x0F,0x10,0x11,0x12,0x13,0x14,0x16,0x18,0x19,0x1A,0x1C,0x1D,0x1F,0x21,0x22,0x23,0x25,0x28,0x2A,0x2B,0x2C,0x2E,0x30,0x31,0x33,0x34,0x35,0x38,0x3C,0x3D,0x3E,0x41,0x42,0x44,0x45,0x46,0x47,0x48,0x4A,0x4B,0x4C,0x4D,0x4E,0x4F,0x50,0x53,0x54,0x56,0x57,0x58,0x59,0x5B,0x5C,0x5D,0x5E,0x5F,0x60,0x61,0x63,0x65,0x66,0x67,0x69,0x6A,0x6D,0x6E,0x6F,0x70,0x71,0x72,0x73,0x75,0x77,0x78,0x79,0x7A,0x7B,0x7D,0x7E,0x7F,0x80,0x82,0x84,0x87,0x89,0x8B,0x8E,0x90,0x92,0x94,0x97,0x99,0x9B,0x9D,0xA0,0xA2,0xA4,0xA5,0xA6,0xA8,0xA9,0xAA,0xAB,0xAC,0xAD,0xAE,0xAF,0xB1,0xB2,0xB3,0xB4,0xB5,0xB6,0xB9,0xBA,0xBB,0xBD,0xBF,0xC0,0xC2,0xC4,0xC6,0xC7,0xC8,0xCB,0xCC,0xCD,0xCE,0xCF,0xD1,0xD4,0xD5,0xD6,0xD7,0xD8,0xD9,0xDA,0xDC,0xDD,0xDE,0xDF,0xE0,0xE1,0xE2,0xE4,0xE6,0xE8,0xEA,0xEB,0xED,0xEF,0xF1,0xF2,0xF3,0xF5,0xF6,0xF8,0xF9,0xFA,0xFB,0xFC,0xFF,0x01,0x03,0x04,0x05,0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0F,0x10,0x11,0x12,0x13,0x15,0x16,0x18,0x19,0x1A,0x1B,0x1C,0x1D,0x1E,0x20,0x21,0x23,0x24,0x25,0x27,0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x30,0x32,0x33,0x35,0x36,0x37,0x3A,0x3B,0x3C,0x3E,0x40,0x43,0x44,0x45,0x47,0x48,0x49,0x4A,0x4C,0x4D,0x4E,0x50,0x55,0x56,0x57,0x59,0x5A,0x5B,0x5E,0x5F,0x60,0x61,0x62,0x63,0x65,0x66,0x67,0x68,0x69,0x6B,0x6C,0x6F,0x70,0x71,0x72,0x73,0x74,0x76,0x77,0x79,0x7A,0x7B,0x7D,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x88,0x89,0x8A,0x8B,0x8C,0x8D,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x99,0x9B,0x9D,0x9F,0xA2,0xA4,0xA6,0xA8,0xAB,0xAD,0xAF,0xB1,0xB4,0xB6,0xB7,0xB8,0xBB,0xBD,0xBE,0xBF,0xC0,0xC1,0xC2,0xC4,0xC5,0xC6,0xC7,0xC8,0xC9,0xCA,0xCC,0xCD,0xCE,0xCF,0xD1,0xD3,0xD6,0xD8,0xDA,0xDC,0xDE,0xDF,0xE0,0xE1,0xE3,0xE4,0xE5,0xE7,0xE8,0xE9,0xEA,0xEC,0xEF,0xF0,0xF1,0xF2,0xF3,0xF4,0xF5,0xF7,0xF8,0xF9,0xFA,0xFB,0xFC,0xFE,0x01,0x03,0x04,0x05,0x07,0x09,0x0A,0x0B,0x0C,0x0E,0x10,0x12,0x13,0x14,0x15,0x17,0x18,0x1A,0x1C,0x1E,0x1F,0x20,0x21,0x23,0x24,0x25,0x26,0x27,0x28,0x29,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,0x31,0x32,0x34,0x35,0x37,0x39,0x3C,0x3E,0x40,0x42,0x43,0x45,0x47,0x49,0x4A,0x4B,0x4C,0x4E,0x50,0x52,0x53,0x54,0x56,0x57,0x58,0x59,0x5B,0x5C,0x5D,0x5F,0x60,0x61,0x62,0x64,0x66,0x68,0x69,0x6B,0x6C,0x6D,0x6E,0x70,0x71,0x72,0x74,0x75,0x76,0x78,0x79,0x7B,0x7C,0x7D,0x7F,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x8A,0x8B,0x8C,0x8D,0x8F,0x90,0x91,0x93,0x94,0x95,0x96,0x97,0x98,0x9B,0x9D,0x9F,0xA1}; static PROGMEM const unsigned char onsets3[652] = {0xF3,0x31,0x59,0x76,0x98,0xBA,0xDD,0xFF,0x43,0x66,0x88,0xAA,0xC7,0xEF,0x0B,0x2D,0x50,0x72,0x8E,0xB1,0xD3,0xF5,0x17,0x3A,0x5C,0x7E,0xA0,0xC8,0xE5,0x0D,0x29,0x6E,0x90,0xAC,0xD5,0xF7,0x13,0x35,0x58,0x7A,0x9C,0xB9,0xE1,0xFD,0x42,0x6A,0x86,0xA8,0xC5,0x0F,0x31,0x54,0x7C,0x92,0xB5,0xCB,0xF9,0x1B,0x43,0x60,0xA4,0xC1,0xE3,0x28,0x4A,0x72,0x8E,0xB1,0xD3,0xF5,0x17,0x34,0x5C,0x78,0xBD,0xDF,0x01,0x46,0x62,0x84,0xCF,0x0D,0x30,0x52,0x7A,0x91,0xD5,0xF7,0x1A,0x5E,0x86,0xA3,0xE7,0x26,0x5F,0x92,0xAF,0xF3,0x1B,0x32,0x5A,0x7C,0x9F,0xBB,0xE3,0x00,0x28,0x4A,0x66,0x89,0xAB,0xC7,0x0C,0x34,0x4A,0x72,0x95,0xB7,0xD9,0xFB,0x1E,0x3A,0x62,0x7F,0x9B,0xC3,0xE0,0x2A,0x52,0x69,0x91,0xB3,0xD5,0xF7,0x1F,0x36,0x58,0x80,0x9D,0xB9,0xE1,0xF8,0x42,0x65,0x81,0xA9,0xCB,0xE8,0x10,0x54,0x93,0xD2,0x16,0x60,0x9F,0xE4,0x28,0x6D,0xAB,0xF0,0x12,0x34,0x79,0xB2,0xDA,0x02,0x46,0x85,0xAD,0xCF,0xF2,0x0E,0x30,0x4D,0x75,0x97,0xB9,0xD0,0xFE,0x1A,0x65,0x87,0xA3,0xC5,0xE2,0x2C,0x4E,0x6B,0x8D,0xAF,0xD7,0xEE,0x38,0x5B,0x77,0xC1,0x00,0x45,0x67,0x89,0xAB,0xCE,0xF0,0x01,0x57,0x7F,0x95,0xDA,0xFC,0x1E,0x5D,0x7F,0x9C,0xE0,0x25,0x6F,0x91,0xAE,0xF2,0x14,0x3C,0x7B,0x98,0xBA,0x04,0x82,0xAF,0xCC,0x16,0x33,0x77,0x94,0xBC,0xD2,0xFA,0x1D,0x3F,0x61,0x7D,0xA6,0xC8,0xE4,0x29,0x51,0x8F,0xAC,0xCE,0xF0,0x13,0x35,0x57,0x79,0x9C,0xBE,0xE0,0x02,0x47,0x69,0x8B,0xCA,0xF2,0x31,0x53,0x75,0x98,0xBA,0xD6,0xF9,0x15,0x5F,0x82,0xA4,0xC6,0xE8,0x05,0x33,0x60,0x7D,0xBC,0xFA,0x3F,0x83,0xC2,0x0C,0x51,0x95,0xD4,0x18,0x5D,0xA1,0xE0,0x25,0x69,0xA8,0xD0,0xE7,0x0F,0x31,0x53,0x75,0x98,0xB4,0xDC,0xF9,0x1B,0x3D,0x5F,0x7C,0xA4,0xC0,0x05,0x21,0x49,0x88,0xD2,0xF4,0x11,0x55,0x94,0xBC,0xDE,0x1D,0x4B,0x62,0x8F,0xAC,0xF0,0x2F,0x57,0x74,0x96,0xB2,0xD5,0xF7,0x1F,0x3B,0x63,0x86,0xAE,0xC4,0xEC,0x09,0x47,0x8C,0xD0,0xF3,0x15,0x54,0x98,0xC0,0xE2,0x05,0x21,0x66,0x88,0xA4,0xD2,0xEF,0x39,0x72,0xBC,0xD9,0xFB,0x23,0x3F,0x62,0x84,0xA0,0xC3,0xF0,0x07,0x2F,0x4C,0x74,0x90,0xCF,0xF7,0x13,0x3B,0x58,0x74,0x9C,0xB9,0xDB,0x03,0x1F,0x6A,0x86,0xA3,0xED,0x0F,0x31,0x4E,0x76,0x92,0xB5,0xF9,0x27,0x38,0x7C,0xA4,0xC1,0x05,0x28,0x4A,0x8E,0xCD,0x11,0x3A,0x50,0x9B,0xBD,0xDF,0x93,0x24,0x40,0x68,0xA7,0x2A,0x58,0x74,0xB9,0xDB,0xF7,0x3C,0x5E,0x80,0xA3,0xC5,0xE7,0x09,0x2C,0x48,0x70,0x8D,0xD1,0xF9,0x38,0x54,0x77,0x9F,0xBB,0xDD,0x00,0x22,0x60,0x83,0x9F,0xE9,0x11,0x2E,0x50,0x72,0x95,0xB7,0xDF,0xFB,0x18,0x40,0x5C,0x7F,0xA1,0xB8,0x08,0x2A,0x46,0x6E,0x8B,0xAD,0xD5,0xFD,0x14,0x58,0x97,0xDC,0x20,0x59,0xA9,0xEE,0x32,0x71,0xB5,0xF4,0x38,0x77,0x99,0xC1,0x06,0x4A,0x6D,0x8F,0xAB,0xCE,0xF0,0x0C,0x34,0x57,0x79,0x95,0xBD,0xDA,0x02,0x1E,0x46,0x5D,0xA7,0xE6,0x25,0x6F,0xAE,0xF2,0x14,0x37,0x5F,0x7B,0xC0,0xE8,0xFE,0x21,0x43,0x6B,0x8D,0xC6,0x10,0x33,0x55,0x77,0x99,0xBC,0xD8,0x00,0x1D,0x45,0x5B,0x83,0xA0,0xE4,0x29,0x67,0x8F,0xAC,0xF0,0x18,0x35,0x63,0x79,0xB8,0xFD,0xC1,0x4D,0x6F,0x86,0xCA,0xF2,0x09,0x4D,0x92,0xBA,0xD6,0xF9,0x15,0x37,0x59,0x82,0xA4,0xBA,0xE8,0x05,0x27,0x49,0x6B,0x8E,0xAA,0xCC,0xEF,0x17,0x33,0x78,0xB6,0x01,0x3F,0x7E,0xC3,0xEB,0x07,0x4C,0x90,0xB2,0xD5,0xFD,0x19,0x5E,0xA2,0xBE,0xE1,0x03,0x25,0x47,0x64,0xAE,0xD6,0xED,0x15,0x31,0x59,0x76,0xB5,0xF9,0x1B,0x3E,0x7C,0xA4,0xC7,0xE9,0x0B,0x33,0x50,0x8E,0xB6,0xD9,0x01,0x11,0x56,0x7E,0x95,0xDF,0x9F,0x13,0x29,0x46,0x68,0x8A,0xAC,0xC9,0xEB,0x0D,0x2A,0x52,0x6E,0xAD,0xCF,0xF7,0x25,0x30,0x64,0x7B,0xA3,0xBF,0x09,0x42,0x8D,0xCB}; #endif </code></pre> <p>And here's what I see from Serial:</p> <pre><code>499 499 499 data using same index: index: 0 value:1654 index: 1 value:1654 index: 2 value:1654 index: 3 value:1654 index: 4 value:1654 index: 5 value:1654 index: 6 value:1654 index: 7 value:1654 index: 8 value:1654 index: 9 value:1654 data using counter: index: 0 value:4294945024 index: 1 value:4294962688 index: 2 value:12806 index: 3 value:28928 index: 4 value:4294948096 index: 5 value:4294964224 index: 6 value:14337 index: 7 value:30464 index: 8 value:4294940928 index: 9 value:4294951174 </code></pre> <p>I see what I expect for first 3 values and also for data using same index, but no when using a variable as an index for the PROGMEM arrays.</p> <p>What is going on and how can I fix this ?</p> <p><strong>Update</strong> Mikael's answer is the solution, but I will post a working snippet here for reference:</p> <pre><code>#include &lt;avr/pgmspace.h&gt; #include "flashData.h" void setup() { Serial.begin(115200); delay(2000); unsigned char c1,c2,c3; unsigned long value; Serial.println("data using counter:"); for(int i = 0 ; i &lt; 652; i++){ c1 = (unsigned char) pgm_read_byte(&amp;onsets1[i]); c2 = (unsigned char) pgm_read_byte(&amp;onsets2[i]); c3 = (unsigned char) pgm_read_byte(&amp;onsets3[i]); value = (((unsigned long) c1) &lt;&lt; 16) | ((unsigned long)c2 &lt;&lt; 8) | (unsigned long)c3; Serial.print("index: "); Serial.print(i); Serial.print("\tvalue:"); Serial.println (value); delay(10); } } void loop() { } </code></pre> <p>The key is not only explicitly casting the data read, but also correctly reading the the PROGMEM data.</p>
<p>I got it to work by typecasting firmly and using multiplications:</p> <pre><code> Serial.println("data using counter:"); for (int i = 0 ; i &lt; 10; i++) { c1 = onsets1[i]; c2 = onsets2[i]; c3 = onsets3[i]; value = (uint8_t)c3 + (uint16_t)((uint8_t)c2*256)+(uint32_t)(c1*65536); Serial.print("index: "); Serial.print(i); Serial.print("\t"); Serial.print(c1, HEX); Serial.print(", "); Serial.print(c2, HEX); Serial.print(", "); Serial.print(c3, HEX); Serial.print(" "); Serial.print("\tvalue:"); Serial.println (value, HEX); } </code></pre> <p>The result:</p> <blockquote> <pre><code>data using counter: index: 0 A1, F6, 0 value:A1F600 index: 1 FC, A7, 0 value:FCA700 index: 2 B5, 7A, B8 value:B57AB8 index: 3 EF, DB, 0 value:EFDB00 index: 4 14, F9, 0 value:14F900 index: 5 D7, 7F, 0 value:D77F00 index: 6 F2, 72, 1 value:F27201 index: 7 6F, DB, 0 value:6FDB00 index: 8 5E, 5E, 0 value:5E5E00 index: 9 F0, E7, B8 value:F0E7B8 </code></pre> </blockquote>
18341
|arduino-uno|bluetooth|relay|remote-control|
Controlling 2 relays with IR remote, push button and bluetooth - sort of works, need help!
2015-12-02T13:17:24.337
<p>I'm still very new to arduino and coding and having some difficulties trying to figure out what I am doing wrong here. </p> <p>This program is to have control over 2 relays, using a combination of an IR receiver and a ir_remotecontrol with pre-programmed buttons (ir_remote buttons 1 = relay 1 toggle, button 2 = relay 2 toggle). A master momentary hard wired switch to override changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if only 1 relay is on toggle it off with first click of button then toggle both back on after second click of button. The Bluetooth module and android app is to also control relays the same as the ir_remote via integers sent through the serial port.</p> <p>It all sort of works at the moment...</p> <p>If I just work the relays using the ir remote and the momentary switch it all works perfectly. </p> <p>if I make sure the relays are in the off position using the remote switch and then use the Bluetooth it also works perfectly. </p> <p>The problem only is when I use a combination of the ir remote or switch and the Bluetooth - things get weird - the Bluetooth commands seem to reverse and the relays start making a buzzing noise and the momentary switch muddles things up so basically it's all bad news! I've stared at this code for hours and tried a few different things but I just can't see what's wrong.</p> <p>Let me know if I need to give a more detailed example of the errors I am having. Just thinking it is probably obvious for you pro's out there when you see my noob code!. </p> <p>Any help would be greatly appreciated! </p> <pre><code>/*This program is to have control over 2 relays, using a cobination of an IR reciever and remote control with pre programmed buttons (ir_remote buttons 1 = relay 1 toggle, 2 = relay 2 toggle). A master momentery hard wired switch to overide changes to the relays and toggle their states i.e if both relays are on via ir remote - toggle them off, or if 1 only relay is on toggle it off with first click of button then toggle both back on after sencond click of button. Bluetooth module and andoid app to also control relays the same as the ir_remote. */ //include libaries, and initialise variables #include &lt;SoftwareSerial.h&gt; #include &lt;IRremote.h&gt; #define irPin 8 #define RxD 7 #define TxD 6 #define relay1 13 #define relay2 12 #define buttonPin 2 SoftwareSerial blueTooth(RxD, TxD); IRrecv irrecv(irPin); decode_results results; int comdata; const int wait = 30; int sensorValue = 0; int sensorOut = 0; int relay1State = 0; int relay2State = 0; int masterState = 0; int buttonState = 0; int lastButtonState = 0; long lastDebounceTime = 0; long debounceDelay = 50; void setup() { blueTooth.begin(38400); //set bluetooth baud rate delay(500); irrecv.enableIRIn(); //enable infrared recieve pinMode(relay1, OUTPUT); //setting relays 1 &amp; 2 to output pinMode(relay2, OUTPUT); pinMode(buttonPin, INPUT); //setting momentery swith (overide) to inpt digitalWrite(relay1, relay1State); //putting current status of relays into a variable digitalWrite(relay2, relay2State); } void loop() { if (blueTooth.available()) //setting a variable for bluetooth recieved serial commands comdata = blueTooth.read(); if(comdata == '1'){ digitalWrite(relay1, relay1State); //if bluetooth receivs "1" toggle relay1state -- essentially relay 1 ON } if(comdata == '0'){ digitalWrite(relay1, !relay1State); //if bluetooth receivs "0" toggle relay1state -- essentially relay 1 OFF } if(comdata == '2'){ digitalWrite(relay2, relay2State); //if bluetooth receivs "2" toggle relay2state -- essentially relay 2 ON } if(comdata == '3'){ digitalWrite(relay2, !relay2State); //if bluetooth receivs "3" toggle relay2state -- essentially relay 2 OFF } if (irrecv.decode(&amp;results)){ //Start listing for ir commands, if set remote button code is recvived toggle the variable relay1State or relay2state switch (results.value){ case 0xFF30CF: relay1State = !relay1State; digitalWrite(relay1, relay1State); delay(250); break; case 0xFF18E7: relay2State = !relay2State; digitalWrite(relay2, relay2State); delay(250); break; } irrecv.resume(); } int reading = digitalRead(buttonPin); //debounce used to help with faulse readings from momentery switch if (reading != lastButtonState) { lastDebounceTime = millis(); } if ((millis() - lastDebounceTime) &gt; debounceDelay) { if (reading != buttonState) { buttonState = reading; if (buttonState == HIGH) { //if the momentery switch is pressed toggle masterstate which is both relay 1 and relay 2 state masterState = !masterState; relay1State = masterState; relay2State = masterState; } } } digitalWrite(relay1, relay1State); digitalWrite(relay2, relay2State); lastButtonState = reading; } </code></pre>
<p>Looks like it could be reusing the old comdata values in the first part of loop(). Maybe make the first chunk:</p> <pre><code> if (blueTooth.available()) { comdata = blueTooth.read(); switch (comdata) { // set state variables based on bluetooth case '0': // if bluetooth receivs "0" clear 1 relay1State = 0; break; case '1': // if bluetooth receivs "1" set 1 relay1State = 1; break; case '2': // if bluetooth receivs "2" set 2 relay2State = 1; break; case '3': // if bluetooth receivs "1" clear2 relay2State = 0; break; case '4': // if bluetooth receivs "4" toggle 1 relay1State = !relay1State; break; case '5': // if bluetooth receivs "5" toggle 2 relay2State = !relay2State; break; case '6': // if bluetooth receivs "6" toggle master/both masterState = relay1State = relay2State = !masterState; break; } // end of switch // apply state variables to outputs // (could be left to the end of the loop() code) digitalWrite(relay1, relay1State); digitalWrite(relay2, relay2State); } // end of bluetooth processing ... /// IR processing code // debounce button and toggle masterstate &amp; set state vars accordingly // see http://arduino.stackexchange.com/questions/17443/how-to-simulate-delay-to-debounce-mechanical-button-using-millis // // re-ensure output state matches the state variables. digitalWrite(relay1, relay1State); digitalWrite(relay2, relay2State); } </code></pre> <p>As it is, the if() statements trigger on the state of the last read comdata, not on the whether a new command was read.</p> <p>Also, maybe check whether the toggling comments match the code or the code matches the intention properly.</p>
18348
|programming|arduino-mega|data-type|
Arduino Variable Data Type?
2015-12-02T16:28:15.437
<p>Is there a variable data type available for Arduino? I have a class that should have a member that will differ in data type, in the past I have used the "variable" keyword in c++ but when I tried to use it the compiler yelled at me. I searched online and found a couple of articles that mentioned that if you are using an alternate GUI (I am using eclipse mars) that you can enable the feature but I can not find the correct settings as the examples I had found were for Juno and below.</p> <p>Here is an example of what I am trying to accomplish</p> <pre><code>class DisplayItem{ public: variant *displayVar; void Display(){ Serial.println(displayVar); } } int intDisplay; String strDisplay; DisplayItem item(); item.displayVar = &amp;intDisplay; item.Display(); item.displayVar = &amp;strDisplay; item.Display(); </code></pre> <p>I realize I could create a overloaded function to display different data types but it would be allot easier if I could simply assign a reference to a variant datatype and reuse the variable.</p> <hr> <p><strong>Edit</strong></p> <p>So after looking through the answers I think I have this figured out. I needed to keep track of which variable was being set, I put together a quick example in hopes it will help someone else out with the same question.</p> <pre><code>class DisplayItem{ private: int iVarType; union{ int *i; float *f; } displayVar; public: void SetVar(int *var){ displayVar.i = var; iVarType = 0; } void SetVar(float *var){ displayVar.f = var; iVarType = 1; } void Display(){ if (iVarType == 0){ Serial.println(displayVar.i); }else if (iVarType == 1){ Serial.println(displayVar.f); } } } int intDisplay = 1; float floatDisplay = 0.123; DisplayItem item(); item.SetVar(&amp;intDisplay); item.Display(); item.SetVar(&amp;floatDisplay); item.Display(); </code></pre> <p>Will Display:</p> <pre><code>1 0.123 </code></pre>
<p>For the situation illustrated in the question – displaying data – polymorphic functions already exist, and might as well be used in this case. Specifically, use the <code>Streaming.h</code> <a href="https://www.arduino.cc/en/Reference/Libraries" rel="nofollow">contributed library</a>. It adds some “syntactic sugar” to Arduino C. At compile time it converts C++-like <code>&lt;&lt;</code> Serial stream operators to <code>Serial.print</code> statements, without increasing code size. You can install it via <a href="http://arduiniana.org/Streaming/Streaming5.zip" rel="nofollow"><code>Streaming5.zip</code></a> from <a href="http://arduiniana.org/libraries/streaming/" rel="nofollow">arduiniana.org</a> .</p> <p>In other cases, a <code>union</code> data structure allows treating an area of memory different ways. Wikipedia's <em><a href="https://en.wikipedia.org/wiki/Union_type" rel="nofollow">Union type</a></em> article explains the general idea. See eg <a href="http://www.tutorialspoint.com/cprogramming/c_unions.htm" rel="nofollow">tutorialspoint.com/cprogramming</a> for <code>union</code> syntax and usage. For some reason, arduino.cc's <a href="https://www.arduino.cc/en/Reference/HomePage" rel="nofollow">Language Reference</a> page hasn't got <code>union</code> on its list of language features. However, mcgurrin.com has a page called <em><a href="http://www.mcgurrin.com/robots/?p=127" rel="nofollow">There is Power in a Union</a></em> that codes a simple Arduino C example two ways (where <code>bearing</code> is an <code>int</code>):</p> <pre><code>higherByte = compass.read(); lowerByte = compass.read(); bearing = ((higherByte&lt;&lt;8)+lowerByte)/10 </code></pre> <p>-vs-</p> <pre><code>union Data { byte b[2]; int value; }; ... union Data data; data.b[0] = compass.read(); data.b[1] = compass.read(); bearing = data.value/10; </code></pre>
18349
|interrupt|atmega328|timers|avrdude|avr-gcc|
Trouble with Timer 0
2015-12-02T16:30:07.767
<p>I'm taking my first wobbly steps outside the Arduino IDE and I'm not having much success with timers / interrupts. I can set a pin to output and light an LED with registers fine but I cannot for the life of me get it to blink using a timer. I have tried numerous tutorials and followed the Atmel ATmega328 datasheet very closely.</p> <p>Using an Arduino Uno R3 &amp; Atmel ICE (ISP.) My dev system is Raspbian (Debian) with the GNU AVR toolchain (avr-gcc, avr-objcopy, avrdude.) Apart from not having a bootloader it's a bog standard board (including fuses.)</p> <p>Here's my current code:</p> <pre><code>#include &lt;avr/io.h&gt; #include &lt;avr/interrupt.h&gt; ISR(TIMER0_COMPA_vect) { PORTB ^= (1 &lt;&lt; PB5); // Toggle Arduino Pin #13 } int main (void) { DDRB = (1 &lt;&lt; DDB5); // Arduino Pin #13 is Output cli(); // Clear Interrupts OCR0A = (unsigned char)0xFF; // Compare Register A = 255 TIMSK0 = (1 &lt;&lt; OCIE0A); // Enable Interrupt for Comp. Reg. A TCCR0A = (1 &lt;&lt; WGM01); // CTC Mode sei(); // Set Interrupts TCCR0B = (1 &lt;&lt; CS02) | (1 &lt;&lt; CS00); // Divide by 1024 Prescaler (GO!) return 0; } </code></pre> <p>I don't know if I'm just not seeing something or if I've set registers in the wrong order but it's driving me crazy.</p>
<p>Returning from <code>main</code> does not reset the device (it would start up again and do it all over in that case). It calls <code>exit</code> which turns interrupts off and loops indefinitely.</p> <pre><code>00000068 &lt;__ctors_end&gt;: 68: 11 24 eor r1, r1 6a: 1f be out 0x3f, r1 ; 63 6c: cf ef ldi r28, 0xFF ; 255 6e: d8 e0 ldi r29, 0x08 ; 8 70: de bf out 0x3e, r29 ; 62 72: cd bf out 0x3d, r28 ; 61 74: 0e 94 52 00 call 0xa4 ; 0xa4 &lt;main&gt; 78: 0c 94 61 00 jmp 0xc2 ; 0xc2 &lt;_exit&gt; ... 000000a4 &lt;main&gt;: a4: 80 e2 ldi r24, 0x20 ; 32 a6: 84 b9 out 0x04, r24 ; 4 a8: f8 94 cli aa: 8f ef ldi r24, 0xFF ; 255 ac: 87 bd out 0x27, r24 ; 39 ae: 82 e0 ldi r24, 0x02 ; 2 b0: 80 93 6e 00 sts 0x006E, r24 b4: 84 bd out 0x24, r24 ; 36 b6: 78 94 sei b8: 85 e0 ldi r24, 0x05 ; 5 ba: 85 bd out 0x25, r24 ; 37 bc: 80 e0 ldi r24, 0x00 ; 0 be: 90 e0 ldi r25, 0x00 ; 0 c0: 08 95 ret 000000c2 &lt;_exit&gt;: c2: f8 94 cli 000000c4 &lt;__stop_program&gt;: c4: ff cf rjmp .-2 ; 0xc4 &lt;__stop_program&gt; </code></pre> <p>You can see at address 0x74 it calls main, and then jumps to exit. <code>exit</code> turns off interrupts.</p> <p>With interrupts off your ISR will not toggle pin 13.</p>
18354
|arduino-uno|power|
Arduino Not Working as Intended when using barrel jack
2015-12-02T19:07:08.763
<p>I am using an Arduino to control some mechanical components in a project I have. It controls a motor, two servos, a valve, and a compressor. When plugged into the computer, everything works fine and perfectly. However, when I power it through the barrel jack using our power supply, some weird things happen. First of all, our servos, which are powered through the Arduino, stop working. All the other components work except for them. Secondly, at the end of the code we have a 5 second delay. Using the computer it works fine. When powered with our supply the delay doesn't seem to happen at all. Any ideas?</p>
<p>I had a similar problem recently while powering a servo with a Arduino. It did turn out to be power, our Arduino could only supply about 500ma and with sufficient speed or torque on the servo (a lot of times just the boot sequence) we would it the 500ma at peak, the effect however was baffling at first because when we hit the peak current the Arduino would reboot, this could account for you extra delay at the end.</p> <p>For us the solution was simple bypass the Arduino when supplying current to the servos, in our case it as a 5v battery, you would probably need to drop the 12v to 6v in your case.</p>
18369
|arduino-uno|serial|arduino-mega|reset|
Reset Arduino Uno R3 from Serial when it freezes (stops looping)?
2015-12-03T02:09:06.780
<p>I have an Uno that loops processing serial commands and reading from a DHT11 sensor. For whatever reason, the device often stops responding. I put an LED on a pin and gave it a blink to see whether the loop is running, and sure enough the loop() stops running (the LED stays ON or OFF, depending on when it froze). I enabled the watchdog at 2 seconds, but it does not reset the device [it still stays frozen, even though wdt_reset() is called at basically the same time as the blinking LED is toggled].</p> <p>I then tried various combinations of BaudRate=1200 (or 9600), Open(), Close(), DtrEnable=true [on both the Uno and the Mega], yet none of the combinations would make the device reset. The device <em>will</em> reset, however, if I re-upload the sketch using the Arduino IDE. I would like to emulate this resetting functionality from my own program's code. Reading on the official site, it sounds like the Baud=1200 reset feature is available only on certain models (not the Uno or Mega).</p> <p>My code is by no means simple as I am no beginner when it comes to programming. This is the first time, however, that I have had a finicky unit that freezes all the time (say between 10 minutes and 2 hours into running). I merely want to reset the unit from the PC using code, like the Arduino IDE does. On the other hand, if the watchdog worked correctly, that would be fine as well. At the same time, I am not that experienced with electronic circuits, so making a circuit that would "press" the "reset" pin when the LED stops blinking is not something I am quite ready to do. Plus, I do not want to add a bunch more components if the job can be done through code.</p> <p>On a side note, the Serial connection appears to be fully functional the whole time. The LED on the unit that indicates receiving from the PC continues to function whenever I send data to the device. I can connect and reconnect without any apparent issues. Plus, the Arduino IDE has no problem uploading new sketches and resetting the device. Naturally, no data is received from the device after it freezes (until it gets reset, of course).</p> <p><strong>Update 1</strong>: I made a simple sketch (see below) that would run for about 20 seconds and then let the WDT watchdog timeout do its thing. Result: (a) Running the code on an Arduino-brand Mega 2560, the device simply resets every 20 seconds and keeps blinking; (b) Running the code on a generic (made in China) Uno R3, at timeout the L light turns on and the device becomes completely unresponsive (not even the reset button or the Arduino IDE can save it); It must be unplugged to reset it. (c) Running the code on an Arduino-brand Uno R3 works as expected, just like on the Mega 2560.</p> <pre><code>#include &lt;avr/wdt.h&gt; void setup() { wdt_reset(); wdt_enable(WDTO_2S); wdt_reset(); pinMode(A5, OUTPUT); delay(1); Serial.begin(125000); } unsigned int LoopCount = 0; bool TestLED = false; void loop() { if(LoopCount % 300 == 0){ TestLED = !TestLED; digitalWrite(A5, TestLED ? HIGH:LOW); if(LoopCount &lt; 20000) wdt_reset(); } delayMicroseconds(1000); LoopCount++; } </code></pre> <p>Nevertheless, I still would like if someone could provide a solution in terms of resetting a frozen generic Uno from Serial in .NET code -- not the WDT frozen, but the normal frozen (of unknown origin). I may be the one coding, but I'm unfortunately not the one deciding which units are put into production.</p> <p><strong>Update 2</strong>: I switched the EasyDriver to its own power source, where the only things in common with the stepper and the Arduino were the ground and the two signal wires. The generic Uno board ended up being even more problematic, going into a new freeze mode (after just a minute or two, pretty reliably) where the L light would blink very quickly. I'm not sure whether it had anything to do with toggling of the DtrEnable property, but I decided to stop messing with the generic board for the time being. The name-brand Uno appeared to freeze occasionally or malfunction as well with the original wiring, but the Watchdog did its thing and reset it straight away every time. Also, I tried toggling the RtsEnable property with the generic board, but it didn't seem to make a difference. The board would become unresponsive and unrevivable, even from the Arduino IDE.</p> <p>Some more background: The reliability problem only really started to surface when I hooked up the DHT11 temperature sensor, <em>even though</em> the freezing would tend to happen only when the stepper motor was running. I have the DHT11 hooked up exactly as advocated by Adafruit, and it tends to read correctly most of the time.</p> <p><strong>Update 3</strong>: I was thinking maybe the SainSmart Mega2560 would be different from the no-name generic I was using. After getting one and hooking it up, I have found it to have the exact same problem. The SainSmart CPU crashes between 5 and 15 minutes into running. The serial chip (or module) keeps going as you can still see the serial lights change when you send to it. However, the on-board reset button does nothing, and the Arduino IDE cannot upload to the device or reset it. Only a power cycle can save it.</p>
<p>Since we don't know the nature of the freeze-up, and the clone-board behaves differently than an Arduino-brand board but we don't know how or why, there's not much more we can offer beyond suggesting you recommend a higher quality board to your management. You surely have reason enough to do so. </p> <p>The last remaining thing I can think of, and it's kludgey work-around (shame on me) is:</p> <p>You know the board will come back after a power-cycle. Kludge up a 555 timer circuit that powers-down the board for a second or two, and trigger it from the DTR line. This is really a broken fix for a broken board!</p> <p>If my management or a client was intent on shipping a product built with these, I'd have to speak up about potential damage to the company's reputation - and possible liability, if a failure could have real consequences someone - and if necessary, write my objections to the next three levels above me. This board should not be shipped in a product.</p>
18373
|current|
Can I use 5V 1A Adapter to power Arduino UNO?
2015-12-03T07:25:39.160
<p>I have two Adapters, one is rated as Output 12V 500mA (used to power an old modem) and another one is rated as 5V 1A (old mobile phone charger).</p> <p>My question is can use any of these to power my Arduino UNO with a barrel connector?</p> <p>What does it mean when any adapter is rated as Output DC 5V 1A, Does it mean maximum we can draw 1A of current through it? What will happen if I draw more current than that.</p>
<p><a href="https://i.stack.imgur.com/Ep3D4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ep3D4.jpg" alt="enter image description here"></a></p> <p>If we look at <a href="https://www.arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow noreferrer">technical specifications</a>, it is recommended to supply voltage from 7-12V so use your adapter 12V/500mA (<strong>never go above 20V</strong>). 5V/1A adapter is not enough when connecting via DC barrel jack according to technical specifications.</p>
18381
|timers|attiny|spi|
ATtiny85 SPI with Timer 0
2015-12-03T12:56:54.700
<p>Trying to shift out from ATtiny85 to a shift register using the USI in SPI mode. I have Timer 0 running as slowly as possible (checked it was running by temporarily changing it to toggle a pin with an LED attached.) I have LEDs hooked up to USCK and DO so by rights I should be able to see them blinking as it sends.</p> <p>What else do I need to do in order to get it shifting out in sync with Timer 0? All the examples I've looked at so far strobe the USI clock manually.</p> <pre><code>#include &lt;avr/io.h&gt; int main(void){ DDRB = (1 &lt;&lt; DDB2) | (1 &lt;&lt; DDB1); // USCK &amp; DO Output DDRB &amp;= ~(1 &lt;&lt; DDB0); // DI Input PORTB |= (1 &lt;&lt; DDB0); // Pullup Resistor for DI TCCR0A = (1 &lt;&lt; WGM01); // Timer 0 in CTC Mode OCR0A = 0xFF; // Timer 0 Compare A TCCR0B = (1 &lt;&lt; CS02) | (1 &lt;&lt; CS00); // Prescaler / 1024 USICR = (1 &lt;&lt; USIWM0); // USI 3 Wire Mode USICR |= (1 &lt;&lt; USICS0); // Timer 0 for USI 4-bit Clock Source USIDR = 0x7F; // Why you no go? :c USISR |= 0x08; // Set Counter to 8 USISR = (1 &lt;&lt; USIOIF); // Clear Counter Overflow while(1); return 0; } </code></pre>
<p>Did you forget to load the counter and clear flags in USISR? </p>
18382
|arduino-uno|sensors|
Measuring acceleration in g's
2015-12-03T12:59:01.083
<p>I am using adxl335 accelerometer with Arduino uno r3 to measure acceleration due to gravity along x axis. I am using 50 ms delay and printing to serial. I have two questions, which are;</p> <ul> <li>Can I measure fractional values, like .8 in acceleration due to gravity?</li> <li>when I shake the accelerometer up down along x axis, I don't see any variations in 'g'?</li> </ul> <p>I am using analog pins and 3.3V power supply from Arduino to power the sensor.</p>
<p>If you read the <a href="http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL335.pdf" rel="nofollow">datasheet</a> you can quickly find that the output of the device is 300mV per <em>g</em>. That means:</p> <ol> <li>Read the analog value</li> <li>Convert it to millivolts</li> <li>Divide it by 300</li> </ol> <p>The result is the <em>g</em> value. If you do it using floating point then yes, you get fractions of a <em>g</em> resolution.</p> <p>For instance:</p> <pre><code>float mv = analogRead(0) / 1023.0 * 5000.0; float g = mv / 300.0; </code></pre> <p>If the analog channel has 1024 steps, that's 5/1024 = 0.0048828V per step, or 4.8828mV per step. Divide that by 300 and you get a resolution of 0.01628g</p> <p>As for not seeing variations in X when you shake up and down, maybe that is because you really want to look at the Z axis, not the X. X is left/right, Y is forward/backward and Z is up/down. It's all in the <a href="http://www.analog.com/media/en/technical-documentation/data-sheets/ADXL335.pdf" rel="nofollow">datasheet</a> - it makes for good reading, I suggest you take a look.</p>
18406
|arduino-uno|
One LED being constant and another blinking
2015-12-03T23:15:24.813
<p>I have just started my first project. I got through with 2 periodically blinking LEDs. Now I want one LED (blue) to be lit constantly and the other (red) to be blinking as before. Can anyone help me with this?</p> <p>This is my code for blinking LEDs.</p> <pre><code>int red_led = 4; int blue_led = 3; void setup() { pinMode(red_led, OUTPUT); pinMode(blue_led, OUTPUT); } void loop() { digitalWrite(blue_led, LOW); digitalWrite(red_led, HIGH); delay(1000); digitalWrite(blue_led, HIGH); digitalWrite(red_led, LOW); delay(1000); } </code></pre>
<p>Remember that the setup() function runs once, and then the loop() function runs forever. So to keep the blue LED light, simply turn it on, but never off. The code for the red LED remains unchanged.</p> <pre><code>const int red_led = 4; const int blue_led = 3; void setup() { pinMode(red_led, OUTPUT); pinMode(blue_led, OUTPUT); digitalWrite(blue_led, HIGH); // LED On } void loop() { digitalWrite(red_led, HIGH); // LED On delay(1000); digitalWrite(red_led, LOW); // LED Off delay(1000); } </code></pre>
18407
|arduino-uno|serial|sketch|string|code-optimization|
What is better: one sprintf() or multiple strcat() and itoa()?
2015-12-03T23:24:29.420
<p>I was creating Arduino function which sends two <code>int</code> and additional <code>char</code>s between them and at the beginning and end of <code>char</code> array - then print that array to the serial port in almost real time. (For example "X50Y100T".)</p> <p>I don't want to use <code>String</code> object in Arduino and I found two possible solutions:</p> <ul> <li><p>Using <code>sprintf()</code>:</p> <pre><code>char sendBuffer[16]; void dataSend(int first, int second) { sprintf(sendBuffer, "X%dY%dT", first, second); Serial.println(sendBuffer); }; </code></pre></li> <li><p>Or something like this:</p> <pre><code>char sendBuffer[16]; void dataSend(int first, int second){ char convert[6]; sendBuffer[0] = 'X'; itoa(first, convert, 10); strcat(sendBuffer, convert); sendBuffer[strlen(sendBuffer)] = 'Y'; itoa(second, convert, 10); strcat(sendBuffer, convert); sendBuffer[strlen(sendBuffer)] = 'T'; Serial.println(sendBuffer); memset(sendBuffer,0,sizeof(sendBuffer)); }; </code></pre></li> </ul> <p>My question is - which one is better from technical point of view?</p> <p>The <code>sprintf()</code> looks better but it increases the sketch size by ~1,5KB. Are there any other drawbacks of <code>sprintf()</code>? The second solution do many things to achieve same thing and I don't know if it's efficient... Maybe there are other solutions for sending this kind of <code>char</code> array?</p>
<p>The sprintf() function has a memory cost because of the library import at compile time. But it only costs that once, no matter how many more times you use it. Unless you're running out of space, memory used is not a big deal. There's no point keeping some memory unused on an Arduino.</p> <p>I think it's better to use sprintf() because:</p> <ul> <li>sprintf() produces code that is more readable, since the final output string can be easily visualised - obviously with only place holders for the variable parts.</li> <li>Making minor changes to the output is quicker, since there's not lines of output generator functions to re-organise.</li> <li>You end up with less code. Less code is is easier to debug and maintain.</li> </ul> <p>I would however, encourage you to use snprintf(). This function differs from sprintf() by taking the maximum buffer size as an argument. This will help prevent problems with buffer-overruns (i.e.: accidentally putting more data into a string than in can hold)</p> <p>Sprintf on Arduino does not include support for floating point numbers though. This is quite a drawback. One needs to use additionally use dtostrf(). </p> <p>The real takeaway point is this: Only optimise your program when you need to. <a href="https://en.wikipedia.org/wiki/Donald_Knuth" rel="nofollow">Donald Knuth</a> said: "Premature Optimisation is the root of all evil".</p>
18422
|arduino-mega|
Can I work with larger numbers than an unsigned long long in Arduino?
2015-12-04T09:26:01.853
<p>I would like to use larger numbers than an unsigned long long in Arduino. Is that possible?</p>
<p>There are many ways to use numbers bigger than an <code>unsigned long</code> on Arduino. The right one depends on the application.</p> <p><strong>Floats and Doubles</strong> <code>float</code>s and <code>double</code>s types on Arduino can hold exact integers up <code>2^53</code>. That is a very large number. They are built into the Arduino compiler. </p> <p><strong>uint64_t</strong> The <code>uint64_t</code> type can hold exact integers up to <code>2^64</code>. That is a very large number. This type is built into the Arduino compiler, but note that some Arduino library functions do not have versions for this type so may need to down-convert for printing and serializing and stuff like that. </p> <p><strong>BigNumber (or bc)</strong> The <code>BigNumber</code> type can represent exact numbers (integer or otherwise) limited only by available memory- but certainly hundreds of digits long on Arduino. These are extremely big numbers. This type is not built into the Arduino, but there is a nice Arduino library version available... </p> <p><a href="https://github.com/nickgammon/BigNumber" rel="nofollow">https://github.com/nickgammon/BigNumber</a></p> <p>Again, this type is not supprted by the Arduino built-in library functions so you will need to either down-convert or find <code>BigNumber</code> compatible functions for things like printing and serializing. </p>
18429
|assembly|avr-toolchain|
Interleave Assembly and Source for avr-objdump
2015-12-04T16:19:27.647
<p>Trying to get avr-objdump to generate a listing that interleaves the assembly with the source code. I've tried a bunch of debugging arguments in different configurations but I can't seem to get it. The best I could do was getting it to interleave the object with line numbers from the assembly (avr-objdump -lS spi.o)</p> <p><a href="https://github.com/AshlynBlack/tinySPI/blob/c0748ee5fe1d5b85813ac7b4628bb84014d4a0d4/examples/Makefile" rel="nofollow">Original Makefile</a></p> <p>Here's my current Makefile:</p> <pre><code>PREFIX=avr- CC=${PREFIX}gcc OBJCOPY=${PREFIX}objcopy BIN=knightrider MCU=attiny85 OBJS=../src/tinySPI.o src/knightrider.o PROG?=atmelice_isp PORT?=usb CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections ${BIN}.hex: ${BIN}.elf @mkdir -p bin ${OBJCOPY} -O ihex -R .eeprom build/$&lt; bin/$@ ${BIN}.elf: ${OBJS} @mkdir -p build ${CC} ${LDFLAGS} -o build/$@ $? install: ${BIN}.hex avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U flash:w:${BIN}.hex:i -qq clean: rm -f build/* rm -f bin/* fuses: avrdude -c ${PROG} -P ${PORT} -p ${MCU} -U lfuse:w:0x62:m -U hfuse:w:0xDF:m -U efuse:w:0xFF:i -qq </code></pre> <p>What would I need to change in order to run avr-objdump and get an interleaved listing of an .o and its corresponding .c (e.g. spi.o and spi.c)?</p>
<p>First make sure you add <code>-g</code> to all your compilation commands.</p> <p>Then you can run <code>avr-objdump -S build/spi.elf</code> (for instance).</p> <p>Also I see you're missing the MCU definition in your link command. Without that it won't link in the proper C startup routines and your program will most probably not run.</p> <p>Here is a makefile I use:</p> <pre><code>PREFIX=avr- CC=${PREFIX}gcc CXX=${PREFIX}g++ LD=${PREFIX}ld AS=${PREFIX}as OBJCOPY=${PREFIX}objcopy OBJDUMP=${PREFIX}objdump BIN=blink MCU=atmega328p OBJS=blink.o CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections ${BIN}.hex: ${BIN}.elf ${OBJCOPY} -O ihex -R .eeprom $&lt; $@ ${BIN}.elf: ${OBJS} ${CC} ${LDFLAGS} -o $@ $? ${OBJDUMP} -S $@ &gt; ${BIN}.dis install: ${BIN}.hex avrdude -C ./avrdude.conf -c usbasp -p ${MCU} -U flash:w:${BIN}.hex -qq clean: rm -f *.o *.elf *.hex fuses: avrdude -c usbasp -p ${MCU} -C avrdude.conf -U lfuse:w:0xff:m -U h fuse:w:0xd6:m -U efuse:w:0x05:m -qq </code></pre>
18433
|power|usb|
Trinket: Battery + USB at the same time?
2015-12-04T16:57:41.830
<p>Is it allowed to have battery and USB connected to the Trinket(3.3V) at the same time?</p> <p>I am using the battery to also power other components, so always disconnecting power, hooking USB to re-program and vice-versa is quite time consuming (and I fear to ruin the connectors).</p>
<p>From <a href="https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258" rel="nofollow">https://learn.adafruit.com/system/assets/assets/000/010/773/original/adafruit_products_trinket3.png?1378223258</a> it looks OK -- there are blocking diodes D3 and D2 that prevent backfeeding either the battery or the USB +5.</p> <p>If you are worried, or want to monitor battery-only performance, you could make a special USB cable with the +5 red wire disconnected, and rely on the in-circuit battery to power the device, while still using the USB data lines. See <a href="https://www.pjrc.com/teensy/external_power.html" rel="nofollow">https://www.pjrc.com/teensy/external_power.html</a> Option 2 for an example of the cable surgery. </p>
18440
|shift-register|
max current while using a shift register
2015-12-04T19:29:33.673
<p>In arduino's official page about ShiftOut <a href="https://www.arduino.cc/en/Tutorial/ShiftOut" rel="nofollow">https://www.arduino.cc/en/Tutorial/ShiftOut</a>, a drawing with two 74HC595 powered by the arduino board, is displayed. </p> <p>Since the resistors are 220Ω, the total current should be 5/220x16 = 0.36A which exceeds the maximum total current of 0.20A for the arduino device.</p> <p>So, could someone turn on simultaneously 16 LEDs using two shift registers without damaging the device?</p> <p>Thank you</p>
<p>0.20A is <em>not</em> the maximum current for an Arduino device. 0.20A is the maximum current for <em>the chip that is on the Arduino</em>. Thus it is only relevant to devices that are <em>directly</em> connected to the Arduino's IO pins (that connect direct to the chip).</p> <p>The shift registers take their own power from the +5V pin, which is limited to between 500mA and 800mA depending on how you power your board. Each shift register has its own power limits that are completely separate to the Arduino's main chip's power limits.</p>
18445
|power|battery|
Trinket Pro 5V red light flashing when battery attached
2015-12-04T15:48:13.037
<p>I am using <a href="http://www.adafruit.com/product/2000" rel="nofollow noreferrer">Trinket Pro 5V</a> to run a simple i/o code. The input from the piezo vibration sensor is read by the Trinket and Translated into a servo position. It works fine powered through a USB connection, however as soon as I try to power it using a 9V battery (plugged into the Bat+ and G terminals), the code stops running and the red light on the Trinket starts to blink.</p> <p>Is the power source not sufficient - 9V?</p> <p>Has anyone faced a similar problem?</p>
<p>Please consider reading the <a href="http://learn.adafruit.com/trinket-gemma-servo-control/wiring" rel="nofollow noreferrer">"https://learn.adafruit.com/trinket-gemma-servo-control/wiring"</a> tutorial.</p> <p>It says</p> <blockquote> <p>It is suggested you use an external wall or battery supply and not power the servo via the regulator. servos can draw up to 500mA and the Trinket regulator can only source 150 milliamps (USB power generally 500 milliamps).</p> </blockquote> <p>No matter what power supply you hook to the "Bat+" battery pin, if you hook the servo power to the "5V" pin on the trinket, the trinket's on-board 5V regulator will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.</p> <p>Instead, please hook the servo power directly to the battery. Alas, a typical partially-drained 9V battery has enough internal resistance that the battery's voltage will temporarily collapse under the load of the servo, which typically causes the system to reset over and over again.</p> <p>Instead, use a better power source.</p> <p>Many people, even when they intend to eventually run their system on batteries, start out using a wall-wart power supply, so they don't have to keep wondering "Is this glitch because of a bug in my software, or is the battery just going dead?".</p> <p>The <a href="http://learn.adafruit.com/16-channel-pwm-servo-driver/hooking-it-up" rel="nofollow noreferrer">"Adafruit 16-Channel Servo Driver with Arduino"</a> tutorial says:</p> <blockquote> <p>Good power choices are:</p> <ul> <li><a href="http://www.adafruit.com/products/276" rel="nofollow noreferrer">5v 2A switching power supply</a></li> <li><a href="http://www.adafruit.com/products/658" rel="nofollow noreferrer">5v 10A switching power supply</a></li> <li><a href="http://www.adafruit.com/products/830" rel="nofollow noreferrer">4xAA Battery Holder</a> - 6v with Alkaline cells. 4.8v with NiMH rechargeable cells.</li> <li>4.8 or 6v Rechargeable RC battery packs from a hobby store.</li> </ul> </blockquote> <p>You might also want to look at other <a href="http://www.adafruit.com/category/135" rel="nofollow noreferrer">Battery holders</a> that hold lots of AA batteries in a convenient package.</p> <p>Related: <a href="https://electronics.stackexchange.com/questions/73169/how-to-get-high-current-from-9-volt-batteries">"How to get high current from 9 volt batteries"</a> and <a href="http://forum.arduino.cc/index.php?topic=132106.0" rel="nofollow noreferrer">"What is the max current I could draw from a 9V battery?"</a>.</p>
18477
|relay|
Relay to Mains lightswitch
2015-12-06T14:48:35.513
<p>So I purchased a 4 channel Relay which handles AC250V 10A ; DC30V 10A. But am I able to connect this to replace a light switch so I can automate it? My bedroom runs on 15 amps.</p> <p><a href="https://i.stack.imgur.com/8rZDF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8rZDF.jpg" alt="relay board"></a></p> <p><a href="http://rads.stackoverflow.com/amzn/click/B00VHVIBAM" rel="nofollow noreferrer">http://amazon.com/gp/product/B00VHVIBAM?psc=1&amp;redirect=true&amp;ref_=oh_aui_detailpage_o00_s00</a></p>
<h1>All mains electrical work should be performed by a fully qualified electrician.</h1> <p>Yes, this relay board will easily switch a light bulb.</p> <p>A note on current: A single 100 Watt incandescent globe will only draw 0.83 Amps at 120V AC (0.416 Amps at 240V AC). The equation I used: I=P/V. You would start coming close to the maximum rating after 10 globes (although I advise staying well below the maximum).</p> <p>You mention that your bedroom runs on 15 Amps, which I assume means that the mains runs through a 15 Amp circuit breaker (or fuse). This circuit breaker will trip if the total current to all devices after it exceeds 15 Amps.</p> <p>A <a href="https://electronics.stackexchange.com/q/33312/104097">similar question</a> was asked by Matthieu Napoli over on the Electrical Engineering Stack Exchange site. There are a number of high quality answers there that would be helpful for you. Worthiest to mention is <a href="https://electronics.stackexchange.com/a/33366/104097">Cybergibbons answer</a> where he recommends using the <a href="http://www.powerswitchtail.com/" rel="nofollow noreferrer">PowerSwitch Tail</a> as a very safe way of switching mains voltage. You don't need an electrician when using the PowerSwitch Tail providing the light you are controlling has the matching plugs.</p>
18478
|arduino-uno|led|time|millis|
Issue with simple project
2015-12-06T15:28:00.020
<p>I'm new to Arduino and today I have a problem with this code:</p> <pre><code>int led_1 = 10; int led_2 = 11; int led_3 = 12; int button = 3; int time = 0; byte val = 0; void setup() { // put your setup code here, to run once: pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(button, INPUT); } void loop() { // put your main code here, to run repeatedly: val = digitalRead(button); if (val == HIGH){ time = millis(); while (digitalRead(button) == HIGH) { if (millis() - time &lt; 1000) {digitalWrite(led_1, HIGH);} else if (millis() -time &gt; 1000 &amp;&amp; millis()-time &lt;2000) {digitalWrite(led_2, HIGH);} else if (millis()-time &gt;2000) {digitalWrite(led_3, HIGH);} } } else { time =0; digitalWrite(led_1, LOW); digitalWrite(led_2, LOW); digitalWrite(led_3, LOW); } } </code></pre> <p>The code should work like this: If I press the button less than one second, <code>led_1</code> will turn on. If I press it between one and two seconds, <code>led_2</code> will turn on; and if I press the button more than 2 seconds, <code>led_3</code> will turn on. If I don't press a button, the LEDs remain off. The <code>time</code> variable is used to take the time when I start to press the button and then the control <code>millis()- time</code> should give how long I press the button.</p> <p>It works for a while, then after a random time (I think) if I push the button, only the <code>led_3</code> turns on. Why?</p>
<p>Your code seems inefficient and there is a <code>tempo</code> variable that doesn't appear elsewhere.</p> <pre><code> if (val == HIGH) { time = millis(); while (digitalRead(button) == HIGH) { int time0=millis(); if (time0 - time &lt; 1000) { digitalWrite(led_1, HIGH); } else if (time0 - time &lt; 2000) { digitalWrite(led_2, HIGH); } else if (time0 - time &gt; 2000) { digitalWrite(led_3, HIGH); } } } </code></pre> <p>Note that this code will turn on all LEDs, one by one. If you want to turn off the other, you'll have to had code for that in the tests.</p>
18485
|arduino-uno|serial|shift-register|
Best way to implement score board logic using Arduino and Shift Registers?
2015-12-06T20:57:52.733
<p>I am from a mobile development background and very new to Arduino. I am trying to make an electronic cricket score board. The logic is simple. </p> <p><strong>Score - 888 (3 Digits)</strong> - I have implemented this logic using shift registers. Three pin used from Arduino Uno and this is working fine.</p> <p><strong>Overs - 88 (2 Digits)</strong> - Need to find a best way to implement it</p> <p><strong>Wickets - 8 (1 Digit)</strong> - Need to find a best way to implement it</p> <p>Now I need to add Wickets and Overs to the logic. I think there are two ways to do it. </p> <ol> <li><p>One is passing data from Score shift registers. I think this way is a bit complicated in logic level. But if this is a good way, then great.</p></li> <li><p>The other is, connect to Arduino Uno pins directly rather than getting information from score shift registers. There are only few pins.</p></li> </ol> <p><strong><em>Please Note: I need to print this design in PCB</em></strong></p> <p>This might be a basic question. But I would like to the know which way is efficient, and its advantages. If both are not, I would like to the know the best one.</p>
<p>There isn't really a <em>best</em> way (and such questions are usually discouraged as they can easily descend into argument).</p> <p>Personally I would go for chaining all of the '595s together so you only ever use the 3 pins; it gives you the opportunity to use a smaller MCU like the ATtiny when you put it all on a board later which makes it (slightly) cheaper and (potentially) smaller.</p> <p>From a software point of view, it doesn't make a huge amount of difference - doing it the way I have suggested means you send the 3 values out in the correct order every time one of them updates. Separating the 3 scores with their own dedicated pins means juggling which one needs to be updated each time. Neither option is particularly complicated and with this sort of application efficiency of code is mostly redundant because the entire MCU is dedicated to the (simple) task.</p>
18487
|arduino-uno|shields|sd-card|
Connecting and Programming LinkSprite Camera to Arduino
2015-12-07T01:39:36.663
<p>I recently bought the LinkSprite color jpeg camera: <a href="https://www.sparkfun.com/products/12804" rel="nofollow">https://www.sparkfun.com/products/12804</a> And the Arduino Wireless SD Shield: <a href="https://www.arduino.cc/en/Main/ArduinoWirelessShield" rel="nofollow">https://www.arduino.cc/en/Main/ArduinoWirelessShield</a></p> <p>I was wondering how to connect the camera to the Arduino and how to have it take and save a picture to the sd card when a button is pressed.</p>
<p>Connect the camera to a serial port (hardware or software serial depending on Arduino board). See further information on <a href="http://linksprite.com/wiki/index.php5?title=JPEG_2M_Pixel_Color_Camera_Serial_Interface%28TTL_level%29" rel="nofollow">wiki</a>. </p> <p>Control the camera and fetch the image over the serial connections (see commands) and write to the SD disc. </p>
18503
|arduino-uno|serial|ir|remote-control|
Script stops functioning after calling irsend() function in irlibrary!
2015-12-07T14:49:50.410
<p>I have the following script which checks if the user has pressed the numbers "770" or "769" continuously in the remote. The script works fine and displays all numbers. When I press the buttons "770" or "769" continuously the function powerOff() is called and I get no serial input.</p> <pre><code>/* * IRremote: IRrecvDemo - demonstrates receiving IR codes with IRrecv * An IR detector/demodulator must be connected to the input RECV_PIN. * Version 0.1 July, 2009 * Copyright 2009 Ken Shirriff * http://arcfn.com */ #include &lt;IRremote.h&gt; int RECV_PIN = 11; IRrecv irrecv(RECV_PIN); IRsend irsend; decode_results results; int intValue; String strValue; String str3; void setup() { Serial.begin(9600); irrecv.enableIRIn(); // Start the receiver } void loop() { if (irrecv.decode(&amp;results)) { intValue = results.value; Serial.print("Integer value : "); Serial.println(intValue); strValue = String(intValue); Serial.print("String str : "); Serial.println(strValue); Serial.print("Length : "); Serial.print(strValue.length()); Serial.println(); if(strValue.length() &lt;= 1){ str3 += strValue; Serial.println(str3); // Receive the next value } delay(200); irrecv.resume(); } //Serial.println(str3); if(str3.endsWith("770")){ powerOff(); str3 = ""; } else if(str3.endsWith("769")){ powerOff(); str3 = ""; } else{} //powerOff(); } void powerOff(){ irsend.sendRC6( 0xC0000C, 24); irrecv.resume(); // Receive the next value } </code></pre>
<p>Apparently you should be calling <code>irrecv.enableIRIn()</code> after sending, not <code>irrecv.resume()</code>. Sorry for suggesting the wrong thing on IRC before :-)</p>
18505
|sensors|
minIMU 9 and Arduino reading Gyro angle
2015-12-07T15:13:54.557
<p>I'm using minIMU-9 <a href="https://www.pololu.com/product/1268" rel="nofollow noreferrer">https://www.pololu.com/product/1268</a> and I want to read pitch, roll and yaw angles. I applied this library <a href="https://github.com/pololu/minimu-9-ahrs-arduino" rel="nofollow noreferrer">https://github.com/pololu/minimu-9-ahrs-arduino</a> but there is a slope when sensor is not moving or vibrating. How can i fix or compensate this. The y axis is angle in degree and x axis is time in seconds</p> <p>Pitch</p> <p><a href="https://i.stack.imgur.com/Us5BU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Us5BU.png" alt="Pitch"></a></p> <p>Roll</p> <p><a href="https://i.stack.imgur.com/9oRC2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9oRC2.png" alt="Roll"></a></p> <p>Yaw</p> <p><a href="https://i.stack.imgur.com/dzEgx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dzEgx.png" alt="Yaw"></a></p>
<p>I suppose "at desktop readings" means you have your sensor resting on the desktop so you where looking for a constant output value over the time. Well, there are some mechanical limitations about gyroscope's accuracy, resolution and external factor like temperature that make noisy or non-sense readings.</p> <p>What you are obtaining from this library is a calculated orientation that carries or accumulate an error over time. Basically there is not a perfect algorithm to calculate orientation as at MEM's scale electrons still moving due to temperature and other radiations.</p> <p>Solution depends on your application scenario: if your sensor will be most the time quite, maybe just mathematical compensate with inverted slope (about 4-5 degrees per minute) and look for more rapid changes to determine movement. If your application will be on constant move maybe it is not required any compensation. Trade off must be considered if both scenarios will take place on your application. Anyway, reading measures on your actual application will give you more clue on how to handle this.</p> <p>Below the L3GD20's mechanical characteristics</p> <p><a href="https://i.stack.imgur.com/6Zs5P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6Zs5P.png" alt="Gyro&#39;s mechanical characteristics"></a></p>
18528
|arduino-mega|battery|
Supply arduino through Vin pin with a battery
2015-12-08T13:22:44.907
<ol> <li>is it dangerous for arduino the below circuit because GND pin is common with -12V battery pole?</li> <li>is it dangerous for lots of 5v circuit to be grounded on -12v battery pole?</li> <li>in case i don't connect GND arduino pin with -12v , does arduino works?</li> <li>in case that 1,2 question is dangerous for arduino,does it safe if a connect a diode at P1 mark?</li> </ol> <p><a href="https://i.stack.imgur.com/i1YTZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/i1YTZ.jpg" alt="enter image description here"></a></p>
<p>Voltages, being a <em>potential difference</em> are always measured relative to another voltage. Normally that reference voltage is referred to as <em>ground</em>, though may not always be.</p> <p>The + and - on the battery refers to the <em>polarity of the battery</em> not the <em>polarity of the voltage</em>.</p> <p>For instance, <em>relative to the - terminal</em> the positive terminal is 12 volts higher, or +12V. <em>Relative to the + terminal</em> the negative terminal is 12V lower, so -12V.</p> <p>When one of your battery terminals is connected to a point in your circuit nominated as ground (the - terminal of your battery in this case) then your battery voltage at the + terminal is measured relative to ground, which we say is 0V. So the + terminal is 12V higher than the - terminal, and the - terminal is 0V, so therefore the + terminal must be 12V <em>with respect to ground</em>. The - terminal, since it is connected to ground is at the same voltage as ground, so it is 0V <em>with respect to ground</em>.</p> <p>If you were to connect the + terminal of a battery to ground instead, then the - terminal would be 12V <em>lower</em> than ground, so would be -12V <em>with respect to ground</em>. The + terminal would be 0V <em>with respect to ground</em>.</p>
18531
|avrdude|programmer|
What does the 'arduino' avrdude programmer do?
2015-12-08T17:13:51.023
<p>The command line that my toolchain (<a href="https://www.jetbrains.com/clion/" rel="nofollow">CLion</a> + <a href="http://platformio.org/#!/" rel="nofollow">PlatformIO</a>) uses to program my Arduino (Uno) includes includes</p> <pre><code>avrdude ... -c arduino ... </code></pre> <p>but <a href="http://www.nongnu.org/avrdude/user-manual/avrdude_4.html" rel="nofollow">the documentation</a> for this programmer simply reads</p> <blockquote> <p>-c programmer-id<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ...<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;arduino&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Arduino<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; ... </p> </blockquote> <p>What does the <code>arduino</code> programmer do. Does it just correspond to using the bootloader?</p>
<p>Yes, the -c option specifies the methods of interacting with the device's loader.</p> <p>The source code of the arduino programmer is <a href="http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&amp;view=markup" rel="nofollow">http://svn.savannah.nongnu.org/viewvc/trunk/avrdude/arduino.c?root=avrdude&amp;view=markup</a> </p> <p>Specifically, '-c arduino' chooses the client side code tailored to the bootloader in the Arduino Uno. Looking at the code in the above link, it tweaks the DTR and RTS lines to get the Ardunino into an stk500 compatible mode, and then invokes the stk500 protocol. </p>
18537
|arduino-uno|shields|ethernet|rtc|
connecting RTC DS1307 to ethernet shield
2015-12-08T21:43:47.740
<p>What is the easiest way to mount DS1307 to ethernet shield? </p> <p>I tried to do this: <a href="https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up" rel="nofollow">https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/wiring-it-up</a></p> <p>but my program just freezes when I try to read data from RTC. Is there any other ways to do it?</p> <p>Code looks like this:</p> <pre><code>const int RTCpin2 = 2; const int RTCpin3 = 3; void setup() { pinMode(RTCpin2, OUTPUT); pinMode(RTCpin3, OUTPUT); analogWrite(RTCpin2, LOW); analogWrite(RTCpin3, HIGH); } void loop() { // process RTC time } </code></pre>
<p>I assume that snippet of code is supposed to provide the +5Vand GND for powering the RTC module. Well, there's two fundamental flaws with it:</p> <ol> <li>Pins 2 and 3 are the DIGITAL pins, not the analog pins. Instead you want to be using pins A2 and A3.</li> <li>analogWrite controls the PWM output on pins that support PWM. HIGH is 1, so analogWrite will be providing a 1/255 duty cycle PWM signal on that pin.</li> </ol> <p>So to fix it:</p> <ol> <li>Use pins A2 and A3 instead of 2 and 3</li> <li>Use digitalWrite() instead of analogWrite().</li> </ol>
18538
|programming|c++|
Multithreading with Arduino
2015-12-08T22:18:50.953
<p>Well I've just started learning the concept of multithreading with C++ and immediately a bunch of questions came to mind about the possibility of using multithreading with microcontrollers in general and Arduino specifically.</p> <p>So, is it possible to use multithreading on any type of Arduino boards?</p>
<p>I use <a href="https://www.google.mn/url?sa=t&amp;source=web&amp;rct=j&amp;url=http://atomthreads.com/&amp;ved=0ahUKEwizhomMgsrRAhXMHZQKHV74DcAQFggYMAA&amp;usg=AFQjCNGsxGMmrzZ5XhSCrSidilYeNhcdwg&amp;sig2=EUhC4i0J711ypa5OhK2o7g" rel="nofollow noreferrer">Atomthreads</a> on Atmega128, it is very lightweight with minimum overhead. Have task scheduler, mutex, semaphores and queue. Code is portable but might require some configuration to use with Arduino IDE (I use Atmel Studio). I primarily use task scheduler, never had problems. Just checked, the development is still active.</p>
18541
|arduino-uno|resistor|
What is the minimum wattage of resistors for breadboarding with Arduino Uno?
2015-12-08T22:47:06.760
<p>I'd like to buy new resistors for breadboarding with my Arduino Uno. There are 0.25W, 0.4W, 0.6W, 1W, 2W, 3W, 5W, 10W resistors in the shop. What is the most suitable for this operation?</p>
<p>Go with 1/4 Watt resistors but be prepared to use 1/2 Watts if the leads don't press down cleanly into the breadboard which is what I think you are asking about. If you need anything in the higher wattage range and you are working with an Arduino, then you are doing it wrong. An Arduino could not smoke a 1/4 watt if it tried.</p> <p>I have fought for years with our purchasing agent over this at the college I work for. He buys 1/8th watt resistor in bulk, but fails to heed the advice that you cannot use these on standard classroom breadboard without bending the leads at best and failing to even make a good connection at worst. You need reliable connections and 1/8th and smaller are useless on breadboards. Just my two cents from years and years of experience.</p>
18564
|voltage-level|attiny|
Where is the Aref pin for Attitny88
2015-12-09T17:23:51.430
<p>I would like to use the external analog refence voltage in an Attiny88 project I am working on that will be powered with batteries. </p> <p>However, the datasheet for this processor does not show an Aref pin like other versions of the attiny, like attiny85 and attiny84, where it is usually the pin PA0 or PB0. Does anyone know where is the pin for the external voltage reference in attiny88 (e.i. Aref pin)? Does this chip has the functionality for an external analog reference voltage?</p>
<p>As shown in the detailed information for the ADMUX register in the ADC section of the datasheet, the ATtiny88 has no external voltage reference. Consider using a ATmega8 or ATmega88PB instead.</p>
18569
|hardware|
Sending IR (NEC)-Signals with Arduino
2015-12-09T16:02:12.277
<p>I have an <strong>Arduino Micro</strong> where I want to control a display with IR commands. So the Arduino should send the IR commands to the display.</p> <p>I have found a library "<a href="https://github.com/z3t0/Arduino-IRremote" rel="nofollow">Arduino-IRremote</a>", which I am using to transmit Commands to the display. The display works perfectly with its remote control, however I can't get it accept signals from my Arduino.</p> <p>Now the special part about my setup is, that I do not use a "classic" IR transmitter. Instead i uset an IR cable, which is connected to "IR-In" of the display. So no LED - only a wired connection. The IR-cable consists of 3 wires. 2 for power supply (VIN and GND) and one is for the data connection. The wire with the data connection is connected with the Arduino PWM pin 3 (like it is said on the example in the linked library), but I tried all other pins anyway.</p> <pre><code>#include &lt;IRremote.h&gt; IRsend irsend; void loop() { for (int i = 0; i &lt; 2; i++) { digitalWrite(RXLED, HIGH); irsend.sendNEC(0x004eff71, 32); Serial.println( "sendNEC 00 4E FF 71" ); digitalWrite(RXLED, LOW); delay(40); } delay(1000); } </code></pre> <p><code>004eff71</code> is a NEC-Command from the original remote control</p> <p>Now can somebody tell me, what I'm doing wrong? The program compiles and the LED lights up, everytime it should send the NEC-command. But still the display receives nothing. What is wrong?</p>
<p>It would help to know the specifications of the IR input on the device you're trying to control but after a bit of googling it looks like most of them are just expecting a connection to an IR receiver. I found a link to what appears to be a common one, TSOP22.., TSOP24.., TSOP48.., TSOP44.. and here's a link to the data sheet (<a href="http://www.vishay.com/docs/82459/tsop48.pdf" rel="nofollow">http://www.vishay.com/docs/82459/tsop48.pdf</a>). If you check the Vo on page 2 it shows 0-5V. You didn't mention if you're using a 5V or 3V Arduino so that could be an issue.</p> <p>The PWM outputs do in fact generate square wave signals so at first glance this does not look like a hardware issue (assuming it is wired correctly for the IR input on your equipment).</p> <p>I'd start taking a look at the data you're trying to send. I haven't looked into the library you mentioned and hopefully it contains a sample to show how to properly initialize the library and send data. Maybe instead of first byte first it needs to be sent first byte last or requires a fixed number of bytes to send...</p> <p>Providing more details about your project you might get a better answer.</p>
18575
|arduino-uno|esp8266|softwareserial|
Send AT commands to ESP8266 from Arduino Uno via a SoftwareSerial port
2015-12-10T04:26:14.473
<p><strong>GOAL</strong></p> <p>From Arduino UNO, send AT commands to ESP8266 via a SoftwareSerial port and receive results.</p> <p><strong>CURRENT STATUS</strong></p> <p>I either send AT commands and get nothing back (<em>wiring scheme 1</em>) or I send AT commands and get garbage back (<em>wiring scheme 2</em>).</p> <p>Using the Arduino as a pass through (as explained in the tutorial listed in the resources section), I can send AT commands. I have found that I can communicate with the ESP8266 at 115200 baud. </p> <p>This is the results of running <code>AT+GMR</code>:</p> <pre><code>AT version:0.40.0.0(Aug 8 2015 14:45:58) SDK version:1.3.0 Ai-Thinker Technology Co.,Ltd. Build:1.3.0.2 Sep 11 2015 11:48:04 </code></pre> <p><strong>WIRING SCHEME 1</strong></p> <p><em>!! I have the green wire attached to pin 3 on the Arduino Uno and the yellow wire attached to pin 2; not 1 and 0 as the picture suggests !!</em></p> <p><a href="https://i.stack.imgur.com/0yEju.png" rel="noreferrer"><img src="https://i.stack.imgur.com/0yEju.png" alt="enter image description here"></a></p> <p><strong>WIRING SCHEME 2</strong></p> <p>Same wiring as above, but I have RX and TX reversed. The green wire is attached to pin 2 and the yellow wire is attached to pin 3. </p> <p><strong>CODE</strong></p> <p><em>This is running on Arduino Uno</em></p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial esp8266(2, 3); void setup() { // Open serial communications and wait for port to open: Serial.begin(115200); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } Serial.println("Started"); // set the data rate for the SoftwareSerial port esp8266.begin(115200); esp8266.write("AT\r\n"); } void loop() { if (esp8266.available()) { Serial.write(esp8266.read()); } if (Serial.available()) { esp8266.write(Serial.read()); } } </code></pre> <p><strong>RESULTS FROM RUNNING SKETCH</strong></p> <p><em>Wiring Scheme 1</em></p> <pre><code>Started </code></pre> <p><em>Wiring Scheme 2</em></p> <pre><code>Started ����� </code></pre> <p>I have tested the ESP8266 via the instructions listed in the tutorial in the <em>Resources I've Used</em> section below. The ESP8266 works just fine when sending it instructions via the Serial Prompt.</p> <p><strong>RESOURCES I'VE USED</strong> <a href="http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf" rel="noreferrer">http://rancidbacon.com/files/kiwicon8/ESP8266_WiFi_Module_Quick_Start_Guide_v_1.0.4.pdf</a></p> <p><strong>QUESTION</strong></p> <p>Does anyone know if what I am trying to do is possible? And if it is, what am I doing wrong?</p>
<p>Here are a few tips when using ESP8266 Module.</p> <ol> <li><p>Don't use software serial as it's unreliable especially at higher baud rates.</p></li> <li><p>Always <a href="http://absaransari.com/2018/01/26/connecting-esp8266-wifi-mobile-with-computer-using-pl2303/" rel="nofollow noreferrer">connect ESP module to computer</a> and test all AT commands before interacing with Arduino to ensure that you are working in right direction</p></li> <li><p><a href="http://absaransari.com/2018/01/25/how-to-power-esp8266-from-5v-supply/" rel="nofollow noreferrer">Make a power adaptor board</a> to make ESP module compatible with Arduino 5v supply</p></li> </ol> <p>Also check out <a href="http://absaransari.com/category/esp8266/" rel="nofollow noreferrer">this link</a> for more details</p>
18580
|arduino-uno|pwm|solar|
MPPT using preassembled 'adjustable' buck/boost IC
2015-12-10T11:56:25.193
<p>This is more of a thought experiment, as I don't know if I'll have the time to work on it.</p> <p>Items:</p> <ul> <li>Arduino</li> <li><a href="http://www.instructables.com/id/ARDUINO-SOLAR-CHARGE-CONTROLLER-Version-30/?ALLSTEPS" rel="nofollow noreferrer">Homebrew MPPT controller from Instructables</a></li> <li><a href="https://i.stack.imgur.com/9iE2z.jpg" rel="nofollow noreferrer">LM2596 Adjustable Buck Regulator</a></li> </ul> <p>Idea:</p> <p>Looking at the Instructable, that seems like a fairly interesting and robust circuit, originally developed by one Tim Nolan whose website no longer seems to exist.</p> <p>I'm somewhat lazy/fearful of messing things up when building from scratch, so I like to get preassembled modules and tinker instead. So, my thought is simple (ish). Looking at the LM2596 module, the output voltage is determined by the setting of the multiturn pot. I'd like to replace that pot with, say, a PWM controlled voltage from an Arduino, which I can then adjust using Tim Nolan's code to achieve MPPT.</p> <p>So to be very specific, the question is: can I safely remove that pot and use a PWM'd voltage in its place, in order to control the output for MPPT?</p>
<p>The pot is actually part of the feedback mechanism, so you can just feed it a fixed voltage (based on PWM duty cycle). See the <a href="http://www.ti.com/lit/ds/symlink/lm2596.pdf" rel="nofollow">second diagram on page 9 of the datasheet</a></p> <p>You could however replace it with a <a href="https://www.sparkfun.com/products/10613" rel="nofollow">digital pot</a> (not necessarily 10k).</p>
18582
|ir|arduino-micro|
How to send unmodulated IR-Signal via cable?
2015-12-10T14:52:36.410
<p>I need to generate en (extended) NEC signal. I have connected an Arduino with a display-device via an IR cable.</p> <p><code>Arduino --&gt; IR-cable --&gt; IR-input of display device</code></p> <p><strong>IR-cable:</strong> <a href="https://i.stack.imgur.com/rAIhP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rAIhP.jpg" alt="IR Cable datasheet"></a></p> <p>One plug is cutted and the 3 wires are connected with the arduino.</p> <p>The arduino should generate NEC Signals, and the display shall react to it. Basically the arduino acts like a wired remote control.</p> <p>The problem is: There are many tutorials around, that show how to do this with a sensor (e.g by using this <a href="https://github.com/z3t0/Arduino-IRremote" rel="nofollow noreferrer">library</a>). But none of the tutorials says how to do it with a cable.</p> <p>I found out, my previous attempts all failed, because I tried to generate a modulated NEC-signal to the display. The display however does not understand it, because there is no device that demodulates the signal. The IR sensor normally does this, which is missing in this case.</p> <p>e.g. This is, what an modulated NEC signal looks like:</p> <p><code>00 4e ff 61</code></p> <p>The library generates the moduled signal (pulse bursts) and this is how it works for IR sensors.</p> <p>But how do I have to send my IR-command, that the display understands it? How do I send a not-modulated IR signal?</p> <p><strong>The following graphic demonstrates the issue:</strong></p> <p><a href="https://files.cablewholesale.com/mailimages/ir-transmission.gif" rel="nofollow noreferrer"><img src="https://files.cablewholesale.com/mailimages/ir-transmission.gif" alt="IR"></a></p> <p>I do not have IR-LED Transmitter, Amplifier, Limiter, Band Pass Filter, Demodulator, Integrator, Comparator.... I just want to create the green Output-signal directly from my Arduino</p>
<p>I needed the same thing, so I created a library for it: <a href="https://github.com/dennisfrett/Arduino-Direct-NEC-Transmitter" rel="nofollow noreferrer">https://github.com/dennisfrett/Arduino-Direct-NEC-Transmitter</a>.</p> <p>It basically just pulls the pin high and low with the correct timings for the NEC protocol.</p>
18588
|i2c|wire-library|
Olimexino 32u4: Wire.endTransmission() hangs
2015-12-10T19:35:38.347
<p>I'm trying to get a TAE5767 (FM radio) to work. According to <a href="http://www.instructables.com/id/TEA5767-FM-Radio-Breakout-Board-for-Arduino/?ALLSTEPS" rel="nofollow">this instructable</a> I'm trying it on a 5V-Olimexino 32u4 (Leonardo-compatible) with following code (Arduino 1.6.3):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;Wire.h&gt; void setFrequency(float frequency) { unsigned int frequencyB = 4 * (frequency * 1000000 + 225000) / 32768; byte frequencyH = frequencyB &gt;&gt; 8; byte frequencyL = frequencyB &amp; 0xFF; Wire.beginTransmission(0x60); Wire.write(frequencyH); Wire.write(frequencyL); Wire.write(0xB0); Wire.write(0x10); Wire.write(0x00); Serial.println("sending"); Wire.endTransmission(); Serial.println("sent"); } void setup() { Serial.begin(9600); while (!Serial) { } Wire.begin(); setFrequency(89); } void loop() { } </code></pre> <p>Unfortunately, it only prints</p> <pre><code>sending </code></pre> <p>First, I thought I'd damaged my chip, but I'm now using the second with the same result. I've also tried the I2C-Scanner from <a href="http://www.gammon.com.au/i2c" rel="nofollow">Nick Gammon</a>, but it prints nothing. I've tried adding 2.2k resistors from SCL and SDA to 5V without success. Does someone has a clue what I can try?</p>
<p>I've did not got it working with <code>Wire</code>. Hence I've implemented a I2C protocol myself using bit-banging and then it works.</p> <p><strong>Update from 2017-September-16</strong></p> <p>The problem was not <code>Wire.h</code> but a specialty of the Olimexino 32u4 board. I've only found out by using a Real Time Clock connected to the UEXT port's I2C bus, that I have to switch on the power for the UEXT port by setting D8 to LOW. Otherwise SDA or SCL seem to be pulled down preventing any I2C communication.</p>
18598
|arduino-uno|serial|sensors|softwareserial|
Read serial data from XV11 sensor
2015-12-11T02:57:42.673
<p>I am trying to read data from an XV-11 sensor using the description of the format found here <a href="https://xv11hacking.wikispaces.com/LIDAR+Sensor" rel="nofollow">https://xv11hacking.wikispaces.com/LIDAR+Sensor</a>. This is the code I am currently using to communicate with the computer by USB and the sensor with software serial on an arduino uno.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(10, 11); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for native USB port only } mySerial.begin(115200); } int count = 0; void loop() { if(mySerial.available()) { byte in = mySerial.read(); Serial.println(in, HEX); } } </code></pre> <p>However, the data I am receiving on the computer is inconsistent with what I expect. For example, I am expecting a 0xFA byte every 22 bytes, however this only sometimes happens. Many times extra or fewer bytes appear in the middle of the data. I am using the 5 volt arduino serial communication, however I have heard that it is still compatible with 3.3 V sensor communication, so I doubt it is the problem. I don't thinkthe sensor is broken, as it is new from a working unit.</p>
<p>Soft Serial is totally unreliable. You may have a better error rate at other baud rates, but you will never achieve the same as a hardware based serial connection. I'd switch my debugging connection to the software serial, nd use the hardware serial for the XV-11.</p>
18601
|arduino-uno|arduino-ide|
Sublime Text Compilation Issue
2015-12-11T05:53:34.000
<p>I've tried searching for this issue but came up empty. Due to the desire to use a better IDE, I installed Sublime Text 3 and Stino. I have installed the Stino package and now have the Arduino menu inside the Sublime Text editor. I have selected the Arduino application folder appropriately. However, when I compile the simple Blink example, I'm presented with the following error. This error comes up when I attempt to compile any Arduino project. Have I forgotten to configure a setting? All videos and tutorials I've seen just follow the same steps as I have and don't seem to include any additional configuration (besides selecting the Arduino application folder).</p> <pre><code>[Stino - Start building "Blink"...] [ 3%] Creating C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o... "C:\Program Files (x86)\Arduino/hardware/tools/avr/bin/avr-g++" -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=161 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\Program Files (x86)\Arduino\examples\01.Basics\Blink" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" "-IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard" "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp" -o "C:\Users\cketc_000\Documents\Arduino\Blink\Blink.ino.cpp.o" The filename, directory name, or volume label syntax is incorrect. [Stino - Exit with error code 1.] </code></pre>
<p>As a quick update for anyone who runs into a similar issue (granted, a week later)...</p> <p>I upgraded to 1.6.5 of the Arduino IDE, making sure to set my Arduino application folder appropriately, and the compilation issue has disappeared. I am able to compile and upload projects successfully.</p>
18615
|bootloader|atmega32u4|
What does the bootloader do?
2015-12-11T15:23:27.280
<p>As far as I understand it checks for a valid serial connection (new program incoming) and then either writes it to flash or starts executing the existing program.</p> <p>Can't the 32u4 or EDBG fill the role of an ISP and program the MCU instead of the MCU self-programming? I know the EDBG is accessed via OpenOCD to write the bootloader to the SAMD21 on Arduino Zero boards so why is the bootloader even required?</p>
<p>The bootloader is there for convenience.</p> <p>Yes, you understand what the bootloader does and how it operates. However, you have missed out one benefit, and that is evident when you're <em>not</em> using the bootloader. That is, when you're not using the bootloader the <em>same</em> connection can be used for a serial connection to the PC. If the 32U4 were directly programming the main MCU then it would be talking to the SPI pins not the UART pins, so you would need a second connection, or both a connection to the UART <em>and</em> the SPI pins, and much more complex firmware on the 32U4, in order to get a serial connection to the PC.</p> <p>So the simplest option is just to have a dumb pass-through interface from the USB to the UART pins and have the main MCU self program with a bootloader.</p> <p>It also means that you don't need any special programming hardware when making your own board - just something (another arduino maybe) to get the bootloader on there in the first place (or buy the MCU pre-programmed) and then use any TTL serial interface to program it with your main program.</p>
18619
|arduino-uno|lcd|wireless|
Message received with 1 character less
2015-12-11T21:57:13.533
<p>I have the following situation:</p> <p>One Arduino Uno with a 433mhz transmitter wired to the laptop to have serial communication. Another Arduino Uno with a 9V battery wired with a 433mhz receiver and an LCD screen (16x2, I2C).</p> <p>I have the following code to transmit:</p> <pre><code>#include &lt;VirtualWire.h&gt; void setup() { //Force low when enabled vw_set_ptt_inverted(true); //Set pin 12 for transmitter vw_set_tx_pin(12); //Setup with speed of the data transfer. vw_setup(4000); //Set serial communication at 9600 baud Serial.begin(9600);//set Serial //Set pin 13 to light up when transmitting pinMode(13,OUTPUT); } void loop() { //If message send via serial monitor if (Serial.available()) { //wait a bit for the entire message to arrive delay(100); while (Serial.available() &gt; 0) { //Read serial into string String message = Serial.readString(); //Initialize char array char msg[message.length()]; //Write string to char array message.toCharArray(msg, message.length()); //send char array as unsigned int (bits) vw_send((uint8_t *)msg, strlen(msg)); //Wait until the complete message has been send vw_wait_tx(); //Turn on light when finished digitalWrite(13,HIGH); delay(200); } }else{ //Turn off light digitalWrite(13, LOW); } } </code></pre> <p>And the following code to receive a message and print on a LCD screen:</p> <pre><code>#include &lt;LiquidCrystal_I2C.h&gt; #include &lt;VirtualWire.h&gt; LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address void setup() { //start up LCD with 16 chars with 2 lines lcd.begin(16,2); //Turn on backlight lcd.backlight(); //Write initialising message lcd.setCursor(0,0); lcd.print("Initialisation.."); //Force low when enabled vw_set_ptt_inverted(true); //Set pin 12 to receive vw_set_rx_pin(12); //Setup with speed of the data transfer. vw_setup(4000); //set pin 13 for light pinMode(13, OUTPUT); //Start receiver vw_rx_start(); //Set message on LCD that setup has completed lcd.setCursor(0,1); lcd.print("Completed!"); } void loop() { //initialize array for message uint8_t msg[VW_MAX_MESSAGE_LEN]; uint8_t msgLength = VW_MAX_MESSAGE_LEN; //If message received if (vw_get_message(msg, &amp;msgLength)){ //Turn on light digitalWrite(13, HIGH); //Print on lcd lcd.clear(); lcd.setCursor(0,0); lcd.write(msg, msgLength); }else{ //Else turn of light digitalWrite(13, LOW); } } </code></pre> <p>My problem is that the message that is being transmitted and received by the other arduino always is short 1 character. For example if I send "test", it receives and displays "tes". What am I missing?</p> <p>(My short solution was to just add a space to the message, then the space got cut off. But I want to understand what is going wrong.)</p>
<p>I haven't found the source of the problem by reading through the code, and will limit my comments to advice about debugging the problem.</p> <p>With the code as it stands, there are half a dozen points where the missing character might have dropped out. With just a final result, the problem location is difficult to narrow down. Modify your code to display intermediate data. </p> <p>For example, in the sending code, print the read-in string and its length to Serial. Eg, if you <code>#include &lt;Streaming.h&gt;</code> you can say: </p> <p><code>Serial &lt;&lt; message &lt;&lt; ' ' &lt;&lt; message.length() &lt;&lt; endl;</code> <code>Serial &lt;&lt; msg &lt;&lt; ' ' &lt;&lt; strlen(msg) &lt;&lt; endl;</code></p> <p>and so forth.</p> <p>[Note, <code>msg</code> actually occupies strlen(msg)+1 bytes, the last byte being a null-byte terminator, which your code doesn't send or receive.]</p> <p>In the receiving code, besides the <code>lcd.write</code> of <code>msg</code>, do an <code>lcd.print</code> with <code>msgLength</code>.</p> <p>You can also do some code clean-up in the sender. Remove the line</p> <p><code>while (Serial.available() &gt; 0) {</code>, and its corresponding <code>}</code>, because <code>Serial.readString()</code> already contains a character-wait loop with timeout.</p>
18621
|interrupt|softwareserial|
Are INTx pins the only ones eligible for Software Serial?
2015-12-12T00:03:42.803
<p>As opposed to PCINT (Atmel's Pin Change INTerrupt, INTx is arduino-compatible interupt) In other words, does Software Serial use atmel's pin change or arduino falling interrupt?</p>
<p><code>SoftwareSerial</code> uses PCINT. <code>AltSoftSerial</code> uses INT0 or INT1, which has FALLING, RISING, CHANGE or LOW LEVEL options. See Section 12.2, p. 71 of the Atmel <a href="http://www.atmel.com/images/doc8161.pdf" rel="nofollow">ATmega328 spec</a>, for example.</p>
18625
|magnetometer|
Converting three-axis magnetometer values to degrees
2015-12-12T03:42:48.777
<p>I have a 9-DOF sensor (<a href="https://cdn.sparkfun.com/datasheets/Sensors/IMU/MPU-9150-Datasheet.pdf" rel="nofollow noreferrer">MPU-9150</a>) and I want to use its magnetometer to retrieve the rotation angle, from 0 to 359. However, its library returns three values: x, y and z.</p> <p>I do not know how to transform this into a single value. Is there any way to do this?</p>
<p>I wanted to expand upon what Anon is getting at and provide some math as I've just gone through this process for a similar 9-axis device.</p> <p>First, it's good to know what the magnetic field vector means. I like <a href="https://lohmannlab.web.unc.edu/geomagnetic-imprinting/" rel="noreferrer">this source</a> because it provides <a href="https://lohmannlab.web.unc.edu/wp-content/uploads/sites/8154/2014/10/geomagnetic-field-low-res-624x385.jpg" rel="noreferrer">an image</a> showing where magnetic vectors point as you move up and down earth. It points downward on the northern hemisphere and upward in the southern hemisphere. The text is otherwise not relevant as it more or less just explains how you can approximate laitudinal position from that data - the angle of the horizontal component is all that we need to be concerned with in order to obtain a heading.</p> <p>The problem with Edgar's answer is that it assumes that your reference plane is flat against earth. As soon as you add any pitch or roll, that answer won't be right. To correct, you need to project the magnetic field vector onto your horizontal plane. Luckily, that sensor also provides you with an accelerometer which provides a way to tell you which way is down due to the force of gravity as long as you're not moving around too quickly.</p> <p>What I did was <a href="https://en.wikipedia.org/wiki/Vector_projection" rel="noreferrer">project the magnetic field vector onto the acceleration vector</a> then subtracted that from the magnetic field vector to get the horizontal component vector. Then I could retrieve the vector angle on the X/Y plane just as described by others.</p> <p>First, a partial definition of a vector so I'm not depending on external libraries:</p> <pre class="lang-cpp prettyprint-override"><code> class Vector3D { public: Vector3D() : mArr{} {} Vector3D(double x, double y, double z) { mArr[0] = x; mArr[1] = y; mArr[2] = z; } double dot(const Vector3D&amp; rhs) const { double out = 0; for (int i = 0; i &lt; NUM_DIMENSIONS; ++i) { out = out + mArr[i] * rhs.mArr[i]; } return out; } Vector3D operator* (double x) const { Vector3D out; for (int i = 0; i &lt; NUM_DIMENSIONS; ++i) { out.mArr[i] = mArr[i] * x; } return out; } Vector3D operator- (const Vector3D&amp; x) const { Vector3D out; for (int i = 0; i &lt; NUM_DIMENSIONS; ++i) { out.mArr[i] = mArr[i] - x.mArr[i]; } return out; } double getX() const {return mArr[0];} double getY() const {return mArr[1];} double getZ() const {return mArr[2];} private: static const int NUM_DIMENSIONS = 3; double mArr[NUM_DIMENSIONS]; }; Vector3D operator* (double x, const Vector3D&amp; y) { return (y * x); } </code></pre> <p>Here is how the compass angle can be computed:</p> <pre class="lang-cpp prettyprint-override"><code> // mag: magnetic vector // accel: acceleration vector (due to gravity) double computeYaw(double mag_x, double mag_y, double mag_z, double accel_x, double accel_y, double accel_z) { const Vector3D vector_mag(mag_x, mag_y, mag_z); const Vector3D vector_down(accel_x, accel_y, accel_z); const Vector3D vector_north = vector_mag - ((vector_mag.dot(vector_down) / vector_down.dot(vector_down)) * vector_down); return atan2(vector_north.getX(), vector_north.getY()) * 180 / M_PI; } </code></pre> <p>EDIT: I changed the code so needed elements of a Vector are defined here so there is no confusion.</p> <p>EDIT2: <a href="https://www.mdpi.com/1424-8220/11/10/9182/pdf" rel="noreferrer">Here</a> is a good resource on this subject if you need a more accurate solution. As stated in this resource, the above is only really useful if you're not moving around too much and your magnetic environment is clean.</p>
18629
|led|arduino-nano|
Blink question with breadboard & LED
2015-12-12T13:36:08.697
<p>I tried a basic Blink example and I found a strange case where :</p> <p>Works <a href="https://i.stack.imgur.com/tfcD5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tfcD5.jpg" alt="Working example"></a></p> <p>Does not work <a href="https://i.stack.imgur.com/rpYOF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rpYOF.jpg" alt="NOT working example"></a></p> <p>Can someone explain me what is happening ?</p>
<p>It is because the rail in the middle breaks the vertical connections. So the positive leg in the first example is not connected to the negative leg of the LED.</p> <p>In your second example both the negative leg and the positive leg are connected on the same rail, because of the that the power is not flowing through the LED but directly back to the GND pin of your arduino.</p> <p>Same for the resistor. Since both legs are connected to the same rail, the resistor has no effect.</p>
18632
|arduino-uno|analogread|
MQ135 output on Arduino Uno
2015-12-12T17:39:06.670
<p>I bought an FC-22 (MQ135) gas sensor module which I plugged into my Arduino Uno. I connected it to the A0 analog port. Then created a code that reads the raw data from A0 (code below).</p> <p>When I run the code on my Arduino Uno in my house I get values of about 30. If I blow over the sensor I get values until about 160. My question is now how I have to read / interpret these values.</p> <p>According to the MQ135 specifications the sensor has a sesitivity for air quality, measuring benzene, alcohol and smoke.</p> <p>How can I interpret the values I get? What is a good value and what isn't? Do I have to calculate something out of these values?</p> <p>My code looks like this:</p> <pre><code>void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { int sensorValue = analogRead(0); Serial.print(sensorValue, DEC); delay(100); if (sensorValue &gt; 50) { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); } } </code></pre>
<p>According to the <a href="https://www.olimex.com/Products/Components/Sensors/SNS-MQ135/resources/SNS-MQ135.pdf" rel="nofollow">datasheet</a> you have to calibrate it.</p>
18639
|arduino-uno|arduino-ide|ubuntu|
Arduino IDE fails without sudo
2015-12-12T22:54:37.863
<p>I use Arduino IDE 1.6.6 on Ubuntu 15.10.</p> <p>Starting the Arduino IDE without using <code>sudo</code> fails for both:</p> <ul> <li>uploading the code to the Arduino Uno</li> <li>starting the serial monitor</li> </ul> <p>The group I need to add my user to is called <code>dialout</code>:</p> <pre><code>myuser@mycomputer:~$ ls -l /dev/ttyACM* crw-rw---- 1 root dialout 166, 0 Dez 12 17:57 /dev/ttyACM0 </code></pre> <p>So I added <code>myuser</code> to <code>dialout</code>:</p> <pre><code>sudo usermod -a -G dialout myuser </code></pre> <p>Somewhere I read that I have to add <code>myuser</code> to <code>tty</code> as well, so I did it:</p> <pre><code>sudo usermod -a -G tty myuser </code></pre> <p>Though I still fail with the above mentioned when trying to use the IDE with <code>myuser</code>.</p> <p>What do I have to do to get the IDE working with <code>myuser</code>?</p>
<p>There should be a command like 'id' or something similar that will show the groups you are a member of. Run that to check that the new groups have taken effect – you may need to log out and then log back in.</p> <p>The other thing to check is the group owner of the device itself (in /dev). that will also need to match the group you assigned to yourself. Also make sure that the device permissions allow group access.</p>
18642
|arduino-uno|c++|led|
Displaying binary to LEDs
2015-12-13T07:42:26.667
<p>I've written a program for Arduino UNO and 3 LED lights. The program is supposed to turn an inputted number into binary and then display it on the LEDs, on being 1 and off being 0 I have looked it over quite a few times and don't understand why it is not working as it should. I'm a beginner at working with Arduino so I probably just need a more experienced eye to show me where I have messed up. I have a link to a picture of the Arduino setup below. Thanks! <a href="https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing" rel="nofollow">https://drive.google.com/file/d/0B8k_WNZ3eFOkZHkwNUllTEp4WGM/view?usp=sharing</a></p> <pre><code>//setting up lights const int lightOne = 13; const int lightTwo = 12; const int lightThree = 11; //array of the lights for when printing the binary int lights[] = {lightOne, lightTwo, lightThree}; void setup() { //setting pin modes and starting up the serial monitor pinMode(lightOne, OUTPUT); pinMode(lightTwo, OUTPUT); pinMode(lightThree, OUTPUT); Serial.begin(9600); } //converts a given number into binary String binary(int number) { String r; while(number!=0) { r = (number % 2 == 0 ? "0" : "1")+r; number /= 2; } return r; } //outputs the binary string to the lights (not expecting numbers larger than 9) void printBinary(String binaryNumber) { for (int i = 0; i &lt; sizeof(binaryNumber); i++) { digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH)); delay(2000); } } void loop() { int input = Serial.read(); //get the number String binaryNumber = binary(input); //convert number to binary Serial.println(binaryNumber); //print binary to serial monitor printBinary(binaryNumber); //display number in binary on LEDs } </code></pre>
<h1>Welcome to SE Arduino!</h1> <h2>Long Version</h2> <p>You have a couple of things to look at:</p> <ol> <li>Don't use <code>String</code> class it has too much overhead for Arduino.</li> <li>Your conversion function is not really necessary because you can convert it on your <code>Serial.println()</code> by specifying <code>binary</code> as output. eg: <a href="https://www.arduino.cc/en/Serial/Println" rel="nofollow"><code>Serial.println(number, BIN)</code></a>;</li> <li>The <code>Serial.read</code> returns an integer, but that <code>int</code> only contains a <a href="https://www.arduino.cc/en/Reference/Byte" rel="nofollow"><code>byte</code></a> (unsigned) value anyway (unless there's nothing to be read, in which case it returns <code>-1</code>). Because you're taking a number (not really relevant) and you want it to be a number on the return, just use <code>int</code> or <code>byte</code> (unsigned: <code>0 &lt;-&gt; 255</code>) or <a href="https://www.arduino.cc/en/Reference/Char" rel="nofollow"><code>char</code></a> (signed: <code>-127 &lt;-&gt; +128</code>). </li> <li>You could/should/doesn't matter if you use <code>Serial.available()</code> or not, it is a matter for yourself, I usually do, but it's non blocking anyway and if there's nothing there to be read, it'll just continue on anyway. Although if you're not going to use it, you should test for that <code>-1</code> as what you're doing at the moment is taking that and converting it to binary (which is <code>0xFF</code> which is everything on). <strong>This is one of your major problems in the code</strong> (the other is in the <strong>Short Version</strong> section.</li> <li>You're using <code>"0"</code> and <code>"1"</code> which are <code>ASCII</code> values, and you haven't indicated how you're getting the number. So it may be <code>ASCII</code> (<code>byte</code>) or actually a <code>byte</code> value. ie, <code>"0"</code> is <code>48 (dec)</code> or <code>30 (hex)</code>. Whereas a <code>0</code> is just <code>zero</code>. Funnily enough, because you're using modulo (<code>%</code>) it doesn't really matter because you're only interested in the lowest nibble, which for the sake of your code, doesn't matter what's encoded at the higher end. ie: <code>1</code> (<code>0b00000001</code>) is the same as <code>"1" = 49 (dec) = 0x31 = 0b00110001</code> when used with <code>%2</code>.</li> <li>Ditch your <code>delay(2000)</code>. Delays are evil* :) You could write the values to the pins all day, you're not going to cause any problems, if you want to output less to your serial port (which you should do), you could do timed outputs back to Serial. ie, do your <code>Serial.println()</code> once a second, or record the values into backup/old variables and compare them, and only print the output if the value changes</li> <li>The big one is in the next section</li> </ol> <h2>Short Version</h2> <p>This is your <em>main</em> problem, on this line:</p> <pre><code>digitalWrite(lights[i+11], (binaryNumber[i] == '0' ? LOW : HIGH)); </code></pre> <p>I think you need:</p> <pre><code>digitalWrite(lights[i], (binaryNumber[i] == '0' ? LOW : HIGH)); </code></pre> <p>You already have the pin value encoded in the array, you don't want to add 11 to the index, that's going to throw you above your three light values :)</p> <p><strong>* Delays are evil</strong>: It's a matter of opinion, and that's just how I feel, I actually googled it and this is just a random response. But it contains the crux of what I'd say anyway: <a href="http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/" rel="nofollow">http://www.makeuseof.com/tag/arduino-delay-function-shouldnt-use/</a></p>
18644
|arduino-nano|
Rotating a motor with L293D
2015-12-13T10:19:09.833
<p>I'm following this <a href="http://communityofrobots.com/tutorial/kawal/how-drive-dc-motor-using-l293d-arduino" rel="nofollow noreferrer">tutorial</a> to control a DC motor with an Arduino.</p> <p>I have the same problem as this stackexchange post arduino.stackexchange.com/questions/10049/problems-with-l293d where the motor is not rotating.</p> <ul> <li>The chip is heading to the right. (5v pins are on the right)</li> <li>Connecting directly the motor to the battery works.</li> <li>Current (5V on the bottom &amp; 2*1.5V) is flowing everywhere expected EXCEPT on the yellow &amp; green wires of the motor (the red wire of the battery pack is connected to the second line of the breadboard).</li> <li>Connecting directly the motor to the battery works.</li> <li>I copied the code of the above tutorial which is basically : "digitalWrite(4,HIGH);", there is current on the cable.</li> </ul> <p>Am I wrong into thinking that a L293D chip can output sufficient current ? Is the chip malfunctioning ?</p> <p><a href="https://i.stack.imgur.com/FE9o4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FE9o4.jpg" alt="My montage"></a></p>
<p>Your picture shows a holder for two AA cells, yielding something in the neighbourhood of 3v. That is far too little for an L293D. (This isn't really your fault, as it appears you got this erroneous idea from following a bad tutorial, but it does demonstrate that not everything you read on the Internet is sensible. Using a 9v "transistor" battery is also a bad idea). 3 cells would be about the minimum, but even there it would not work well, as that chip has two bipolar transistors in the path yielding a voltage drop of over a volt. </p> <p>To use a an L293D you really want at least a 5 or 6 volt system, and a motor wound for low to moderate current at that voltage.</p> <p>If you want to use a lower voltage, look at a more modern MOS-based H bridge chip - the TB6612FNG is an often used example. You will however still want to choose motors wound for moderate current at a 3- or 4- cell voltage - those intended for 2-cell usage typically draw more current than is ideal for an IC driver chip.</p> <p>It is entirely possible that there are additional issues with your attempt as well. Normally, a question such as this would require a complete and accurate schematic diagram, which you have not provided.</p>
18652
|programming|c++|arduino-leonardo|
How to learn electronics/programming with Arduino?
2015-12-13T17:38:16.857
<p>I want to learn core and mechanics of microcontrollers with Arduino, and I don't really know where to find good source of knowledge. </p> <p>Every Arduino related tutorial is about very basic stuff like connecting the LCD display without explaining what every pin does. When it comes to programming tutorials only explain what functions are needed and do not explain what happens inside the hardware. </p> <p>For example i know what delay() function does, and I know that I can find definition in the source files:</p> <pre><code>void delay(unsigned long ms) { uint16_t start = (uint16_t)micros(); while (ms &gt; 0) { yield(); if (((uint16_t)micros() - start) &gt;= 1000) { ms--; start += 1000; } } } </code></pre> <p>But what I really want to know what that code does, and how to write own functions. I would appreciate if you could provide me with any starting point. Should I just follow the source files until I get it or is there any better reference?</p> <p>I have Arduino Leonardo, and experience in programming in C/C++.</p>
<p>For information about the “core and mechanics of microcontrollers with Arduino”, there are numerous articles with lots of details on the <a href="http://forum.arduino.cc/" rel="nofollow">arduino.cc</a> forum. However, most of the code posted there sucks, as does most of the code posted here on <a href="http://arduino.stackexchange.com">Arduino Stackexchange</a>. That's a natural consequence of people posting code that doesn't work and they wonder why.</p> <p>For a reasonably organized and accurate body of information about Arduino hardware and software, see <a href="http://www.gammon.com.au/forum/index.php?bbtopic_id=123" rel="nofollow">Nick Gammon's Arduino pages</a>. Also see <a href="https://arduino.land/FAQ/showcat.html" rel="nofollow">arduino.land</a> pages. For better understanding of Arduino software internals, see <a href="http://garretlab.web.fc2.com/en/arduino/inside/index.html" rel="nofollow">garretlab's “Internal Structure of Arduino Software”</a> pages, which are well organized and quite informative about the subjects they cover.</p> <p>Regarding the specific <code>delay()</code> code shown in the question, first consider this slightly simpler version, from Arduino 1.6.3: </p> <pre><code>void delay(unsigned long ms) { uint16_t start = (uint16_t)micros(); while (ms &gt; 0) { if (((uint16_t)micros() - start) &gt;= 1000) { ms--; start += 1000; } } } </code></pre> <p>Ignoring data type constraints, it's evident that the <code>while</code> loop counts down <code>ms</code> from its original value to zero. The burden of the <code>if</code> executes about once per millisecond, because <code>start</code> advances 1000 microseconds each time within the <code>if</code>.</p> <p>The casts of <code>micros()</code> – ie, where <code>uint16_t</code> appears in parentheses before <code>micros()</code> – tell the compiler to throw away the upper two bytes of <code>micros()</code> [which is actually an unsigned long, or <a href="http://www.cplusplus.com/reference/cstdint/" rel="nofollow"><code>uint32_t</code></a>] and treat it as an unsigned 16-bit integer. The low two bytes of <code>micros()</code> overflow every 65536 microseconds, on which occasions within a millisecond it will come to pass that although <code>(uint16_t)micros()</code> is less than <code>start</code>, due to use of unsigned arithmetic <code>((uint16_t)micros() - start) &gt;= 1000</code>.</p> <p>The code you included has one more statement in the <code>while</code> loop:</p> <pre><code> yield(); </code></pre> <p>For most models of Arduino, <code>yield()</code> is an empty function, a do-nothing if compiled at all. On the Due, with <a href="https://www.arduino.cc/en/Reference/Scheduler" rel="nofollow"><code>Scheduler.h</code></a> in use to support cooperative (non-preemptive) multitasking using multiple stacks, <code>yield()</code> gives the scheduler an opportunity to schedule another task, if one is ready to run. Note that if a “cooperative” but malignant task always takes just under 65536 microseconds to do its work, it can happen that <code>delay()</code> as shown never returns.</p>
18661
|arduino-uno|nrf24l01+|
nRF24L01 Problem
2015-12-14T00:21:04.457
<p>I'm trying to code a simple transmitter - Receiver program with nRF24L01</p> <p>Very simple code. Compiles. But when I try to test it using serial monitor. But only the first character is printed on the screen just once.</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SPI.h&gt; #include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; #define CE_PIN 9 #define CSN_PIN 10 const uint64_t pipe = 0xE8E8F0F0E1LL; RF24 radio(CE_PIN, CSN_PIN); int smth[1]; // the transmitter data int x=0; // the copy of the receiver data char rec[1]; //the receiver data int ledPin = 3; // choose the pin for the LED int inPin = 7; // choose the input pin (for a pushbutton) int val = 0; // variable for reading the pin status void setup() { Serial.begin(9600); pinMode(ledPin, OUTPUT); // declare LED as output pinMode(inPin, INPUT); // declare pushbutton as input radio.begin(); radio.openWritingPipe(pipe); //originally transmitter } void loop(){ val = digitalRead(inPin); // read input value if (val==HIGH) { // check if the input is HIGH (button released) digitalWrite(ledPin, HIGH); // turn LED OFF Serial.println('1'); smth[0] = '1'; radio.write(smth, sizeof(smth)); } else { digitalWrite(ledPin, LOW); // turn LED ON Serial.println('0'); smth[0] = '0'; radio.write(smth, sizeof(smth)); } } </code></pre> <hr> <p>Serial Monitor :</p> <p>0</p> <hr> <p>Instead of printing a zeros for infinite time till I change the mode of the switch, even though if I change the mode of the switch from low to high, nothing is printed on the screen.</p> <p>I'm using Library for instance <a href="http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01" rel="nofollow">http://playground.arduino.cc/InterfacingWithHardware/Nrf24L01</a></p> <p>Any help?</p>
<p>Completing TisteAndii reply I suggest to have a look at init. According to the RF24 classe list, it seems radio.begin(); and radio.openWritingPipe(pipe); are "void" function. I personnaly use NRFLite from Dave Parson and his lib send a return value for his _radio.init function. That's interesting because a lot of lib have a "send feature" which don't return until the receiver replied. So if you turn on your nRF and send data while the receiver is OFF, you're blocked. With a test at init, you can check that and loop until the receiver is available.</p> <p>Note: I let my answer, but that's not the good one. As indicate in the coment, the init function dont tell if the receiver is avaible, but only if the nRF is connected (your nRF, so not the other one). </p>
18669
|rs485|rs232|
Problem in RS485 Communication between Arduino and PC
2015-12-14T04:54:52.357
<p>I'm trying to sending and receiving data via RS485 communication. Interfacing Arduino and PC(laptop) using SN75176 RS485. I wrote a program to send a string "Hello" from arduino via Tx pin. My intention is to receive the "Hello" string in my PC's hyperterminal. After uploading the program im receiving junk data. The baud rate i've mentioned in my program and i gave in hyperterminal are same. I've checked the wire connection, it is ok. Then, what is the problem?</p> <p>Code:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SoftwareSerial.h&gt; int Txpin = 1; int ditpin = 5; //for 1st rs485 int ditpin1 = 2; //for 2nd rs485 void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(Txpin,OUTPUT); digitalWrite(ditpin, HIGH); //For transmit data from arduino digitalWrite(ditpin1, LOW); //For receive data to hyperterminal } void loop() { Serial.println("Hello\r\n"); delay(1000); } </code></pre> <p>Wire connection:</p> <p><a href="https://i.stack.imgur.com/aQ7y2.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aQ7y2.jpg" alt="enter image description here"></a></p>
<p>You cannot connect from Arduino serial input/output with RS485 circuit and then to the PC RS232 port. You need a TTL to RS232 adapter. For instance an adapter based on <a href="http://pdfserv.maximintegrated.com/en/ds/MAX3222-MAX3241.pdf" rel="nofollow noreferrer">MAX3222</a>. </p> <p><a href="https://i.stack.imgur.com/TPUVf.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TPUVf.gif" alt="MAX3232 circuit diagram"></a></p> <p>Cheers!</p>
18674
|programming|
Convert Long to binary - least signifant bit first
2015-12-14T12:37:07.107
<p>I have found an Arduino function which converts a 2-bytes-<code>long</code>-value to a binary value.</p> <p>e.g. I call <code>sendCommand(0x05)</code> And it gives me an output:</p> <p><code>00000101</code></p> <pre><code>void sendCommand(unsigned long command){ for (unsigned long mask = 1UL &lt;&lt; (7); mask; mask &gt;&gt;= 1) { if (command &amp; mask) { Serial.print( "1" ); } else { Serial.print( "0" ); } } } </code></pre> <p>my Problem is, that I want to have the Least significant bit first. How do I have to adjust this function to achieve this?</p> <p>e.g. <code>sendCommand(0x05)</code> shall give an output:</p> <p><code>10100000</code></p>
<pre><code>void sendCommand(unsigned long command){ for (unsigned long mask = 1UL; mask&lt;256UL; mask &lt;&lt;= 1) { if (command &amp; mask) { Serial.print( "1" ); } else { Serial.print( "0" ); } } } </code></pre> <p>PS a long is actually 4 bytes long. But your code only uses 1 byte of it.</p>
18686
|serial|arduino-mega|
Converting ASCII value to String
2015-12-14T20:34:10.697
<p>I have this code.</p> <pre><code>String incoming; // for incoming serial data void setup() { Serial.begin(9600); // opens serial port, sets data rate to 9600 bps } void loop() { // send data only when you receive data: if (Serial.available() &gt; 0) { // read the incoming byte: incoming = Serial.read(); String mysrr = String(incoming); // say what you got: Serial.print("I received: "); Serial.println(mysrr); } } </code></pre> <p>A few of you will recognise this as an Arduino example.</p> <p>However, when I run it ( I sent it the message "hi"), I get this in the serial:</p> <pre><code>I received: 104 I received: 105 </code></pre> <p>Why is this happening?</p>
<p>Serial.read() returns an int not a String. <a href="https://www.arduino.cc/en/Serial/Read" rel="nofollow">https://www.arduino.cc/en/Serial/Read</a></p> <p>Use an int for incoming (as the example). Or even better use a char and skip all the strings. </p> <p>Cheers!</p>
18689
|led|
Light leds on this board one at a time
2015-12-14T21:11:38.730
<p>I am playing around with this Tinycircuits <a href="https://www.tiny-circuits.com/tiny-shield-16-edge-led.html" rel="nofollow">16 LED board</a> and I can figure out how to persistently light two LEDs at the same time. The page comes with an example that i can modify but I can only do 1 at a time </p> <p><strong>How do I light more than one LED at a time?</strong></p> <pre><code>/* TinyDuino Edge LED Demo April 9 2014, by Ben Rose This example code is in the public domain. http://www.tiny-circuits.com */ void setup() { LedOn(0);//Pass a zero to turn all LEDs off } void loop() { for(int i=1;i&lt;16;i++){ LedOn(i); delay(20); }; for(int i=16;i&gt;1;i--){ LedOn(i); delay(20); }; } void LedOn(int ledNum) { for(int i=5;i&lt;10;i++){ pinMode(i, INPUT); digitalWrite(i, LOW); }; if(ledNum&lt;1 || ledNum&gt;16) return; char highpin[16]={5,6,5,7,6,7,6,8,5,8,8,7,9,7,9,8}; char lowpin[16]= {6,5,7,5,7,6,8,6,8,5,7,8,7,9,8,9}; ledNum--; digitalWrite(highpin[ledNum],HIGH); digitalWrite(lowpin[ledNum],LOW); pinMode(highpin[ledNum],OUTPUT); pinMode(lowpin[ledNum],OUTPUT); } </code></pre>
<p>That is an interesting challenge. You should include the circuit diagram for this. It really helps understand the code. </p> <p><a href="https://i.stack.imgur.com/J3WQz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J3WQz.png" alt="Charleplex Circuit"></a>. </p> <p>There is excellent information on this technique to reduce number of pins <a href="http://playground.arduino.cc/Code/Charlieplex" rel="nofollow noreferrer">here</a>. </p> <p>Cheers!</p>
18693
|arduino-uno|web-server|tcpip|
TCP or HTTP connection between web server and arduino
2015-12-14T23:23:07.323
<p>If arduino works as a client and tries to connect to web server (the server is mine), should I connect to it via TCP or HTTP connection? Data will be simple strings (20 chars at max) so TCP connection should probably be enough? </p> <p>The connection has to work in both ways - web server sending data to arduino and arduino sending data back to server. </p>
<p>It's time you learned the <a href="https://en.wikipedia.org/wiki/OSI_model" rel="nofollow">OSI 7 layer model: PDNTSPA</a>.</p> <p>HTTP is a <em>P</em>resentation (protocol) that runs over a TCP <em>S</em>ession. If you are interacting with a web server then you will be opening a TCP socket and sending HTTP requests.</p> <p>There is no other way of talking to a web server. It only speaks HTTP, and you can only connect to it through TCP.</p>
18695
|arduino-uno|
Arduino / BitVoicer Sending IR code on loop
2015-12-14T23:47:58.143
<p>I was designing a voice automated kitchen lighting system. I have led strips under the cabinets which are remote controlled by an IR remote, so I captured the IR codes and got an IR led to turn them on. Now I introduced BitVoicer so that I could use voice commands to control the LED. I have ran into the issue that the IR led keeps turning the lights on and off, but my IR codes worked prior to using BitVoicer.</p> <p>Here is my arduino code:</p> <pre><code>#include &lt;BitVoicer11.h&gt; int IRledPin = 13; BitVoicerSerial bvSerial = BitVoicerSerial(); void setup() { Serial.begin(9600); pinMode(IRledPin, OUTPUT); } void loop() { bvSerial.getData(); if(bvSerial.strData == "") { return; } if(bvSerial.strData == "wake") { LightOnCode(); } } void pulseIR(long microsecs) { cli(); while (microsecs &gt; 0) { digitalWrite(IRledPin, HIGH); delayMicroseconds(10); digitalWrite(IRledPin, LOW); delayMicroseconds(10); microsecs -= 26; } sei(); } void LightOnCode() { pulseIR(8940); delayMicroseconds(4380); pulseIR(520); delayMicroseconds(600); pulseIR(520); delayMicroseconds(560); pulseIR(560); delayMicroseconds(560); pulseIR(520); delayMicroseconds(580); pulseIR(520); delayMicroseconds(560); pulseIR(540); delayMicroseconds(580); pulseIR(520); delayMicroseconds(580); pulseIR(520); delayMicroseconds(580); pulseIR(540); delayMicroseconds(1660); pulseIR(520); delayMicroseconds(1680); pulseIR(520); delayMicroseconds(1660); pulseIR(540); delayMicroseconds(1680); pulseIR(520); delayMicroseconds(1680); pulseIR(500); delayMicroseconds(1680); pulseIR(540); delayMicroseconds(1680); pulseIR(520); delayMicroseconds(1660); pulseIR(540); delayMicroseconds(580); pulseIR(520); delayMicroseconds(560); pulseIR(560); delayMicroseconds(560); pulseIR(520); delayMicroseconds(600); pulseIR(500); delayMicroseconds(580); pulseIR(540); delayMicroseconds(560); pulseIR(520); delayMicroseconds(1680); pulseIR(540); delayMicroseconds(560); pulseIR(520); delayMicroseconds(1680); pulseIR(540); delayMicroseconds(1660); pulseIR(520); delayMicroseconds(1680); pulseIR(520); delayMicroseconds(1640); pulseIR(580); delayMicroseconds(1660); pulseIR(520); delayMicroseconds(1660); pulseIR(560); delayMicroseconds(560); pulseIR(520); delayMicroseconds(1680); pulseIR(520); } </code></pre> <p>If anyone could answer my question as to why the led keeps sending extra signals I would appreciate it! If you have any questions don't hesitate to ask!</p>
<p>Taking a quick look at the <a href="http://www.bitsophia.com/BitVoicer/v12/BitVoicerManual_v12_en.pdf" rel="nofollow">Documentation</a> on page 22, it looks like you need to use your <code>bvSerial.strData</code> calls within a function called <code>void serialEvent()</code> rather than inside of your loop. I would recommend trying out their tutorial on that page just to make sure you get BitVoicer to work properly before scaling it for your application.</p> <p>Hope that helps!</p>
18701
|pins|ethernet|wires|
Connect ethernet cable wires directly to pins
2015-12-15T08:49:57.087
<p>Is it possible to uncrimp a RJ45 plug and connect the wires directly to the Arduino pins? I guess I'd have to decrypt the ethernet signal then on my Arduino which might not have enough processing power at command for such a task.</p> <p>I don't want to do it with an Ethernet shield, so please don't link any in the answers.</p>
<p>As others have stated, it's not physically possible for an Arduino to encode or decode standard Ethernet protocol messages over CAT5 cable with wires at one end connected directly to the Arduino pins, and the other plugged into a standard Ethernet device. Standard Ethernet runs at least 10 Mbit/s for <a href="http://www.fpga4fun.com/10BASE-T3.html" rel="nofollow">10BASE-T, each bit Manchester encoded</a>, so effectively 20 Mbit/s. See <a href="http://www.testequity.com/documents/pdf/ethernet-debugging.pdf" rel="nofollow">"TCP/IPv4 and Ethernet 10BASE-T/ 100BASE-TX Debugging"</a> for a lot of photos of what the standard Ethernet protocol looks like on an oscilloscope screen. An Arduino running at 16 MHz can't sample a pin at 20 Mbit/s.</p> <p>However, Arduinos can easily transmit and receive messages using a variety of other, slower <a href="http://en.wikibooks.org/wiki/Embedded_Systems/Common_Protocols" rel="nofollow">communication protocols</a>. Devices that use such protocols can often be wired directly to the Arduino pins, with the Arduino programmed appropriately with that protocol.</p> <p>Occasionally people use CAT5 cable (commonly called "ethernet cable") to carry those non-Ethernet messages from one device to another.</p> <p>Sometimes people wire a RJ45 socket (also called a 8p8c socket) directly to an Arduino and corresponding RJ45 socket wired directly to the other device (often with a big "THIS IS NOT ETHERNET" warning on both sockets), and use standard off-the-shelf CAT5 patch cables with standard <a href="http://cp.literature.agilent.com/litweb/pdf/5989-7528EN.pdf" rel="nofollow">RJ25 plugs (also called 8p8c plugs)</a> to carry those non-Ethernet messages between the sockets. (For example, the connection between the Arduino-compatible "<a href="http://reprap.org/wiki/Motherboard_1_2" rel="nofollow">Motherboard 1.2 Generation 3</a>" and the "<a href="http://reprap.org/wiki/Stepper_Motor_Driver_2.3" rel="nofollow">Stepper Motor Driver 2.3 Generation 3</a>" used in some early RepRaps; the <a href="http://reprap.org/wiki/TechZone_Tip_Assembly#Thermocouple_A-D_converter_with_OneWire" rel="nofollow">TechZone Thermocouple A-D converter</a> and other <a href="http://www.opencircuits.com/1-wire" rel="nofollow">1-wire devices that use the 1WRJ45 standard</a>; etc. As far as I can tell, none of the many CAT5 cables Nate connected to various Arduinos in <a href="https://www.sparkfun.com/tutorials/282" rel="nofollow">"Lessons from Rebuilding Illumitune"</a> actually carry any Ethernet messages.)</p> <p>Sometimes people cut and strip the ends of CAT5 cable, using them as a convenient bundle of wires that can be used pretty much like any wire.</p> <p>Hooking wires directly between two Arduinos (or an Arduino and some other device using some non-Ethernet protocol) often seems to work when both are plugged into the same power supply and connected by a short cable. The "extra hardware" people use to interface between an Arduino and a Ethernet network or CANbus or RS485 bus or MIDI or etc. helps avoid a variety of problems that happen when two devices are plugged into different power supplies or have long cable runs between them or both.</p>
18712
|arduino-nano|rgb-led|
Negative voltage output Or Controling negative voltage
2015-12-15T15:15:48.470
<p>I've got an RGB led strip I'm trying to control. It's a 12v, 4 pin strip. Pin layout seems rather odd to me as 1 pin takes 12v of power and 3 pins (that go to ground) control the colors. In other words, <strong>the LED colors are controlled by limiting outgoing voltage</strong>.</p> <p><a href="https://i.stack.imgur.com/HqvbV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HqvbV.jpg" alt="Led Strip"></a></p> <ul> <li><strong>White</strong>- +12v</li> <li><strong>Green</strong>- Green in negative voltage</li> <li><strong>Red</strong> - Red in negative voltage</li> <li><strong>Blue</strong> - Blue in negative voltage</li> </ul> <p>I've already made a similar setup that uses n-channel MOSFETS (or at least I think that's what they are) between the colored cables and the ground and Arduino power the MOSFET gates as necessary.</p> <p><strong>So my question is:</strong> is it possible to hook these LEDs up directly to arduino and control the negative voltage without aditional electronics?</p> <p>As a slightly off topic question: Is there a specific name for elements that are controlled with negative voltages.</p> <hr> <p>By the way, I'm using Arduino nano, although I don't think it is relevant at this point and I've got Mega and Uno aswell if needed.</p>
<p>No, it's not possible, since the voltages and currents involved (12V) are too high. It will damage your board.</p> <p>Your arrangement with N-channel MOSFETs is the correct arrangement.</p> <p>By the way, you are not working with "negative" voltages at all - it's all positive - you just happen to be between the "load" and ground.</p> <p>This is called a <strong>Low Side Switch</strong> since it is on the "low" (i.e., between the load and ground) side of the circuit.</p> <p>The LEDs you have are in an arrangement called <strong>Common Anode</strong> in that the anodes (+ pins) of the LEDs are all tied together (common) and you control the cathode (- pins) of the LEDs. It means you can use cheap N-channel MOSFETs that are (as you have seen) easy to control with a microcontroller. The other arrangement, <em>Common Cathode</em>, where all the cathodes (- pins) are tied together and you switch the power to the anodes (+ pins) requires P-channel MOSFETs <em>and</em> N-channel MOSFETs to switch the P-channel MOSFETs, which increases costs.</p>
18724
|ir|
What's wrong with my IR sensor
2015-12-15T20:52:03.807
<p>I bought some 'lucky dip' IR sensors from China, no idea what they are, but they appeared to get lost in the post so instead I <a href="http://uk.rs-online.com/web/p/ir-receivers/7085086/" rel="nofollow noreferrer">bought some of these</a> from a reputable place in the UK that come with a <a href="http://docs-europe.electrocomponents.com/webdocs/0e56/0900766b80e56a95.pdf" rel="nofollow noreferrer">datasheet</a>.</p> <p>The next day, both items arrived together! </p> <p>I'm trying to build a very simple proximity sensor for a robot, I built the following circuit:</p> <p><img src="https://i.stack.imgur.com/HJIUW.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fHJIUW.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>and stole this code to test it out:</p> <pre><code>#define IRledPin 8 #define D13ledPin 13 #define IRsensorPin 9 void IR38Write() { for(int i = 0; i &lt;= 384; i++) { digitalWrite(IRledPin, HIGH); delayMicroseconds(13); digitalWrite(IRledPin, LOW); delayMicroseconds(13); } } void setup(){ pinMode(IRledPin, OUTPUT); digitalWrite(IRledPin, LOW); pinMode(D13ledPin, OUTPUT); digitalWrite(D13ledPin, LOW); } void loop(){ IR38Write(); if (digitalRead(IRsensorPin)==LOW){ digitalWrite(D13ledPin, HIGH); } else { digitalWrite(D13ledPin, LOW); } } </code></pre> <p>If I hold my hand in front of it, nothing happens (LED on-board arduino should light up), <em>however</em> if I point a TV remote at it and press a button, the LED lights up. I tested 2 of the 'fancy' sensors that I got and both behaved the same.</p> <p>Then I tried one of the 'lucky dip' sensors, swapped it straight in and the whole thing works perfectly - point a TV remote and the LED lights, hold my hand ~10cm in front of it and the LED lights!</p> <p>So, where have I gone wrong?</p>
<p>The answer I've accepted is the correct answer, but I wanted to add this extra bit for completeness. I reworked my code to use non-blocking delays for the IR LED so the sensor actually gets a chance to see it before it stops transmitting and it works! Range is quite a bit shorter than the 'lucky dip' sensor (~ 2cm).</p> <pre><code>#define IR_LED 8 #define LED 13 #define SENSOR 9 unsigned long burst_timer; unsigned long gap_timer; unsigned long timestamp; char led_state; char burst_count; const char BURST_MAX = 20; void setup() { pinMode(IR_LED, OUTPUT); led_state = LOW; burst_count = 0; digitalWrite(IR_LED, led_state); pinMode(LED, OUTPUT); digitalWrite(LED, LOW); pinMode(SENSOR, INPUT); timestamp = micros(); burst_timer = timestamp; gap_timer = timestamp; } void toggle_led() { if (led_state == LOW) { led_state = HIGH; } else { led_state = LOW; burst_count++; } digitalWrite(IR_LED, led_state); } void loop() { timestamp = micros(); if (timestamp - burst_timer &gt; 13 &amp;&amp; burst_count &lt; BURST_MAX) { toggle_led(); burst_timer = timestamp; gap_timer = timestamp; } if (burst_count &gt;= BURST_MAX &amp;&amp; timestamp - gap_timer &gt; (13*2*BURST_MAX) ) { burst_count = 0; burst_timer = timestamp; gap_timer = timestamp; } if (digitalRead(SENSOR) == LOW) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } } </code></pre> <p>Every time I use <code>delay()</code> (or <code>delayMicroseconds()</code>) I find a new reason not to!</p>
18738
|arduino-uno|interrupt|
How to properly use volatile variables in Arduino?
2015-12-16T18:00:53.327
<p>I was doing a small project with an Arduino Uno. It involved interrupts as I am using encoders to measure how much the differential wheel system moves forward. My robot moves only forward. So I use only a single channel from each encoder. Here are my two interrupt routines:</p> <pre><code>ISR (INT0_vect){ encoderRPos = encoderRPos + 1; } ISR (INT1_vect){ encoderLPos = encoderLPos + 1; } </code></pre> <p>The variables <code>encoderRPos</code> and <code>encoderLPos</code> are of type <code>volatile int</code>. I understand that the variables which undergoes change in any interrupt routine need to be of type volatile. This is to warn other parts of the code that use these variables that it may change anytime.</p> <p>But what happened in my code was a bit strange and I could not explain it. Here is how I compute the distance moved by the left wheel:</p> <pre><code> #define distancePerCount 0.056196868 float SR = distancePerCount * (encoderRPos - encoderRPosPrev); float SL = distancePerCount * (encoderLPos - encoderLPosPrev); encoderRPosPrev = encoderRPos; encoderLPosPrev = encoderLPos; </code></pre> <p>But when I print the following on my serial monitor, I notice an anomaly:</p> <p><a href="https://i.stack.imgur.com/DMDlf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DMDlf.png" alt="enter image description here"></a></p> <p>If you look at the third column, (SL) it's value is too high just for some time. This is upsetting all my calculations. </p> <p>The only clue I can get it, if I take the value of SL that I got (3682), which is always a constant, and calculate back <code>(encodeLPos - encoderLPosPrev)</code>, I will get 65519.66, which is close to the max value of <code>unsigned int</code>. Which means <code>(encoderLPos - encoderLPosPrev)</code> is causing an overflow while both the values whose difference is taken is somewhere around 5000 only!</p> <p>And I managed to solve it. It was by luck. This is how I modified the code:</p> <pre><code> static int encoderRPosPrev = 0; static int encoderLPosPrev = 0; int diffL = (encoderLPos - encoderLPosPrev); int diffR = (encoderRPos - encoderRPosPrev); float SR = distancePerCount * diffR; float SL = distancePerCount * diffL; encoderRPosPrev = encoderRPos; encoderLPosPrev = encoderLPos; </code></pre> <p>I can't comprehend what has happened. Is there something about volatile variables that I should have known about?</p> <p><strong>Update:</strong> <a href="http://paste.ubuntu.com/14085127/" rel="nofollow noreferrer">Here</a> is the entire code if you ever want to take a look. And it's working very well after changing it to what was suggested in the accepted answer.</p>
<p>/* Hi all and thanks for sharing. From my personal experience here is what I found useful</p> <p>&quot;A DTMF decoder stores the last DTMF code in bytes in its memory It's STQ pin goes HIGH every time a a new DTMF is detected This is just part of the code focused on ISR (Interrupt) &quot;</p> <pre><code> Tips when using ISR with Arduino nano and IDE 18.19 </code></pre> <p>1: HIGH or LOW only, RISING of FALLING will not get triggered properly with Nano using external digital interrupt.</p> <p>2: Watch out when using LOW. As per using HIGH in example you need to use flags(event bytes) and possible counters.</p> <p>3: When you type the attachInterrupt don't use brackets for the void of function you are you are calling, or every time the ISR is triggered it will go from begging of code re-initializing/resetting all global variables no matter if you declare them volatile or static!</p> <p>4: Delay doesn't work only delayMicroseconds()</p> <p>5: Keep it short, byte size variables and no complex math if possible</p> <p>6: Arduino nano external digital ISR pins are 2,3</p> <p>7: Don't run the void you call in your ISR in the loop().</p> <p>8: Keep in mind all other comments posted from the other programmers.</p> <p>*/</p> <pre><code>///////////////// Example ///////////////////////////// byte CFlag; // GLOBAL byte Counter; // GLOBAL #define STQ 3 // GLOBAL setup(); { Serial.begin(9600); pinMode(STQ, INPUT); attachInterrupt(digitalPinToInterrupt(), DragonBalls, HIGH); //WhenSTQ PIN GOES HIGH it runs a void function called DragonBalls() }//end setup void DragonBalls() { Dpin = digitalRead(STQ); delayMicroseconds(10000); if (Dpin == HIGH &amp;&amp; CFlag ==LOW) { CFlag=HIGH; Counter++ ; }//end if else if (Dpin == LOW &amp;&amp; CFlag == HIGH) { CFlag=LOW; DragonPrint();//Serial.print staff }//end else if }// end DragonBalls(void) void DragonPrint() { Serial.print(CFlag); Serial.print(&quot; = CFlag, Counter = &quot;); Serial.println(Counter); }//end void DragonPrint </code></pre>
18742
|arduino-uno|led|pwm|voltage-level|adafruit|
Adafruit TLC5947 breakout board is not working with my Arduino Uno
2015-12-17T01:33:04.023
<p>I am trying to use <a href="https://learn.adafruit.com/tlc5947-tlc59711-pwm-led-driver-breakout/overview" rel="nofollow">this</a> board (setup tutorial on left hand nav) with my Arduino Uno. I have tried using their example code, as well as my own simplified code, to turn on a single blue LED.</p> <p>The simplified code I "wrote" is as follows:</p> <pre class="lang-c prettyprint-override"><code>#include "Adafruit_TLC5947.h" #define NUM_TLC5974 1 #define data 3 #define clock 5 #define latch 6 Adafruit_TLC5947 tlc = Adafruit_TLC5947(NUM_TLC5974, clock, data, latch); void setup() { tlc.begin(); } void loop() { tlc.setPWM(0, 4095); tlc.write(); } </code></pre> <blockquote> <p><a href="https://learn.adafruit.com/tlc5947-tlc59711-pwm-led-driver-breakout/programming" rel="nofollow">Scroll to the bottom for reference. (TLC5947)</a></p> </blockquote> <p>This compiles and uploads successfully. I have DIN connected to 3, CLK to 5, and LAT to 6. V+ is connected to the Arduino 5V pin, and GND to Arduino ground.</p> <p>Using this setup, the LED does not turn on when connected to channel 0 on the board. Using a multimeter, I have verified that the voltage between common ground and the channel 0 pin is ~0V. Checking voltage on the board between GND and V+, I see 4.8V, which looks good. Connecting the LED directly to the V+ line lights it up, but obviously isn't switchable.</p> <p>I have no clue why I'm not seeing anything on channel 0's output when I directly write it to 100% duty cycle.</p> <p>Why is this not working?</p>
<blockquote> <p>... the LED does not turn on when connected to channel 0 on the board. [...] Connecting the LED directly to the v+ line lights it up, but obviously isn't switchable.</p> </blockquote> <p>From this I suspect that you have connected the LED between pin 0 and ground. The problem with doing this is that the TLC594x LED driver outputs are current <strong><em>sinks</em></strong>, and connect the output to ground when on. The LEDs must connect between V+ and the output as shown in the datasheet.</p>
18745
|temperature-sensor|
DHT11 and DHT22 unused pin
2015-12-17T05:22:35.713
<p>The DHT11 and DHT22 is a 4 pin temperature and humidity sensor, where one of the pins is labelled as NC (not connected).</p> <p>I'm curious what the unused pin is used for. Factory calibration?</p>
<p>On the DHT11 it's connected to pin 6 of the SOIC14 inside. So it's at least connected to something. But who knows what it's for.</p> <p>It has a (internal) pull-up resistor to VCC of around 100kOhm on this pin.</p> <p>I connected my logic analyzer to it, there is no signal, even while reading the sensor. Also connecting the arduino's signal wire to this (incorrect) pin does nothing.</p> <p>Factory calibration or testing would be my guess too, but who knows.</p>
18759
|arduino-uno|battery|
powering the arduino uno
2015-12-17T14:52:55.193
<p>I need to power an arduino uno with a battery but for a very long period of time. And I read a lot of thing about this. Some say do not use a 9V battery with a regulator some other say that it is the best way. SO I am really confused and I need to know what's the best solution for this (taking into consideration the fact that I need my board to last a week at least, if it is possible?)</p> <p>Thanks!</p>
<p>Three main things to do to decrease the Uno's power consumption:</p> <ol> <li><p>Remove the power LED (you can Google for instructions if you're not sure how to do it)</p></li> <li><p>Bypass the voltage regulator by providing ~5V of power to the 5V pin. You can arrange three sets of AA batteries in series to get about 4.5V which should be fine except that the crystal may run at a different speed (and you may get incorrect results from the millis() function for example). Obviously if that is unacceptable then you will need to provide a constant 5V voltage either by using the Arduino's regulator (which is quite inefficient) or buying a more efficient third-party regulator. The voltage provided by the batteries will vary somewhat, and over time the batteries will start putting out less voltage and eventually your Arduino may start to behave erratically or not at all. If reliability is of high importance then this may not be acceptable to you.</p></li> <li><p>Use sleep modes to the greatest extent possible (see <a href="http://playground.arduino.cc/Learning/ArduinoSleepCode" rel="nofollow">http://playground.arduino.cc/Learning/ArduinoSleepCode</a>). If your Arduino only needs to wake up for a few seconds every hour, you can make a few batteries go a very long way. Note that if you're using a regulator, it will still draw significant power even while the Arduino is sleeping.</p></li> </ol> <p>Bonus tip: buy a micro instead, or build your own board. (Avamander suggests a Pro Mini 3.3V in the comments below, he's probably right, I don't know much about that board)</p>
18763
|arduino-uno|
None of the programs in Arduino example is compiling
2015-12-17T15:50:53.470
<p>I am new to Arduino. I have connected the Arduino to the computer and I have installed the necessary drivers. But when I am compiling the Blink.ino program and other programs, which is present in the example, I am getting an compilation error. I have the IDE folder in D:\ drive</p> <pre><code>exec: "D:\\Arduino\\arduino-nightly\\tools-builder\\ctags\\5.8-arduino5/ctags": file does not exist Error compiling. </code></pre> <p>I don't know what to do. Please help me</p>
<p>A couple of things here look odd – but then I don't use Windows very often – I'd suggest that you download a fresh copy of the stock (not development) Arduino IDE. You can get it <a href="https://www.arduino.cc/en/Main/Software" rel="nofollow">here</a>.</p> <p>What's odd looking too me is:</p> <ol> <li><p>The double backslashes, they could be causing the file to appear not to exist, and</p></li> <li><p>The <code>arduino-nightly</code> component in the path. That suggests to me that you're using a "bleeding edge" version of the IDE where problems are likely to creep in. These versions are for developers and people who like living on the edge (or who want to help with testing new features and the like).</p></li> </ol> <p>One thing to do to check out the first oddity is to actually try to follow that path (both with and without the double backslashes). If the file is there (without the double backslashes) then it seems like something is odd with the path construction in the IDE.</p>
18767
|usb|arduino-nano|mac-os|
Arduino Nano Atmega328P doesn't work on Macbook
2015-12-17T17:59:40.620
<p>I've bought and Arduino Nano compatible on eBay:</p> <p><a href="https://i.stack.imgur.com/Qax36.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qax36.png" alt="enter image description here"></a></p> <p>But by the time I connect it to my Macbook Pro (OS X El Capitan 10.11.2) doesn't appear under "Tools -> Port" in Arduino IDE:</p> <p><a href="https://i.stack.imgur.com/IkAtJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IkAtJ.jpg" alt="enter image description here"></a></p> <p>I've followed some instructions by other posts here in StackOverflow:</p> <ul> <li><a href="https://arduino.stackexchange.com/questions/5119/arduino-nano-no-serial-port-for-macbook-air-2013">Arduino Nano no serial port for MacBook Air 2013</a></li> <li><a href="https://arduino.stackexchange.com/questions/13813/arduino-nano-with-mac-os-yosemite-10-10">Arduino Nano with Mac OS Yosemite 10.10</a></li> </ul> <p>But none of them worked :(</p> <p>If someone could help me out with this issue I'll be grateful.</p> <p>Thanks.</p>
<p>I was be able to solve the issue.</p> <p>By looking for the serial chip my board has: CH340G I found this blog post: </p> <p><a href="http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html" rel="nofollow">http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html</a></p> <p>So I downloaded the signed driver for my chip and now it works :D</p> <p>Driver: <a href="http://kiguino.moos.io/downloads/CH34x_Install.zip" rel="nofollow">http://kiguino.moos.io/downloads/CH34x_Install.zip</a> </p>
18770
|library|
Can I increase the 10 event limit in Simon Monk's Timer library?
2015-12-17T19:02:05.467
<p>On Dr. Monk's library page <a href="http://www.doctormonk.com/2012/01/arduino-timer-library.html" rel="nofollow">here</a>, he states: "You can attach up to 10 events to a timer." I am wondering if this is a hardware limit, or if it was an arbitrary number he chose for his library.</p> <p>In Timer.h, he defines the maximum number of timed events like this:</p> <pre><code>#define MAX_NUMBER_OF_EVENTS (10) </code></pre> <p>Can you foresee any problems if I changed that to a higher number? My sketch is already approaching the limit of 10 timed events running at the same time, so it would help me if I was able to increase the maximum number of timed events to about 20.</p>
<p>I don't see anything that would cause any issue. Just don't exceed 255.</p>
18771
|arduino-mega|power|
Can I run a Mega 2560 on 14v?
2015-12-17T19:12:28.927
<p>I have a Mega 2560 with a ramps 1.4 shield. I noticed when I turn on the 14v power supply the mega would also power up and run. </p> <p>Am I damaging it running it at 14v? If not is there a solder or jumper somewhere that I can set it to only run the mega/logic on the usb power? The 14v is just for the stepper motors.</p>
<p>You <em>can</em>, but you shouldn't, because the the board will heat excessively, as you're out of the recommended range for the input voltage on vin (7-12V).</p> <p>Unless you have a <em>switching</em> regulator (the one on the board is linear), then you shouldn't' have too much of a difference between the operating voltage and vin as an operating principle because of efficiency (and thus heat) issues.</p>
18779
|arduino-uno|pwm|pid|
Is there any realy working setup for multicopter with codes
2015-12-17T21:12:08.780
<p>I'm searching pc controlled quadrotor code projects. I tried to do <a href="https://github.com/strangedev/Arduino-Quadcopter" rel="nofollow">strangedev's project</a> but not works for me. Is any one test this project. PID commands works like relays. suddenley speeds up and down. I tried to tune PID constants with Ziegler nichols but no success. Is there any realy working code and setup. Can you share your experiences? </p>
<p>I've not used the (unmaintained) code you reference, but if a PID is responding much too fast in a new system, cut the parameters down significantly, first focusing on P and later I. Turn off the D, and the I terms, then slow the P down until it is behaving reasonably. Once Proportional control is working then try bringing I up in proportion to the change you did with P. </p> <p>The <a href="https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62" rel="nofollow">https://github.com/strangedev/Arduino-Quadcopter/blob/master/quadcopter/quadcopter.ino#L62</a> code starts with (P,I,D) values of (0.5,0,1), so back off to (0.25,0,0) or (0.05,0,0) or lower to get the speed or response more as you expect, and then experiment.</p> <p>Higher P will make it faster and saturate to the PID limit values quicker and make it more-relay like. If your system is in a relay-like bang-bang mode, then Zeigler-Nichols tuning will be hard to do well. Reduce P until you get a non-relay-like response. Show your code and add in some print/debugging to see what sort of pitch values give you what sort of outputs. PID isn't magical, if you want a pitch measurement of -30 to cause a control output of +10, P=10/(-30)=0.3 might be a good starting point. </p> <p>The way the unmaintained code looks, value of P=20 will saturate at your output limits of +/-20 with only a pitch measurement of +/-1 degrees.</p> <p>Show your actual code and values in your question, slow down the PID, and add debugging output. </p>
18780
|uart|arduino-galileo|
How to connect HC-05 to an arduino Galileo?
2015-12-17T21:29:49.757
<p>I connected a logic analyzer on digital pins 0 and 1 (Rx and Tx). Using <code>Serial.</code> functions on Galileo and the integrated terminal on Arduino IDE, I noticed this UART port was not used when chars were received and transmitted, what is sustained by the blocks diagram of Galileo <a href="https://www.arduino.cc/en/uploads/ArduinoCertified/IntelGalileoLogicSchematics.jpg" rel="nofollow">here</a>.</p> <p>So, if UART1 is used on PC communications, I would like to use UART0 to other things, like a bluetooth adapter. Any tips?</p>
<p><a href="http://alextgalileo.altervista.org/blog/galileo-uart-and-arduino-serial-objects-mapping/" rel="nofollow">This</a> might answer your questions about the Serial mapping on Galileo. Seems like you should use Serial1 for UART0 and Serial2 for UART1.</p> <p>Cheers!</p>
18789
|data-type|
invalid conversion from 'char' to 'const char*'
2015-12-18T05:53:22.593
<p>My intention was to overload a function to handle optional parameters. My code looks like</p> <pre><code>void functionA(const char *errorMsg) { functionA('0', errorMsg); } void functionA(char errorCode, const char *errorMsg) { ... } </code></pre> <p>The line functionA('0',... generates the error</p> <pre><code>invalid conversion from 'char' to 'const char*' </code></pre> <p>How do I fix that?</p>
<p>The compiler needs the <a href="http://www.cplusplus.com/doc/tutorial/functions/" rel="nofollow">prototypes</a> of the functions before the body containing the call to the overloaded function otherwise if starts complaining that the parameters does not match the known function (at this point in the source code).</p> <pre><code>// The function prototypes void functionA(const char *errorMsg); void functionA(char errorCode, const char *errorMsg); ... void functionA(const char *errorMsg) { functionA('0', errorMsg); } void functionA(char errorCode, const char *errorMsg) { ... } </code></pre> <p>Cheers!</p>