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
11950
|arduino-nano|display|
HIGH and LOW reversed
2015-05-18T07:02:18.120
<p>i've got a seven-segment-display on my arduino-nano and want to write some numbers on it. The problem is that HIGH and LOW seems to be reversed. If the output should be </p> <pre><code>0 </code></pre> <p>it displays </p> <pre><code>- </code></pre> <p>I could solve this, replacing all HIGH and LOW through HIGHX and LOWX, and defining them reversed:</p> <pre><code> #define HIGHX 0x0 #define LOWX 0x1 </code></pre> <p>but this is reversed and not a <em>good</em> solution...<br><br></p> <p>The wiring is correct like this (just GND not connected): <img src="https://i.stack.imgur.com/DwotM.png" alt="enter image description here"></p> <p>But if i connect the GND, the hole display isn't showing something anymore.</p>
<p>If your display is a common anode type, the following will happen.</p> <p>Suppose you put a HIGH on D12, and LOW on D2 then current will flow from D12 through the base-collector diode of Q1, through the LED and out D2 to ground.</p> <p>If you now connect Gnd to ground wihout changing anything else, the current from D12 will flow through the base-emitter diode of Q1 to ground and not through the LED.</p> <p>So the display is probably of the wrong type for your design. </p>
11951
|programming|
Arduino OR operator
2015-05-18T07:21:38.703
<p>I have been trying OR conditional operator in a if condition statement in my arduino program and the result is not what I expected. </p> <p>My program:</p> <pre><code>// three variables assigned to const int datatype as the // pin numbers they are assigned to are going to remain // constant through out the program. const int led1=10; const int led2=11; const int led3=12; void setup(){ // assigning the pins as input/output. pinMode(10,INPUT); pinMode(11,INPUT); pinMode(12,OUTPUT); } void loop(){ control(); } void control() { int task1 = digitalRead(led1); int task2 = digitalRead(led2); if (task1==HIGH || task2==HIGH) { digitalWrite(led3,HIGH); } else { digitalWrite(led3,LOW); } } </code></pre> <p>if the 'IF' conditional statement used without 'OR' operator is working fine that is not including both the tasks instead only one task either task1 or task2, else it is working without errors but the result is not as expected. hardware part is all fine. i reckon that there is a problem with the OR || operator.</p>
<p>If you aren't getting the expected result, as JRobert suggested you should look at your hardware. Ensure pull-ups/downs are being used correctly, your interpretation of your hardware's logic is correct (positive/negative logic), and maybe even use a simple sketch to check that everything is working correctly. Firstly I would simplify the control function. You could try replacing the OR with a bitwise OR, or changing your variables to booleans. Realistically, more code and a diagram illustrating your implementation would help us reproduce and troubleshoot this with you. I'm a little confused as to whether pins 10 &amp; 11 are LEDs or Buttons. I would be happy to help you get a test program together if you can provide more detail. :)</p> <pre><code>void control() { boolean task1 = digitalRead(led1); boolean task2 = digitalRead(led2); // Note that the if isn't needed digitalWrite(led3, (task1 || task2)); // If your buttons use negative logic // digitalWrite(led3, (!task1 || !task2)); } </code></pre> <p>For humour-sake when I hit a problem that doesn't make sense, I rework my logic to break down the problem and output in stages, or use the Serial library to output what is going on periodically. </p> <ul> <li><p><a href="http://www.arduino.cc/en/reference/serial" rel="nofollow">Arduino Serial Reference</a></p></li> <li><p><a href="http://www.ladyada.net/learn/arduino/lesson4.html" rel="nofollow">Arduino Serial Tutorial</a></p></li> </ul> <p>Typically for inputs and outputs I define a structure which buffers everything per IO, and write my code with a loop-based mentality, much like how a game loop is implemented in video games. It is easy to print and trace when troubleshooting, and the positive/negative/default-state logic is abstracted. This will help you get started if you are curious.</p> <ul> <li><a href="http://rbwhitaker.wikidot.com/the-game-loop" rel="nofollow">Game Loop Example</a></li> </ul>
11959
|motor|
Troubleshooting DC motor
2015-05-18T10:48:45.330
<p>I worked on the starterkit project #9 motorized pinwheel, and the motor worked just fine.</p> <p>I then tried to add a potentiometer, and now the motor won't rotate at all any more (neither in the current nor in the project's baseline configuration). I also tried connecting the motor to the 9V battery directly, to no avail.</p> <p>I did check the battery by briefly connecting a LED right away. The motor apparently also still generates current if I turn it manually (checked with a directly connected LED either).</p> <p>What else can I do to check what's wrong with the motor? Is it possible that I somehow accidently killed it with my attempts with the potentiometer?</p>
<p>If your motor doesn't work when connected to the 9V battery, either the battery is flat (which is likely since you were able to connect the LED without destroying it!! - they are a 2.5-3v part, not a 9v part) or the wiring to the motor is damaged. When you connect the motor directly to a 9v battery, it should turn pretty fast - may also work if you connect it to between 2 &amp; 4 AA batteries. </p> <p>9v batteries don't have that much energy in them... you would be better off with a battery pack with 6 AA batteries in it.</p>
11960
|arduino-mega|display|
How to draw a bitmap on a tft display?
2015-05-18T11:01:31.317
<p>I'd like to print a bitmap on my TFT.</p> <p>I setup my screen with this library: <a href="http://forum.arduino.cc/index.php?topic=292777.0" rel="nofollow noreferrer">http://forum.arduino.cc/index.php?topic=292777.0</a></p> <p>It is like the Adafruit_GFX library (only a little bit changed). Everything works.</p> <p>With the tool Img2Code I converted my image into a bitmap.</p> <pre><code>void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color) </code></pre> <p><img src="https://i.stack.imgur.com/5fnlO.png" alt="screenshot"></p> <p>How to include this code and print the bitmap on the tft?</p>
<p>As the function prototype you have show suggests, the data needs to be in a uint8_t array format.</p> <pre><code>void Adafruit_GFX::drawXBitmap(int16_t x, int16_t y, const uint8_t *bitmap, int16_t w, int16_t h,uint16_t color) </code></pre> <p>So your array data would look like:</p> <pre><code>const uint8_t myBitmap[] = { 0xff, 0xff, 0xc0, 0x00, 0xc0, 0xff, 0xc0, 0xc0, 0xff, 0xff, 0xde, 0xad, 0xbe, 0xef, .... etc .... 0xff, 0xff, 0xff, 0xff, 0xff }; </code></pre> <p>You then call the function with the needed parameters:</p> <pre><code>tft.drawXBitmap(10, 20, myBitmap, 100, 80, 0xFFFF); </code></pre> <p>That is assuming you want to place it at (top left corner) 10,20 and the bitmap is 100x80 pixels in size. It will draw it in white (0xFFFF).</p>
11962
|motor|interrupt|rotary-encoder|
How to read data from a rotary encoder with ATmega328
2015-05-18T12:32:46.643
<p>I'm using a home made "bare bones" Arduino, made with the ATmega328, and I need to read angle data from a geared DC drill motor, turning at speeds between 0 and 450 RPM. This is so I can use it as feedback for an angle control system implemented on the Arduino.</p> <p>I've not yet bought the encoder. I'm waiting until I find a suitable one which works easily with Arduino.</p> <p>I have already written the control algorithm. I'm using state variable feedback, and the algorithm depends on a <code>getAngle()</code> function that I have not written yet. This function is inside an if statement that executes every 0.2 seconds. It needs to return the angle of the DC motor in degrees.</p> <p><strong>My questions:</strong></p> <ul> <li><p>How can I implement this <code>getAngle()</code> function using a rotary encoder? </p></li> <li><p>What is an example of a rotary encoder that is suitable for this application?</p></li> <li><p>Will it be better to use the interrupt pins of the Atmega328, or use some other method? </p></li> </ul> <p>I have seen <a href="http://playground.arduino.cc/Main/RotaryEncoders" rel="nofollow">a few library's on Arduino Playground</a> that claim to make reading angle data easier, but how do I use them? I need something that is fast (it, and the control algorithm operations, both needs to finish before the 0.2 seconds sample time), and more importantly it needs to be easy to implement. I'm coming up to the project deadline so I don't want to have to spend a whole day figuring out how to implement this <code>getAngle()</code> function.</p> <p>Thank you!</p>
<p>You will have to use interrupts or otherwise the encoder might be rotating but your Arduino is doing something else than reading the encoder. By using interrupts, the encoder counter is always updated when the encoder moves. This also means that the interrupt function has to be very short so that it only takes a few cycles to complete and thus leaves the majority of the Arduinos computing time for your sketch.</p> <p>Here is a code that I've used in many applications from CNC handwheels to servos and for reading extremely accurate angle sensors. It is dead simple, uses two interrupts to read the quadrature signal (A &amp; B channel) and also makes use of Arduinos built in pull-up resistors to keep the channels held high for reliable readings.</p> <p>Assuming that your encoder is an open-collector output and works with 5V, you only need to connect 5V and GND to it and then the A channel to the first interrupt pin #2 and channel B to #3. That's it for the hardware.</p> <p>This code goes at the start of your sketch, right before setup() function:</p> <pre><code>const signed byte encoderDirections[] = {0, -1, 1, 0, 1, 0, 0, -1, -1, 0, 0, 1, 0, 1, -1, 0}; volatile long encCount = 0; </code></pre> <p>It defines a constant array that is used for finding the direction that the encoder has turned based on the previous value and the current value. It is defined as constant as it is never changed. Also a global variable calle encCount is defined as a long type variable so that the encoder can count in both directions. It is absolutelu imperative to declare it as volatile so that the compiler and the microprocessor never try to do any "shortcuts" when you use this variable, but instead always loads it from its respective memory address. This is done so because the interrupt can fire at any time and change the variables value without any other function knowing it.</p> <p>Next, in your setup() function you will want to include these lines to make the Arduino pins as inputs with the internal pull-up resistors connected. The latter two lines attach the interrupts 0 &amp; 1 (hardware pins pins 2 &amp; 3) so that whenever the pin state changes (low to high or vice versa), it halts the microprocessors operation and jumps to the encoder_interrupt function immediately.</p> <pre><code>pinMode(2, INPUT_PULLUP); pinMode(3, INPUT_PULLUP); attachInterrupt(0, encoder_interrupt, CHANGE); attachInterrupt(1, encoder_interrupt, CHANGE); </code></pre> <p>Last you will need the actual interrupt function that reads the encoder and updates the counter value.</p> <pre><code>void encoder_interrupt() { static unsigned int oldEncoderState = 0; oldEncoderState &lt;&lt;= 2; oldEncoderState |= ((PIND &gt;&gt; 2) &amp; 0x03); encCount += encoderDirections[(oldEncoderState &amp; 0x0F)]; } </code></pre> <p>First this defines a variable that holds the previous encoder value that was read from the pins 2 &amp; 3. This is declared as static, so the value is stored in memory even when this function exits so that it can be used the next time the interrupt routine is run.</p> <p>The second line moves the previous interrupt channel values two bits to the left (multiply by 4) to make room for the new values.</p> <p>The third line is an interesting one. It reads the PIND, meaning all the pins at D register, which holds many Arduino pin states, including the pins 2 &amp; 3 that we are interested in. Next it shifts this value 2 bits to the right (divide by 4) to "drop" the pin 2 &amp; 3 states to the lowest bits of this byte. Then it AND's this byte with 0x03 to zero everything else but the lowest two bits that now contain the interrupt channel states. Lastly these two bytes are OR'd with the previous encoder state values to obtain a 4 bit number.</p> <p>On the forth line this 4 bit number is AND'd with a 0x0F to make sure the highest 4 bits are zero to make sure this number is truly a 4 bit number that stays between 0..15, as it is used as an index for the constant array we defined at the start of the program to get the encoders direction of rotation and this is then added to the counter variable.</p> <p>And now you have an accurate and extremely fast way of reading a two channel encoder to keep track of its position.</p> <p>If you want to calculate an angle from the encoders current position, you could do a function like this, but you have to know the line count of your encoder and multiply it by 4 so you know the encoder pulse count per revolution. For example, a 100 line rotary encoder gives out 400 pulses per revolution. I assume that there is a constant defined as follows at the start of program:</p> <pre><code>const int LINE_COUNT = 400; </code></pre> <p>Also, this function assumes that the encoder could have turned more than one revolution and you just want the angle from some reference spot in degrees. Do take in to account that the long type variable will overflow after +-2 147 483 648 pulses as it is a 32 bit signed variable.</p> <pre><code>float getAngle() { long curCount = encCount; // Store the current count. while(curCount &lt; 0) { curCount += LINE_COUNT; } while(curCount &gt;= LINE_COUNT) { curCount -= LINE_COUNT; } return (curCount / LINE_COUNT * 360.0); } </code></pre> <p>First the encoder count is copied to a one use variable. then two while statements make sure the values is positive from 0 to LINE_COUNT-1, so it basically reduces the count to what it would be with just under one revolution. Then it returns the number of degrees by calculating the current position as a fraction of a one revolution count and multiplies this with 360 to get the degrees.</p>
11976
|arduino-uno|programming|c++|
How to define function/macro so it is accesible throughout various cpp files
2015-05-18T21:55:06.343
<p>I recently came across <a href="http://www.utopiamechanicus.com/article/low-memory-serial-print/" rel="nofollow">this</a> nice <code>SerialPrint()</code> implementation:</p> <pre><code>void StreamPrint_progmem(Print &amp;out,PGM_P format,...) { // program memory version of printf - copy of format string and result share a buffer // so as to avoid too much memory use char formatString[128], *ptr; strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem // null terminate - leave last char since we might need it in worst case for result's \0 formatString[ sizeof(formatString)-2 ]='\0'; ptr=&amp;formatString[ strlen(formatString)+1 ]; // our result buffer... va_list args; va_start (args,format); vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args ); va_end (args); formatString[ sizeof(formatString)-1 ]='\0'; out.print(ptr); } #define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__) #define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__) </code></pre> <p>I want to use it in my more complex projects to save precious RAM space.</p> <p>This works really well when I have just one *.ino file where I'm using the SerialPrint() function. When I try to use it in my more complext projects, which consist of a central *.ino files and several <em>.cpp/</em>.h files (mostly one cpp/h pair per class). The problem is if I put the code below into the *.ino file, it will not be known inside any of the *.cpp files. The compiler is not complanining, but I'm never seeing the serial output of my code.</p> <p>Any ideas how to fix it? I've tried putting this code in a central global.cpp/h file which I include everywhere, but it does not seem to work (no output on serial).</p> <p>Thanks in advance!-</p>
<p>Have you thought of turning it into a small library?</p> <p>libraries/StreamPrint/StreamPrint.cpp:</p> <pre><code>#include &lt;StreamPrint.h&gt; void StreamPrint_progmem(Print &amp;out,PGM_P format,...) { // program memory version of printf - copy of format string and result share a buffer // so as to avoid too much memory use char formatString[128], *ptr; strncpy_P( formatString, format, sizeof(formatString) ); // copy in from program mem // null terminate - leave last char since we might need it in worst case for result's \0 formatString[ sizeof(formatString)-2 ]='\0'; ptr=&amp;formatString[ strlen(formatString)+1 ]; // our result buffer... va_list args; va_start (args,format); vsnprintf(ptr, sizeof(formatString)-1-strlen(formatString), formatString, args ); va_end (args); formatString[ sizeof(formatString)-1 ]='\0'; out.print(ptr); } </code></pre> <p>libraries/StreamPrint/StreamPrint.h:</p> <pre><code>#include &lt;Arduino.h&gt; extern void StreamPrint_progmem(Print &amp;out,PGM_P format,...); #define Serialprint(format, ...) StreamPrint_progmem(Serial,PSTR(format),##__VA_ARGS__) #define Streamprint(stream,format, ...) StreamPrint_progmem(stream,PSTR(format),##__VA_ARGS__) </code></pre> <p>Then in your code, wherever you want to use it:</p> <pre><code>#include &lt;StreamPrint.h&gt; </code></pre> <p>You can read more about writing libraries here: <a href="http://www.arduino.cc/en/Hacking/LibraryTutorial" rel="nofollow">http://www.arduino.cc/en/Hacking/LibraryTutorial</a></p>
11984
|arduino-uno|ethernet|rtc|
Set dynamically hour - DS1307
2015-05-19T12:27:54.020
<p>I want keep my RTC1307 always updated with my server, so I created this code to first search the time on the server then passes to getServerTime() function to divide it and set in the RTC. I use the rtc.adjust() to adjust my watch.</p> <p><strong>Problem</strong>: My watch is getting wrong, this is set <strong>2165/165/165 165:165:85</strong>. I think the problem is in defining the time in rtc.adjust(), I'm going as follows:</p> <pre><code>//tempDate -&gt; May 19 2015 //tempHour -&gt; 09:25:14 rtc.adjust(DateTime(tempDate, tempHour)); </code></pre> <p>Does anyone know the cause of this error?</p> <pre><code>#include &lt;Ethernet.h&gt; #include &lt;SPI.h&gt; #include &lt;Wire.h&gt; #include &lt;RTClib.h&gt; RTC_DS1307 rtc; byte server[] = { 192, 168, 0, 8 }; byte ip[] = { 192, 168, 0, 237 }; byte mac[] = { 0xDE, 0xAD, 0xAD, 0xEF, 0xFE, 0xED }; void setup() { Ethernet.begin(mac, ip); Serial.begin(9600); } void loop() { getServerTime(getSiteData()); DateTime now = rtc.now(); Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(' '); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.print(now.second(), DEC); Serial.println(); Serial.println(); delay(5000); } char * getSiteData() { EthernetClient http; unsigned char startRead = 0, i = 0; char inString[50]; if (http.connect(server, 80)) { http.println("GET /util/date.php HTTP/1.1"); http.println("Host: "); http.println("Connection: close"); http.println(); while (http.connected()) { while (http.available()) { char c = http.read(); if (c == '&lt;' ) startRead = 1; else if (startRead) { if (c != '&gt;') { inString[i] = c; i++; inString[i] = '\0'; } else { startRead = 0; http.stop(); http.flush(); return inString; } } } } Serial.println(inString); http.stop(); http.flush(); } else Serial.println("Tentativa de conexão falhou. Sem internet ou servidor inacessivel"); } //May 19 2015-09:17:24 void getServerTime(char* siteData) { char *tempDate, //May 19 2015 *tempHour; //09:17:24 tempDate = strtok(siteData, "-"); tempHour = strtok(NULL, "-"); rtc.adjust(DateTime(tempDate, tempHour)); } </code></pre>
<p>The numbers you are reporting are very familiar to me. They are telling me that it is not possible to obtain the time from the RTC chip.</p> <p>You are getting the time from your server, and as long as the string is actually what you think it is, then the values should be fine. This snippet works perfecty:</p> <pre><code>#include &lt;RTClib.h&gt; char siteData[] = "May 19 2015-09:17:24"; void setup() { Serial.begin(115200); char *tempDate = strtok(siteData, "-"); char *tempHour = strtok(NULL, "-"); DateTime now(tempDate, tempHour); Serial.print(now.year(), DEC); Serial.print('/'); Serial.print(now.month(), DEC); Serial.print('/'); Serial.print(now.day(), DEC); Serial.print(' '); Serial.print(now.hour(), DEC); Serial.print(':'); Serial.print(now.minute(), DEC); Serial.print(':'); Serial.print(now.second(), DEC); Serial.println(); Serial.println(); } void loop() { } </code></pre> <p>So it must be in the passing of the data through the RTC chip that is failing.</p> <p>Check that the chip is actually wired up properly, is running, and is responding normally before you try adding in the code to set the time from the server.</p>
11989
|led|voltage-level|analogwrite|
Could an `analogWrite` command and its variable output values be used to power multiple leds with same intensity?
2015-05-19T18:07:59.457
<p>I seem to be getting the right response on single LED but with multiple LEDS or a relay connected LED strip the voltage outputs seem to be insuffiecient. What kind of analogWrite values does an LED respond to? </p>
<p>Single LEDs like the standard 5mm leds work from low voltages such as 1.7 - 2.1v, so can be directly driven via an Arduino pin (through a resistor to prevent excess current draw which would damage the pin). </p> <p>LED strips such as automotive LED strips (12v) require the use of a relay if you are simply switching the LEDs on and off. You can't run the relay directly from an Arduino pin, you will need to use a transistor to act as a buffer between the relay and the Arduino to prevent damaging the Arduino. Instead of the motor and diode in the below diagram, you connect your 12v led strip.</p> <p><img src="https://i.stack.imgur.com/Oqukb.png" alt="relay arduino connection"></p> <p>If you want to control intensity, you will need to use a transistor, or a mosfet (mosfets are easier). You can then use AnalogWrite to control the intensity of the LEDs via the MOSFET. You will need to connect the control pin for the MOSFET to one of the PWM-capable pins on the Arduino (the pins which have the ~ mark next to them), otherwise you will only be able to switch the MOSFET on and off, similar to the Relay. This site has a good guide on how to do this with a <a href="http://bildr.org/2012/03/rfp30n06le-arduino/" rel="nofollow noreferrer">MOSFET</a>. It also has a guide on how to use a transistor, but I can't include the link yet due to not enough reputation points. It shows both the code needed, and how to connect the components to the Arduino.</p> <p><img src="https://i.stack.imgur.com/SAKF3.png" alt="mosfet arduino connection"></p>
11993
|arduino-ide|
how to multi merge code
2015-05-19T19:21:08.453
<p>i do have sketch from various people out there who have build nice code to do what i need done BUT not for my application and well they grant us permission to use and or modify their code so this is what i attempt to do with your help.</p>
<p>Unfortunately there is no easy way to do this. All you can hope to do if you see multiple sketches, which if combined would achieve your desired goal, is to splice the code into a single sketch (by copying and pasting), and hope that there are no conflicts resulting from the merging of the different sets of code. </p> <p>For simple things like two sketches using the same pins, you may be able to fix that by changing which pins are used (unless they are special purpose pins such as PWM or hardware interrupts). </p> <p>For harder to diagnose problems like two libraries not working if used the same sketch, that is almost impossible to resolve unless you know the hardware or library well enough. Best option there is to find another that does the same job, but differently. </p>
11994
|arduino-uno|sensors|pwm|
Supplying near perfect DC signals from Arduino UNO
2015-05-19T19:38:53.840
<p>My problem seems very simple but has been impossible to find a straight forward answer searching online. I need my Arduino to output different DC voltages from six ports (probably PWM ports), like 2 V from port 3, 2.1 V from port 5 and so on. And then be able to quickly change to like 4 V from port 3, and 4.1 V from port 5 and so on. But these DC signals need to be near perfect for the highly sensitive sensor I am working with. Everywhere I've searched says to use the PWM outputs and then an RC filter but the ripple from this process is concerning, can I get the the ripple to be under a few mV amplitude? Is there more smoothing I can do beyond a simple RC lowpass filter? </p> <p>TLDR: I basically need a DC voltage generator that can select between 1 and 5 volts at 0.1 V intervals, and I need to be able to do it with output from the Arduino and some external hardware that will provide a near perfect DC signal to a sensor.</p>
<p>(1) A multipole active lowpass filter works wonders.<br> Something like a 5 pole Bessel filter will probably meet your need. That needs two active stages (1 input RC pole +2 +2 ). You can use transistors in emitter follower mode with some reservations but using 2/4 of a quad opamp per filter is easier overall. I can't spare the lookup time just now (later maybe) but AD &amp; LT and NatSemi all have good free active filter design programs. </p> <p>(2) A Simple sample &amp; hold per channel will give you steady output limited only by the drift of the opamp used. You can buy commercial S&amp;H ICs or use std opamps. I've used even the venerable LM324 for this but there are much better - you apply the voltage via a switch to a cap[acitor at a unity gain buffer input and then turn off the switch. Again, the "switch can be as simple as an ancient CD4016 or CD4051 but much better more modern ICs are available.</p> <p>With 1 x CD4051 and 2 x LM324 (or better) you can feed 8 x S&amp;H and update them occasionally top compensate for drift. If you add another CD4051 with identical addressing but working backwards you can read back the current capacitor voltage and "nudge" it with a simple digital on signal via a diode and high R resistor if it is slightly off. You can even do ALL signal setting this way if required with NO PWM (or you are effectively implementing adaptive PWM without formally doing so). You eg use 4 driver lines - a fast and slow drive high and a fast and slow drive low. Each is just a digital pin + a resistor and a diode. Select one output channel with the output mux (CD4051 or whatever, and the return mux connects it to your ADC. Pump it up to about right with fast-high, top it off with slow-high and correct with slow-low if needed, then step the mux to the next channel and the S&amp;H cap looks after it. Note that the return channel to the ADC must not load the cap significantly while reading. </p> <p>If this answer attracts significant interest I can add detail and suggestions re more modern components etc. If not, the above is all a keen person needs to look into the concept. </p>
11998
|power|
AC ceiling fan speed control using arduino Uno R3
2015-05-19T20:10:47.280
<p>How can I control an AC ceiling fan speed using Arduino Uno R3? I cannot understand the key behind controlling AC voltage using Arduino (though I know how to on/off ac appliances using arduino and relays). </p>
<p><strong>Controlling the speed of an AC motor is not an easy undertaking, and messing around with mains voltages if you're not experienced and know what you're doing can be fatal.</strong></p> <p>Now that's the disclaimer out of the way, on to your question.</p> <p>Unlike DC, you cannot use PWM to control the average power of AC. That is, after all, what PWM does - the on-off ratio creates a percentage of the power - but it can only be done if the incoming power is of a steady state.</p> <p>For AC there are two ways of reducing the output power - either reduce the voltage, which can be done with resistors (look inside a multi-speed fan and you'll see resistors to change the speed); or chop up the AC waveform, which is a little like PWM but more specialized.</p> <p>If you only want specific speeds then you could pre-define them using resistors and switch different resistor combinations in and out using relays. It's crude, but simple, and also probably the safest option for the beginner.</p> <p>If you want proper variable speed, though, then you're going to have to chop up the waveform. The theory is quite simple: Start where the waveform crosses 0V in either direction, with the output on, and turn it off again at some percentage of the way through the cycle.</p> <p>Like PWM it's the on-off percentage that defines the output power (and thus the speed), but timing is critical - you must start the PWM sequence at 0V and it must last exactly one cycle.</p> <p><img src="https://i.stack.imgur.com/RxuQX.gif" alt="enter image description here"></p> <p>A number of simple circuits work in the opposite way - they remain off until the input waveform reaches a certain point, then switch on, until they reach the zero-crossing point. While simple, these circuits aren't good. The reason being that the sudden rise from 0V to the "trigger" voltage when the output becomes live can cause large spikes and noise in the circuit, which can cause lights to blow etc. It's the same effect as why bulbs most often blow when you turn them on, not when they have been running for a while - it's that very rapid rise from 0V to a high voltage which causes them to be over-stressed and blow.</p> <p>So any circuit you choose should really be a proper one which turns on at 0V and turns off after a period, not turn on at a voltage and turn off at 0V.</p>
12002
|arduino-uno|serial|uploading|
Upload sketch remotely through a serial-IP-serial connection
2015-05-19T21:46:43.093
<p>I tried different times to use socat and ser2net in order to upload a sketch to an Arduino Uno (connected to a PC) from my laptop, unsuccessfully. Can anyone teach me how to achieve this goal? I use Linux.</p>
<p>You can use an ethernet to ttl adapter and then install a virtual com software. </p> <p>What i did was the following. </p> <p>I used an ethernet to 232 converter, and tweaked the board as you can see in the attached photo, I removed the 232 chip and jumpered the ttl directly to the output. </p> <p>Then I installed USR-VCOM and set a virtual com port that shows in the arduino ide, it works without any software /boot changes </p> <p>I am not sure how to remote reset the arduino.... Probably someone else knows. </p> <p><img src="https://i.stack.imgur.com/1Jr5U.jpg" alt="enter image description here"></p>
12006
|node.js|
To what extent is Javascript used in robots?
2015-05-19T23:22:27.587
<p>I originally discouraged my friend against the use of Javascript in his robot project because I didn't know any use for Javascript outside of web developement but then I saw <a href="http://rads.stackoverflow.com/amzn/click/1457186950" rel="nofollow">this</a> book on amazon. Since I wouldn't want to mislead him could someone help me develop a better understanding of how often Javascript is used when making robots with an Arduino?</p>
<p>It wouldn't be my first choice for programming of robotics, but it's certainly doable.</p> <p>Thanks to NodeJS, JavaScript (or ECMAScript as it is properly known) has broken free of the browser and is now a general programming language.</p> <p>Thanks to the BeagleBone Black (and others), which runs most of its systems by default through NodeJS, including its web-based IDE, you can program the whole board with ECMAScript.</p> <p>So yes, you <em>can</em> do robotics with ECMAScript, and there are platforms which <em>do</em> allow you to do robotics with ECMAScript.</p> <p>Would you want to do it in a real industrial environment?</p> <p>As I said - it wouldn't be my first choice.</p>
12016
|analogread|
Trouble reading V_BG
2015-05-20T04:39:35.260
<p>I would like to read MUX 14 with the ADC. On page 263 of the <a href="http://www.atmel.com/Images/doc8161.pdf" rel="nofollow">Atmega328 data sheet</a> it shows 1110b on the MUX corresponding with reading V_BG.</p> <p>I need to read this so I can calibrate my sensor readings taken with the 5v reference to those taken with the 1.1v reference. Because the 5v power supply may vary and the 1.1 is more stable, I need to be able to translate the readings taken with a 5v reference based on how the internal 1.1v is read.</p> <p>Based on the <a href="http://garretlab.web.fc2.com/en/arduino/inside/arduino/wiring_analog.c/analogRead.html" rel="nofollow">code for analogRead</a>, I wrote this:</p> <pre><code>int readVBG(int _analogReference) { uint8_t low, high; ADMUX = (_analogReference &lt;&lt; 6) | 14; sbi(ADCSRA, ADSC); while (bit_is_set(ADCSRA, ADSC)); low = ADCL; high = ADCH; return (high &lt;&lt; 8) | low; } </code></pre> <p>_analogReference is either 1 or 3 depending on the reference voltage desired.</p> <p>I expect to read 1023 when _analogReference is 3 and about 225 when _analogReference is 1. Instead I get smaller values which I'm guessing are from a floating (unconnected) analog pin.</p>
<p>The problem is that a 2ms delay is required after setting the ADMUX bits before starting the conversion. Thank you Majenko for the link.</p> <pre><code>int readVBG(int _analogReference) { uint8_t low, high; ADMUX = (_analogReference &lt;&lt; 6) | 14; delay(2); // Wait for voltage to settle sbi(ADCSRA, ADSC); while (bit_is_set(ADCSRA, ADSC)); low = ADCL; high = ADCH; return (high &lt;&lt; 8) | low; } </code></pre> <p>The above code is specifically for the Arduino UNO. Majenko's link above has #ifdef statements which support other devices.</p>
12021
|sensors|
Hc Sr 04 Ultrasonic Sensor
2015-05-20T12:42:31.943
<p>I'm using Hc-Sr 04 ultrasonic sensor for my project and I want to know that if I could or not utilize an slope. Have you an idea?</p>
<p>I have a couple of these running right now, and they will often work at a slope when the surface is complex (not flat). However, the detection angle, as it comes from the sensors, appears to be about 30deg from centre in each direction. Hence, the sensors do need to be relatively pointed at the object being detected.</p> <p>When placing my hand directly above it, it doesn't really matter what angle I tilt my hand, presumably since I have fingers that are not flat. On the other hand, if I put a paper towel in front of it, it will stop seeing it if I angle the paper towel more than 20 or so degrees.</p> <p>Overall, if you keep the object within 30 degrees from the sensor's fixation point, it will work, granted the object, if flat, is "pointed" at (facing) the sensor flat-wise within about 20 to 25 degrees. For irregularly surfaced objects, it does not seem to matter too much unless the angle is pretty steep, such as 60 degrees.</p> <p>Here is what I mean:</p> <p><a href="https://i.stack.imgur.com/sKF5E.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sKF5E.png" alt="enter image description here"></a></p>
12023
|arduino-uno|voltage-level|battery|electronics|
Create a Li-Polymer Battery Charger
2015-05-20T15:22:23.753
<p>I want to Create a battery Charger with the Arduino with real time battery status. I don't have any idea how to do that same time as the charging.<br><br></p> <blockquote> <p><strong>I know to use a serial monitor to get battery status but not to charge.</strong></p> </blockquote> <p><br><br> I would like to know how to do that simultaneously so that I don't over charge the battery. </p> <ul> <li>This is the battery for Lumia 822 </li> <li>Nokia BP-4W 1800mAh 3.7v 6.7Wh</li> </ul>
<p><strong>(1) A simple method</strong></p> <p>BEST method is to use a proper charger - they are not high cost if you look around and doing it properly extends precious battery life.</p> <p>Next best in this context is my &quot;better&quot; method in 2. below.</p> <p>BUT, given the system you say you are using now, the following very simple method will greatly improve your result and ave your battery from an early death.</p> <p>You need a 1 Ohm resistor and a voltmeter that you can trust to read a 4.1V votage accurately. Without these the simple method risks battery damage or destruction - just as your present method does.</p> <p>Warning: Straight connection to a USB port is very unwise but may be viable if the port current-limits.</p> <ul> <li><p>If the current is ever higher than the rated maximum then battery destruction may occur.</p> </li> <li><p>If the battery voltage ever exceeds 4.2V at room temperature battery damage WILL occur and battery destruction may occur.</p> </li> </ul> <p>Worst case a badly treated battery can turn into a flaming inferno in seconds.</p> <p>A usably OK result can be gained by:</p> <p>(1) Calculate Imax = same mA as battery mAh capacity.<br /> LOWER is OK. Higher is not.<br /> eg 1200 mAh battery = 1200 mA max and say 1000 or 500 or lower mA is OK.</p> <p>(2) Connect a ONE OHM resistor in USB to battery line.</p> <p>(3) Connect <strong>discharged</strong> LiPo battery to USB port via 1 Ohm.</p> <p>(4) Measure voltage across the resistor. The voltage will be 0.001 Volt for every mA that flows. eg<br /> 1000 mA gives 1.000 Volt 789 mA gives 0.789 V. 1234 mA gives 1.234 V. etc.</p> <p>If the measured mA is LESS THAN Imax in (1) above then this is OK to charge with.</p> <p>(5) Use Arduino analogRead() function WHILE CHARGING to measure battery voltage.<br /> BE SURE that the voltage that you read with the Arduino matches what a quality meter says.<br /> When Vbattery (measured from Bat + to Bat- AT the battery) measures 4.1 V STOP CHARGING, remove voltage.<br /> Battery will be perhaps 70% charged and will have a long cycle life (if not already damaged).</p> <p>For 10 bit ADC = 1024 counts total (0-1023) then<br /> for 5V reference 4.1V count = 4.1/5 x 1023<br /> = 838 counts.<br /> Using 830 counts to start with is safer.</p> <p>When battery is at the upper charge limit, and <strong>before</strong> removing Vcharge, measure voltage at battery with calibrated quality meter. Result should be 4.1V using above system.</p> <p>Even with a quality calibrated meter NEVER exceed 4.2V - and 4.1V is better.</p> <p>The BEST method is to use a proper charger - they are not high cost if you look around and they extend precious battery life.</p> <p>._______________________________</p> <p><strong>(2) A better method:</strong></p> <p>LiIon (Lithium Ion)and LiPo (Lithium Polymer) batteries are functionally the same for charging purposes. I'll use the term &quot;LiPO&quot; from here on. I'll assume single cell batteries as most in cellphones and similar are. If the terminal voltage is between about 2.5V (should really be higher) and 4.3V they are single cell,</p> <p>LiPo batteries have 4 main charge areas.</p> <ul> <li><p>Under about 2V = dangerously dead. Discard</p> </li> <li><p>2V to about 3V = under voltage - charge very slowly</p> </li> <li><p>3V to 4.2V = charge at CC = Constant Current.</p> </li> <li><p>On reaching 4.2V charge at CV = Constant Voltage until current reduces &quot;automatically&quot; (under battery chemistry control) to about 1/4 x max rate.</p> </li> </ul> <p>Max charge rate is set by the manufacturer but is almost always the numerical mAh rating in mA. eg for a 1000 mAh battery max rate is 1000 mA. For a 3300 mAh battery it's 3300 mA etc. In a very few cases it is lower - maybe =half standard values and for a very small number of cells its higher - assume you do not have those.</p> <p>Max voltage <strong>MUST NOT</strong> exceed 4.2V at room temperature. Lower, say 4.1V, does no harm and increases battery cycle life while slightly reducing capacity per charge.</p> <p>The battery mAh rating is known as &quot;C&quot;.<br /> If C = 1200 then a cahrage rate of 1200 mA = C/1,<br /> a charge rate of 300 mA = C/4,<br /> a charge rate of 12 mA = C/100 etc</p> <p>An easy charging method that gives long cycle life and about 70% to 80% of max possible capacity and a fast charge is</p> <ul> <li><p>Determine max charge rate = C = Imax = same mA as battery has mAh capacity.</p> </li> <li><p>If Vbattery is &lt; 3V, charge at C/20 or less until Vbattery reaches 3V.<br /> If Vbattery never reaches 3V it is dead.</p> </li> <li><p>When V_battery = &gt;= 3V, charge at C/1 until Vbattery = 4.2V ( or 4.1V)</p> </li> <li><p>Finished!.</p> </li> <li><p>Remove applied voltage. DO NOT EVER leave 4.2V applied to a charged battery.</p> </li> </ul> <p>A more usual method that is only slightly harder is.</p> <ul> <li><p>Monitor charge current.</p> </li> <li><p>Charge as above until Vbat = 4.2V.</p> </li> <li><p>While holding Vbat at 4.2V monitor charge current. This will fall as the battery absorbs additional charge.</p> </li> <li><p>When Icharge falls to C/2 or C/4, stop charge. C/4 adds slightly more charge than C/2 but shortens cycle life.</p> </li> <li><p>Again - DO NOT leave 4.2V applied to battery once charged. Doing so will destroy the battery rapidly. Remove all voltage once charged.</p> </li> </ul> <p>.______________________________</p> <p><strong>Battery University:</strong></p> <p><a href="http://batteryuniversity.com/learn/article/charging_lithium_ion_batteries" rel="nofollow noreferrer">Charging Lithium Ion &amp; LiPo</a></p> <p><a href="http://batteryuniversity.com/learn/article/how_to_prolong_lithium_based_batteries" rel="nofollow noreferrer">Increasing lifetime</a></p> <p><a href="http://batteryuniversity.com/learn/" rel="nofollow noreferrer">Index</a></p> <p>.______________________</p> <h3>Q&amp;A</h3> <blockquote> <p>Q: This is a 3.7v battery by giving 4.2v will it destroy it or are you referring 4.2v to explain the concept.</p> </blockquote> <p>Read the above material and the battery university pages.</p> <p>4.1 V ABSOLUTE MAXIMUM is what I recommended.</p> <ul> <li><p>Most LiPo single cell batteries are labelled as 3.6 V or 3.7 V as that is approximately the <strong>average voltage</strong> across the discharge cycle.</p> </li> <li><p>When <strong>fully charged</strong> they are at <strong>about 4.2 V (or 4.1 V if you take my advice -</strong> which you should :-).</p> </li> <li><p>As they discharge the voltage falls and by the time they get to just above 3 V they are essentially fully discharged. They should never be discharged below 3 V as it damages them and there is only a tiny amount of energy left.</p> </li> </ul> <p>So 4.1 V ABSOLUTE MAXIMUM is good<br /> MEASURED WHILE CHARGING and<br /> AT the battery terminals or very close to them.<br /> ie no long leads or resistors or connectors.</p> <p>If using an Arduino to measure battery voltage, connect an Arduino ground lead to battery negative with as short a wire as practical and the ADC +ve input to the battery +ve at the battery connection point.</p> <p>So once more: A LiPo battery labelled as 3.6V or 3.7V can and should be charged to 4.1V maximum and never discharged to below 3V.</p>
12028
|relay|
How to implement a 2D lookup table?
2015-05-20T20:15:17.137
<p>This is my first post to this forum. I am fairly experienced in electronics, but am in the process of learning C, Arduino coding, and how to use microcontrollers in general for various applications.</p> <p>I have a toy-like 5 degree of freedom (DOF) robot arm that is currently controlled using the OEM hand-held switch box. It is a basic electromechanical robot arm to illustrate the fundamentals and it uses DC motors to drive the joint motions. The direction of motion is controlled by changing the polarity of the applied voltage. The manufacturer did offer an "interface board" and SW to be able to hook up the arm and control it using a computer program. However, this approach was fairly dated and their SW was not compatible with windows 8.1. I wanted to experiment and use an Arduino Uno Rev 3 and 5V DC relay PCBs to develop my own interface system.</p> <p>Basically, the HW aspect was straightforward and is working fine. The Arduino SW also is working fine. I am playing around with 2 variations of the program: 1) One program that simultaneously moves up to 3 joints and 2) A sequential joint movement program where each joint only moves after the other has finished moving. One <strong>note</strong> about the simultaneous program is that I am using the "internal" batteries in the robot's base (only 3V each direction) and thus can not realistically move more than 3 joints at the same time without putting too much load on the source voltage.</p> <p><strong>Ok, now to my question!</strong> As it stands now, the program works well, but is not intuitive. Each joint has 2 relays associated with it: one for each direction of travel. There are 5 joints total in the robot arm. I am able to use the program easily since I know directly (from setting up the HW and then the SW) which relays correspond to which Arduino pins and of course which relays correspond to each joint. I'd like to make the program more intuitive where instead of "2,2,0,0,3,4" input string for example, the user would do something like "B,CCW,S,CW" where B is for B = base, CCW = is counter clockwise etc. </p> <p>Please note that in the numerical only input string "2,2,3,4" for example, the 2nd value corresponds to the duration in seconds that the relay will be ON (and thus the joint moving). The robot arm is not very sophisticated in that it doesn't have encoders for position feedback. The simplest way (and the method which the OEM interface board uses) to interface this arm and make a program where the arm will move in a "hands-off fashion" was to use relays and program delays (to create time durations of joint movement". The numerical only input works really well currently and it was very easy to use examples to figure out how to parse a comma separated string.</p> <p>I understand (I think) from looking at the examples how to parse a comma separated text string and pull from it the input values.</p> <p>BUT, I am uncertain how to use those input values and then associate them in the SW with the correct relays (Arduino Pins)!</p> <p>I have already tried seeking help with this but am unable to understand this thread: <a href="http://forum.arduino.cc/index.php/topic,94701.0.html" rel="nofollow noreferrer">http://forum.arduino.cc/index.php/topic,94701.0.html</a></p> <p>Basically, I need a 2D table where the joint and direction are input and then the SW associates one particular relay with those inputs. Please see the table below for a graphical example of what I tried to say above.</p> <p>One possible solution that I <strong>dread</strong> and saw mentioned was to use a ton of <strong>if else-if statements....</strong> I dread this since I want to be able to input any joint in any order and thus it seems like when the code parses the input string for the ith relay, it would have to check ALL of the conditions to see which joint it is, which direction etc. For example, I think I could minimize the # of if statements needed if I only entered in the input commands in a certain order: base first, shoulder next, etc. Doing so however, limits the intuitiveness of the program.</p> <p><img src="https://i.stack.imgur.com/zkLUT.png" alt="enter image description here"></p> <p>Thank you all for reading this! I hope this isn't too challenging!</p>
<p>The other answers have presented some good techniques that are flexible enough to be adapted to other, similar problems. By contrast, the following method is specialized to work with the particular chart of joint-letters and relay-numbers mentioned in the question. (It can be modified for other relay-number sequences, as noted in program's comments.)</p> <p>Rather than requiring entry of verbose text like CCW, or obscure abbreviations like DN, OP, and CL, it accepts a + or a - to set motor direction, with “+” corresponding to choices CW, UP, and OP, and “-” corresponding to other choices. For example, the question's sequence “B,CCW,S,CW” could be written as any of “B-S+”, “b-s+”, “B- S+”, “B-,S+”, etc (ie, case is ignored, and spaces and commas are ignored before a joint-letter).</p> <p>Note, the code as shown assumes each command-list line starts with a number that gives desired delay time in tenths of a second. For example, “23 e-s+” would run E down and S up for 2.3 seconds. The command-list “47” would sit idle (no motors on) for 4.7 seconds. </p> <pre><code>#include &lt;ctype.h&gt; void operateRelays(char *cmdList) { char *joints = "BSEWG", *c=cmdList, *j; byte relay, delaytenths= 0; while (*c &amp;&amp; isdigit(*c)) // Get # of tenths-of-seconds to delay delaytenths = 10*delaytenths + *c-'0'; for (; *c; ++c) { while (*c &amp;&amp; !isalpha(*c)) ++c; // Ignore non-alphas before joint if (!*c) break; // At end of command list, break for (j=joints; *j; ++j) if (toupper(*c) == *j) break; if (!*j) break; // Ab-exit if joint-letter not found if (!*(++c)) break; // Advance to + or - relay = 2*(j-joints) + 1 + (*c != '+'); // The last term is 0 or 1 digitalWrite(relay, HIGH); // If relay numbers aren't contiguous as in question, just use // an array (like: byte relays[] = {2,1,5,4,6,3,7,9,10,8};) // and in above statement say digitalWrite(relays[relay-1], HIGH);. } delay (100*delaytenths); // Wait specified time for (relay=1; relay&lt;11; ++relay) // Turn motors off digitalWrite(relay, LOW); } </code></pre>
12034
|programming|avr-gcc|
Passing arguments to LCD.print through another function
2015-05-21T02:50:27.803
<p>I'd like to write a function like this:</p> <pre><code>void lcdPositionPrint(int row, int col, content) { lcdPosition(row, col); LCD.print(content); } </code></pre> <p>but I'm not certain how to declare "content", because it might be a string, or an int, or who knows what, just as it is for the "Serial.print" function or the LCD.print() function. Is there an easy way to do this? </p>
<p>There isn't really a great way to do it, but there are a few ways to get it to work. Most of the problem here is that there is actually a different <code>LCD.print</code> function for every data type. You aren't really calling the same function, your calling different functions that share the same name.</p> <p><strong>You could use templates.</strong> They are a powerful system built into C plus plus for generating functions and avr-gcc supports them well. With them, you can make the compiler generate all the necessary versions of your function for you. Your function would then look like this:</p> <pre><code>template&lt;typename T&gt; void lcdPositionPrint(int x, int y, T content) throw() { lcdPosition(row, col); LCD.print(content); } </code></pre> <p>That part about <code>throw()</code> isn't doing anything except keeping the ".ino" preprocessor from messing the template function up. You can call the templated function like normal, or with an explicit type </p> <pre><code>lcdPositionPrint(0,0,"hello"); lcdPositionPrint&lt;float&gt;(0,0,32.0f); </code></pre> <p><strong>You could also use the preprocessor.</strong> Your function is very simple, so you could just as easily make it a preprocessor macro that just places you code you want in the file whenever your "function call" appears. It looks like this:</p> <pre><code>#define lcdPositionPrint2(row,col,content) \ do { lcdPosition(row, col); LCD.print(content); } while (0) </code></pre> <p>The <code>\</code> there tells the preprocessor that the next line is also part of the macro, and you will need one on every line but the last of your function. Wrapping it in a <code>do</code> loop that immediately ends makes it nicely substitute into more situations. Micros don't scale up well, but they are a bit simpler for quick debugging situations. The code is duplicated in each call location instead of being bundled into functions though.</p>
12040
|serial|bluetooth|communication|softwareserial|arduino-micro|
SoftwareSerial problems
2015-05-21T08:35:59.953
<p>Hi we are using an Arduino Micro and working with a Bluetooth device and a Rfid Scanner from Sparkfun(ID-20 LA). For that we implemented 2 SoftwareSerial objects and the Serial port for the Serial Monitor. If we use one SoftwareSerial object and the normal Serial everything works fine. For example we can send and receive things over Bluetooth. But when adding another SoftwareSerial object( Rfid then ) One of them doesn't work. </p> <p>Starting with the Rfid SoftwareSerial ends up to the same result.</p> <p>We've also already tried to change the ports and so one.</p> <p>Every help is appreciated. Thanks in advance.</p> <p>The Code ( this is already the third programm nothing has changed )</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial rf(11, 12); SoftwareSerial bt(8,9); void setup() { Serial.begin(9600); rf.begin(9600); bt.begin(9600); } void loop() { if(Serial.available()) { while(Serial.available()) Serial.write(Serial.read()); Serial.println(""); } if(rf.available()) { while(rf.available()) Serial.write(rf.read()); Serial.println(""); } if(bt.available()) { while(bt.available()) Serial.write(bt.read()); Serial.println(""); } } </code></pre>
<p>Taken from <a href="http://www.arduino.cc/en/Reference/SoftwareSerial" rel="nofollow">http://www.arduino.cc/en/Reference/SoftwareSerial</a>:</p> <p>Limitations</p> <p>The library has the following known limitations:</p> <pre><code>If using multiple software serial ports, only one can receive data at a time. </code></pre> <p>If your project requires simultaneous data flows, see Paul Stoffregen's AltSoftSerial library. <a href="http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html" rel="nofollow">AltSoftSerial</a> overcomes a number of other issues with the core SoftwareSerial, but has it's own limitations. Refer to the AltSoftSerial site for more information. </p> <p>If you look at SoftwareSerial's code, you'll understand the limitation:</p> <pre><code>/* static */ inline void SoftwareSerial::handle_interrupt() { if (active_object) { active_object-&gt;recv(); } } </code></pre> <p>Basically, the code waits for an interrupt to detect state changes on the pin, and directs it to the "active" serial object.</p> <p>Hope this helps.</p>
12045
|nrf24l01+|
Not able to make my NrF24L01 work
2015-05-21T09:48:04.183
<p>I have been trying to make my two Nrf24L01 wireless model work for few days now, to do so I follow the tutorial in the following link. </p> <p><a href="http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo" rel="nofollow noreferrer">http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo</a></p> <p>I followed the link exactly, i changed nothing, expect i didn't add the bypass capacitor , as they said it will improve the performance and reduce heat, however mine is not working at all. </p> <p>here is a pictures of my hardware setup ,</p> <p><img src="https://i.stack.imgur.com/L5eu9.jpg" alt="arduino setup"><br> <img src="https://i.stack.imgur.com/YsFHC.jpg" alt="anther picture for the setup"> <img src="https://i.stack.imgur.com/KRdBz.jpg" alt="my whole setup"> <img src="https://i.stack.imgur.com/o8wjR.jpg" alt="nrf24L01 model"></p> <p>for the code i didnt change any this from the tutorial but i will past it to make it easy to follow Transmitting code </p> <pre><code> /* YourDuinoStarter Example: nRF24L01 Transmit Joystick values - WHAT IT DOES: Reads Analog values on A0, A1 and transmits them over a nRF24L01 Radio Link to another transceiver. - SEE the comments after "//" on each line below - CONNECTIONS: nRF24L01 Modules See: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 9 4 - CSN to Arduino pin 10 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - Analog Joystick or two 10K potentiometers: GND to Arduino GND VCC to Arduino +5V X Pot to Arduino A0 Y Pot to Arduino A1 - V1.00 11/26/13 Based on examples at http://www.bajdi.com/ Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include &lt;SPI.h&gt; #include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 9 #define CSN_PIN 10 #define JOYSTICK_X A0 #define JOYSTICK_Y A1 // NOTE: the "LL" at the end of the constant is "LongLong" type const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe /*-----( Declare objects )-----*/ RF24 radio(CE_PIN, CSN_PIN); // Create a Radio /*-----( Declare Variables )-----*/ int joystick[2]; // 2 element array holding Joystick readings void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(9600); radio.begin(); radio.openWritingPipe(pipe); }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { joystick[0] = analogRead(JOYSTICK_X); joystick[1] = analogRead(JOYSTICK_Y); radio.write( joystick, sizeof(joystick) ); }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ //NONE //*********( THE END )*********** </code></pre> <p>Receiving code :</p> <pre><code>/* YourDuinoStarter Example: nRF24L01 Receive Joystick values - WHAT IT DOES: Receives data from another transceiver with 2 Analog values from a Joystick or 2 Potentiometers Displays received values on Serial Monitor - SEE the comments after "//" on each line below - CONNECTIONS: nRF24L01 Modules See: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo 1 - GND 2 - VCC 3.3V !!! NOT 5V 3 - CE to Arduino pin 9 4 - CSN to Arduino pin 10 5 - SCK to Arduino pin 13 6 - MOSI to Arduino pin 11 7 - MISO to Arduino pin 12 8 - UNUSED - V1.00 11/26/13 Based on examples at http://www.bajdi.com/ Questions: terry@yourduino.com */ /*-----( Import needed libraries )-----*/ #include &lt;SPI.h&gt; #include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; /*-----( Declare Constants and Pin Numbers )-----*/ #define CE_PIN 9 #define CSN_PIN 10 // NOTE: the "LL" at the end of the constant is "LongLong" type const uint64_t pipe = 0xE8E8F0F0E1LL; // Define the transmit pipe /*-----( Declare objects )-----*/ RF24 radio(CE_PIN, CSN_PIN); // Create a Radio /*-----( Declare Variables )-----*/ int joystick[2]; // 2 element array holding Joystick readings void setup() /****** SETUP: RUNS ONCE ******/ { Serial.begin(9600); delay(1000); Serial.println("Nrf24L01 Receiver Starting"); radio.begin(); radio.openReadingPipe(1,pipe); radio.startListening();; }//--(end setup )--- void loop() /****** LOOP: RUNS CONSTANTLY ******/ { if ( radio.available() ) { // Read the data payload until we've received everything bool done = false; while (!done) { // Fetch the data payload done = radio.read( joystick, sizeof(joystick) ); Serial.print("X = "); Serial.print(joystick[0]); Serial.print(" Y = "); Serial.println(joystick[1]); } } else { Serial.println("No radio available"); } }//--(end main loop )--- /*-----( Declare User-written Functions )-----*/ //NONE //*********( THE END )*********** </code></pre> <p>The output result on the serial is No radio available </p> <p>dose anyone know where i can go from here ? or how i can debuge such a problem ? i dont even know if the problem is with the sender or receiver or both of them </p>
<p>If adding a 47uF capacitor between the 3.3V and GND is not enough to solve your problem, try to:</p> <ul> <li>power the NRF24 through a 3.3V voltage regulator (like a LM1117T-3.3) and power the voltage regulator (NOT the NRF24) through the Arduino's 5V pin. Indeed, the Arduino 3.3V pin is limited to 150mA output, while the the 5V pin can provide you about 400mA.</li> <li>don't use a breadboard: the NRF24 chip is very sensitive, so try to connect it directly to the board through jumpers or PCB / perf-board.</li> <li><p>Add to your code the line: </p> <pre><code>radio.setPALevel(RF24_PA_MIN); </code></pre></li> </ul> <p>and check if it works in that way; if it does, the issue is probably about the chip's current consumption.</p> <p>Hope this helped</p>
12046
|arduino-uno|
Arduino to mysql database?
2015-05-21T12:20:48.123
<p>I found a lot of methods on the internet and I was wondering what would be the best method to send data from sensors connected to Arduino to a MySQL database in a WAMP server continuously.</p>
<p>There is no absolute "best" way, there is only the way that "works best for your situation".</p> <p>In a nutshell, the different methods that I can think of, and their pros and cons, are:</p> <ul> <li>Simple HTTP GET with parameters</li> </ul> <p>Quick to implement, light weight, but not very secure or robust. Perfectly fine for things like "send the temperature once a minute" etc, but crafting very long GET requests with lots of parameters can severely impact on both your RAM and your sanity.</p> <ul> <li>HTTP POST request</li> </ul> <p>Like the GET request it's fairly simple to implement, but needs more RAM since you need to know the size of the data you're sending first so you can send a <code>Content-length</code> header. You can send much more that way though, assuming you have the resources for it.</p> <ul> <li>SOAP</li> </ul> <p>This is basically HTTP POST but with a specially XML formatted body. It has the advantage that it's a standard protocol for transferring data and commands around the place, so there are plenty of resources to help you. The main problem is crafting the XML at the Arduino side.</p> <ul> <li>Custom TCP</li> </ul> <p>Connect to a special port to communicate with your own software. You define all of the protocol, but you have to write all (or most) of the software too. This can be more like a serial connection to your computer but through the network. Good for sending larger amounts of data, such as images from a camera, etc.</p> <ul> <li>Custom UDP</li> </ul> <p>If you want to send lots of small values very frequently this is probably the best bet. Harder to implement than most of the others, but the light-weight nature of UDP means you can send data much more rapidly. Of course, with UDP, you run the risk of losing packets since it's very much a "fire and forget" protocol - you send a packet and hope it gets there. Fine if you don't mind missing the odd bit of data, say for higher speed temperature logging. Of course, you have to write the server side software yourself, but there's plenty of resources to help you with that online.</p> <p>So it's really not a case of "best" but "most suitable". Define what the data is and how often you want to send it, then think about how complex you are willing to get with your programming.</p> <p>Nine times out of ten a simple HTTP GET request fits the bill.</p>
12048
|arduino-mega|avr|atmel-studio|
How can I indicate that I am using ATmega2560 so that Arduino libraries understand it?
2015-05-21T12:38:14.820
<p>I am developing AVR microcontollers in Atmle Studio and sometimes I am using Arduino libraries(such as LiquidCrystal). </p> <p>When I initialize <code>LiquidCrystal lcd(12, 11, 5, 4, 3, 2);</code> I don't think Arduino Libraries use registers and ports of ATmega2560, although I am building my code with the device selection ATmega2560 option of Atmel Studio. Atmel Studio works in order to program 2560 but how can I tell Arduino libraries that I am using 2560?</p>
<p>There are two things that have to be considered here.</p> <p>One is telling the code what board you are using, so it can compile in the right optional parts, and the other is getting the right pin mappings.</p> <p>The first can be covered simply with a compilation flag:</p> <pre><code>-DARDUINO_MEGA2560 </code></pre> <p>That defines the macro <code>ARDUINO_MEGA2560</code> which is used in some places to know which board you are using.</p> <p>Second is the pin mappings. These are stored in the file <code>pins_arduino.h</code> and each board variant has its own copy. You need to ensure that this file (and be sure to get the right one) is included in your code in the right places to ensure that the pins can be mapped right. If you are including the whole Arduino core (which it sounds like you must be in order for things to even have a hope of working) then you just need to ensure that you have the compiler set up to include the right copy of the <code>pins_arduino.h</code> file.</p> <p>That means making sure you have an include path in your compile command line which points to where the <code>pins_arduino.h</code> file is before anything else Arduino core related.</p> <pre><code>-IC:\Path\to\arduino\mega2560\variant </code></pre> <p>or</p> <pre><code>-I/path/to/arduino/mega2560/variant </code></pre>
12054
|arduino-uno|serial|
Reading and interpreting Serial information
2015-05-21T18:32:54.317
<p>I am trying to use a Raspberry Pi to control a ESC and for that I am sending the instructions for the ESC using serial. My problem is that when i send the instructions i can not interoperate them, and by interoperate I mean check what the first letter is and then remove it and make the Arduino output a PWM signal. My problem is when I use the serial monitor to send an instruction it firstly comes up on several lines, and when I try and look at the first letter of the string the if statement thinks it is true for all inputs of "FirstLetter" my function to get the serial input it </p> <pre><code>String readSerial() { char SerialInput; String Data = ""; if (Serial.available()) { SerialInput = Serial.read(); Data.concat(SerialInput); //Serial.println(Data); } return Data; } </code></pre> <p>the function that should interoperate the information from readSerial() is</p> <pre><code>void DecodeInput() { String input = readSerial(); if (input != "") { char FirstLetter = input.charAt(1); if (FirstLetter = 'U') { Serial.println("Hello World"); //input.setCharAt[0, ''); //SetPower('U', Power); } </code></pre>
<p>You may want to look at the Firmata protocol, and not re-invent the wheel. Although doing so (re-inventing the wheel) is a good learning exercise, so is understanding something already written.</p> <p><a href="http://www.arduino.cc/en/Reference/Firmata" rel="nofollow noreferrer">http://www.arduino.cc/en/Reference/Firmata</a></p> <p>Then move on to the <a href="http://cylonjs.com/" rel="nofollow noreferrer">cool stuff</a> that uses it.</p> <p><img src="https://i.stack.imgur.com/ZlA4M.png" alt="enter image description here"></p>
12059
|rtc|
Creating a clock using Arduino
2015-05-22T01:04:05.070
<p>I want to make a large clock, 16 inch x 7.5 inch, which will display dd Month yyyy. What would be the best way to do this? Does Arduino have a built in clock, and I'd just need logic to turn on/off LEDs on a display that already has dd Month yyyy? Do such displays exist which I can connect to Arduino?</p>
<p>If you are willing to go the “barebones” route, you can turn an ATmega328P (the MCU at the heart of the Arduino Uno) into a very accurate RTC by hooking a watch crystal to it's clock pins. Given proper calibration, you can get an accuracy of <strong>a few seconds per year</strong>.</p> <p>This would require some coding though, and is not as straightforward as using an off-the-shelf RTC. C.f. <a href="https://arduino.stackexchange.com/a/9039">this answer</a> for the details.</p>
12067
|serial|
lilypad works with wrong baudrate
2015-05-22T08:27:15.477
<p>I wrote a simple code on lillypad with fdti module as below:</p> <pre><code>void setup(){ Serial.begin(57600); } void loop(){ Serial.println("ddd"); delay(500); } </code></pre> <p>but it gives wrong characters at serial port window of arduino ide at 57600 baudrate. But I changed baudrate to 115200 at same window it gives right string as "ddd". Other baudrates do the same thing. What is the solution or where is the problem. I couldnt understand why baudrate shift occurs</p>
<p>The baud rate shift occurs because of a mismatch between the speed your program thinks the chip is running at and the speed the chip is actually running at.</p> <p>You may also have noticed that <code>delay(500)</code> is too fast and actually lasts as long as <code>delay(250)</code> would.</p> <p>By the numbers involved it looks like the board is running twice as fast (115200 / 57600 = 2) as your board definition says it is - maybe you're using an 8MHz definition for a 16MHz board, or a 1MHz definition for a 2MHz board, etc.</p> <p>Make sure you have the right board definition selected in the IDE for your board.</p>
12070
|arduino-mega|
I guess, pull-up/down resistors fried. What can i do?
2015-05-22T14:57:19.890
<p>Arduino Mega ADK is working well but it is not working circuit in which pull-up/down resistors. It is generating wrong results. I guess, pull-up/down resistors fried. What can i do? </p>
<p>If you want internal pullup or pulldown resistors on input pins, you can use external ones to do the same job as internal ones if you wish to. Generally, if you use say 100 k Ohms from a pin to V+ or ground then it will act as a pullup or pull down respectively on an input pin, but have much effect on an output pin - which is what you want to happen. </p> <p>However, it is unlikely that 'fried internal resistors is the reason for code not working and, if this is the case, there is probably unknown and unknowable other damage as well. Pull up/down resistors are usually not actually resistors. They are FETs with high Rds_on values that look resistor like when on. Anything that "fries" them has a reasonable prospect of doing other damage as well.</p>
12073
|serial|
ping pong with two Arduinos over serial
2015-05-22T16:48:06.840
<p>I have two Arduino boards and want to make them communicate with each other over serial. The code I have used for the two boards is almost identical.</p> <ul> <li>Every one second the &quot;A&quot; board sends a &quot;ping&quot; message over serial.</li> <li>The &quot;B&quot; board receives the &quot;ping&quot; message and responds with a &quot;pong&quot; one.</li> <li>The &quot;A&quot; board receives the &quot;pong&quot; message and prints it on screen.</li> </ul> <p><strong>Board A - ping code</strong></p> <pre><code>String inputString = &quot;&quot;; boolean stringComplete = false; void setup() { Serial.begin(9600); inputString.reserve(200); } void loop() { Serial.print(&quot;ping&quot;); if (stringComplete) { Serial.println(inputString); inputString = &quot;&quot;; stringComplete = false; } delay(1000); } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputString += inChar; if (inChar == 'g') { stringComplete = true; } } } </code></pre> <p><strong>Board B - pong code</strong></p> <pre><code>String inputString = &quot;&quot;; boolean stringComplete = false; void setup() { Serial.begin(9600); inputString.reserve(200); } void loop() { if (stringComplete) { Serial.println(&quot;pong&quot;); inputString = &quot;&quot;; stringComplete = false; } } void serialEvent() { while (Serial.available()) { char inChar = (char)Serial.read(); inputString += inChar; if (inChar == 'g') { stringComplete = true; } } } </code></pre> <p>The code seems to work, but not exactly as expected. I initiate the serial monitor of the board &quot;A&quot; and expect to see every one second:</p> <blockquote> <p>pingpong</p> </blockquote> <p>Instead I see this:</p> <blockquote> <p>pingpong</p> <p>pong</p> <p>pong</p> <p>....</p> </blockquote> <p>which means that the pong message is repeated more than one time per second. But I want the &quot;B&quot; board to transmit the &quot;pong&quot; message only when it receives the &quot;ping&quot; one.</p> <p>Why is this happening? Is there an error in the code? Is there a detail about the serial protocol which escapes me?</p> <p>Any thoughts would be appreciated.</p>
<p>The problem is with your protocol and also with how you are using the serial.</p> <p>You are using the same serial channel both for your communication protocol <em>and</em> for the reporting of the results. What you see the B end sees.</p> <p>So A sends <code>ping</code>, and when it sees the letter <code>g</code> it responds with <code>pong</code>. You then print that <code>pong</code> to the serial, so end B sees <code>pong</code>. It gets the character <code>g</code> and thinks "That was a ping, I'll respond with a pong", so it does - it sends <code>pong</code>, which you then receive and duly print - starting the sequence over yet again.</p> <p>You either need to separate out the communication and the reporting, or make your protocol look for the whole string "ping" so it never inadvertently responds to a "pong" when it shouldn't.</p> <p>Here's a good resource about reading serial strings on the Arduino: <a href="http://hacking.majenko.co.uk/reading-serial-on-the-arduino" rel="nofollow">http://hacking.majenko.co.uk/reading-serial-on-the-arduino</a></p>
12076
|arduino-uno|
2.8" TFT Touchscreen Prohibits Access to Unused Pins
2015-05-22T17:28:35.790
<p>This is probably a beginner question. You've been warned.</p> <p>I recently purchased a touchscreen (<a href="http://www.adafruit.com/products/1651#tutorials" rel="nofollow">http://www.adafruit.com/products/1651#tutorials</a>) specifically because it left so many pins open to work with and I needed to hook up one, possibly two more items to my Arduino. However the touchscreen fits over the Arduino and covers all the pins.</p> <p><strong>How do I access the pins that the LCD isn't using?</strong></p> <p>To be specific, I will be adding a Galvanic Skin Sensor on two analog pins. </p>
<p>get a Protoshield, a good one and put it between the arduino and the shield <a href="https://i.stack.imgur.com/b27ia.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/b27ia.jpg" alt="Proto shield that will work"></a></p>
12079
|wifi|
Compatibility between Particle Photon and Arduino
2015-05-22T18:30:19.190
<p>Is it possible to run Arduino on a <a href="https://store.particle.io/?product=particle-photon" rel="nofollow">Particle Photon</a>?</p> <p>I want complete software control over the device so I can connect it to the internet and do stuff without going through Particle's cloud, logins, etc.</p>
<p>You can use the new particle dev platform to do this <a href="https://www.particle.io/dev" rel="nofollow">https://www.particle.io/dev</a></p>
12082
|power|arduino-pro-mini|
Unable to power an Arduino Pro Mini through the RAW pin
2015-05-22T20:30:32.663
<p>I've recently bought an Arduino Pro Mini, the 3.3V and 8MHz version. The first time I powered it, using the VCC pin, all worked. But, as soon as I attempt using the RAW pin instead, nothing lights up... Is my regulator broken ? Or is this a typical issue ?</p>
<p>I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".</p> <p><img src="https://i.stack.imgur.com/qoVld.png" alt="enter image description here"></p> <p>I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.</p>
12087
|arduino-pro-mini|
How do I make a atmega 32u4 mp3 player?
2015-05-23T08:24:48.583
<p>Is there a way to use the atmega 32u4 breakout board to make a mp3 player without the mp3 shield?</p> <p><img src="https://i.stack.imgur.com/L56Jq.jpg" alt="atmega 32u4 breakout from adafruit"></p>
<p>You don't.</p> <p>A basic ATmega lacks the computational (and perhaps memory also) resources for mp3 decoding. And even if you do decode to a linear PCM format, you do not have a good way to output it.</p> <p>You can playback linear PCM data by pulse width modulating a pin, but the limited clock rate will result in limited resolution, and thus poor fidelity. You will also end up with a low sample rate, making it hard to avoid audible artifacts.</p> <p>The situation can actually be somewhat better with an ATtiny85 - still no MP3 decoding of course, but you can clock the counter/time block at a higher rate and so playback PWM audio with higher fidelity, provided you are willing to tolerate the inaccuracy of the onboard clock oscillator that may shift your audio frequencies by a small amount.</p> <p>If you want to do MP3, you will need either a more powerful processor (often no more expensive than the one you have, and typically cheaper as a module than anything "-duino"), or else a dedicated function chip to act as a coprocessor for that purpose.</p>
12090
|arduino-pro-mini|
Powering an Arduino Pro Mini directly from a LiPo
2015-05-23T09:02:45.980
<p>I've recently purchased an Arduino Pro Mini, 3.3V version. I've planned to use it in a diy remote: I've empty a ps2 remote, just left the buttons, and the board will be inside. The remote will be wireless: I use an xbee, which also fit inside the ps2 controller. To power it, I use a one cell Lipo, which will empower the Arduino and the XBee, here comes my issue: As you've seen, there will be many things an a single ps2 controller, so I try to minimize connections and external components. But, the XBee will take more than the maximum 150mA provided by internal regulator of the Arduino. So, either I use an external regulator, or I directly plug the lipo in the VCC pin if the Arduino. Can the board survive? If the voltage is greater than 3.3V, will it damage the board? </p>
<p>The only thing about the 3.3V Pro Mini that is actually 3.3V is the 3.3V regulator. The main chip (pretty much the only other component) is good for anything from 1.8V up to 5.5V.</p> <p>Running direct from a 3.7V LiPo or Li-Ion will be perfectly fine. You might want to disconnect or otherwise disable the regulator though to reduce current consumption - the latest Minis have a solder jumper <em>SJ1</em> for doing just that, but older versions you may want to actually cut the 3.3V OUT pin of the regulator or de-solder it entirely.</p>
12095
|arduino-uno|serial|keyboard|
How to tell Arduino Uno that I pressed or released a key on PC keyboard over serial?
2015-05-23T15:08:32.407
<p>I want to implement a simple musical keyboard with Arduino using <code>tone()</code> and <code>noTone()</code> functions, etc.</p> <p>The desired behavior is:</p> <ul> <li>While PC and Arduino are connected via USB/Serial...</li> <li>...when I press a key, a corresponding note starts playing...</li> <li>...and if I release that key that note stops playing...</li> <li>...or if I press <em>another</em> key, another note replaces the former one.</li> </ul> <p>So, basically, instead of "while key is pressed" logic, I would like to just write a byte to serial when a key is pressed, write nothing while the key is held pressed, and write another byte when that key is released.</p> <p>I will be using a Python script in the PC, but examples in other languages, or just using a plain serial monitor, are fine.</p>
<p>UPDATE: When I posted this answer I had not yet any knowledge of the Processing Language. If you came to this answer with the same intention I had (the question title), I strongly suggest you to use Processing instead, which has much more straightforward keyboard event capturing and serial communication working out of the box with minimal code.</p> <p>A question showing this in action is here: <a href="https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard">https://stackoverflow.com/questions/18366482/processing-to-arduino-with-keyboard</a></p> <hr> <p>After realizing that what I actually wanted was to "capture keyboard events", I ended up using <a href="http://www.pygame.org/news.html" rel="nofollow noreferrer">PyGame</a> due to its minimalistic setup. Now I can send whatever I want to the Arduino using <a href="http://playground.arduino.cc/interfacing/python" rel="nofollow noreferrer">PySerial</a>.</p> <p>PS.: Don't be fooled by the lame aesthetics of PyGame website, it is a very mature gaming platform.</p> <p>Full code here: <a href="https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard" rel="nofollow noreferrer">https://github.com/heltonbiker/Experiments/tree/master/SerialMusicKeyboard</a></p> <pre><code>#/usr/bin/env python import pygame import serial import glob import time def pygameSetup(): pygame.init() screen = pygame.display.set_mode((468, 60)) background = pygame.Surface(screen.get_size()) background = background.convert() background.fill((250, 250, 250)) if pygame.font: font = pygame.font.Font(None, 36) text = font.render("Shut up 'n play yer keyboard!", 1, (10, 10, 10)) textpos = text.get_rect(centerx=background.get_width()/2) background.blit(text, textpos) screen.blit(background, (0, 0)) pygame.display.flip() def main(): pygameSetup() initialized = False while not initialized: try: serialpath = glob.glob('/dev/ttyACM*')[0] ser = serial.Serial(serialpath, 9600) initialized = True print "serial up" except: time.sleep(500) print "waiting for serial" while True: for event in pygame.event.get(): if event.type == pygame.QUIT: return elif event.type == pygame.KEYDOWN: print event ser.write(chr(event.key)) elif event.type == pygame.KEYUP: ser.write(chr(0)) if __name__ == '__main__': main() </code></pre>
12096
|arduino-leonardo|
Where are the digital and analog pins for the adafruit atmega 32u4 breakout board?
2015-05-23T15:12:50.637
<p>Which pins are the analog and digital pins? I've been searching the internet for an hour and I could get an answer.</p>
<p>The information is right there on the product page for you. It took be a total of about 4 seconds to find it.</p> <p><a href="http://ladyada.net/products/atmega32u4breakout/" rel="nofollow noreferrer">http://ladyada.net/products/atmega32u4breakout/</a></p> <p><img src="https://i.stack.imgur.com/d4NSw.png" alt="enter image description here"></p>
12101
|nrf24l01+|
Multiple nodes with the same receiving and transmitting address
2015-05-23T18:37:41.767
<p>I want to make a network with arduinos and nrf24l01 chips. The network will be like this: </p> <ul> <li>1 master arduino </li> <li>multiple (no specific number) slave nodes</li> </ul> <p>I want all nodes to have the same receiving and the same transmitting address and the master arduino to understand which one send the message from the message itself. For example:</p> <p><strong>Master:</strong> Receiving: 0xABCDABCD71 Transmitting: 0xABCDABCD01</p> <p><strong>Slave 1</strong> Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71</p> <p><strong>Slave 2</strong> Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71</p> <p><strong>Slave 3</strong> Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71</p> <p><strong>Slave 4</strong> Receiving: 0xABCDABCD01 Transmitting: 0xABCDABCD71</p> <p>When master send a message, all nodes will receive it. What I want to ask is : </p> <ul> <li>Is that possible? </li> <li>Will there be any problems? </li> <li>Is there any other way so I can add more nodes in the future without changing the code?</li> </ul>
<p>as well as comment #1 the other thing will be the ack packets that the slaves will send back to the master to confirm message recieved. with all slaves sending back a ack at about the same time there will be no way for master to tell which ack is from which client, and thus who needs a retransmit. a way around this is to turn off ack for the clients and make the master transmit max times regardless. there is a rf24 fork that has broadcast mode, the makes it more easy to specify not to wait for ack before retransmitting</p>
12102
|arduino-leonardo|
What is wrong with my 32u4 breakout board from adafruit?
2015-05-23T19:53:28.873
<p>I recently bought the atmega 32u4 breakout board from adafruit. I uploaded a sketch, then it says that there isn't a timer 2 on it and it won't do as I programmed my sketch. how can I fix this?</p>
<p>You will need to port any libraries and code that depend on timer 2 to the '32U4 architecture. There is no way to add timer 2 to the chip, and it is likely that trying to force it to use a different timer won't help since it may configure things the other timer doesn't have.</p>
12106
|arduino-uno|debugging|arduino-uno-smd|
Starting Off Low-Level Port Access
2015-05-23T22:28:45.347
<p>&nbsp;&nbsp;&nbsp;I'm trying to teach myself some low[er] level code, but I just can't get it to work. I've tried OR-ing stuff in, AND-ing stuff in, and just straight up defining stuff, but it's not blinking! What am I doing wrong here?</p> <p>I am using an Arduino UNO R3 DIP for this. I am just using the on-board LED, (on pin13/PORTB_5)</p> <p>Current code:</p> <pre><code>#define STATE B00001000 #define ZERO B00000000 void setup() { DDRB = STATE; } void loop(){ PORTB |= STATE; delay(500); PORTB &amp;= ZERO; delay(500); } </code></pre>
<p>It would probably help if you were using the right pin. In the pins_arduino.h file for the Uno is this diagram:</p> <pre><code>// +-\/-+ // PC6 1| |28 PC5 (AI 5) // (D 0) PD0 2| |27 PC4 (AI 4) // (D 1) PD1 3| |26 PC3 (AI 3) // (D 2) PD2 4| |25 PC2 (AI 2) // PWM+ (D 3) PD3 5| |24 PC1 (AI 1) // (D 4) PD4 6| |23 PC0 (AI 0) // VCC 7| |22 GND // GND 8| |21 AREF // PB6 9| |20 AVCC // PB7 10| |19 PB5 (D 13) // PWM+ (D 5) PD5 11| |18 PB4 (D 12) // PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM // (D 7) PD7 13| |16 PB2 (D 10) PWM // (D 8) PB0 14| |15 PB1 (D 9) PWM // +----+ </code></pre> <p>That shows that pin D 13 is PB5 which would be a binary value of <code>0b00100000</code> not <code>0b00001000</code> as you have, which would be PB3, or pin D11.</p> <p>The only way I can come up with <code>0b00001000</code> is if I count from the left (wrong) and start at 1 (wrong) rather than count from the right (right) and start at 0 (right).</p>
12114
|arduino-uno|atmega328|c|avr|compile|
Basic makefile for avr-gcc
2015-05-24T16:25:09.870
<p>I would like to make a makefile for compiling c programs for the arduino. I am somewhat familiar with make but have never used it with avr-gcc. What is the simplest way I could put the commands below in a makefile?</p> <pre><code>$ avr-gcc -Os -DF_CPU=16000000UL -mmcu=atmega328p -c -o led.o led.c $ avr-gcc -mmcu=atmega328p led.o -o led $ avr-objcopy -O ihex -R .eeprom led led.hex $ avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyACM0 -b 115200 -U flash:w:led.hex </code></pre>
<p>The accepted answer is great as it has given me a valuable lesson in all kinds of debugging tools (avr-objdump -D has become a close friend). Namely, the line:</p> <p><code>${OBJCOPY} -O ihex -R .eeprom $&lt; $@</code></p> <p>is missing the architecture flag and should read</p> <p>${OBJCOPY} <strong>-mmcu=atmega328p</strong> -O ihex -R .eeprom $&lt; $@</p> <p>Without the -mmcu architecture flag, avr-gcc guesses we are compiling for 8515 architecture (definitely not) and it produces the .elf file without initial instructions for initializing, i.e. without instructions to call the "main" function etc.</p> <p>This results in confusing behavior as any simple program (e.g. blink) with only the "main" function works perfectly, but if you define another function before or after the "main", it runs that function and never calls "main" or it restarts all the time etc.</p> <p>I am also not a particular fan of avoiding the verification of correct MCU type and uploaded program, so I'd advocate not to use -F and -V and use -v instead.</p> <p>So, the improved answer could be:</p> <pre><code>PKG=led BIN=${PKG} OBJS=${PKG}.o MCU=atmega328p CC=avr-gcc OBJCOPY=avr-objcopy CFLAGS=-Os -DF_CPU=16000000UL -mmcu=${MCU} -Wall PORT=/dev/ttyACM0 ${BIN}.hex: ${BIN}.elf ${OBJCOPY} -O ihex $&lt; $@ ${BIN}.elf: ${OBJS} ${CC} -mmcu=${MCU} -o $@ $^ install: ${BIN}.hex avrdude -v -c arduino -p ${MCU} -P ${PORT} -b 115200 -U flash:w:$&lt; clean: rm -f ${BIN}.elf ${BIN}.hex ${OBJS} </code></pre>
12115
|arduino-mega|sd-card|audio|
How can I play audio from an SD card?
2015-05-24T16:26:24.450
<p><strong>What is the best / simplest way to play audio files from an SD card?</strong></p> <p>I'm currently working on a sound board, where each button plays a different sound. But I have yet to find the right combination of shields / hardware to do this efficiently.</p> <p>Is there a shield that supports this directly (SD card -> speaker)? Note that I also need additional pinheads for my buttons to connect to. I think I will be using the Arduino Mega for that purpose.</p>
<p>There are several audio products/shields. Because you mention "speakers", the first one listed can come with an on-board amplifier to drive speakers directly. Most shields just give line-out to drive a pre-amp.</p> <ul> <li>Adafruit Music maker shield plays MP3/WAV/OGG from microSD <a href="http://www.adafruit.com/products/1788" rel="nofollow">http://www.adafruit.com/products/1788</a></li> <li>Adafruit Wave shield plays WAV files on SD card <a href="http://www.adafruit.com/products/94" rel="nofollow">http://www.adafruit.com/products/94</a></li> <li>SparkFun MP3 trigger board supports 256 tracks and a serial protocol for running individual tracks. <a href="https://www.sparkfun.com/products/11029" rel="nofollow">https://www.sparkfun.com/products/11029</a></li> <li>SparkFun MP3 shield board plays MP3/WAV/OGG <a href="https://www.sparkfun.com/products/10628" rel="nofollow">https://www.sparkfun.com/products/10628</a></li> </ul>
12117
|programming|c|compile|
Arduino Yun doesn't link any library
2015-05-24T22:41:00.437
<p>I'm writing code for a project with Arduino Yun. My project is quite simple: it takes a picture with a webcam and saves it in a PNG or JPEG file format. I've already installed the uvc driver for Arduino Yun and tested it with my webcam and the fswebcam application. The application saved pictures both in PNG and JPEG format successfully, so I went on and installed the C compiler, make and binutils for Arduino Yun and started to write my own application that would do the same thing (just taking a picture and saving it in PNG format). After writing the code to capture the pixels of the image, I decided to write them down in a PNG file format by using the libpng library available for Arduino Yun through luci web control panel. After installing the package, I included the png.h (using #include png.h) in my source code and wrote the code to write those pixels down in a simple PNG file (thanks to this tutorial: <a href="http://www.labbookpages.co.uk/software/imgProc/libPNG.html" rel="nofollow">http://www.labbookpages.co.uk/software/imgProc/libPNG.html</a>). What's the problem? It just won't compile! I tried everything and all I got were "undefined reference to 'function name here'" errors. I thought that, maybe, libpng was buggy so I moved to libjpeg. No luck! I get the same errors over and over again. I really don't know what else I can do, I tried everything, it just seems that the Arduino Yun C compiler can't handle "external" libraries. I thank you in advance for any help you'll give me...</p> <p>Here are the errors I get when I try to compile it using the libjpeg library:</p> <pre><code>/tmp/ccdzMFgN.o: In function `salvaImmagineJPEG': ScattaFoto.c:(.text+0x1d9c): undefined reference to `jpeg_std_error' ScattaFoto.c:(.text+0x1da8): undefined reference to `jpeg_std_error' ScattaFoto.c:(.text+0x1dc8): undefined reference to `jpeg_CreateCompress' ScattaFoto.c:(.text+0x1dd4): undefined reference to `jpeg_CreateCompress' ScattaFoto.c:(.text+0x1dec): undefined reference to `jpeg_stdio_dest' ScattaFoto.c:(.text+0x1df8): undefined reference to `jpeg_stdio_dest' ScattaFoto.c:(.text+0x1e2c): undefined reference to `jpeg_set_defaults' ScattaFoto.c:(.text+0x1e38): undefined reference to `jpeg_set_defaults' ScattaFoto.c:(.text+0x1e54): undefined reference to `jpeg_set_quality' ScattaFoto.c:(.text+0x1e60): undefined reference to `jpeg_set_quality' ScattaFoto.c:(.text+0x1e78): undefined reference to `jpeg_start_compress' ScattaFoto.c:(.text+0x1e84): undefined reference to `jpeg_start_compress' ScattaFoto.c:(.text+0x1ed8): undefined reference to `jpeg_write_scanlines' ScattaFoto.c:(.text+0x1ee4): undefined reference to `jpeg_write_scanlines' ScattaFoto.c:(.text+0x1f10): undefined reference to `jpeg_finish_compress' ScattaFoto.c:(.text+0x1f1c): undefined reference to `jpeg_finish_compress' collect2: ld returned 1 exit status </code></pre>
<p>It's not the compiler, it's the libpng package (and other libraries too). It only contains the runtime shared library (<code>.so</code>) files. You can't use it for development.</p> <p>I haven't yet found if it's possible to directly install a full development package or not - normally development for OpenWRT is done outside the low-powered chip using a cross-compiler environment on a PC.</p>
12130
|arduino-nano|
Function generator with Arduino Nano
2015-05-25T15:55:33.123
<p>I'm trying to convert the project <a href="http://www.arduino.cc/en/Tutorial/DueSimpleWaveformGenerator" rel="nofollow noreferrer">here</a> to an Arduino Nano.</p> <p>I scaled the waveforms from 12 bit to 8 bit values. I replaced the <code>analogReadResolution</code> and <code>analogWriteResolution</code> calls with <code>pinMode(10, OUTPUT)</code> and <code>pinMode(11, OUTPUT)</code> and changed the two <code>analogWrite</code> calls to write to pins 10 and 11. Otherwise the program is unchanged.</p> <p>My thinking (and this is where my poor electronics skills come into play) is that I just need a simple low pass filter to convert the PWM into the appropriate waveform (which, at startup, ought to be a sine wave on both pins). According to the article, the frequency generator tops out at 170Hz. I figure the PWM signal is going to be significantly higher than that, so I use R=3.3K and C = .1uF for my RC filter which ought to give me a -3dB at about 480Hz, but what I'm seeing on my scope is a mess. Not a stable signal at all.</p> <p>This is the waveform I'm seeing on my scope:</p> <p><img src="https://i.stack.imgur.com/RK99A.jpg" alt="OscopeImage"></p> <p>Can someone educate me?</p> <p>Update: BTW, this is the initial waveform which ought to be a sine wave.</p>
<p>What you're proposing <a href="http://interface.khm.de/index.php/lab/interfaces-advanced/arduino-dds-sinewave-generator/" rel="nofollow">can work</a>, but the PWM frequency needs to be <em>much</em> higher than the frequency you're trying to generate. If you look at the <a href="http://playground.arduino.cc/Code/PCMAudio" rel="nofollow">PCMAudio sample</a> you'll see that it tunes the PCM frequency almost as high as it will go.</p>
12136
|arduino-uno|shields|sd-card|
How do I use the prototyping area on a SparkFun MicroSD Card shield?
2015-05-26T01:08:22.090
<p>I'm having trouble figuring this out. I'm using this popular shield: <a href="https://www.sparkfun.com/products/12761" rel="nofollow">https://www.sparkfun.com/products/12761</a></p> <p>There is a breadboard area in the middle of the shield. But what confuses me is the lack of lines (order). On normal breadboards you can tell which row would be at the same voltage. If I wanted to put something on this prototyping area, how would I connect it? For example an LED, which would have a resistor attached to the positive side going to 5V and the negative side going to ground?</p>
<p>This type of board, "pad per hole", has no pre-made interconnects. If you use thin enough wire sometimes you can push two pieces of wire into the same hole before you solder, say a resistor lead and another wire to connect to the next component. You can also solder an interconnect wire to the protruding leg of a DIP chip. You can make a buss for ground or 5v by assigning a whole row for that purpose, on the top side wire everything that needs to connect to that buss, and on the bottom side solder a straight piece of bare wire to all those wire ends in that row. </p>
12139
|arduino-uno|led|
Reusing LED from RC helicopter controller
2015-05-26T02:13:51.187
<p>I have an old RC helicopter controller, but not the helicopter. I recently purchased an Arduino Uno and would like to do something with LEDs(beside the on-board one built-in). Can I use an LED from the controller, that is already soldered in, cut it free and plug into my breadboard.</p> <p><em>Side Note</em></p> <p>I have no experience in soldering and don't own a soldering iron.</p>
<p>Ignacio's drawing shows you how to connect a LED. If you don't have any soldering tools you can use a <strong>solderless breadboard</strong>. <a href="https://www.adafruit.com/products/65" rel="nofollow noreferrer">This small one</a> from Adafruit is ideal for small circuits:</p> <p><img src="https://i.stack.imgur.com/Cdd2f.jpg" alt="enter image description here"></p> <p>(They exist in all sizes from very small to very large). The holes in each 5-hole row are all internally connected. </p> <p>The problem with cutting the LED from the board may be that the remaining wire length is too short to fit in the breadboard. (You'll need at least something like 6 mm.) LEDs are a nice way to start with electronics, since you need minimal part count to make something visible. If you can't cannibalize the LED from the controller, just buy one from your local electronics shop. They're dirt cheap.</p>
12146
|arduino-uno|communication|
MQTT Arduino add quality of service
2015-05-26T10:22:44.637
<p>I'm making a project with MQTT Arduino, but on publish messages i read that it's not possible to publish with qos 1 and 2? It is true? If is not, how can i put qos on publish messages? </p>
<p>What MQTT client are you using?</p> <p>Paraphrased from the <a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099" rel="nofollow" title="MQTT spec">MQTT spec</a> <a href="http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099" rel="nofollow">http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/os/mqtt-v3.1.1-os.html#_Toc398718099</a></p> <blockquote> <p>The MQTT protocol provides three qualities of service for delivering messages between clients and servers: "at most once", QOS0; "at least once" QOS1; and "exactly once" QOS2. For QOS 1&amp;2: The message must be stored locally at the publisher, until the publisher receives confirmation that the message has been delivered to the receiver. However, for QOS0 there is no storage requirement.</p> </blockquote> <p>The problem with the Arduino is that there is no large quantity of storage available. If the client is disconnected from the broker while using a QOS of 1 or 2 the client must store the messages until a connection is reestablished and the message transfers are acknowledged. On an Arduino there is no guarantee all the messages can be saved. Consider a sensor node collecting 16-bits (int value) every second. Then supposed the broker goes down over the weekend and a repair person isn’t paid to work on the weekend. That’s two days’ worth of data or 172800 readings or about 1/3 MB (without overhead). The Arduino does not have that much storage.</p>
12150
|servo|arduino-pro-micro|
Running a servo and tone() won't compile? "multiple definition of `__vector_32'"?
2015-05-26T14:25:28.527
<p>Im using Spark fun pro micro:<a href="https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro" rel="nofollow">https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/hardware-overview-pro-micro</a></p> <p>I am controlling a servo motor which reads its data from a pot connected to A0, and then writes to the servo on D9.</p> <p>A speaker is connected to A5. Im using tone()</p> <p>If I comment out the servo part of it, the tone() works out just fine and vise versa.. The error message I get is "multiple definition of `__vector_32'"</p> <p>Got a clue??! Thanks! </p>
<p>The link you provided shows a board built around the ATmega32U4. On this chip, “__vector_32” is the low-level name of an ISR (Interrupt Service Routine) named “TIMER3_COMPA_vect”. Your problem comes from having two libraries trying to define an ISR for the same interrupt, which is generated by the timer&nbsp;3 of the chip. Merging the ISRs is actually unlikely to work, because since each library configures the timer in its own way, the timing of the interrupts will be wrong for at least one of the libraries. You really have to use different timers.</p> <p>On my copy of Tone.cpp I can read:</p> <pre class="lang-c++ prettyprint-override"><code>#elif defined(__AVR_ATmega32U4__) #define AVAILABLE_TONE_PINS 1 #define USE_TIMER3 const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 3 /*, 1 */ }; static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ }; </code></pre> <p>which shows that the code is configured to use timer 3 on this particular chip. In Servo.h I have:</p> <pre class="lang-c++ prettyprint-override"><code>#elif defined(__AVR_ATmega32U4__) #define _useTimer1 typedef enum { _timer1, _Nbr_16timers } timer16_Sequence_t ; </code></pre> <p>which shows it should use timer 1, and not conflict with Tone.cpp.</p> <p>It seems we have different versions of Servo.h. Mine is from Arduino 1.0.5. You may try to fix the problem by modifying the relevant section of either file (just after <code>#elif defined(__AVR_ATmega32U4__)</code>) and have them use different timers.</p> <p><strong>Edit</strong>: It appears this issue has already been fixed... on June 2012! See this diff: <a href="https://github.com/arduino/Arduino/commit/f60f17f79ae383a948a9cc4baa8bd0983fad6465" rel="nofollow">Avoid TIMER3 conflict with Servo and tone()</a> on the Arduino GitHub repository. The simplest fix in your case may be to just upgrade your Arduino software. You could also manually apply that (really small) diff to your current copy.</p>
12175
|pwm|attiny|spi|
Is crystal mandatory on attiny84?
2015-05-27T17:03:22.547
<p>I am trying to make a mini project with attiny84 and I searched the web so I can make an arduino on breadboard. What I saw on the internet is that they didnt use crystal. Is it mandatory if I want to use 1 pwm pin and the SPI interface on the attiny84?</p>
<p>Only if you need crystal accuracy. If the internal RC oscillator is accurate enough then feel free to use it instead.</p>
12179
|arduino-uno|led|pwm|attiny|
ATTiny to drive LEDs
2015-05-27T22:15:20.147
<p>I'm installing some daylight running lights in my car and I have purchased 2 LED bars, each with 8 white LEDs. They use 12V and I need to make some effect when they turn on. Like in some modern cars, when I turn on the key, LEDs should blink(shake like when old fluorescent tubes turns on) and then turn on slowly(brightness from 0-100).</p> <p>I can do this with Arduino-Uno and I need to put this in a smaller chip. What would be the best suitable ATTiny chip for this project? Because using an ATmega328 is not worth for a small project like this.</p>
<p>The <a href="http://www.atmel.com/devices/attiny85.aspx" rel="nofollow">ATtiny85</a> is an 8-pin AVR device with 3 PWM channels available in DIL and SO packages. The Arduino core can be downloaded from <a href="https://code.google.com/p/arduino-tiny/" rel="nofollow">arduino-tiny</a>. It can be programmed via ISP using either <a href="http://www.arduino.cc/en/Tutorial/ArduinoISP" rel="nofollow">ArduinoISP</a> or a dedicated programmer.</p>
12181
|i2c|lcd|
How do I use two I2C LCDs with 4 pins?
2015-05-27T22:57:55.987
<p>I have two I2C LCD screens:</p> <ul> <li>one with 2 lines</li> <li>one with 4 lines.</li> </ul> <p>Both have 4 pins each: <code>GND</code>, <code>VCC</code>, <code>SDA</code>, <code>SDL</code>. I connect <code>SDA</code> and <code>SDL</code> to <code>A4</code> and <code>A5</code> respectively, and I display text on each one of them with:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; LiquidCrystal_I2C lcd(0x27,16,4); </code></pre> <p>But how can I use both of them at the same time?</p> <p>I connected the second one's <code>SDA</code> and <code>SDL</code> to <code>A2</code> and <code>A3</code>, but apparently I have to provide the right address for them (like <code>0x27</code>), right? </p> <p>However, while both are connected, using <a href="http://playground.arduino.cc/Main/I2cScanner" rel="noreferrer">I2C_Scanner</a> only shows one device:</p> <pre><code>Scanning... I2C device found at address 0x27 ! done </code></pre> <p>What am I missing?</p>
<p><strong>With the I2C backpack there are three pairs of landings, A0, A1, A2, which determine the 3 LSB of the device's address, using inverted binary.</strong> </p> <p>Left alone, they generate part of the F or 7 part of the address. 0x3F is common, as is 0x27.</p> <p><strong>To use more than one device it is necessary to jumper them all uniquely.</strong></p> <p>The upper bits that generate the 0x3 are hard-wired. So is the highest bit of the lower byte. Only the three lowest-order bits can be changed.</p> <p>Since these address bits are inverted, jumpering the A0 will subtract 1 from the address. 0x3F will become 0x3E, 7 will become 6. </p> <p><strong>You have control enough to make up to 7 LCD modules on the same I2C bus.</strong> </p> <p>The only caveat is that if you have more than one device writing to the various LCDs you might get collisions, which can mess up the display pretty good. </p> <p>There are questions on I2C collision avoidance and detection on <a href="http://RaspberryPi.StackExchange.com">http://RaspberryPi.StackExchange.com</a> if that is your situation.</p> <p><strong>Jumpering one or more of them is pretty easy - just pre-tin some wire and solder it quickly then cut off the excess.</strong></p> <p>Wire the SDA and SCL wires of the LCDs in parallel and to the SDA and SCL pins on the Arduino, usually A4 and A5. (I always begin with a breadboard for this). Make sure you have discrete pull-up resistors (10K is common) on each, in only one place on the bus.</p> <p>If you have a DS3231 RTC module in the system, you do not need to add pull-ups because it has them internally.</p> <p>If one LCD is already working then you know you have proper pull-up voltage on the bus. (The signals are switched to the ground state to send data on the I2C bus)</p> <h2>So, to Summarize:</h2> <p>If you have two LCDs in your system you can use LCD modules that already come with different addresses, like </p> <pre><code>LiquidCrystal_I2C lcd1(0x27,....); </code></pre> <p>for the first one, then </p> <pre><code>LiquidCrystal_I2C lcd2(0x3F,.....); </code></pre> <p>for the second one. </p> <h2>Note that the parameters for these definitions are</h2> <pre><code>LiquidCrystal_I2C lcdname(addr,en,rw,rs,d4,d5,d6,d7,bl,blpol); </code></pre> <p>0x27 and 0x3F are the most common stock addresses and <strong>0x27 modules are getting harder to find.</strong> </p> <p>If you have a 0x27 then it is very likely that if you buy a newer one it will be 0x3f. <strong>Problem solved.</strong></p> <p>The d4 and d5 in the definition specifies the pins to use for I2C. </p> <p>You can run the i2cscanner program to see what it finds, once they are wired together. If you see two different addresses, say 0x27 and 0x3F, then you are good to go. </p> <p>If only 2F shows, then you want to consider soldering A0 together on one module then run the scanner again to make sure it worked.</p> <h2>Here is how I usually do it when both come set as 0x3f:</h2> <p><strong>I have a Yellow one which is a stock 0x3F and a Blue one where I jumpered A0 to make it 0x3E. They both are 20 x 4 displays.</strong></p> <p>Here are my definitions: (remember, the 4,5 define SDA, SCL pins)</p> <pre><code>LiquidCrystal lcdblue (0x3e,2,1,0,4,5,6,7,3,POSITIVE); LiquidCrystal lcdyellow(0x3f,2,1,0,4,5,6,7,3,POSITIVE); </code></pre> <p>Then in setup() I use this:</p> <pre><code>lcdblue.begin(20,4); lcdblue.backlight(); delay(250); lcdblue.nobacklight(); delay(250); lcdblue.backlight(); lcdyellow.begin(20,4); lcdyellow.backlight(); delay(250); lcdyellow.nobacklight(); delay(250); lcdyellow.backlight(); </code></pre> <p>And it's good to go, using pin A4 as SDA and A5 as SCL.</p> <p>You know they are working as they wink their backlights at you.</p> <p>If one of yours is 20 x 2 then use <code>lcd2.begin(20,2);</code> of course.</p> <p>If you REALLY want to use other pins for your I2C bus then just change the 4,5 in the <code>LiquidCrystal_I2C</code> definition to the pins you want to use. I never have met anyone who would want to do this.</p> <p>Hope this helps.</p>
12184
|arduino-pro-mini|button|nrf24l01+|
Pressing button stops listening on nrf24l01
2015-05-27T23:43:51.990
<p>I have been tinkering for 2 days to manage send and receive between 2 arduinos. My code is bellow:</p> <p>Arduino 1:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;RF24.h&gt; #include "printf.h" #define LED 2 #define RF_CS 8 #define RF_CSN 9 RF24 radio(8,9); String datargb = "rgb: 000000005"; char chartosend; char inchar; String inradio; int endchar = '~'; void check_radio(void); void setup() { // put your setup code here, to run once: Serial.begin(115200); printf_begin(); radio.begin(); radio.setRetries(15,15); radio.openWritingPipe(0x080C600C01LL); radio.openReadingPipe(1,0x080C600C71LL); radio.setPALevel(RF24_PA_MAX); radio.setAutoAck(true); radio.printDetails(); attachInterrupt(0, check_radio, FALLING); radio.stopListening(); } void loop() { // put your main code here, to run repeatedly: int lnth = datargb.length(); for(int i=0; i&lt;lnth; i++){ chartosend=datargb.charAt(i); while(!radio.write( &amp;chartosend, sizeof(chartosend) )){} Serial.println("sent"); } radio.write(&amp;endchar,1); } void check_radio(void){ bool tx,fail,rx; radio.whatHappened(tx,fail,rx); if(rx){ Serial.println("interrupt!!"); radio.startListening(); radio.read( &amp;inchar, sizeof(inchar) ); inradio+=inchar; Serial.println(inchar); if(inradio.endsWith("~")){ Serial.println(inradio); if(inradio.startsWith("rgb: ")){ analogWrite(6,inradio.substring(5,8).toInt()); analogWrite(9,inradio.substring(8,11).toInt()); analogWrite(5,inradio.substring(11,14).toInt()); } inradio = ""; radio.stopListening(); } } } </code></pre> <p>Arduino 2:</p> <pre><code>#include &lt;SPI.h&gt; //#include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; #include "printf.h" //#include &lt;RF24_config.h&gt; RF24 radio(8,10); char data; char chartosend; char endchar = '~'; String inradio; void check_radio(void); String datargb = "To mounti tis manas tou nrf24"; void setup() { // put your setup code here, to run once: pinMode(9, OUTPUT); pinMode(5, OUTPUT); pinMode(6, OUTPUT); pinMode(7, INPUT); attachInterrupt(1, check_radio, FALLING); Serial.begin(115200); printf_begin(); radio.begin(); //radio.setRetries(2,15); // open pipe for writing radio.openReadingPipe(1,0x080C600C01LL); radio.openWritingPipe(0x080C600C71LL); radio.setPALevel(RF24_PA_MAX); radio.startListening(); radio.printDetails(); radio.setAutoAck(true); } void loop() { // put your main code here, to run repeatedly: if(digitalRead(7)==HIGH){ radio.stopListening(); for(int i=0; i&lt;28; i++){ chartosend=datargb.charAt(i); while(!radio.write( &amp;chartosend, sizeof(chartosend) )){} //Serial.println("sent"); } radio.write(&amp;endchar,1); while(digitalRead(7)==HIGH){} radio.startListening(); } } void check_radio(void){ bool tx,fail,rx; radio.whatHappened(tx,fail,rx); if(rx){ Serial.println("interrupt!!"); //radio.startListening(); radio.read( &amp;data, sizeof(data) ); inradio+=data; Serial.println(data); if(inradio.endsWith("~")){ Serial.println(inradio); if(inradio.startsWith("rgb: ")){ analogWrite(6,inradio.substring(5,8).toInt()); analogWrite(9,inradio.substring(8,11).toInt()); analogWrite(5,inradio.substring(11,14).toInt()); } inradio = ""; //radio.stopListening(); } } } </code></pre> <p>Arduino 2 receives all data from ar1 but when I press the button attached to the pin 7 arduino 2 stops listening and only sends the first character of the string.</p>
<p>@Gerber remarked:</p> <p>There is probably a death-lock situation where both arduino's are trying to send data the the other, while both aren't listening. So both are waiting for the other to ack. Like I said at your previous question. Why not send all rgb data in one packet. Also, there is no need to call <code>radio.stopListening</code>.</p> <p>You send one char, and wait for and ACK. Then you send the next char and wait for an ACK. If the other unit doesn't process the message, the buffer will will up after 3 messages, and it will no longer send an ACK (because the buffer is full), and you while loop will hang</p>
12198
|arduino-pro-mini|data-type|
Sending struct from Arduino to Raspberry Pi - wrong types
2015-05-28T19:40:58.097
<p>I'm using Raspberry Pi and Arduinos for my home automation project where Raspberry Pi is the controler of Arduino nodes. I use nRF24 wireless transceivers to communicate.</p> <p>My problem is that when I was sending a structure like following</p> <pre><code>struct TempSensorData </code></pre> <p>{ uint32_t result; uint32_t temperature; uint32_t humidity; };</p> <p>From Raspberry to Raspberry everything went fine but now when I use Arduino as sender I get very strange results:</p> <pre><code>received: status: 335544320, temperature: 754974720 degrees, humidity: 0% </code></pre> <p>While on Raspberry it was</p> <pre><code>received: status: 0, temperature: 22 degrees, humidity: 44% </code></pre> <p>Can this be a problem with types? Or with different type of architecture (like different sizes on 3-2bit and 64-bit arch)?</p> <p>EDIT:</p> <p>Code on Raspberry:</p> <pre><code>if (radio.available()) </code></pre> <p>{ // dump the payloads until we've got everything Message receivedData = {0}; radio.read(&amp;receivedData, sizeof(Message)); TempSensorData data = receivedData.msgData.tempSensorData; std::cout &lt;&lt; "received: status: " &lt;&lt; data.result &lt;&lt; ", temperature: " &lt;&lt; data.temperature &lt;&lt; " degrees, humidity: " &lt;&lt; data.humidity &lt;&lt; "%" &lt;&lt; std::endl; //TODO here we have some strange numbers - check if we have proper types }</p> <p>Before that I have:</p> <pre><code>radio.begin(); radio.setPALevel(RF24_PA_LOW); radio.setChannel(0x4c); radio.openReadingPipe(1, RASPI_READ_ADDR); radio.openWritingPipe(RASPI_WRITE_ADDR); radio.enableDynamicPayloads(); radio.setAutoAck(true); radio.powerUp(); radio.startListening(); </code></pre> <p>And on Arduino:</p> <pre><code>Header header = {thisNodeId, thisNodeType, 0, static_cast&lt;uint8_t&gt;(MsgType::TEMP_SENSOR_DATA), 12345, Status::ok}; TempSensorData dhtData; dhtData.result = DHT.read11(DHT11_PIN); dhtData.humidity = (int)DHT.humidity; dhtData.temperature = (int)DHT.temperature; Message message = {0}; message.header = header; message.msgData.tempSensorData = (dhtData); radio.stopListening(); radio.write(&amp;message, sizeof(message)); radio.startListening(); </code></pre> <p>I also use a common header with defined structures for both Arduino and Raspberry, which contains:</p> <pre><code>#define RASPI_WRITE_ADDR 0xF0F0F0F0F0LL #define RASPI_READ_ADDR 0xF0F0F0F0E1LL struct TempSensorData { uint32_t result; uint32_t temperature; uint32_t humidity; }; enum class Status : uint8_t </code></pre> <p>{<br> ok, error, fail };</p> <pre><code>enum class MsgType : uint8_t { INITIALIZATION, RESET_REQUEST, ACK_NACK, TEMP_SENSOR_DATA, }; struct Header { uint8_t nodeId; uint8_t nodeType; uint8_t location; uint8_t msgType; uint16_t checksum; Status status; }; union MsgData { InitMsgData initMsgData; AckNack ackNack; TempSensorData tempSensorData; }; struct Message { Header header; MsgData msgData; }; </code></pre> <p><code>radio</code> is an item of RF24 class from <a href="https://github.com/TMRh20/RF24/" rel="nofollow noreferrer">https://github.com/TMRh20/RF24/</a></p> <p>Unfortunately the RF24 repo is 64 commits ahead of what I use.</p> <p><strong>EDIT2:</strong></p> <p>Maybe the problem lays in that </p> <pre><code>enum class Status {}; </code></pre> <p>which I use in both files.</p> <p>I must add that I use g++-4.7 when compiling on Raspberry and when compiling on Arduino I use avr-g++-4.8.2</p>
<p>You may have multiple problem. First of all the structure get align to be efficient on the specific architecture, to avoid those filling you have to tell the compiler to pack the structure. There are different way to pack depending on compiler used.</p> <p>Then endianess is different, so the byte composing the value has to be swapped.</p> <p>Finally there may be a desincronization or a bus error. In those case a sync message (normally 2 byte before each transmission) and a CRC are used to fix the issue.</p>
12203
|lcd|
How to program LCD shield?
2015-05-28T22:03:41.257
<p>So I'm using the DFRobot LCD Keypad shield to make a text-based game. Can someone give me an example? Let's just say i want to make the LCD display "text1" and then press up then select, it displays "text2". If I press down then press select, it displays "text3".</p>
<p>Attach the shield to arduino then run the following code to check if everything is ok. Wiring is made default.</p> <pre><code>#include &lt;LiquidCrystal.h&gt; LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // select the pins used on the LCD panel // define some values used by the panel and buttons int lcd_key = 0; int adc_key_in = 0; #define btnRIGHT 0 #define btnUP 1 #define btnDOWN 2 #define btnLEFT 3 #define btnSELECT 4 #define btnNONE 5 int read_LCD_buttons(){ // read the buttons adc_key_in = analogRead(0); // read the value from the sensor // my buttons when read are centered at these valies: 0, 144, 329, 504, 741 // we add approx 50 to those values and check to see if we are close // We make this the 1st option for speed reasons since it will be the most likely result if (adc_key_in &gt; 1000) return btnNONE; // For V1.1 us this threshold if (adc_key_in &lt; 50) return btnRIGHT; if (adc_key_in &lt; 250) return btnUP; if (adc_key_in &lt; 450) return btnDOWN; if (adc_key_in &lt; 650) return btnLEFT; if (adc_key_in &lt; 850) return btnSELECT; // For V1.0 comment the other threshold and use the one below: /* if (adc_key_in &lt; 50) return btnRIGHT; if (adc_key_in &lt; 195) return btnUP; if (adc_key_in &lt; 380) return btnDOWN; if (adc_key_in &lt; 555) return btnLEFT; if (adc_key_in &lt; 790) return btnSELECT; */ return btnNONE; // when all others fail, return this. } void setup(){ lcd.begin(16, 2); // start the library lcd.setCursor(0,0); // set the LCD cursor position lcd.print("Push the buttons"); // print a simple message on the LCD } void loop(){ lcd.setCursor(9,1); // move cursor to second line "1" and 9 spaces over lcd.print(millis()/1000); // display seconds elapsed since power-up lcd.setCursor(0,1); // move to the begining of the second line lcd_key = read_LCD_buttons(); // read the buttons switch (lcd_key){ // depending on which button was pushed, we perform an action case btnRIGHT:{ // push button "RIGHT" and show the word on the screen lcd.print("RIGHT "); break; } case btnLEFT:{ lcd.print("LEFT "); // push button "LEFT" and show the word on the screen break; } case btnUP:{ lcd.print("UP "); // push button "UP" and show the word on the screen break; } case btnDOWN:{ lcd.print("DOWN "); // push button "DOWN" and show the word on the screen break; } case btnSELECT:{ lcd.print("SELECT"); // push button "SELECT" and show the word on the screen break; } case btnNONE:{ lcd.print("NONE "); // No action will show "None" on the screen break; } } } </code></pre>
12212
|c++|nrf24l01+|timing|
bi-directional nrf24 communication
2015-05-29T00:44:34.973
<p>The central arduino <img src="https://i.stack.imgur.com/LnAZh.png" alt="The central arduino"> The 1st node <img src="https://i.stack.imgur.com/HrrK8.png" alt="The 1st node"> The 2nd node <img src="https://i.stack.imgur.com/LT4Vu.png" alt="The 2nd node"></p> <p>I want the central to send to the first node the rgb code like a string on the loop</p> <blockquote> <p>"rgb: 255000255"</p> </blockquote> <p>but when it detects something to PIR to send a string to central. In addition every some seconds the 2nd node to send a string to the central the temperature.</p> <p>As i mentioned in my previous questions i have some problems when it comes to the bi-directional comunication. I have tried a lot of code. Can someone show me how to achieve what i want to do if not with code, with steps. Please help me!!</p>
<p><strong>You <em>cannot</em> (easily) have all nodes on the network with the same address.</strong></p> <p>There are ways of doing it but they aren't easy. They basically involve creating a "broadcast" facility in your network, and that has certain caveats involved with it.</p> <p>The nRF24L01 modules have an "auto-ACK" mode to give reliable communications. <em>This only works with 1:1 addressing</em> and cannot work with broadcast. If you want to (as most people do) use the auto-ACK facility then you have to have each node with its own unique address. After all, if you're sending the <em>ACK</em> to a station, and there are multiple stations with that address, <em>which one will ACK?</em></p> <p>So you have to think about if what you are trying to achieve is really the right way of going about it. It sounds like you want to just program another node with the same code as an existing node without making any changes to that code and "just have it work". That's a very advanced topic and one that even I would spend quite some time implementing it. Yes, you can do unreliable communications (i.e., no auto-ACK) then you could have all the remote stations with the same address, but I would certainly keep the master as a unique address. Better would be for each node to start up with a pre-defined address which it then uses to ask the master for a unique address (a-la DHCP) and the master then keeps a list of what is connected on what address. From then on it can use reliable communications to send and receive data to each node as it needs to.</p> <p><a href="https://github.com/MajenkoLibraries/nrf24l01" rel="nofollow">A system I wrote for the chipKIT boards</a> gives each node two addresses - its own unique address which you have to provide manually, and a more global "broadcast" address. They are each on different pipes within the nRF24L01. To communicate with an individual node you send to its unique address. To broadcast to all nodes you send to the broadcast address. If you're sending to the unique address you can then turn on auto-ACK. If you're sending to the broadcast address you don't turn on auto-ACK.</p> <p>Note that using auto-ACK is a whole topic in itself and requires careful design planning to get it to work properly.</p> <p>Also you have to think about what happens when you send a broadcast packet out and it's received by other nodes - how do they handle that data? Sending temperature data out globally, it will be received by the RGB receiver, which may try and interpret it, causing problems. You need to come up with a way of identifying just what it is you're sending out and only having the right nodes responding to the right data. That means coming up with a strict packet format. Luckily the nRF24L01 chips communicate in fixed packet sizes (incidentally, all nodes on the network will have to be set to use the same packet size or it just won't work) up to 32 bytes, so implementing a packet structure over that is easy enough. Just sending strings of data is both hard to interpret and incredibly inefficient. You should be sending the data as actual data values in variables as part of the packet structure.</p>
12237
|arduino-uno|
How to call a file from the arduino?
2015-05-29T17:36:58.697
<p>I am aware of the simplicity of the question. Nevertheless... </p> <p>I need to code into the arduino the execution of a file. More precisely a .exe. To put things in perspective. I have little to no knowledge of coding. Yet I need to put together a photocabin. I have the arduino to count the coins inserted to my coin collector and I need to take a picture when the precise ammount is reached. Then reset the ammount to avoid taking more pictures. here is what my code looks so far: (taken from the examples on the arduino page)</p> <pre><code>const int coinInt = 0; //Attach coinInt to Interrupt Pin 0 (Digital Pin 2). Pin 3 = Interrpt Pin 1. volatile float coinsValue = 0.00; //Set the coinsValue to a Volatile float //Volatile as this variable changes any time the Interrupt is triggered int coinsChange = 0; //A Coin has been inserted flag void setup() { Serial.begin(9600); //Start Serial Communication attachInterrupt(coinInt, coinInserted, RISING); //If coinInt goes HIGH (a Pulse), call the coinInserted function //An attachInterrupt will always trigger, even if your using delays } void coinInserted() //The function that is called every time it recieves a pulse { coinsValue = coinsValue + 0.05; //As we set the Pulse to represent 5p or 5c we add this to the coinsValue coinsChange = 1; //Flag that there has been a coin inserted } void loop() { if(coinsChange == 1) //Check if a coin has been Inserted { coinsChange = 0; //unflag that a coin has been inserted if(coinsValue &gt;= 0.30) { here goes the code to open a file, then the code to reset coinsValue } } } </code></pre> <p>Thanks a million.</p>
<p>I used the following code to run a program, not from the arduino, but from software listening to a specific character sent from the arduino. Thanks for your help. I share the code that I used. It doesn´t need to print the character, but I copied it exactlyy from microsoft help pages (lost the link). I just aded the if statement and the start.process part (I got this from a stackoverflow answer). Without any further delay:</p> <pre><code>using System; using System.IO.Ports; using System.Diagnostics; class PortDataReceived { public static void Main() { SerialPort mySerialPort = new SerialPort("COM3"); mySerialPort.BaudRate = 9600; mySerialPort.Parity = Parity.None; mySerialPort.StopBits = StopBits.One; mySerialPort.DataBits = 8; mySerialPort.Handshake = Handshake.None; mySerialPort.RtsEnable = true; mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); mySerialPort.Open(); Console.WriteLine("Press any key to continue..."); Console.WriteLine(); Console.ReadKey(); mySerialPort.Close(); } private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(indata); if (indata == "c") { Process.Start(@"C:\Users\Laptop\Desktop\print.ahk"); } } } </code></pre>
12239
|library|nrf24l01+|
What is the type parameter on the NRF24NetworkHeader member
2015-05-29T18:00:18.707
<p><a href="http://maniacbug.github.io/RF24Network/structRF24NetworkHeader.html#a99e675f31589d72cf2fe036e77988026" rel="nofollow">Link of the member</a> What is the character parameter in the above member of the class NRF24Network I cannot understand the use of it.</p>
<p>It's to identify the type of packet. Apparently that code supports types of 0-127, and I guess (impossible to tell without digging into the code) that what you use them for is entirely up to you. Basically it would typically define what is in the rest of the packet - again something which is up to you.</p>
12254
|arduino-uno|
DHT22 Does not update
2015-05-30T16:13:16.027
<p>Good evening :)</p> <p>I am fairily new to coding the fabulous Arduino UNO. My project right now are consisting of reading Temperature from a DHT22 (AM2302) and writing to a 4-digit 7-segment display. I have got the display to work, but the system does not update the temperature at all. Just the first reading are displayed</p> <pre><code>#include &lt;DHT.h&gt; #include &lt;TimerOne.h&gt; #include &lt;SevenSeg.h&gt; #define DHTPIN 4 //Defines the temp-pin /* DHT22- Pin1 (left) - 5V/3.3V Pin2- DATA Connect a 10K res from pin1 to pin2 Pin3 - NC Pin4 - GND */ //#define DHTTYPE DHT11 // DHT 11 #define DHTTYPE DHT22 // DHT 22 (AM2302) //#define DHTTYPE DHT21 // DHT 21 (AM2301) DHT dht(DHTPIN, DHTTYPE); SevenSeg disp (13 ,2 ,3 ,8 ,5 ,6 ,7); // (11, 7, 4, 2, 1, 10, 5) const int numOfDigits =4; int digitPins [ numOfDigits ]={9,10,11,12}; // uten transistorer // (12,9,8,6) Alle med 220 Ohm seriemotstand //int digitPins [ numOfDigits ]={12,11,10,9}; // med transistorer void setup () { Serial.begin(9600); Serial.println("DHT22"); disp . setCommonCathode(); // uten transistorer //disp . setActivePinState(HIGH,HIGH); // med transistoere disp . setDigitPins ( numOfDigits , digitPins ); Timer1.initialize(15); // 0.015 sek Timer1.attachInterrupt(loop); } void loop() { dht.begin(); delay(300); float t = dht.readTemperature(); disp.writeFloat(t); Serial.println(t); } </code></pre> <p>How do I get the Sensor to update regularly?</p>
<p>Try moving <code>dht.begin();</code> to <code>setup()</code>. </p> <p>The DHTs are pretty slow and need some time (of the order of seconds!) between consecutive reads. In <code>dht.begin()</code> an internal timer is reset that is used in <code>readTemperature()</code> to ensure that reading data from the DHT is not attempted in shorter intervals than supported. By calling <code>dht.begin()</code> every 300 ms you're making this meachanism inoperative. You're supposed to call <code>dht.begin()</code> only once at start-up.</p> <p><strong>Edit</strong>: And please also remove the <code>Timer1</code> that calls <code>loop</code>. <code>loop</code> is already an infinite loop, so no good in calling it additionally from an interrupt...</p>
12264
|gsm|gps|
Cheapest Arduino GPRS or 3G solution
2015-05-31T11:55:37.360
<p>I am looking at creating a fleet of low power, Arduino driven devices.</p> <p>I would need some kind of GPS on them all (or could triangulate through phone network?) plus a connection to the internet - just for HTTP POST requests. GPRS or GSM would do but 3G would be better.</p> <p>What are the best (price is a major factor because I'm trying to do a fleet) GSM, GPRS or 3G modules that I can use with Arduinos? As I said, I need their location so one with GPS built in would be great.</p> <p>EDIT: The amount of devices in the fleet will change, so the entire network needs to be dynamic which is why having a GPRS/GSM module on each one would work so well.</p>
<p>If you are finding Cheapest and working module you can you SIM800L less then 4$. </p> <p><a href="https://i.stack.imgur.com/YtyoZ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YtyoZ.jpg" alt="Sim800L"></a></p> <pre><code>aliexpress.com/item/Free-Shipping-Smallest-SIM800L-GPRS-GSM-Module-MicroSIM-Card-Core-BOard-Quad-band-TTL-Serial-Port/32708504554.html </code></pre> <p>You can find many other cheap alternative but they does not work properly.</p> <p>Sim800 have good support and you can find many examples to use this with arduino.</p> <p>Many other model also available in market as per your requirements. </p>
12273
|power|
Arduino UNO/ZERO PRO, enough computing power for PID-controller?
2015-05-31T18:20:33.510
<p>I am currently working on a project, where I design a PID-Controller for a 2-axis stabilization with brushless-propeller-motors.</p> <p>My question is: Does an Arduino UNO have enough computing power to perform this task in a useful manner? <a href="http://www.arduino.cc/en/Main/ArduinoBoardUno" rel="nofollow">Arduino UNO Specs</a></p> <p>And secondly: If the UNO was really too slow for this task, would the newly released Arduino ZERO PRO perform at an acceptable rate? <a href="http://www.arduino.cc/en/Main/ArduinoBoardZero" rel="nofollow">Arduino ZERO PRO Specs</a></p> <p>Thanks for your help and inputs in advance!</p>
<p>Assuming you're not doing anything too fancy, yes, it should be fine.</p> <p>There's even a library to do all the work for you: <a href="http://playground.arduino.cc/Code/PIDLibrary">http://playground.arduino.cc/Code/PIDLibrary</a></p>
12279
|arduino-uno|lcd|display|
Change code so motion sensor prints time instead of a button
2015-05-31T23:59:05.230
<p>I have the code below. At the moment there is a proximity sensor that makes a speaker play happy birthday when it is set off. I also have an LCD shield attached and when one of the buttons on LCD screens interface is pressed, the time that it was when the button was pressed prints on the screen. I need to get it so that when the proximity sensor is set off it plays the sound on the speaker and then prints the time which is was set off on the screen. </p> <pre><code>/*-------------------------------------------------------------------------------------- Includes --------------------------------------------------------------------------------------*/ #include &lt;Wire.h&gt; #include &lt;LiquidCrystal.h&gt; // include LCD library int timer = 1000; int C = 262; int D = 294; int E = 330; int F = 349; int G = 392; int A = 440; int B = 494; int Bflat = 466; int Chigh = 523; const int analogPin = A1; // pin that the sensor is attached to const int threshold = 400; /*-------------------------------------------------------------------------------------- Defines --------------------------------------------------------------------------------------*/ // Pins in use #define MILLIS_OVERFLOW 34359738 #define BUTTON_ADC_PIN A0 // A0 is the button ADC input #define LCD_BACKLIGHT_PIN 3 // D3 controls LCD backlight // ADC readings expected for the 5 buttons on the ADC input #define RIGHT_10BIT_ADC 0 // right #define UP_10BIT_ADC 145 // up #define DOWN_10BIT_ADC 329 // down #define LEFT_10BIT_ADC 505 // left #define SELECT_10BIT_ADC 741 // right #define BUTTONHYSTERESIS 10 // hysteresis for valid button sensing window //return values for ReadButtons() #define BUTTON_NONE 0 // #define BUTTON_RIGHT 1 // #define BUTTON_UP 2 // #define BUTTON_DOWN 3 // #define BUTTON_LEFT 4 // #define BUTTON_SELECT 5 // //some example macros with friendly labels for LCD backlight/pin control, tested and can be swapped into the example code as you like #define LCD_BACKLIGHT_OFF() digitalWrite( LCD_BACKLIGHT_PIN, LOW ) #define LCD_BACKLIGHT_ON() digitalWrite( LCD_BACKLIGHT_PIN, HIGH ) #define LCD_BACKLIGHT(state) { if( state ){digitalWrite( LCD_BACKLIGHT_PIN, HIGH );}else{digitalWrite( LCD_BACKLIGHT_PIN, LOW );} } /*-------------------------------------------------------------------------------------- Variables --------------------------------------------------------------------------------------*/ unsigned long currentMillis, previousMillis, elapsedMillis; int seconds = 0, minutes = 34, hours = 8; byte buttonJustPressed = false; //this will be true after a ReadButtons() call if triggered byte buttonJustReleased = false; //this will be true after a ReadButtons() call if triggered byte buttonWas = BUTTON_NONE; //used by ReadButtons() for detection of button events /*-------------------------------------------------------------------------------------- Init the LCD library with the LCD pins to be used --------------------------------------------------------------------------------------*/ LiquidCrystal lcd( 8, 9, 4, 5, 6, 7 ); //Pins for the freetronics 16x2 LCD shield. LCD: ( RS, E, LCD-D4, LCD-D5, LCD-D6, LCD-D7 ) /*-------------------------------------------------------------------------------------- setup() Called by the Arduino framework once, before the main loop begins --------------------------------------------------------------------------------------*/ void setup() { //button adc input pinMode( BUTTON_ADC_PIN, INPUT ); //ensure A0 is an input digitalWrite( BUTTON_ADC_PIN, LOW ); //ensure pullup is off on A0 //lcd backlight control digitalWrite( LCD_BACKLIGHT_PIN, HIGH ); //backlight control pin D3 is high (on) pinMode( LCD_BACKLIGHT_PIN, OUTPUT ); //D3 is an output //set up the LCD number of columns and rows: pinMode(13, OUTPUT); lcd.begin( 16, 2 ); //Print some initial text to the LCD. Serial.begin(9600); lcd.begin( 16, 2 ); } /*-------------------------------------------------------------------------------------- loop() Arduino main loop --------------------------------------------------------------------------------------*/ void loop() { setClock(); byte button; button = ReadButtons(); /** * After set clock now you have 3 int variables with the current time */ //seconds //minutes //hours lcd.setCursor ( 0, 1); lcd.print(hours); lcd.print(":"); lcd.print(minutes); lcd.print(":"); lcd.print(seconds); lcd.print(":"); lcd.print(elapsedMillis); //get the latest button pressed, also the buttonJustPressed, buttonJustReleased flags //blank the demo text line if a new button is pressed or released, ready for a new label to be written //show text label for the button pressed if(buttonJustPressed || buttonJustReleased) switch( button ) { case BUTTON_LEFT: { lcd.setCursor( 0, 0 ); lcd.print(hours); lcd.print(":"); lcd.print(minutes); lcd.print(":"); lcd.print(seconds); lcd.print(":"); lcd.print(elapsedMillis); break; } default: { break; } } if( buttonJustPressed ) buttonJustPressed = false; if( buttonJustReleased ) buttonJustReleased = false; } /*-------------------------------------------------------------------------------------- ReadButtons() Detect the button pressed and return the value Uses global values buttonWas, buttonJustPressed, buttonJustReleased. --------------------------------------------------------------------------------------*/ byte ReadButtons() { unsigned int buttonVoltage; byte button = BUTTON_NONE; // return no button pressed if the below checks don't write to btn //read the button ADC pin voltage buttonVoltage = analogRead( BUTTON_ADC_PIN ); //sense if the voltage falls within valid voltage windows if( buttonVoltage &lt; ( RIGHT_10BIT_ADC + BUTTONHYSTERESIS ) ) { button = BUTTON_RIGHT; } else if( buttonVoltage &gt;= ( UP_10BIT_ADC - BUTTONHYSTERESIS ) &amp;&amp; buttonVoltage &lt;= ( UP_10BIT_ADC + BUTTONHYSTERESIS ) ) { button = BUTTON_UP; } else if( buttonVoltage &gt;= ( DOWN_10BIT_ADC - BUTTONHYSTERESIS ) &amp;&amp; buttonVoltage &lt;= ( DOWN_10BIT_ADC + BUTTONHYSTERESIS ) ) { button = BUTTON_DOWN; } else if( buttonVoltage &gt;= ( LEFT_10BIT_ADC - BUTTONHYSTERESIS ) &amp;&amp; buttonVoltage &lt;= ( LEFT_10BIT_ADC + BUTTONHYSTERESIS ) ) { button = BUTTON_LEFT; } else if( buttonVoltage &gt;= ( SELECT_10BIT_ADC - BUTTONHYSTERESIS ) &amp;&amp; buttonVoltage &lt;= ( SELECT_10BIT_ADC + BUTTONHYSTERESIS ) ) { button = BUTTON_SELECT; } //handle button flags for just pressed and just released events if( ( buttonWas == BUTTON_NONE ) &amp;&amp; ( button != BUTTON_NONE ) ) { //the button was just pressed, set buttonJustPressed, this can optionally be used to trigger a once-off action for a button press event //it's the duty of the receiver to clear these flags if it wants to detect a new button change event buttonJustPressed = true; buttonJustReleased = false; } if( ( buttonWas != BUTTON_NONE ) &amp;&amp; ( button == BUTTON_NONE ) ) { buttonJustPressed = false; buttonJustReleased = true; } //save the latest button value, for change event detection next time round buttonWas = button; return( button ); } void setClock() { currentMillis = millis(); /** * The only moment when currentMillis will be smaller than previousMillis * will be when millis() oveflows */ if (currentMillis &lt; previousMillis){ elapsedMillis += MILLIS_OVERFLOW - previousMillis + currentMillis; } else { elapsedMillis += currentMillis - previousMillis; } /** * If we use equals 1000 its possible that because of the mentioned loop limitation * you check the difference when its value is (999) and on the next loop its value is (1001) */ while (elapsedMillis &gt; 999){ seconds++; elapsedMillis = elapsedMillis - 1000; } if (seconds == 60){ minutes++; seconds = 0; } if (minutes == 60){ hours++; minutes = 0; } if (hours == 24){ hours = 0; } previousMillis = currentMillis; int analogValue = analogRead(analogPin); if (analogValue &gt; threshold) { tone(13,C,timer/2);// Happy Bday to You delay(200); tone(13,C,timer/2); delay(200); tone(13,D,timer/2); delay(400); tone(13,C,timer/2); delay(400); tone(13,F,timer/2); delay(400); tone(13,E,timer); delay(750); } else { } } </code></pre>
<p>The code seems a little hotchpotch; is the code for reading the sensor supposed to be within the <code>setClock()</code> function? It would be better to put the following within <code>loop()</code>:</p> <pre><code>if(analogRead(analogPin) &gt; threshold) { playMelody(); printTriggerTime(); } </code></pre> <p>And create two new functions that handle the playing of 'Happy Birthday' and the printing of the time:</p> <pre><code>void playMelody() { tone(13, C, timer / 2);// Happy Bday to you ... delay(750); } </code></pre> <p>...which is just a cut-paste of what you've got in the <code>setClock()</code> function, and:</p> <pre><code>void printTriggerTime() { lcd.setCursor(0, 0); ... lcd.print(elapsedMillis); } </code></pre> <p>...which is a copy-paste of the code from within <code>case BUTTON_LEFT:</code>.</p> <p>This will now play 'Happy Birthday' and print the time whenever the proximity sensor is triggered, AND it will print the time when the left-button is pressed (unless you remove that part of the code).</p> <p>On a separate point, it's bad coding practice to use <code>#define</code> for a function, as you have done with <code>#define LCD_BACKLIGHT(state) { if ( state )...</code> - it makes it quite difficult to read the code, and can't conceive any reason why this isn't its own function. However, a nice trick in C is the following 'shortcut' statement:</p> <pre><code>( CONDITION ? DO_IF_TRUE : DO_IF_FALSE ) </code></pre> <p>Thus you should change that line to:</p> <pre><code>#define LCD_BACKLIGHT(state) ( state ? digitalWrite(LCD_BACKLIGHT_PIN,HIGH) : digitalWrite(LCD_BACKLIGHT_PIN,LOW)) </code></pre> <p>That being said, "LCD_BACKLIGHT(state)" isn't actually used anywhere in the program!</p>
12285
|c++|arduino-ide|core-libraries|
How shiftOut function works internally? (explanation on source code)
2015-06-01T08:38:22.453
<p>I were examining <code>shiftOut()</code> function code in <code>wiring_shift.c</code> and I didn't quite understand what is going in digitalWrite function. I see <code>!!(val &amp; (1 &lt;&lt; i))</code> is taking the bit value from <code>val</code> but how exactly it works?</p> <p>The whole function is below.</p> <pre><code>void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val) { uint8_t i; for (i = 0; i &lt; 8; i++) { if (bitOrder == LSBFIRST) digitalWrite(dataPin, !!(val &amp; (1 &lt;&lt; i))); else digitalWrite(dataPin, !!(val &amp; (1 &lt;&lt; (7 - i)))); digitalWrite(clockPin, HIGH); digitalWrite(clockPin, LOW); } } </code></pre>
<p>I'll assume <code>bitOrder == LSBFIRST</code>.</p> <ul> <li><code>i</code> is the bit number, i.e. the “index” of the next bit to write</li> <li><code>1</code> is <code>00000001</code> in binary</li> <li><code>&lt;&lt;</code> is the shift left operator. It returns its first argument shifted left by as many positions as indicated by the second argument</li> <li><code>1&lt;&lt;i</code> is binary <code>00000001</code> shifted left by <code>i</code> positions, i.e. something like <code>0...010...0</code>, where the single 1 is in the i-th position counting from the right (rightmost being position 0)</li> <li><code>&amp;</code> is the “bitwise and operator”, where <code>any_bit &amp; 0</code> is zero and <code>any_bit &amp; 1</code> is <code>any_bit</code></li> <li><code>val &amp; (1 &lt;&lt; i)</code> is <code>0...0(i-th bit of val)0...0</code> in binary, where the i-th bit of val is in the i-th position of the result</li> <li><code>!!</code> is a double negation: it converts zero to zero and any non-zero value to one</li> <li><code>!!(val &amp; (1 &lt;&lt; i))</code> is either 0 or 1, and is exactly the i-th bit of val</li> </ul>
12304
|arduino-mega|variables|class|
Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop
2015-06-02T00:19:34.163
<p>I have this:</p> <pre><code>class Person{ public: int age; }; Person p; p.age; void setup() { ... } void loop() { ... } </code></pre> <p>And I got this error:</p> <pre><code>Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)' MyProgram.ino:18:1: error: 'p' does not name a type Error compiling </code></pre> <p>But is I use the Person instance inside setup or loop functions it compiles find.</p> <pre><code>void setup() { // initialize digital pin 13 as an output. Person p; p.age; } </code></pre> <p>I got this:</p> <pre><code>Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)' Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs) Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum) </code></pre> <p>What is the different? Why the instance only can be used into the blocks? </p> <p>I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?</p>
<p>As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it). More specifically, you can only perform "programatical" operations from within a <em>function</em>. Anything outside a function (known as the <em>global scope</em>) is purely for declaration and initialization of variables and types, etc.</p> <p>Any class variables declared in the <em>global scope</em> have their <em>constructor</em> executed before the rest of the program (even before <code>setup</code>) gets run. However, <code>setup</code> is not the first function to be called at startup.</p> <p>Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used. Things like <code>pinMode</code> and <code>digitalWrite</code> are unsafe to use in a constructor, since there is a chance they may be negated during the startup. That is why the majority of Arduino classes have a <code>.begin()</code> method which is called from <code>setup()</code>.</p> <p>The proper method for using classes with pin control and similar operations is:</p> <ol> <li>The constructor takes the pins to use</li> <li>The constructor saves those pins in variables</li> <li>The begin() method is called in setup()</li> <li>The pins are configured appropriately.</li> </ol> <p>For example:</p> <pre><code>class myClass { private: int _myPin; public: myClass(int pin) : _myPin(pin) {} void begin() { pinMode(_myPin, OUTPUT); digitalWrite(_myPin, HIGH); } }; myClass p(4); void setup() { p.begin(); } void loop() { } </code></pre> <p>The object instance <code>p</code> is in the <em>global scope</em> and can be referenced from any function. The pin is configured only when setup() is run.</p> <p>The startup sequence, more specifically, is typically this:</p> <ol> <li>The memory used by global and static variables is "zeroed".</li> <li>Any pre-defined variable values (<em>BSS</em>) are copied from flash into RAM.</li> <li>Any object constructors are called.</li> <li>The main() function is called (main startup function).</li> <li>The init() function is called which configures the Arduino platform.</li> <li>The initVariant() function is called which performs any board specific setup routines.</li> <li>USB is configured on the boards that have it</li> <li>Your setup() function is called.</li> <li>Your loop() function is called.</li> <li>The serialEvent() system runs if defined.</li> <li>Go to 10.</li> </ol> <p>As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be. Some boards may do nothing more than configure interrupts and enable timers (for things like <code>delay</code> and <code>millis</code>), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself. Anything outside the scope of the class could be changed before you come to use it.</p>
12312
|arduino-uno|arduino-motor-shield|
What is the difference between a motor driver and a motor shield?
2015-06-02T10:57:12.023
<p>what is the difference between a motor driver(like L293D) and a motor shield?</p> <p>what are the advantage?disadvantages of both?</p> <p>And which one do you suggest ?</p>
<p><em>A motor driver is a chip that drives motors. A motor shield is a circuit board with connections on it that contains a motor driver chip that drives motors.</em></p> <p><strong>A shield is convenient since you can just plug it into your Arduino and wire the motors direct to it, but it lacks the flexibility of a raw driver chip which you can wire up precisely as your project demands</strong></p>
12328
|power|arduino-leonardo|
Leonardo broken?
2015-06-02T20:02:00.460
<p>My leonardo was working fine until today, when I plug it to my computer all led (RX/TX/L/ON) stays on (Green for on, amber for others) and my computer no longer see a com port. (by the way, do you know what the L led mean ?) If I add external power, TX goes off then after few seconds RX goes off too then back on. With external power, the atmega goes very hot (I can't touch it). RESET button do nothing.</p> <p>Is my Leonardo dead ? Any idea what could have cause that ? The fact that the atmega is so hot when the board is powered up with 12V let me think that the voltage regulators is no longer working. Good guess ? </p>
<p>By your description, I'd say:</p> <blockquote> <p>Quite Probably.</p> </blockquote> <p>You should check what the 5V and 3.3V voltages are using a DMM.</p>
12331
|arduino-uno|
Being able to run two functions at once
2015-06-02T21:34:50.903
<p>So I am doing a project where a bunch of servos are moving from 90 - 120 degrees and slowly speed up over time until they reach their max speed and so stay at that speed. This is being done by editing the delay under the servo sweep for loop. However though this works it doesn't work with the next component.</p> <p>WHat I want to happen next is an MFRC522 RFID reader to always be scanning and at any time it detects a card and verifies it the servos from whatever speed they are now at start to slow down. The problem is I can't get the two functions to run simultaneously. IF the servo is running its sweep function it must finish before the RFID tag can scan. This makes the whole device look very lagy. Is there a way I can get the RFID scanner to be reading all the time even when the servo sweep for loop is working?</p> <p>Here is the code: Please note that I have put printins everywhere to see how often the RFID is scanning etc just while I test the code out. I essentially have two functions one called nocardservo and yescardservo each one activating if there is a card there or not. Any help would be fantastic!!</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;MFRC522.h&gt; #include &lt;Servo.h&gt; #define RST_PIN 9 // #define SS_PIN 10 // MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance Servo myservo; int pos = 0; int y = 15; int z = y; void setup() { myservo.attach(6); myservo.writeMicroseconds(1518); Serial.begin(9600); // Initialize serial communications with the PC while (!Serial); // Do nothing if no serial port is opened (added for Arduinos based on ATMEGA32U4) SPI.begin(); // Init SPI bus mfrc522.PCD_Init(); // Init MFRC522 //ShowReaderDetails(); // Show details of PCD - MFRC522 Card Reader details //Serial.println(F("Scan PICC to see UID, type, and data blocks...")); } void loop() { // Look for new cards if ( ! mfrc522.PICC_IsNewCardPresent()) { nocardservo(); return; } delay(20); Serial.println("carddetected"); // Select one of the cards if ( ! mfrc522.PICC_ReadCardSerial()) { } Serial.println("correctcard"); yescardservo(); delay(20); return; } //***If card not detected this function runs**// void nocardservo() { for (pos = 90; pos &lt; 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); // waits 15ms for the servo to reach the position } for (pos = 180; pos &gt;= 90; pos -= 1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(15); } } } //***If card is detected this function runs**// void yescardservo() { for (pos = 90; pos &lt; 180; pos += 1) // goes from 0 degrees to 180 degrees { // in steps of 1 degree myservo.write(pos); // tell servo to go to position in variable 'pos' delay(50); // waits 15ms for the servo to reach the position } for (pos = 180; pos &gt;= 90; pos -= 1) // goes from 180 degrees to 0 degrees { myservo.write(pos); // tell servo to go to position in variable 'pos' delay(50); } } </code></pre>
<p>have a look my example program below for you reference. </p> <pre><code>/* * Author BALASAIDULU.N * function -1 : Fading led with pwm pin 9 * fucntion -2 : Blinking LED on pin 13 * connect an LED on pin 9 with a 330 ohms resistor */ int leda=9; int ledd=13; int i,g,s1,s2; int switchPin=8; void setup() { pinMode(ledd,OUTPUT); pinMode(switchPin,INPUT); } void fading() { st: if(s1==0){ if(s1==1){goto hy;} analogWrite(leda,i); delay(30); i+=5; if(i&gt;255){s1=1;} goto st1; } hy: if(i&lt;0){s1=0;goto st;} i-=5; analogWrite(leda,i); delay(30); st1: delay(10); } void blinking() { digitalWrite(ledd,HIGH); delay(30); digitalWrite(ledd,LOW); delay(30); } void loop() { int g; g=digitalRead(switchPin); if(g==1) {delay(50);} if(g==0){ blinking(); fading();} } </code></pre>
12333
|arduino-uno|power|
Motorcycle Battery Powering Arduino UNO
2015-06-03T01:42:39.850
<p><img src="https://i.stack.imgur.com/21gov.png" alt="Arduino power supply"></p> <p>Folks</p> <p>I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.</p> <p>I am wondering if this circuit will work fine.</p> <p>C1 - 1000uF 50V; C2 - 1000uF 25V; D1 - 1N4001 ;</p>
<p>Your circuit is 'going in the right direction' but can be improved.<br /> If you wish to use the regulator shown:</p> <ul> <li><p>The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage &quot;droops&quot;, eg during starting.</p> </li> <li><p>Adding a series resistor to drop some of the input voltage will help C1 filter out noise.<br /> <em>Rin</em> should be V/I = V_drop_max/I_maximum .<br /> With a 9V regulator and 12V supply you cannot afford much drop in the resistor.<br /> If you use the 6V output system I recommend below then you could allow closer to 3V drop in <em>Rin</em>.<br /> If <em>Imax</em> is 100mA then <em>Rin</em> = V/I = 3/0.1 = 30 Ohms.<br /> Typically you'd use 27 Ohms (which is the closest E12 standard value.</p> </li> </ul> <p>Power dissipation is the resistor = I^2 x R.<br /> So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is<br /> I^2 x R = 0.1^2 x 27 = 0.27 Watt<br /> So you'd use at least a 0.5 Watt resistor and ideally Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.</p> <ul> <li>Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if <em>Rin</em> is used. Without <em>Rin</em> the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.</li> </ul> <p>The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.</p> <p>The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.</p> <p>9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).</p> <p>Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.</p> <p>One superb version of this regulator is the LM2931-N <a href="http://www.ti.com/lit/ds/snosbe5g/snosbe5g.pdf" rel="nofollow noreferrer">[<strong>Data sheet here</strong>]</a> - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is &quot;safest&quot;. These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.</p> <p>The datasheet description states:</p> <blockquote> <p>Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.</p> <p>During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.</p> <p>The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.</p> </blockquote>
12335
|arduino-uno|c++|rfid|variables|
How to add data without pre-defining variables?
2015-06-03T02:32:21.043
<p>I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.</p> <p>What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello <code>w</code>, your ID number is <code>xxx xxx xxx xxx xxx</code>. </p> <p>So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?</p> <p>Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach. </p>
<p>Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.</p> <p>As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.</p> <hr> <h2>For those who don't know</h2> <p>In C, data relevant to an object can be stored in a <a href="http://www.cplusplus.com/doc/tutorial/structures/" rel="nofollow">structure</a>, or <code>struct</code>. You can put all sorts of different types of data in a struct, like so:</p> <pre><code>struct personalProfile { char firstName[8]; char lastName[8]; uint cardID; // 'uint' is an unsigned int... bool accessAllowed; }; </code></pre> <p>You can then use that structure to create a 'personal profile' for however many people you want:</p> <pre><code>// within your main program: struct personalProfile Person1; struct personalProfile Person2; // Now you can directly access individual aspects as so: Person1.firstName = "John"; Person1.lastName = "Brown"; Person1.accessAllowed = TRUE; Person2.firstName = "Dodgy"; Person2.lastName = "Dave"; Person2.accessAllowed = NOT_A_HOPE_IN_HELL; </code></pre> <p>You can use the <em>members</em> of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.</p> <p>The best way to store multiple instances of a particular variable type is in an <a href="http://www.cplusplus.com/doc/tutorial/arrays/" rel="nofollow">array</a>:</p> <pre><code>struct personalProfile listOfPeople[5]; </code></pre> <p>You now have an array of five (blank) <code>struct</code>s, which can be accessed by <code>listOfPeople[n].firstName = Potato;</code>, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.</p> <p>An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five <code>struct</code>s in it you can't add or remove any. One solution is to create a massive array, and set all the values in each <code>struct</code> to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.</p> <p>Next comes <a href="http://www.cplusplus.com/reference/stl/" rel="nofollow">containers</a>. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...</p> <hr> <h2>EEPROM basics</h2> <p>The <a href="http://www.arduino.cc/en/Reference/EEPROM" rel="nofollow">EEPROM library</a> that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.</p> <p>Using the function <code>EEPROM.put(address, data)</code> you can put ANY data type - an <code>int</code>, <code>char</code> or - you guessed it - a <code>struct</code> into the EEPROM, starting at the byte specified by <em>address</em>. Of course there has to be enough space so you can't put an <code>int</code>, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)</p> <p>So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.</p> <pre><code>// within main program struct personalProfile Person1; struct personalProfile Person2; // fill in the details for Person 1... // fill in the details for Person 2... // ...then put Person1 in the EEPROM at address 0. EEPROM.put(0, Person1); // Done. Now put in Person2. But where? // You need to make sure you put them AFTER Person1. int AddressJump = sizeof(personalProfile); // AddressJump now equals how many bytes are need to store one person. EEPROM.put(AddressJump, Person2); </code></pre> <p>Simple as that.</p> <p>If you create a Person3, you're going to need to put them <code>sizeof(personalProfile)</code> bytes AFTER Person2, i.e. <code>EEPROM.put(AddressJump*2, Person3);</code>. So, you add Person<em>N</em> to address <code>AddressJump * (N-1)</code>.</p> <p>Retrieving data is the same principle, except you use <code>EEPROM.get()</code>:</p> <pre><code>// provided you've used the above snippet somewhere to actually // populate the EEPROM with something! struct personalProfile personA; EEPROM.get(0, personA); Serial.print("Person A is called:"); Serial.println(personA.firstName); </code></pre> <p>Again, you're going to need <code>sizeof(personalProfile)</code> to read the second, third, or <em>N</em>th person. If you 'send <code>EEPROM.get()</code> to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't <code>put</code> one person on top of another (you could get in trouble for that) and you don't want to <code>get</code> someone that isn't there.</p> <hr> <h2>List management</h2> <p>This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.</p> <p>Your first task is to determine what sort of array you want. Inevitably it's going to be a <a href="http://en.wikipedia.org/wiki/Linked_list" rel="nofollow">Linked List</a>. This is an array of <code>structs</code>, where each <code>struct</code> element in the list <em>contains the memory address of the following element</em>, thus the list is <strong>linked</strong>. You need to consider:</p> <ol> <li>How the array will be linked (if at all);</li> <li>Whether or not the array is space-critical (does it have to be as small as possible);</li> <li>Where the array is going to start;</li> <li>How you're going to keep track of how many people are in the array.</li> </ol> <p>@TL140 I await your response, good luck!</p>
12342
|arduino-uno|
Storing and parsing data with Arduino
2015-06-03T14:30:55.647
<p>I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:</p> <pre><code>client.println("GET http://ramp.local/api/actions?"); </code></pre> <p>The response I get is:</p> <pre><code>[{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17}, {"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20}, {"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17}, {"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}] </code></pre> <p>How to collect a data in a string variable and parse it to get <code>action_status</code>?</p>
<p><a href="https://github.com/bblanchon/ArduinoJson" rel="nofollow">Try this on for size.</a></p> <p>This is an arduino based, open source, JSON processor.</p>
12344
|arduino-mega|memory-usage|
How do I know how many memory that Arduino is use after my code is running for a few time
2015-06-03T15:49:49.307
<p>When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload. </p> <p>How do I know the current size of memory that Arduino is use?</p> <p>I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.</p> <p>Note: I am using the Board: Arduino Mega 2560.</p> <p>I read the question and the answer for <a href="https://arduino.stackexchange.com/questions/11845/measure-sram-usage">Measure SRAN usage</a></p> <p>In the question @fuenfundachtzig ask: </p> <p><strong><em>Can I determine how much SRAM I have left in the live system?</em></strong> </p> <p>In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.</p> <p>I am tryin to know in an specific time what is the size of my memmory. </p> <h3>example...</h3> <pre><code>void setup() { //doing some configuration }; void loop() { // invoke some functions and evil function }; // in other place a evil function void evil(){ MyClass * instance = new MyClass(); //play with the instance and it class create other instances.... //and a dynamic memmory is used but not deleted. } </code></pre> <p>I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.</p>
<p>Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.</p> <p>You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain). </p> <p>You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.</p>
12356
|arduino-uno|
Cannot open ov7670 output file
2015-06-04T01:30:07.720
<p>I have taken a data file using arduino and ov7670 camera module. In this project I used the famous code <a href="https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno" rel="nofollow">https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno</a> . But after taking the datafile ov7670NoRam.hex, I can't open it. I spent 3 hours to search how to open, but failed.</p> <p>Could anyone please let me know how to have a look the image in .hex? or would it be possible to take image data from ov7670 directly to jpg? </p> <p>I tried to convert the hex file to bin using hex2bin, but when I opened the bin, only errors occurred. </p> <p>The following is the content of the ov7670NoRam.hex</p> <pre><code>:100000000C9436000C944B000C944B000C944B0059 :100010000C944B000C944B000C944B000C944B0034 :100020000C944B000C944B000C944B000C944B0024 :100030000C944B000C944B000C944B000C944B0014 :100040000C944B000C944B000C944B000C944B0004 :100050000C944B000C944B000C944B000C944B00F4 :100060000C944B000C944B005244590011241FBEB9 :10007000CFEFD8E0DEBFCDBF12E0A0E0B1E0EAE70D :10008000F2E002C005900D92A235B107D9F70E94A7 :10009000AF000C943B010C9400008093BB0084E8FB :1000A0008093BC008091BC0087FFFCCF8091B90099 :1000B000887F90E070E08617970709F408950E9402 :1000C000A00084EA8093BC008091BC0087FFFCCF35 :1000D0008091B900887F883009F408950E94A000BB :1000E000CF93DF93D82FC62F0E94610068E182E48E :1000F0000E944D0068E28D2F0E944D0068E28C2F17 :100100000E944D0084E98093BC008FE99FE0019735 :10011000F1F700C00000DF91CF910895CF93DF93F6 :10012000EC0103C00E9470002296FE01849131967A :1001300064918F3FB9F76F3FA9F7DF91CF91089591 :10014000259A90E285B1892785B92FEF31EE84E0B9 :10015000215030408040E1F700C00000F3CFF89418 :10016000239A8091B6008F798093B60083E48093C0 :10017000B00089E08093B1001092B30087B1807F16 :1001800087B98AB183708AB92FEF8BE792E9215042 :1001900080409040E1F700C000008091B9008C7F62 :1001A0008093B90088E48093B8001092C50081E084 :1001B0008093C4008091C00082608093C00088E179 :1001C0008093C10086E08093C20060E882E10E94D3 :1001D00070002FEF81EE94E0215080409040E1F7D5 :1001E00000C0000080E091E00E948E0060E285E1A6 :1001F0000E94700060E08CE00E9470008AE392E050 :100200000E948E0088E492E00E948E0069E181E104 :100210000E947000E8E6F0E094918091C00085FFB4 :10022000FCCF9093C6008091C00085FFFCCF319633 :1002300084918111F1CF4B9BFECF4B99FECF40EEC5 :1002400051E08FE792E04A99FECF36B129B1207F85 :100250003F70232B2093C6004A9BFECF9C01215068 :100260003109892B11F0C901EECF415051094115D7 :0A027000510539F7CFCFF894FFCF06 :10027A0012803A0412001713180132B619021A7AB8 :10028A00030A0C003E00703A7135721173F0A20134 :10029A0015027A207B107C1E7D357E5A7F69807616 :1002AA0081808288838F849685A386AF87C488D706 :1002BA0089E813C0000010000D401418A505AB070B :1002CA002495253326E39F78A068A103A6D8A7D84A :1002DA00A8F0A990AA9413C5300031000E610F4B03 :1002EA0016021E07210222912907330B350B371DEF :1002FA003871392A3C784D404E20690074108D4F70 :10030A008E008F009000910096009A00B084B10C84 :10031A00B20EB382B80A430A44F045344658472815 :10032A00483A59885A885B445C675D495E0E6C0A94 :10033A006D556E116F9E6A400140026013C74F806F :10034A00508051005222535E5480589E41083F000B :10035A00750576E14C0077013D484B09C960564066 :10036A0034113B12A48296009730982099309A84CF :10037A009B299C039D4C9E3F78047901C8F0790F14 :10038A00C8007910C87E790AC880790BC801790C2F :10039A00C80F790DC8207909C8807902C8C07903C5 :1003AA00C8407905C8307926FFFF32F617131801BD :1003BA0019021A7A030AFFFF12013D08413D76E14C :0203CA00FFFF33 :00000001FF </code></pre>
<p>I am the author of the code and needless to say I am very confused right now on what you are trying to do. You run make writeflash in order to do what the target names implies write the hex file to microcontroller's internal flash memory. After that is done the code will run and you will use my frame grabber <a href="https://github.com/ComputerNerd/simpleFrameGrabber" rel="nofollow">https://github.com/ComputerNerd/simpleFrameGrabber</a> to capture an image.</p>
12358
|code-optimization|
Cleaning up code? Removing repetition?
2015-06-04T02:06:43.273
<p>I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.</p> <p>Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code. </p> <p>Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.</p> <p>In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!</p> <p>Any suggestions are welcome.</p> <p>Thanks in advance.</p> <p>Example code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;Adafruit_MotorShield.h&gt; boolean runMotor1 = false; boolean Motor1Running = false; unsigned long Motor1StartMillis; unsigned long Motor1RunTime = 5000; boolean runMotor2 = false; boolean Motor2Running = false; unsigned long Motor2StartMillis; unsigned long Motor2RunTime = 10000; //etc etc etc up to 10 Motors Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1); Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2); void setup() { Serial.begin(9600); AFMS.begin(); runMotor1 = true; // set condition to true for testing runMotor2 = true; } void loop() { /// Motor1 START if (runMotor1 == true) { Serial.println("Run Motor 1!"); runMotor1 = false; MotorMotor1-&gt;setSpeed(255); MotorMotor1-&gt;run(FORWARD); Motor1StartMillis = millis(); Motor1Running = true; } if( Motor1Running &amp;&amp; (millis()-Motor1StartMillis &gt; Motor1RunTime) ) { Serial.println("Motor1 Time Elapsed!"); MotorMotor1-&gt;setSpeed(0); MotorMotor1-&gt;run(RELEASE); runMotor1 = false; Motor1Running = false; } /// Motor 2 if (runMotor2 == true) { Serial.println("Run Motor 2!"); runMotor2 = false; MotorMotor2-&gt;setSpeed(255); MotorMotor2-&gt;run(FORWARD); Motor2StartMillis = millis(); Motor2Running = true; } if( Motor2Running &amp;&amp; (millis()-Motor2StartMillis &gt; Motor2RunTime) ) { Serial.println("Motor2 Time Elapsed!"); MotorMotor2-&gt;setSpeed(0); MotorMotor2-&gt;run(RELEASE); runMotor2 = false; Motor2Running = false; } } </code></pre> <p>Thanks for reading, and thank you for any input you may have. Steve</p>
<p>You are perfectly right, a class would help simplify your code. Here is a tentative class that should work for what you are doing:</p> <pre class="lang-c++ prettyprint-override"><code>class Motor { public: Motor(const char *_name, Adafruit_DCMotor *_motor, unsigned long _runTime) : name(_name), startNow(false), running(false), runTime(_runTime), motor(_motor) { } void start() { startNow = true; } void update(); private: const char *name; boolean startNow; boolean running; unsigned long startTime; unsigned long runTime; Adafruit_DCMotor *motor; }; </code></pre> <p>Most of this is almost copy-paste from your actual code, except for your <code>runMotorX</code> variables that I renamed <code>startNow</code>, which seemed more appropriate.</p> <p>Beware that the name of the motor is copied as a pointer. Thus you should better call the constructor with a literal string (like <code>"the name"</code>) as a first parameter. Otherwise it would be more appropriate to allocate memory and copy the characters themselves, but I like to avoid dynamic memory allocation on an Arduino if I can.</p> <p>Now, all the code that you have in <code>loop()</code> for each motor would be the Motor's <code>update()</code> method:</p> <pre class="lang-c++ prettyprint-override"><code>void Motor::update() { if (startNow) { Serial.print("Run "); Serial.print(name); Serial.println('!'); startNow = false; motor-&gt;setSpeed(255); motor-&gt;run(FORWARD); startTime = millis(); running = true; } if (running &amp;&amp; (millis()-startTime &gt; runTime)) { Serial.print(name); Serial.println(" Time Elapsed!"); motor-&gt;setSpeed(0); motor-&gt;run(RELEASE); running = false; } } </code></pre> <p>With this class, your code would now look like:</p> <pre class="lang-c++ prettyprint-override"><code>Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Motor m1("Motor 1", AFMS.getMotor(1), 5000); Motor m2("Motor 2", AFMS.getMotor(2), 10000); //etc etc etc up to 10 Motors void setup() { Serial.begin(9600); AFMS.begin(); m1.start(); m2.start(); } void loop() { m1.update(); m2.update(); } </code></pre> <p>Of course, when you get to 10 motors, this would still be annoying repetition. You can simplify further by putting the motors in an array and looping through it:</p> <pre class="lang-c++ prettyprint-override"><code>Adafruit_MotorShield AFMS = Adafruit_MotorShield(); Motor motors[] = { Motor("Motor 1", AFMS.getMotor(1), 5000), Motor("Motor 2", AFMS.getMotor(2), 10000) //etc etc etc up to 10 Motors }; #define NUM_MOTORS (sizeof motors / sizeof motors[0]) void setup() { Serial.begin(9600); AFMS.begin(); for (unsigned int i = 0; i &lt; NUM_MOTORS; i++) motors[i].start(); } void loop() { for (unsigned int i = 0; i &lt; NUM_MOTORS; i++) motors[i].update(); } </code></pre>
12373
|sram|
What is the most memory-friendly way to declare integer literals?
2015-06-04T08:44:18.363
<p>I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:</p> <pre><code>for(byte i=0;i&lt;16;i++) buf[i]=(char)ap1[i]; </code></pre> <p>Would it make any difference if I declared the integer literal 16 as a constant? </p> <pre><code>const byte BUFSIZE=16; </code></pre> <p>Or using the preprocessor:</p> <pre><code>#define BUFSIZE 16 </code></pre> <p>There's also the macro <code>PROGMEM</code> which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.</p> <pre><code>const byte BUFSIZE PROGMEM=16; </code></pre> <p>AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.</p> <p>This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use</p>
<p>Well, it's easy to just try and see... Let's try the following program:</p> <pre class="lang-c++ prettyprint-override"><code>#ifdef USE_CONST const byte BUFSIZE = 16; #else # define BUFSIZE 16 #endif char buf[BUFSIZE], ap1[BUFSIZE]; int main(void) { for (byte i = 0; i &lt; BUFSIZE; i++) buf[i] = ap1[i]; return 0; } </code></pre> <p>I compiled this for an Uno both with and without <code>#define USE_CONST</code>, and it doesn't make any difference! avr-size reports the same sizes for both versions, and the generated assemblies are identical: the optimizer transformed the loop into something like</p> <pre class="lang-c++ prettyprint-override"><code>byte *Z = ap1; byte *X = buf; do { *X++ = *Z++; } while (Z != ap1 + 16); </code></pre> <p>where X and Z are two of the CPU's pointer registers, and <code>ap1 + 16</code> is an <em>immediate</em> constant, i.e. part of the instruction itself, c.f. the <a href="http://www.csee.umbc.edu/~alnel1/cmpe311/notes/AVRAddressingModes.pdf" rel="nofollow noreferrer">AVR addressing modes</a>.</p> <p>It is worth noting that, in C++, <a href="https://stackoverflow.com/a/998457"><code>const</code> implies internal linkage</a>. Thus a const global variable is very much like a preprocessor constant.</p> <p>This is unlike C, where you would need to qualify the variable as <code>static const</code> in order to get the same behavior. Otherwise the compiler would need to allocate storage to <code>BUFSIZE</code>, just in case it is referenced as <code>extern</code> from another source file, even though it can replace occurrences of <code>BUFSIZE</code> <em>in the same file</em> with its immediate value.</p> <p>On the other hand, the Arduino IDE compiles your code with <a href="https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-funswitch-loops-1114" rel="nofollow noreferrer">-ffunction-sections -fdata-sections</a> and links it with <a href="https://sourceware.org/binutils/docs/ld/Options.html#index-garbage-collection-179" rel="nofollow noreferrer">--gc-sections</a>, which means the linker will eventually get rid of the unused reserved storage.</p>
12382
|arduino-uno|interrupt|ide|atmel-studio|
Where is documentation on Arduino's Internal Interrupts?
2015-06-04T22:10:01.867
<p>First time arduino programmer here...however I have programmed the TI MSP430 in the past...</p> <p>I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.</p> <p>In the Arduino IDE, I am skeptical about writing lines of code like </p> <pre><code>ISR(TIMER1_CAPT_vect) { Serial.Print("Entered Capture Vector"); } </code></pre> <p>Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }</p> <p>And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1_CAPT_vect is without having the library?</p> <p>I found a list of interrupt vector names here: <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html" rel="nofollow">http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html</a></p> <p>But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.</p> <p>Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.</p> <hr> <p>EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.</p>
<pre><code>ISR(TIMER1_CAPT_vect) { Serial.Print("Entered Capture Vector"); } </code></pre> <p>Rule #1. Don't do serial prints inside an ISR. Doing that will likely hang the sketch.</p> <blockquote> <p>Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }</p> </blockquote> <p>Yes you can do that. It just degrades into some function that is never called. The way it is organized with all the defines, any non-valid ISR name effectively creates a non-ISR function, which is therefore ignored. Even getting the capitalization wrong can cause this.</p> <blockquote> <p>I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.</p> </blockquote> <p>There is a considerable amount of detail on my site: <a href="http://www.gammon.com.au/interrupts" rel="nofollow">http://www.gammon.com.au/interrupts</a></p>
12384
|arduino-uno|arduino-ide|interrupt|ide|atmel-studio|
IDE to program Arduino Uno especially internal interrupt vectors
2015-06-04T23:32:48.887
<p>I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?</p> <p>What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.</p> <p>Suggestions?</p>
<p>You can do all you need to do in the Arduino IDE. It doesn't "block" you from doing any low-level operations. Any other IDE will also allow you to do what you want.</p> <p>All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.</p> <p><a href="http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf" rel="nofollow">http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf</a></p>
12397
|arduino-mega|ethernet|
Arduino Ethernet Shield 2 stuck on EthernetServer::begin()
2015-06-05T12:53:26.623
<p>I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.</p> <p>This is my test code:</p> <pre><code>#include &lt;Ethernet.h&gt; #include &lt;SPI.h&gt; byte mac[] = { 0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D }; byte subnet[] = { 255,0,0,0 }; byte gateway[] = { 2,0,0,1 }; IPAddress ip(2, 0, 0, 1); EthernetServer server(80); void setup() { Serial.begin(9600); Ethernet.begin(mac, ip, gateway, subnet); Serial.println("Ethernet started"); server.begin(); Serial.println("Server started"); } void loop() { // put your main code here, to run repeatedly: Serial.println("Loop"); } </code></pre> <p>The output I get from the serial console is:</p> <pre><code>Etrted Ethernet started </code></pre> <p>So I think the program gets stuck inside the EthernetServer::begin() function. I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.</p> <p>Also I don't understand, why it outputs the first line.</p> <p>Thanks for your hints!</p>
<p>Just to get this answered (see comments): It was a weird "bug" in my case. After days of research I found people with the same issue and in their cases it helped to cut all of the pin headers but the ICSP header by 2mm so the ICSP header had better contact. I tried it on my shield and it worked.</p>
12399
|sensors|wifi|android|
control Arduino board using Android sensors and wifi?
2015-06-05T13:59:26.017
<p>i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control ) so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ?? </p>
<p>Is it possible? Yes, it's certainly possible. You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB. The Arduino can be programmed to respond to what it gets through the serial.</p> <p>Is it easy? Well, that depends on how good you are at Android programming.</p> <p>One good place to start might be the <a href="http://shokai.github.io/ArduinoFirmata-Android/" rel="nofollow">ArduinoFirmata-Android</a> project. Don't worry about programming the Arduino, just install Firmata on it. Then it's all down to how you program the Android device. The Arduino just becomes a peripheral to your phone.</p>
12406
|arduino-uno|
What's wrong with my Arduino board?
2015-06-05T17:53:47.427
<p>When I connect the Arduino to my PC the Led "ON" lights for a second then turns OFF. I wonder if the Arduino has a fault?</p>
<p>Most likely a short between VCC (5 volt) and GROUND. When there is a short the fuse will kick in after a second, and disable the whole board, including the ON-led.</p> <p>When you disconnect the board, the fuse will reset.</p> <p>So either the board is faulty of the connection you made to it are.</p>
12413
|arduino-uno|programming|
analogRead-ing Potentiometer Values in void setup()
2015-06-06T04:08:30.913
<p>I've run into a problem while coding a speedometer meant for bicycles. The speedometer would require the diameter of the wheel in inches for maximum accuracy, so I'd like to have an adjustable (by potentiometer) numerical prompt appear on two 7 segment LEDs. So, for example, the device would be turned on, it would display "16," the user would turn the potentiometer knob until the 7 segment LED displays "24," then the user would push a button [indicating the beginning of the loop()], and the speedometer would begin measuring and displaying his or her speed.</p> <p>This would be an easier task to accomplish in the loop section of the code, but, because I only want this series of potentiometer analogReads to occur once, it gets a bit trickier.</p> <p>Some clarification: Every other component of the speedometer works (such as the 7 segment LEDs via shift register and the actual measurements), so I'm only looking for help with the code for the potentiometer.</p> <p>Thanks!</p>
<p>If you really want to use this feature in the setup() then you can do like this:</p> <pre><code>#define BUTTON 2 boolean not_done = true; void stopDiameterSetup() { // some button debounche code ... // we are done with setting up the diameter. not_done = false; } void setup() { ... // POT reading interrupts(); attachInterrupt(); while(not_done) { attachInterrupt(BUTTON, stopDiameterSetup, CHANGE); } } void loop(){ // your loop code } </code></pre> <p>If you can't or afraid to use interrupts then just check for a button pressed inside the while loop.</p>
12418
|sensors|arduino-nano|code-optimization|
Light sensor acting up when used with other code
2015-06-06T09:02:18.320
<p>I have a light sensor that works fine and outputs the correct data to the serial monitor when I only upload the following code to the nano:</p> <pre><code>const int lightSensorPin = A0; int lightSensorValue = 0; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: lightSensorValue = analogRead(lightSensorPin); delay(100); Serial.println(lightSensorValue); } </code></pre> <p>Now when I upload it with all of my other code, which includes lighting up about 6 LED's at one time and getting readings from two rangefinder sensors, the light sensors no longer output expected data, instead spewing out a bunch of random numbers, 0 to over 3000. </p> <p>Could sharing the ground with all the LED's and rangefinders be causing interference for the light sensor? Or could it be a code optimization issue? Here's my entire code if it helps at all:</p> <pre><code>int trigPin1 = 5; int echoPin1 = 6; int blue1 = 7; int green1 = 8; int trigPin2 = A3; int echoPin2 = A4; int blue2 = A2; int green2 = A1; int redLED = 10; int greenLED = 3; int yellowLED = 9; int blueLED = 4; const int lightSensorPin = A0; int lightSensorValue = 0; int securityLength1 = 28; int securityLength2 = 28; int frontEyes(11); int backEyes(12); const char* front = "front"; const char* back = "back"; void setup() { Serial.begin(9600); pinMode(trigPin1, OUTPUT); pinMode(echoPin1, INPUT); pinMode(trigPin2, OUTPUT); pinMode(echoPin2, INPUT); pinMode(blue1, OUTPUT); pinMode(green1, OUTPUT); pinMode(blue2, OUTPUT); pinMode(green2, OUTPUT); pinMode(frontEyes, OUTPUT); pinMode(backEyes, OUTPUT); pinMode(redLED, OUTPUT); pinMode(greenLED, OUTPUT); pinMode(yellowLED, OUTPUT); }//end setup void loop(){ digitalWrite(redLED, HIGH); digitalWrite(greenLED, HIGH); digitalWrite(yellowLED, HIGH); digitalWrite(blueLED, HIGH); eyeballs(trigPin1, echoPin1, securityLength1, green1, blue1, front); eyeballs(trigPin2, echoPin2, securityLength2, green2, blue2, back); lightSensorValue = analogRead(lightSensorPin); delay(100); Serial.println(lightSensorValue); }//end loop void eyeballs(int trigPin, int echoPin, int securityLength, int green, int blue, const char* frontOrBack){ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); long duration = pulseIn(echoPin, HIGH); long distance = (duration/2) / 29.1; Serial.println(distance); if (distance &gt;= securityLength || distance &lt;= 0) { digitalWrite(green,HIGH); digitalWrite(blue,LOW); if (frontOrBack == "front") { digitalWrite(frontEyes, LOW); }//end if else if (frontOrBack == "back") { digitalWrite(backEyes, LOW); }//end else }//end if else if(distance &lt; securityLength) { digitalWrite(blue,HIGH); digitalWrite(green,LOW); if (frontOrBack == "front") { digitalWrite(frontEyes, HIGH); }//end if else if (frontOrBack == "back") { digitalWrite(backEyes, HIGH); }//end else }//end else if }//end function </code></pre>
<p>I'd prefer to delete this question because I'm so embarrassed by the answer. I didn't notice I had <code>Serial.println(distance);</code> in my function. The odd numbers were coming from my rangefinders and being printed in between my light readings. </p>
12419
|led|power|arduino-due|
Connecting battery and LED to Arduino Due
2015-06-06T10:26:33.500
<p>I am brand new to Arduino/robotics and am trying to take baby steps. First I'd like to just power an Arduino and an LED from a 9V battery like so:</p> <p><img src="https://i.stack.imgur.com/tIEGq.jpg" alt="enter image description here"></p> <p>No programming, just simple circuitry. The battery powers the Due, and the Due in turn powers the LED.</p> <p>A few concerns here:</p> <ul> <li>Will the 9V battery fry the Due, which I <em>believe</em> is expecting 3.3V? If so, what can I do to reduce the voltage/amps?</li> <li>Will the 9V battery fry the resistor and/or LED?</li> <li>As you can see by my question marks, I'm not real sure <em>where</em> to connect the battery to the Due (both positive &amp; negative terminals) as well as the <em>where</em> to connect the breadboard to the Due (again, both terminals).</li> </ul> <p>Any ideas?</p>
<p>What you want is something like this (ignore the fact that my mini breadboard is stuck to a shield): <img src="https://i.stack.imgur.com/bvkU1.png" alt="Simple LED example with no software."></p> <p>My starter Arduino kit came with the connector for the 9 volt battery into the power socket on the Arduino, you may need to make one. You cannot connect the 9V battery to any other part of the Due that I am aware of (without damaging it!).</p> <p>It is perfectly safe to power your Arduino with 9V this way, there is circuitry to step the voltage down to the 5V and 3.3V that the board requires.</p> <p>In the connector strip nearest this power socket (labelled Power on my board) there are a couple of Gnd connections and 5V and 3.3V connectors perfect for what you want to do. I have used the 3.3V connector in my photo, but the 5V one should also be fine with the right resistor.</p> <p>In your picture you don't appear to have anything connecting the LED to ground, but other than that, if you were to connect the battery up as I have shown and the red and black LED connectors to 3.3V and Gnd respectively, it should work as desired.</p> <p>As a next step, you could load the sample sketch Examples->01Basic->Blink, write it to your Due, move the red LED connecting wire to pin 13 on the opposite side and your LED would flash (along with one of the LEDs on the Due board itself).</p> <p>Edit (to specifically address your concerns):</p> <ul> <li>The 9V battery will not fry the Due if it is connected through the power socket, which has circuitry to drop the voltage to safe levels.</li> <li>The 9V battery will not damage the LED or resistor as they are connected to 5V or 3.3V that the Due outputs, not the 9V from the battery.</li> <li>Only connect the battery through the power socket. If you have a good quality steady 5V power supply, you can power the board through a 5V pin (at least I have been able to), but you bypass the voltage regulation circuitry that way and it is not recommended. Connect the black wire from your LED to any Gnd pin, connect the red wire from the LED to 3.3V or 5V.</li> </ul> <p>Additional edit: You can connect the battery directly to the Arduino Due board without needing a plug to connect to the power socket. Connect the red battery wire to the Vin pin and the black battery wire to a Gnd pin.</p>
12421
|serial|debugging|
Will writing to serial when no serial is available cause problems?
2015-06-06T11:40:41.140
<p>I have an Arduino UNO, and use the serial for debugging purposes. What happens if I run the arduino on batteries and try to write to serial? Will the code stop running until a serial connection is availible?</p>
<p>No, that will not cause any problem.</p> <p>What might hurt you is the fact that if you want to leave your Arduino in low power mode, but keep the serial potr disconnected <em>and</em> the serial port is a wakeup source, it might pick up sporadic (but frequent enough to cause be noticeable) noise that will trigger wakeups and spam with meaningless data your RX.</p> <p>This, however, is not specific to the serial port, but it can happen to any wake up source that is enabled and left dangling.</p>
12431
|serial|arduino-leonardo|
Leonardo Serial1 enable internal pull-up for removable Bluetooth module
2015-06-06T20:12:48.247
<p>I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.</p> <p>My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins. </p> <p>I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors. </p> <p>I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?</p>
<p>Yes, what you have done is good.</p> <p>It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs. When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.</p> <p>As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.</p> <p>UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter. By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.</p> <p>The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART. If that happens then you want to add an external stronger (lower resistance) pull up.</p> <p>Another thing to think about with your disconnected pins is to protect them from ESD. You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions. </p>
12434
|arduino-uno|arduino-motor-shield|
How to communicate with arduino uno when arduino motor shield connected to arduino uno?
2015-06-07T04:57:06.650
<p>I'm using this Dual Motor Shield <img src="https://i.stack.imgur.com/N5DAh.jpg" alt="L293D Arduino Dual Motor Shield"></p> <p>when I plug Arduino Dual Motor Shield into Aruino uno can't seen any way to communicate with Adruino uno.how can I communicate with uno ?</p>
<p>Communicate with what? A PC? The usb serial port should still work fine, and anything connected to the RX/tx pins (D0 and D1) If your concern is that there is no longer a socket on the top of this shield that you can plug wires into, well you can solder on some wires to the top of the board, or you could get a screw shield board to go between the arduino and motor shield which would make all the pins available. I have also use small gauage wire wrapped around the shield pins and then just insert the shield onto the arduino making kind of a wire wrap connection between the boards.</p>
12449
|resistor|
Use of Resistor in PinWheel Exercise
2015-06-07T19:16:23.410
<p>I'm working on project 9 of the Arduino starter kit - the motorized pinwheel.</p> <p>Here is the schematic:</p> <p><img src="https://i.stack.imgur.com/wKxI0.jpg" alt="enter image description here"> (if img not showing: <a href="https://goo.gl/tqZmKD" rel="nofollow noreferrer">https://goo.gl/tqZmKD</a>)</p> <p>My question is, why is the 10k resistor needed after the switch? Why can't it just go straight to ground? The switch's output just connects to a digital pin, it doesn't care how much voltage there is, correct?</p> <p>Thank you!</p> <p>EDIT**: Additional help from the arduino forums: The resistor is needed so when the switch is closed you don't short the supply to ground. Switch open the resistor pulls the signal to ground and no current flows, when the switch is closed it forms a resistive divider with the 10k (switch contacts might have 0.01 to 0.1 ohms resistance or so), thus pulling the signal to Vcc, but with only 0.5mA flowing through the 10k resistor.</p> <p>Replace the 10k with a wire and you'd simply overload the supply completely and perhaps weld the switch contacts shut. <a href="http://forum.arduino.cc/index.php?topic=328353.new#new" rel="nofollow noreferrer">Arduino Forums</a></p>
<p>It's a pull-down resistor.</p> <p>A pull-up or pull-down resistor is used the make sure that the input of a digital device is confined to strict logic levels, i.e +Vdd (positive, or HIGH) or GND (Ground, or LOW).</p> <p>With the switch open and no resistor present, the Arduino pin is neither high nor low. It will <em>probably</em> read as low if you tried <code>digitalRead()</code>, but there's no guarantee. The probability of the pin being one or the other changes according to the layout of the PCB and other external factors; the pin is termed 'floating' because it could be at any voltage between Vdd and GND.</p> <p>However, if you apply a pull-(somewhere) resistor you force the Arduino pin to one of either Vdd (up) or GND (down) <em>until you press the switch</em>, at which point the Arduino pin switches state.</p> <p>If you removed the resistor and joined the switch directly to ground, what happens when the switch contacts close?</p> <p>Think about it...</p> <p>One side of the switch connected to Vdd.</p> <p>The other side is connected to the Arduino and GND.</p> <p>Close the switch, <em>I dare you.</em></p> <p><strong>Vdd is now connected to GND</strong></p>
12450
|ethernet|nrf24l01+|
w5100 and nrf24l01 - SoftSPI - Radio not starting
2015-06-07T19:24:02.627
<p>I had posted some questions about this project earlier this week. Arduino uno + w5100 ethernet shield + nrf24l01 transeiver.</p> <p>The w5100 is running a webserver to accept GET requests and parse out the variables - Works all the time</p> <p>The nrf24l01 is acting as a transmitter and sending data out to other nodes - Only works with no Ethernet code.</p> <p>What doesn't work is both at the same time. With everything hooked up it parses get fine, gets the variable but I can't transmit it since the radio never seems to fire up. Remove all the ethernet code and leave just the radio code it sends fine.</p> <p>Code here. <a href="http://pastebin.com/SMWC9x4F" rel="nofollow">http://pastebin.com/SMWC9x4F</a> it errors at 146. Which I assume is the radio never starting since the:</p> <pre><code>radio.printDetails(); </code></pre> <p>does nothing.</p> <p>I'm using manicbug's library.</p> <p>I use the EXACT same send bits in that file to test wireless communication, it works. I only need it to transmit wirelessly when it get data from the network.</p> <p>Pinouts:</p> <p>CSN -> 10 CE -> 9 MISO -> 12 MOSI -> 11 SCK -> 13 VCC -> Separate 3.3 source, not the arduino GND -> GND</p> <p>My guess is this is because both are using SPI.</p> <p>Tried the softspi method <a href="http://pastebin.com/4mv612B7" rel="nofollow">http://pastebin.com/4mv612B7</a> . </p> <p>Same thing. I can post GET to it, parse out variables but nothing on the radio side. And I still get no output from radio.printDetails() so it just must not be starting. Commence hair pulling..</p> <p>EDIT: Bloody hell, printDetails() relies on printf...... that would have been handy to figure out an hour or two ago. I can get details now. still having communication issues. Will post more debugging information in a bit.</p>
<p>The issue here is that the Ethernet chip locks the SPI bus thus making it impossible for NRF24L01+ to communicate with the arduino properly. Please use softSPI to fix this.</p>
12452
|motor|transistor|
How is the diode here effective?
2015-06-07T19:36:20.753
<p>I'm working on project 9 of the arduino starter-kit - the motorized pinwheel.</p> <p>Here is the schematic: <img src="https://i.stack.imgur.com/wysl1.jpg" alt="enter image description here"></p> <p>The diode in question (and the only one here) is toward the bottom right of the breadboard. It is to prevent the back-voltage from the motor from harming the circuit. </p> <p>According to the above img, would the backvoltage travel back down the motor's supply of energy (the red wire)? </p> <p>If so, what is the diode preventing here? That whole energy strip will just have current running through it and the diode's cathode will prevent it from running to the transistor - which would also happen fi we just didn't connect anything to that power strip.</p> <p>If not, and the back-voltage is running through the black wire (our ground), then I still do not see how the diode is helping. The diode seems to want to pull the extra energy back to our power strip (which is why the anode is facing toward the left, where the motor's output is. But this doesn't prevent the current from still hitting the green wire which leads to the transistor's 'source'.</p> <p>So how is this diode working?</p> <p>Thanks!</p>
<p>Flywheel Diode.</p> <p>When the transistor shuts off, the stopping of the motor generates <em>back EMF (ElectroMotive Force)</em> . This manifests itself as negative potential difference (voltage) across the motor. In plain English the collector of the transistor, connected to the -Ve side of the motor, is raised to a damagingly high voltage. If you include the diode, this voltage is siphoned immediately back to the positive rail, so the damage is averted.</p>
12460
|serial|arduino-nano|
How to interface arduino nano with sim900A?
2015-06-08T00:51:04.123
<p>I have arduino nano and sim900a modem. <img src="https://i.stack.imgur.com/Ze9I6.jpg" alt="My arduino pinout"></p> <p><img src="https://i.stack.imgur.com/wpPOc.jpg" alt="SIM900A Modem"></p> <p><img src="https://i.stack.imgur.com/kXEOE.jpg" alt="Modem Backside"></p> <p>Rx(pin30) and Tx(pin31) pins of <strong>arduino</strong> shows 3.8VDC respectively and Rx and Tx of <strong>SIM900a</strong> shows 3.6VDC and 2.8VDC respectively. Could i connect the SIM900a modem directly to the arduino? Since Should i use level shifter between arduino TX(3.8v) and SIM900A modem(3.6v)? Any suggestions?</p> <p>Thanks..</p>
<p>The bottom of your board shows a chip that gives every hint of being a charge-pump logic-level to RS232 inverting level shifter, to translate from the SIM900A's levels to the RS232 D-Sub connector.</p> <p>It would appear that the 3 pin header just inside the D-sub would allow you to communicate at these levels.</p> <p>However, a quick look at the SIM900A docs I could find <strong>suggests that these logic levels may be 2.8v, NOT 3.3v, and 3.3v is actually outside absolute maximum rating!</strong></p> <p>Essentially, you have two problems: </p> <ol> <li><p>You need to drive and read signals with 2.8v logic, either by modifying your arduino to run at that voltage, or by using a level shifter. It's possible that a resistor would protect the SIM900A, but that is going to be the most expensive component and so short of finding solid evidence of input protection diodes I'd be more hesitant to do that here than I would in other cases.</p></li> <li><p>You need to make the level shifter not drive a signal into the SIM900A, so you don't fight with it. You could do this by looking in the documenation (if any) for your board and seeing what accommodations they made for this, looking up the level shifter's data sheet and finding the enable pin, or merely desoldering it.</p></li> </ol> <p>Another option would be to make your Arduino talk at RS232 levels using its own shifter board.</p> <p>Finally, there's a sort of hackish option: Connect the <em>transmit</em> data from the SIM900A to a 3.3v Arduino, but connect the transmit from the Arduino through a simple inverter (tinylogic, whatever) to the RS232 <em>receive</em> pin.</p>
12464
|arduino-uno|arduino-mega|
What is the diffrence between following arduino boards and which should i buy?
2015-06-08T09:29:21.880
<h1>Arduino UNO R3 Compatible Board ATmega328P ATmega16U2</h1> <p><a href="http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH_DefaultDomain_203&amp;hash=item2ee26a3860" rel="nofollow noreferrer">http://www.ebay.in/itm/UNO-R3-ATmega328P-ATmega16U2-Compatible-Board-For-Arduino-with-USB-Cable-/201367107680?pt=LH_DefaultDomain_203&amp;hash=item2ee26a3860</a></p> <h1>Arduino UNO R3 ATmega328P USB Development Board CH340G</h1> <p><a href="http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH_DefaultDomain_203&amp;hash=item463beed1f0" rel="nofollow noreferrer">http://www.ebay.in/itm/UNO-R3-Development-Board-SMD-Chip-Arduino-Compatible-/301653217776?pt=LH_DefaultDomain_203&amp;hash=item463beed1f0</a></p> <h3>I will be working on a windows 7 32 bit pc.</h3>
<p>The first is an unofficial clone of an R3 using the same schematic as the real R3. The second is a rough copy using a cheaper USB serial interface chip.</p> <p>Neither of them are real Arduino boards. The first one is closer to the real UNO and should do the same things that a real UNO should do (assuming it works at all). The second one - well, who knows? You certainly can't do any of the fancy things to the USB interface that you can with a real UNO R3.</p> <p>Which should you buy? Well, really, you shouldn't buy either of them - but if you <em>must</em> go for one I'd pick the first one. Better to buy a real UNO from Arduino though, at least then you know what it is you're getting, and you expect it to work. With these cheap Chinese clones (Chinduinos) you may just get a bunch of counterfeit chips selotaped to a piece of cardboard.</p>
12466
|arduino-uno|mpu6050|
MPU6050 causing arduino not to run sketch
2015-06-08T11:42:13.467
<p>I have a mpu6050(which I got from here <a href="http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html" rel="nofollow noreferrer">http://www.sainsmart.com/sainsmart-mpu-6050-3-axis-gyroscope-module.html</a>) and I have connected it to special ports on a sensor shield made for the mpu6050(<a href="http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2" rel="nofollow noreferrer">http://www.amazon.co.uk/SainSmart-InstaBots-SS-SBR-1-0-Sensor-Shield/dp/B00N1YANH2</a>) which is on a Arduino uno. I have a sketch which is meant to print stuff out to the serial monitor, however when the mpu6050 is attached nothing is printed out and when it is not attached the Arduino does print out things to the serial monitor. I attached other things to the sensor shield and things were printed out on the serial monitor, so I know it is the mpu6050 that is the problem. </p> <p>This is my code</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;SPI.h&gt; #include &lt;Mirf.h&gt; #include &lt;nRF24L01.h&gt; #include &lt;MirfHardwareSpiDriver.h&gt; #include &lt;I2Cdev.h&gt; #include &lt;MPU6050.h&gt; MPU6050 accelgyro; int16_t ax, ay, az; int16_t gx, gy, gz; #define Gry_offset 0 #define Gyr_Gain 0.00763358 #define Angle_offset 4 #define RMotor_offset 20 #define LMotor_offset 20 #define pi 3.14159 long data; int x, y; float kp, ki, kd; float r_angle, omega; float f_angle; float Turn_Speed = 0, Turn_Speed_K = 0; float Run_Speed = 0, Run_Speed_K = 0, Run_Speed_T = 0; float LOutput,ROutput; unsigned long preTime = 0; float SampleTime = 0.08; unsigned long lastTime; float Input, Output; float errSum, dErr, error, lastErr; int timeChange; int TN1=3; int TN2=4; int ENA=9; int TN3=5; int TN4=6; int ENB=10; void setup() { Wire.begin(); accelgyro.initialize(); pinMode(TN1,OUTPUT); pinMode(TN2,OUTPUT); pinMode(TN3,OUTPUT); pinMode(TN4,OUTPUT); pinMode(ENA,OUTPUT); pinMode(ENB,OUTPUT); Mirf.spi = &amp;MirfHardwareSpi; Mirf.init(); Mirf.setRADDR((byte *)"serv1"); Mirf.payload = sizeof(long); Mirf.config(); Serial.begin(115200); Serial.print("Hello"); } void loop() { Recive(); accelgyro.getMotion6(&amp;ax, &amp;ay, &amp;az, &amp;gx, &amp;gy, &amp;gz); r_angle = (atan2(ay, az) * 180 / pi + Angle_offset); omega = Gyr_Gain * (gx + Gry_offset); //Serial.print(" omega="); Serial.print(omega); if (abs(r_angle)&lt;45){ myPID(); PWMControl(); } else{ analogWrite(ENA, 0); analogWrite(ENB, 0); } } void Recive(){ if(!Mirf.isSending() &amp;&amp; Mirf.dataReady()){ Mirf.getData((byte *)&amp;data); Mirf.rxFifoEmpty(); y = data &gt;&gt; 16; x = data &amp; 0x0000ffff; //Serial.print(" x="); Serial.print(x); //Serial.print(" y="); Serial.println(y); if(x &gt;= 520){ Run_Speed_K = map(x, 520, 1023, 0, 100); Run_Speed_K = Run_Speed_K / 50; Run_Speed = Run_Speed + Run_Speed_K; } else if(x &lt;= 480){ Run_Speed_K = map(x, 480, 0, 0, -100); Run_Speed_K = Run_Speed_K / 50; Run_Speed = Run_Speed + Run_Speed_K; } else{ Run_Speed_K = 0; } if(y &gt;= 520){ Turn_Speed = map(y, 520, 1023, 0, 20); } else if(y &lt;= 480){ Turn_Speed = map(y,480,0,0,-20); } else{ Turn_Speed = 0; } } else{ x = y = 500; } } void myPID(){ kp = analogRead(A0)*0.1; //kp=17; Serial.print(" kp=");Serial.print(kp); kd = analogRead(A2)*1.0; //kd=840; Serial.print(" kd=");Serial.print(kd); //ki = analogRead(A3)*0.001; Serial.print(" ki=");Serial.print(ki); //kp = 0; Serial.print(" kp=");Serial.print(kp); //kd = 0; Serial.print(" kd=");Serial.print(kd); ki = 0.08; Serial.print(" ki=");Serial.print(ki); unsigned long now = millis(); float dt = (now - preTime) / 1000.0; preTime = now; float K = 0.8; float A = K / (K + dt); f_angle = A * (f_angle + omega * dt) + (1 - A) * r_angle; Serial.print(" f_angle=");Serial.print(f_angle); timeChange = (now - lastTime); if(timeChange &gt;= SampleTime){ Input = f_angle; error = Input; errSum += error * timeChange; dErr = (error - lastErr) / timeChange; Output = kp * error + ki * errSum + kd * dErr; LOutput = Output + Run_Speed + Turn_Speed; Serial.print(" LOutput=");Serial.print(LOutput); ROutput = Output + Run_Speed - Turn_Speed; Serial.print(" ROutput=");Serial.println(ROutput); lastErr = error; lastTime = now; } } void PWMControl(){ if(LOutput &gt; 0){ digitalWrite(TN1, HIGH); digitalWrite(TN2, LOW); } else if(LOutput &lt; 0){ digitalWrite(TN1, LOW); digitalWrite(TN2, HIGH); } else{ digitalWrite(TN1, HIGH); digitalWrite(TN2, HIGH); } if(ROutput &gt; 0){ digitalWrite(TN3, HIGH); digitalWrite(TN4, LOW); } else if(ROutput &lt; 0){ digitalWrite(TN3, LOW); digitalWrite(TN4, HIGH); } else{ digitalWrite(TN3, HIGH); digitalWrite(TN4, HIGH); } analogWrite(ENA, min(255, abs(LOutput) + LMotor_offset)); analogWrite(ENB, min(255, abs(ROutput) + RMotor_offset)); } </code></pre> <p>and this is a picture of the mpu6050 on the sensor shield </p> <p><img src="https://i.stack.imgur.com/S8koh.jpg" alt="enter image description here"></p>
<p>The shield you linked to is no longer sold.</p> <p>The current version is <img src="https://i.stack.imgur.com/F7ccO.jpg" alt="enter image description here"></p> <p>But it has no special connection for an MPU6050 breakout (and BTW that same 6050 board is $6 about everywhere else). A shield serves no purpose for just the 6050 really.</p> <p>If you connected the 6050 to the I2C lines (aka A4 &amp; A5), Then you also need to connect an additional interrupt line. If you are using unmodified example code, it depends on the interrupt being connected.</p> <p>Here is a post made a while back using the 6050</p> <p><a href="http://www.spiked3.com/very-cool-imu-demo/" rel="nofollow noreferrer">http://www.spiked3.com/very-cool-imu-demo/</a></p> <p>It is possible to use the 6050 without interrupts but you would have to (understand and) modify the standard example code.</p> <p>Update: I knew you had a different board, and it had a connector for the 6050, the comment was that the link you provided, since it was 'no longer available', did not link to any documentation. Without a schematic it can not be known how it is hooked up beyond simple I2C. As you are using other devices I am not familiar with, I would expect some sort of conflict on the i2C bus maybe. Are all i2c bus devices using the same reference voltage? It does not matter if they are all 5v or all 3.3V as long as they are all the same.</p> <p>Since you say 'nothing is printed' and your second line of setup is 'initialize' gyro, odds are good it is not getting past that. Simple (archaic) debugging, put a print (and a small delay) before and after the call to initialize.</p> <p>My code uses the following for Wire.begin</p> <pre><code>#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE Wire.begin(); TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz) #elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE Fastwire::setup(400, true); #endif </code></pre> <p>I dont know if your Arduino is different and if it would make any difference.</p> <p>I have a line after initialize</p> <pre><code>mpu.testConnection(); </code></pre> <p>That may or may not help you.</p> <p>FYI PI is already defined, as is DEG_TO_RAD and RAD_TO_DEG</p> <pre><code>if (abs(RAD_TO_DEG * headingDelta) &gt; .1F) poseChanged = true; </code></pre> <p>Update: I just looked quickly at the code, and the only thing initialize does is write to i2c, it never waits really. And that means writing to I2C is hanging. I ran into this once when I had an unpowered device on the bus. I thought it would not harm, but I was wrong. Does the power light on the mpu come on? (is it really getting power?) I have run them at 3.3v and 5V so I do not think that would be a problem, but if you can, switch it to 3.3V to be sure. Getting down to the nitty gritty, you could check if the default pullup resistors are still on the board and did not get accidentally knocked off. Even better would be to try it with a known good MPU. I have about 10 of them within reach :P (spiked3.com)</p>
12468
|arduino-uno|
Which Arduino Board should I start with?
2015-06-08T12:33:26.380
<p>I am interested in Arduino projects. I want to learn to develop my own Arduino based system. The problem is I am not sure which Adruino board must I start with. Any ideas are appreciated, I have searched many discussion forum but could not find a satisfactory answer.</p> <p>My questions are:</p> <ol> <li>Which Arduino Board should I start with?</li> <li>Is it possible to work on Arduino based projects without the board; like having a simulation of the board? If so how?</li> </ol>
<p>My advice: - get a model with USB port (some do not have one) - the DUE might seem attractive, but you have less libraries available and less examples, I'd recommend it more as follow up - you will get frustrated if you do not know how to code, at least a bit, so if you have not programmed before, you might want to spend some time trying simple stuff just with your PC - same about electronics: if you do not have previous experience, it might be preferable to play a bit with a breadboard and some components (LEDs, resistors, switches, etc.); this will reduce the likelyhood that you fry your Arduino. Remember to buy some cables MM/MF/FF, you will end up needing all of them, sooner or later. For powering the board, you can find nice power supplies that cn be powered by a USB cable.</p> <p>I have bought UNOR3 clones at $4-$5 on ebay, so if you can afford it, I'd suggest you buy a couple, that will enable you playing with I2C master slave and similar configurations.</p>
12476
|power|arduino-due|voltage-level|
Arduino Due and Vin, 3.3V and 5V power inputs
2015-06-08T16:05:42.707
<p>I just want to confirm something before I wire up my first ever Arduino project and fry all the stuff I just spent money on.</p> <p>It is my <em>understanding</em> that the <code>Vin</code> power input will tolerate a 9V battery and use voltage regulators to pare it down to either 3.3V or 5V (as different parts of the board require). So it is then my <em>assumption</em> that if I have a 9V battery running to <code>Vin</code>, that I could then connect a power wire to the <code>3.3V</code> connector, and reliably get a 3.3V signal (and ditto for 5V), <strong>yes?</strong></p> <p>Or, is it that they are <em>input</em> jacks <em>expecting</em> either 3.3V or 5V signals? I guess I'm confused over this:</p> <ul> <li>Will <code>Vin</code> then power the 3.3V and 5V inputs, giving me access to voltage at that level; or</li> <li>Do I have to choose between 3.3V, 5V or <code>Vin</code>, and only use one of those to power my board (with the appropriate voltage level)</li> </ul>
<p><code>DC Jack</code> is connected, through a diode, to <code>Vin</code>.</p> <p><code>Vin</code> is stepped down to <code>5V</code> on-board.</p> <p><code>5V</code> is stepped down to <code>3V3</code> on board.</p> <p>Thus you can do any one of the following numbered items.</p> <ol> <li><p>Connect a 7-12V supply to the <code>DC Jack</code>; thus:</p> <ul> <li>use <code>Vin</code> as a supply @ DC - 0.7V for off-board peripherals, and</li> <li>use <code>5V</code> as a supply for off-board peripherals, and</li> <li>use <code>3V3</code> as a supply for off-board peripherals.</li> </ul></li> <li><p>Connect a 6-12V supply to <code>Vin</code>; thus:</p> <ul> <li>use <code>5V</code> as a supply for off-board peripherals, and</li> <li>use <code>3V3</code> as a supply for off-board peripherals.</li> </ul></li> <li><p>Connect 5V supply to the <code>5V</code>; thus:</p> <ul> <li>use <code>3V3</code> as a supply for off-board peripherals.</li> </ul></li> </ol> <p>The above is only guaranteed for boards that <strong>follow the reference schematic</strong>, as plenty of clone/compatible boards do. If you buy a cheap Chinarduino and something doesn't work, or the thing breaks, after following anything above then that's your tough luck.</p>
12477
|pins|arduino-due|
Arduino Due Pinout with Explanations?
2015-06-08T16:12:57.473
<p>I am trying to understand what each pin on my Arduino Due is and what it is used for, and so I have been searching for things like "<em>Arduino Due pinout</em>", "<em>Arduino Due pin mapping</em>" and similar.</p> <p>The best I could find was <a href="http://www.arduino.cc/en/Hacking/PinMappingSAM3X" rel="nofollow">this table</a>, however it doesn't help you out at all if you are completely new to electronics and have no idea what <code>TX2</code>, <code>SDA</code> or <code>NPCSO</code> mean, etc.</p> <p>Does anybody know of Arduino/Due documentation that explains what each I/O pin is?</p>
<p>The Arduino Due is backed by an Atmel SAM3X8E ARM Cortex-M3 microprocessor and most of the pins on the Due are connected directly to this chip. Therefore, you can refer directly to the chip's datasheet for descriptions of these hardware features.</p> <p><a href="http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf" rel="nofollow">Atmel SAM3X8E ARM Cortex-M3 datasheet</a></p>
12480
|arduino-uno|c++|pwm|analogread|hardware|
How to increment and decrement an output voltage by using two buttons?
2015-06-08T17:11:42.157
<p>I'm trying to create a code using an Arduino Uno board to increment and decrement the output voltage of the Arduino Uno which is 5 volts and I need to step it up to 10 volts which I have done below. </p> <p>The things that are missing on the schematic are two buttons. I want to be able to increment 0.5 volts with each press of Button-A until the Arduino is at 5 volts. With Button-B I want to be able to lower the voltage by 0.5 volts with each press of the button till value is 0. </p> <p>I can do the calculations and the circuit design but I'm not much of a programmer. I just want to know if anyone can point me in a good direction of where I can get the right code. I have already looked at all the tutorials on the Arduino Website. I do know I have to work with the PWM functions as well as <code>attachinterrupt()</code> and <code>Debounce()</code> functions. Also, how do I set the increments so that I don't go over, say it takes 10 presses to get to 5 volts on the 11th press have it not do anything so I don't break anything. So can anyone please help me with any suggestions? </p> <p>I have a low pass filter on the circuit for noise handling and like I said I need to add in the buttons to my schematic. </p> <p><img src="https://i.stack.imgur.com/sMiDk.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fsMiDk.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>Here is my code I have made. I'm using an LED to test the V<sub>out</sub> aspect. So far I can only get my LED to flicker from 2 to 4 volts and my buttons A and B don't work. Can someone look over my code and see how bad I made this?</p> <pre class="lang-C++ prettyprint-override"><code>int PWMPin = 6; // output pin supporting PWM int buttonApin = 9; // buttonA to pin 9 PWM int buttonBpin = 10; // buttonB to pin 10 PWM float value = 0; // read the value at 0 int fadeValue = value; void setup() { Serial.begin(9600); //initialize serial communication at 9600 baud pinMode(buttonApin, INPUT_PULLUP); pinMode(buttonBpin, INPUT_PULLUP); pinMode(PWMPin, OUTPUT); } void loop() { { int port = analogRead(0); port = map(port, 0, 10, 0, 255); analogWrite(6, port); } { if (digitalRead(buttonApin) == LOW, fadeValue) { // fade from min to max in increments of 25.5 points: basically (0.5 volts) for(int fadeValue = 0 ; fadeValue &lt;= 255; fadeValue +=25.5) digitalWrite(PWMPin, fadeValue); // sets the value (range from 0 to 255): Serial.println(PWMPin); analogWrite(PWMPin, fadeValue); } } { if (digitalRead(buttonBpin) == LOW, fadeValue) { // fade from max to min in increments of 25.5 points: for(int fadeValue = 255 ; fadeValue &gt;= 0; fadeValue -=25.5) digitalWrite(PWMPin, fadeValue); // sets the value (range from 0 to 255): basically (0.5 volts) analogWrite(PWMPin, fadeValue); } } } </code></pre>
<p>I suggest you to use debounce to detect if a pin has been definitely pressed. You could also test using interrupts (hint: interrupts can happen multiple times even if you "only" pressed once). So either use Arduino's example of debounce or take a look at the <a href="http://playground.arduino.cc/Code/Bounce" rel="nofollow">Bounce2 library</a> found on their website. </p> <p>Now that you can check whether or not either button A or B has been pressed, how do you keep track of the voltage to be output? You should use a <code>counter</code> variable that will be incremented when button A is pressed and decremented when button B is pressed. Here is a pseudocode: </p> <pre class="lang-C++ prettyprint-override"><code>if(ButtonA == pressed) counter++; else if(ButtonB == pressed) counter--; </code></pre> <p>This <code>counter</code> variable can be used to control the output voltage. Remember that the argument for <code>analogWrite()</code> function on the Arduino Uno is the duty cycle which takes in values from 0 to 255. So <code>analogWrite(0)</code> ≣ 0 Volt and <code>analogWrite(255)</code> ≣ 5 Volt. So at the moment, you couldn't just do <code>analogWrite(counter)</code> because you would need to press 255 times button A!</p> <p>Instead, you would need a way to convert your counter to reflect the increment you need. You mentioned that it should require 10 presses to reach 5 Volt at the Arduino output, and the easiest way to accomplish this is to use Arduino's <a href="http://www.arduino.cc/en/Reference/Map" rel="nofollow">Map function</a>. The pseudocode would look like this: </p> <pre class="lang-C++ prettyprint-override"><code>Output = map(counter, 0, 10, 0, 255); analogWrite(Output); </code></pre> <p>Now there is one last step! The map function will limit the output voltage from 0 to 5 Volt so everything will be safe; however, the counter is not limited to 0 to 10. This means that even if the counter is at 15 (because you pressed button A too many times) the voltage will be 5 Volt and you would need to press button B at least 6 times to see the voltage go down! So to limit the counter you could easily implement your own function:</p> <pre class="lang-C++ prettyprint-override"><code>if(counter &gt;= 10) counter = 10; else if (counter&lt;= 0) counter = 0; </code></pre> <p>You could also use Arduino's <code>constrain()</code> function which more information can be found on their website.</p> <p>Hopefully this points you in the right direction.</p>
12496
|arduino-uno|arduino-mega|current|
PYM-1 PIR sensor current concerns
2015-06-09T02:21:34.030
<p>I am busy toying with some PIR sensors to detect movement etc for a nightlight for my kids. One of the sensors I ordered is the PYM-1 PIR sensor.</p> <p>The data sheet states the following:</p> <ul> <li>Operating Voltage: 4,5~5V.</li> <li>Standby current: 65 micro-amps (65uA)</li> <li>Operating Current: 40mA (40 milli-amps)</li> </ul> <p>The limit for current on the arduino pins is 40mA. According to documentation at the arduino site 40mA is the upper limit per pin and the site clearly states: Absolute Maximum Ratings - the point where damage will start to happen I would rather avoid sinking the current directly on the Arduino.</p> <p>So my question is will sinking 40mA on a pin cause damage? I have not been visited by the blue smoke genie yet and would rather avoid it at this point. </p> <p>I suspect it might be safer to run this via a transistor and external power than directly on the arduino?</p>
<p>This is completely acceptable for your intended purpose.</p> <p>By itself it will act as a light on/off trigger as others have noted.<br> An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form using an Arduino is overkill. </p> <p>By itself it will act as a light on/off trigger as others have noted.<br> An Arduino could be added if you wish to add extra features when the PIR is triggered. In it's most basic light-switching form adding an Arduino is overkill. </p> <p>When it comes to playing overkill can be good :-)</p> <hr> <p><strong>To use it to provide input to an Arduino and NOT to a mains level light:</strong></p> <p><strong>NB</strong> relay contacts may only be connected to mains for light switching <strong>OR</strong> to the Arduino. <strong>NEVER</strong> to both at the same time.</p> <p>Connect it's DC supply input to your Arduino (or other) power supply.<br> As long as the <strong>supply</strong> can provide 40 mA when needed it will work OK.<br> 40 mA is a <strong>power supply</strong> rating This is unrelated to the Arduino pin loading.</p> <p>Connect the output to an Arduino digital pin configured as an input. </p> <p><img src="https://i.stack.imgur.com/HrPkj.jpg" alt="enter image description here"></p> <p>The output is a relay, activated when an object is sensed.<br> When inactive the centre pin is probably connected to the right pin - Check with Ohm meter. </p> <p>When activated the left pin in connected to the centre pin (see their diagram)</p> <p>Connect ground to right pin.<br> Connect Arduino digital input to centre pin. Connect a "high" level to left hand pin.<br> OR as Majenko suggests, just set the pin to have pullups enabled. </p> <p>If connecting to V+ as shown then V+ can be Vcc (=5V for a 5V Arduino, 3v3 for a 3V3 Arduino) DO NOT set V+ to higher than Arduino's Vcc. You can connect a say 1k to 10k resistor from V+ to the voltage source bur still do not set V+ above Vcc.<br> OK - just have pullups enabled:-)</p> <p>eg (untested) </p> <blockquote> <p>int ADCMode = 0;<br> int PIRPin = 6; // PIR connected to digital pin 6<br> void setup()<br> {<br> pinMode(PIRPin, INPUT_PULLUP); // set PIRpin as input with pullup<br> }<br> void loop()<br> {<br> ...<br> ADCMode = digitalRead(PIRpin); // $Read PIR status<br> ...<br> } </p> </blockquote> <p>When the circuit activates digitalRead() will return a high.<br> When the circuit is not activated digitalRead() will return a low. </p> <hr> <p>See <a href="http://www.arduino.cc/en/Tutorial/DigitalPins" rel="nofollow noreferrer">here</a> re Arduino pin modes </p>
12509
|programming|
How do you call to a previous function?
2015-06-09T18:53:55.887
<p>I'm using an Arduino to control a reverse osmosis machine, I would like after a certain number low pressure events to return to the testing routine. Can you call to previous functions? </p>
<p>You need to get your head around the Finite State Machine (FSM).</p> <p>It is a programming method which allows your program ("Machine") to be in any of a certain number ("Finite") of states ("State"). One state would be reading pressure. Another state would be "testing", or whatever.</p> <p>I wrote a tutorial ages ago about it: <a href="http://hacking.majenko.co.uk/finite-state-machine" rel="nofollow">http://hacking.majenko.co.uk/finite-state-machine</a></p>
12515
|lcd|library|adafruit|
Adafruit_GFX setRotation not working when called from within a class
2015-06-10T02:14:14.033
<p>Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working. The code is very straight forward.</p> <p>If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.</p> <p>Outside of the class, the rotation works fine.</p> <p>Any help would be greatly appreciated!</p> <pre><code>#include "SPI.h" #include "Adafruit_GFX.h" #include "Adafruit_ILI9341.h" #define TFT_DC 5 #define TFT_CS 3 Adafruit_ILI9341 *tft; uint8_t newRotationAngle = 0; void drawStuff() { tft-&gt;setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff)); tft-&gt;fillRect(0, 0, tft-&gt;width(), tft-&gt;height(), ILI9341_BLACK); tft-&gt;setCursor(0, 0); tft-&gt;print(F("01234567890")); delay(250); } class test { public: void init(Adafruit_GFX *_p) { ptrTft = _p; }; void inClassRotation(int newRotation) { ptrTft-&gt;setRotation(newRotation); drawStuffInClass(); }; void drawStuffInClass() { ptrTft-&gt;setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff)); ptrTft-&gt;fillRect(0, 0, ptrTft-&gt;width(), ptrTft-&gt;height(), ILI9341_BLACK); ptrTft-&gt;setCursor(0, 0); ptrTft-&gt;print(F("01234567890")); delay(250); } Adafruit_GFX *ptrTft; }; test instance; void setup() { tft = new Adafruit_ILI9341(TFT_CS, TFT_DC); tft-&gt;begin(); tft-&gt;setTextSize(2); instance.init(tft); } void outsideClassRotation(Adafruit_GFX *passed) { passed-&gt;setRotation(newRotationAngle); drawStuff(); } void loop(void) { newRotationAngle++; // This works. No problems. // outsideClassRotation(tft); // This does NOT rotate but still prints the text fine. instance.inClassRotation(newRotationAngle); } </code></pre>
<p>I would actually be quite surprised if <code>outsideClassRotation()</code> actually worked. My guess is that <em>it does not work as is</em>. Maybe it did work at some point, but then you made some subtle changes to your code and did not check that it is still working.</p> <p>Here is the deal: there are two <code>setRotation()</code> methods:</p> <ul> <li><code>Adafruit_GFX::setRotation(unsigned char)</code> does very little besides storing the rotation angle... which is not used anyway.</li> <li><code>Adafruit_ILI9341::setRotation(unsigned char)</code> actually sends commands to the LCD asking it to apply the rotation; this is the method you want.</li> </ul> <p>The problem is that <em>these methods are not <code>virtual</code></em>, which means that when you call them through a pointer, as in <code>some_pointer-&gt;setRotation(the_angle);</code>, you get the method corresponding to <em>the type of the pointer</em>, not the type of the actual object. For example:</p> <pre class="lang-c++ prettyprint-override"><code>tft-&gt;setRotation(the_angle); // calls Adafruit_ILI9341::setRotation() ptrTft-&gt;setRotation(the_angle); // calls Adafruit_GFX::setRotation() passed-&gt;setRotation(the_angle); // calls Adafruit_GFX::setRotation() </code></pre> <p>I checked this by uncommenting your call to <code>outsideClassRotation()</code> and disassembling the compiled binary: both times you are calling <code>Adafruit_GFX::setRotation()</code>.</p> <p><strong>Solution</strong>: change your <code>Adafruit_GFX *</code> pointers to be of type <code>Adafruit_ILI9341 *</code>, or patch Adafruit_GFX.h to make <code>setRotation()</code> virtual.</p>
12520
|led|pwm|max7219|
Fading the brightness of LEDs using MAX7219 and PWM
2015-06-10T11:30:28.873
<p>I am doing a project with bi-color led matrix 8x8 and MAX7219 as the LED driver. I want to implement a fading effect on the LEDs, like mixing the two colors by varying the individual duty cycles.</p> <p>My idea is the use of the <code>Iset</code> parameter; I would connect the PWM pin from Arduino through the <code>Rset</code> resistor and feed that into the Iset of the MAX7129 instead of 5V supply. Please suggest whether or not this is possible, if not what can be the alternative approach?</p>
<p>This is possible in two ways:</p> <ol> <li>The MAX72xx has its own internal intensity control register. From the datasheet:</li> </ol> <blockquote> <p>Digital control of display brightness is provided by an internal pulse-width modulator [...]. The modulator scales the average segment current in 16 steps from a maximum of 31/32 down to 1/32 of the peak current set by RSET [...].</p> </blockquote> <p>This of course requires no extra components or effort, but you are limited slightly by only a 4-bit intensity resolution. Also, there is no 'off' so you'd have to either manually blank the displays or put the ICs into shutdown mode.</p> <ol start="2"> <li>Your suggested way is possible. However, the low frequency of the Arduino's PWM may lead to flickering if the MAX7219's internal segment current reference driver needs a steady voltage. You'll have to consider smoothing the PWM output through a low pass filter - the TL072/TL082 has two op-amps so you can use one for colour A and the other for colour B. I'd choose an op-amp over passive filtering because the current drawn from the Arduino will be negligible and the stability of the current into the MAX7219 will be improved.</li> </ol>
12523
|led|power|arduino-due|battery|
Simple LED circuit is not working
2015-06-10T14:16:24.410
<p>This is my first circuit ever (!) and so I'm hoping that I'm just making an easy-to-spot rookie mistake. I am trying to power an Arduino Due with a 9V battery and then have the Due in turn power a red LED. No blinking. No sketchpad/C program flashed to the chip. Just straight up electricity:</p> <p><img src="https://i.stack.imgur.com/1dQW0.jpg" alt="enter image description here"></p> <p>When I connect the battery, several things happen:</p> <ol> <li>There is a green power LED on the Due that lights up; and</li> <li>Right next to it is an orange LED (on the Due itself) that blinks every few seconds (not sure what this LED is or what the blinking means, but providing that detail for good measure); and</li> <li>The red LED on the breadboarrd does <strong>not</strong> light up</li> </ol> <p>This is a 2V/15mA LED, and as you can see I'm powering it from the 5V power jack on the Due. So a 220 ohm resistor should be perfect for it (<code>R = (Vs - V) / I = (5V-2V) / .015A ~= 220 ohms</code>).</p> <p>So, for the first time ever, I busted out my multimeter, set it to the voltage setting, and started testing the circuit. First I tested <code>Vin</code> and <code>GND</code> on the Due (that is, the connection between the battery and the Due), and the multimeter lit up and hovered (correctly) around 5V. So far so good. Next I tested the power and ground connections on the breadboard power rails (indicated in green above). Again, the multimeter reported a roughly 5V power supply. Then I tested the connection from the power rail to the row (purple in pic above) feeding power to the resistor, and to my surprise, the multimeter reports <strong>no power</strong> at those two purple locations.</p> <p>My <em>understanding</em> was that the power rail will power the entire column its connected to (in my case, the left-most column), and then any rows connecting to a power rail/column will also be powered. So I'm not understanding why there's voltage on my power rail/column, but not on the wire connecting my power rail to the resistor. Any ideas?</p> <hr> <h3>Update:</h3> <p>Here is my corrected circuit per initial feedback. Please note this is still not working, but I think I'm getting close:</p> <p><img src="https://i.stack.imgur.com/lxCrP.jpg" alt="enter image description here"></p>
<p>What connects the resistor to the LED?</p> <p><img src="https://i.stack.imgur.com/E3mmD.png" alt="enter image description here"></p> <p>Absolutely nothing.</p> <p>It's hard to work out which holes the LED is plugged into, but I think your current circuit looks something like this:</p> <p><img src="https://i.stack.imgur.com/moMz2.png" alt="enter image description here"></p> <p>You need to connect that resistor and LED together.</p> <p>For your edit:</p> <p>Now your circuit looks like this:</p> <p><img src="https://i.stack.imgur.com/zM9rH.png" alt="enter image description here"></p> <p>Behind the 5 pins in that column with the ground wire there is a big chunk of metal connecting them all together. It's no different to if you'd taken the LED and twisted the pins together into one. There's no way the power can get up one and down the other when they are connected together like that. You need to separate them into different columns.</p> <p>And this is how the (black) connections inside are laid out, and how your (red) electricity is flowing:</p> <p><img src="https://i.stack.imgur.com/7Q11H.jpg" alt="enter image description here"></p> <p>And here is how the circuit should look, using a program called Fritzing. It's a pretty basic design tool, but great for showing wiring.</p> <p><img src="https://i.stack.imgur.com/X23yu.png" alt="enter image description here"></p> <p>You can see how the green highlighting shows the columns that are connected.</p>
12527
|serial|programming|c++|
How do I print the reading serial data sending from Arduino
2015-06-04T17:39:28.830
<p>I am sending data to Arduino using QtSerialPort. When I read the data the ouput has several not printer characters. I am using a QTexEdit (in left hand) to insert the data to send and other (in right hand) to insert the data to read.</p> <p><img src="https://i.stack.imgur.com/EaziF.png" alt="enter image description here"></p> <p>You can see the receive data has some no printer character.</p> <h1>Workflow of sending and receiving data between QtSerialPort and Arduino</h1> <h3>Sending Data with QtSerialPort</h3> <pre><code>void MainWindow::sendData(){ QString m_allData = m_sendEdit-&gt;toPlainText(); int i = 0; int size = m_allData.size(); QString line = ""; int c = 0; while(i &lt; size){ line.append(m_allData[i]); if(c == 24){ int sended = m_serialPort-&gt;write(line.toUtf8(), 24); m_serialPort-&gt;flush(); line.clear(); c = 0; } i++; c++; } if(c &gt; 0){ m_serialPort-&gt;write(line.toUtf8(), c); } m_serialPort-&gt;flush(); } </code></pre> <p>I want to send the data with a buffer size of 24 bytes.</p> <h3>Reading and Sending Data with Arduino</h3> <pre><code> void setup() { Serial.begin(9600); } void loop() { delay(1000); if (Serial.available() &gt; 0){ short i = 0; int size = Serial.available(); String data = Serial.readString(); Serial.print(data); } } </code></pre> <p>The Arduino code is simple. </p> <h3>Receiving Data with QtSerialPort</h3> <pre><code>void MainWindow::readData(){ int c = 0; char * dataBuffer; int size = m_serialPort-&gt;bytesAvailable(); dataBuffer = new char[size]; c = m_serialPort-&gt;read(dataBuffer, size); m_receiveEdit-&gt;setText(m_receiveEdit-&gt;toPlainText() + QString::fromUtf8(dataBuffer)); delete dataBuffer; } </code></pre> <p>I am trying to read the same data that I send to Arduino. What kind of convertion do I have to do?</p>
<p>You have no warranty that Qt will receive the whole message in a single chunk. It may receive "no se" as the first chunk, and then "q pasa" as the second chunk. Since <code>dataBuffer</code> is dynamically allocated, it initially contains garbage, and you are printing the part of this garbage that you did not overwrite.</p> <p>An easy fix would be to simply NULL-terminate the buffer:</p> <pre class="lang-c++ prettyprint-override"><code>dataBuffer = new char[size + 1]; // + 1 byte for '\0' c = m_serialPort-&gt;read(dataBuffer, size); dataBuffer[c] = '\0'; // terminate the string </code></pre>
12528
|serial|programming|c++|
How do I receive more that 64 bytes with Arduino
2015-06-05T15:48:40.853
<p>I am using QtSerialPort to send and receive data from Arduino. I am sending <strong>more than 64 bytes</strong> (125, 220, more), I receive the data with Arduino, and trying to sending back the same data, but Arduino <strong>sending only 64 bytes</strong> in its response. Then I am thinking that the problem is with Arduino buffer. I am trying to clear the data but without result.</p> <p>Here is my Arduino code:</p> <pre><code>void loop() { if (Serial.available() &gt; 0) { int i = 0; delay(500); int size = Serial.available(); while (i &lt; size) buffer[i++] = Serial.read(); Serial.print(buffer); //delay(500); int j = 0; while (j &lt; size) buffer[j++] = '\0'; //while (Serial.available()) Serial.read(); I tried it //Serial.flush(); Also tried it, but nothing. } } </code></pre>
<p>Instead of blocking the loop for 500&nbsp;ms, you should be actively reading the data as it comes. Otherwise the internal buffer of the <code>Serial</code> object will overflow after only 64&nbsp;bytes are received.</p> <p>Here is an example that copies the incoming bytes into a larger buffer (256&nbsp;bytes) and, upon receiving an end-of-line character, echoes back the whole line.</p> <pre class="lang-c++ prettyprint-override"><code>void loop() { static char buffer[256]; static size_t pos; // position of next write while (Serial.available() &amp;&amp; pos &lt; sizeof buffer - 1) { // Read incoming byte. char c = Serial.read(); buffer[pos++] = c; // Echo received message. if (c == '\n') { // \n means "end of message" buffer[pos] = '\0'; // terminate the buffer Serial.print(buffer); // send echo pos = 0; // reset to start of buffer } } } </code></pre>
12534
|arduino-uno|mpu6050|
Reading values from the register of a slave
2015-06-10T15:59:27.873
<p>I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.</p> <pre><code>// MPU-6050 Short Example Sketch // By Arduino User JohnChi // August 17, 2014 // Public Domain #include&lt;Wire.h&gt; const int MPU=0x68; // I2C address of the MPU-6050 int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; void setup(){ Wire.begin(); Wire.beginTransmission(MPU); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); Serial.begin(9600); } void loop(){ Wire.beginTransmission(MPU); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU,14,true); // request a total of 14 registers AcX=Wire.read()&lt;&lt;8|Wire.read(); // 0x3B (ACCEL_XOUT_H) &amp; 0x3C (ACCEL_XOUT_L) AcY=Wire.read()&lt;&lt;8|Wire.read(); // 0x3D (ACCEL_YOUT_H) &amp; 0x3E (ACCEL_YOUT_L) AcZ=Wire.read()&lt;&lt;8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) &amp; 0x40 (ACCEL_ZOUT_L) Tmp=Wire.read()&lt;&lt;8|Wire.read(); // 0x41 (TEMP_OUT_H) &amp; 0x42 (TEMP_OUT_L) GyX=Wire.read()&lt;&lt;8|Wire.read(); // 0x43 (GYRO_XOUT_H) &amp; 0x44 (GYRO_XOUT_L) GyY=Wire.read()&lt;&lt;8|Wire.read(); // 0x45 (GYRO_YOUT_H) &amp; 0x46 (GYRO_YOUT_L) GyZ=Wire.read()&lt;&lt;8|Wire.read(); // 0x47 (GYRO_ZOUT_H) &amp; 0x48 (GYRO_ZOUT_L) Serial.print("AcX = "); Serial.print(AcX); Serial.print(" | AcY = "); Serial.print(AcY); Serial.print(" | AcZ = "); Serial.print(AcZ); Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet Serial.print(" | GyX = "); Serial.print(GyX); Serial.print(" | GyY = "); Serial.print(GyY); Serial.print(" | GyZ = "); Serial.println(GyZ); delay(3330); } </code></pre> <p>Now there are a few things i want to ask regarding this code: 1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous (<a href="https://www.olimex.com/Products/Modules/Sensors/MOD-MPU6050/resources/RM-MPU-60xxA_rev_4.pdf" rel="nofollow">see datasheet here</a>) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?</p> <p>2.<code>AcX=Wire.read()&lt;&lt;8|Wire.read();</code></p> <p>This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works? </p>
<p>For reading non-consecutive bytes, the “normal” way would be to do a one-byte request and a one-byte read for each byte you want. However, if the bytes you want are close enough (e.g. you want every other byte), it would be faster to do a contiguous read and just ignore the bytes you do not want. E.g.:</p> <pre class="lang-c++ prettyprint-override"><code>byte data1 = Wire.read(); // read first byte Wire.read(); // read and ignore second byte byte data3 = Wire.read(); // read third byte </code></pre> <p>For your question regarding the meaning of <code>Wire.read()&lt;&lt;8|Wire.read();</code>:</p> <ol> <li><code>Wire.read()</code> return a 16-bit integer, where the 8 most significant bits are zero and the 8 least-significant bits contain the actual data. In binary, it's something like <code>00000000xxxxxxxx</code>, where <code>x</code> are the data bits.</li> <li><code>&lt;&lt;8</code> means “shift left by eight positions”, where the missing bits are replaced by zeros. Thus <code>Wire.read()&lt;&lt;8</code> is <code>xxxxxxxx00000000</code> in binary.</li> <li>The second call to <code>Wire.read()</code> return another 16-bit integer in the form <code>00000000yyyyyyyy</code>.</li> <li>The vertical bar <code>|</code> is the bitwise-or operator: each bit of the left operand is or-ed with the corresponding bit of the right operand to give one bit of the result: <code>x or 0</code> is <code>x</code>, <code>0 or y</code> is <code>y</code>.</li> <li>Then, the whole expression gives <code>xxxxxxxxyyyyyyyy</code>, where <code>xxxxxxxx</code> comes from the first <code>Wire.read()</code> and <code>yyyyyyyy</code> from the second.</li> </ol> <p>The problem here is that the “first” and “second” <code>Wire.read()</code> in the sentence above refer to the position of the call in the line, not to the actual order in which the calls are performed. Thus you may be lucky and get the the correct byte order... or not. You should instead do a single read per statement if you want to control the byte order. For MSB first:</p> <pre class="lang-c++ prettyprint-override"><code>AcX = Wire.read() &lt;&lt; 8; // read most significant byte first AcX |= Wire.read(); // then least significant byte </code></pre> <p>And for LSB first:</p> <pre class="lang-c++ prettyprint-override"><code>AcX = Wire.read(); // read least significant byte first AcX |= Wire.read() &lt;&lt; 8; // then most significant byte </code></pre>
12540
|arduino-ide|arduino-due|uploading|avrdude|
Problems uploading sketch to Arduino Due
2015-06-10T18:20:39.063
<p>Windows 7 here. I just bought an <a href="http://www.arduino.cc/en/Main/ArduinoBoardDue" rel="nofollow">Arduino Due</a> and downloaded the Arduino IDE. I wrote a simple "blink LED" program (see below) and am trying to flash it to the Due.</p> <p>When I connected the Due to my laptop (via micro USB cable), I got a warning on my laptop that it could not find the correct device driver. So I followed the instructions discussed on <a href="https://www.youtube.com/watch?v=fCxzA9_kg6s" rel="nofollow">this excellent video tutorial</a> and went into <code>Control Panel &gt;&gt; System &gt;&gt; Device Manager &gt;&gt; Arduino</code> and pointed it to load the appropriate device driver from <code>C:\Program Files (x86)\Arduino\drivers</code>. This got rid of the warning. Hooray!</p> <p>I then Verified &amp; Compiled my program:</p> <pre><code>int led = 13; void setup() { pinMode(led, OUTPUT); } void loop() { digitalWrite(led, HIGH); delay(5000); digitalWrite(led, LOW); delay(5000); } </code></pre> <p>Great success! Now it was time for me to upload the program to my Due. The first time I tried to upload it, I got the following error:</p> <pre><code>Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno" Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes. avrdude: ser_open(): can't open device "\\.\COM1": The system cannot find the file specified. Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions. This report would have more information with "Show verbose output during compilation" enabled in File &gt; Preferences. </code></pre> <p>So then in the IDE I went to <code>Tools &gt;&gt; Port</code> and changed the selection from <code>Serial</code> to <code>COM3</code> (again, sort of explained in that video tutorial). I tried to upload again:</p> <pre><code>Arduino: 1.6.4 (Windows 7), Board: "Arduino Uno" Sketch uses 1,068 bytes (3%) of program storage space. Maximum is 32,256 bytes. Global variables use 11 bytes (0%) of dynamic memory, leaving 2,037 bytes for local variables. Maximum is 2,048 bytes. avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x09 avrdude: stk500_recv(): programmer is not responding avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x09 Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions. This report would have more information with "Show verbose output during compilation" enabled in File &gt; Preferences. </code></pre> <p>I thought it was interesting that the IDE thinks this is an Arduino Uno. So then I went to <code>Tools &gt;&gt; Board</code> and changed the selection from <code>Uno</code> to <code>Duemilanove</code>, hoping that Due and Duemilanove are compatible for the programmer/flasher tool. This time the error was the same as last, except the first line reads:</p> <pre><code>Arduino: 1.6.4 (Windows 7), Board: "Arduino Duemilanove or Diecimila, ATmega328" </code></pre> <p>So at least the IDE is switching board correctly. :-) I should note that my <code>Tools &gt;&gt; Board</code> menu <strong>does not</strong> have an "Arduino Due" option. And when I go to <code>Tools &gt;&gt; Board &gt;&gt; Board Manager</code>, searching for Due does not turn up anything either.</p> <p>I also tried running the upload with verbose output, but that really didn't tell me anything more. I'm happy to post the exact verbose output but figured I could omit it here for brevity. I also <em>did</em> peruse the <a href="http://www.arduino.cc/en/Guide/Troubleshooting#upload" rel="nofollow">troubleshooting link</a> that the error output recommends, but it looks like I've already exhausted all of those recommendations as well.</p> <p>I'm stuck and frustrated, any suggestions?</p> <p>What do I need to do to get the IDE programming my Due?</p>
<p>Yes, I just had this problem myself.. Unless you use the Boards Manager Menu and install the Arduino SAM Boards (32Bits ARM cortex M3) board info you will not be able to upload your sketch. After installing in the Boards Manager you will see the Arduio Due programming port and Arduino Native port as an extra options at the bottom or the TOOLS>BOARD menu. That should fix the problem.(Check which you are connected to and which COM port) If you still have trouble, disconnect and reconnect the DUE and restart the IDE and if required restart you computer.</p> <p>This seems to be a common problem when people switch from the Uno or MEGA to the Due. I'm surprised this is not installed as standard in the IDE. I am using 1.6.5r2.</p> <p>Thanks also to Ignacio Vazquez-Abrams.</p>