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
18790
|programming|arduino-mega|
How to set address for using more than MPU9250
2015-12-18T06:23:42.797
<p>I am trying to build a project that contains more than one MPU 9250, until now I'm still confused to MPU9250. If I were going to that, does anybody here know how to set addresses to each of the MPU's I am going to use? Thank you for spending time reading my question. I hope someone will help me get through this.</p>
<p>It is possible to have up to two MPU 9250 devices on an I2C bus without any extra logic. Pin 9 (AD0/SD0) defines the lowest bit in the I2C address of the device. Please see <a href="http://43zrtwysvxb2gf29r5o0athu.wpengine.netdna-cdn.com/wp-content/uploads/2015/02/MPU-9250-Datasheet.pdf" rel="nofollow">Chap 7.2 I2C Interface</a> </p> <p>If you need to connect more than two devices this can be done by connecting the AD0/SD0 pin of each device to a chip select pin on the arduino. This pin is asserted when addressing the device (This solution was provided by @Gerben, see comments below).</p> <p>An example with three MPU 9250: Arduino D4-D6 are used as chip select pins. MPU1 AD0/SD0 pin connected to D4, MPU2 pin to D5, and MPU3 to D6. D4..D6 are initiate to HIGH. When addressing a MPU the chip select pin is set to LOW and the lower I2C address is used for access. The other MPUs will be listening for the higher I2C address. </p> <p>Cheers!</p>
18799
|serial|usb|
Can I receive data on the Arduino by sending data to /dev/ttyACM0?
2015-12-18T11:53:47.397
<p>I'm working on a Raspberry Pi connected to an Arduino. When I execute</p> <pre><code>echo 'Hello' &gt; /dev/ttyACM0 </code></pre> <p>, the Arduino receives the data, as indicated by its LED. How can I read the data on the Arduino and process it?</p>
<p>Use Serial.read() there are plenty of examples that come with the Arduino IDE, just make sure the baud rates on the Raspberry Pi and Arduino match.</p>
18802
|analogread|adc|
Arduino Mega 2560 ADC sampling instant and other timings
2015-12-18T15:03:05.413
<p>Hello Everyone (I might be making some mistake in asking this "question", bear with me as I am new to these sites... I honestly think this is the best way to frame my inquiry because it's rather elaborate)</p> <p>I'd like some help in understanding the "timings" of Arduino MEGA 2560's ADC module, especially with respect to the command <em>analogRead</em>.</p> <p>I read <a href="http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf" rel="nofollow">ATmega2560 microcontroller Datasheet</a> </p> <p>Let's assume, for now, that our conversions are normal ones ( the other type being a "first" conversion, which takes 25 ADC clock cycles instead of 13, due to the time required for the initialization of analog components )</p> <p>From what I understood, on a normal single conversion, the sample and hold happens after 1.5 ADC clock cycles from the start of the conversion.</p> <p>Let's say that I set the prescaler to 32 with the following commands:</p> <pre><code>const unsigned char PS_32 = (1 &lt;&lt; ADPS2) | (1 &lt;&lt; ADPS0); const unsigned char PS_128 = (1 &lt;&lt; ADPS2) | (1 &lt;&lt; ADPS1) | (1 &lt;&lt; ADPS0); ADCSRA &amp;= ~PS_128; // remove bits set by Arduino library ADCSRA |= PS_32; // set our own prescaler to 32 </code></pre> <p>hence 16MHz / 32 = 500 kHz should be the new ADC clock frequency ( or 2 microseconds ADC clock period )</p> <p>since a normal single conversion takes 13 ADC cycles, the entire conversion should take about 26 microseconds</p> <p>If I'm not mistaken, (2 microseconds * 1,5) = 3 microseconds after the ADC conversion starts, my analog pin value is set on hold, right?</p> <p>I measured the elapsed time using the micros() function and, like I'd expect, I found out that there's a little overhead introduced with analogRead function because it takes about 28 \ 32 \ 36 microseconds (these are empirical measures).</p> <p>analyzing the code in wiring_analog.c ( which is located in the folder [...]/arduino/hardware/arduino/cores/arduino/ ) the actual conversion seems to happen at line 77</p> <pre><code>// start the conversion sbi(ADCSRA, ADSC); </code></pre> <p>does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?</p> <p>how can I know how much time passed before that sbi function call is issued?</p> <p>I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)</p> <p>Now, considering the so called "first" conversion, which take 25 ADC clock cycles</p> <p>does this conversion happen just the first time I call analogRead since I powered on Arduino? or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)</p> <p>Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?</p>
<blockquote> <p>does that mean that this is the instant from which the actual ADC conversion start, and so 1.5 ADC clock cycles from here, my analog pin value is set on hold?</p> </blockquote> <p>Yes. After between 3ΞΌs and 5ΞΌs. This is because conversion start at the following rising edge of the ADC clock cycle. This rising edge might have just happened, which means you need to wait 31 (main) clock cycles.</p> <blockquote> <p>how can I know how much time passed before that sbi function call is issued?</p> </blockquote> <p>You could copy the original code and create your own <code>analogRead2</code> function that measures the time before setting ADSC.</p> <blockquote> <p>I saw that a single instruction on arduino won't take more than 4 microseconds (but micros() function has that resolution so I don't exactly know!)</p> </blockquote> <p>A single instruction will take 1 or 2 clock cycles (if I remember correctly). So at 16Mhz that will mean 62.5ns (nano seconds) per clock cycle. Not 4ms</p> <blockquote> <p>Now, considering the so called "first" conversion, which take 25 ADC clock cycles</p> <p>does this conversion happen just the first time I call analogRead since I powered on Arduino? or does it happen even after some time , because the ADC module gets powered off? (of course, I consider the case when Arduino remains powered on all the time)</p> <p>Judging by the timings I measured it seems like that the former is the one really happening, even if I don't use ADC for some time, but can anyone confirm?</p> </blockquote> <p>This first conversion is after the <code>ADEN</code> bit changes from 0 to 1. If you don't unset this bit, all further conversions will take the shorter time.</p> <p>PS on the first conversion, the sample-and-hold takes place after the extra 12 ADC clock cycles, so between cycle 12 and 13.5.</p> <p>PPS this info is actually based on the ATMega328, but should be pretty similar in the 2560.</p>
18805
|power|battery|
Using a phone battery as a power source possible?
2015-12-18T16:26:04.860
<p><strong>Use</strong><br> I am assuming that this is possible for any phone model's battery. I am making this vague on purpose (this isn't for a specific project). The <strong>goal</strong> is to have the most compact and long-lasting battery possible for my arduino projects.</p> <p><strong>Note</strong><br> I don't care about the cost. This would be for personal use (not selling this or using it for school), so I don't care about patenting or copyright issues.</p> <p><strong>Question</strong><br> I want to know if this even makes sense for a portable arduino power source option. I want to benefit from newer phones' long battery life, as well as their compact size.</p> <p><em>Also:</em><br> Are there better alternatives to this using different batteries? (I have looked at Nick Gammon's posts over setting sleep cycles to extend battery life (<a href="http://www.gammon.com.au/power" rel="nofollow">http://www.gammon.com.au/power</a>); If utilizing his methods on different batteries are better than using a phone battery please let me know...)</p> <p><strong>If Possible...</strong><br> Does it make sense for something like a:</p> <ul> <li>LED suit (lasting 12 hours)</li> <li>Portable gaming system (lasting 8 hours) - similar to: (<a href="https://www.adafruit.com/products/2510" rel="nofollow">https://www.adafruit.com/products/2510</a>)<br> <em>I Know this is for Raspberry Pi</em></li> <li>BlueTooth Speaker (lasting 6 hours)</li> </ul> <p>etc...</p>
<p>I've done this before, but not very practical as a bare "flat-pack" outside its case presents other "issues", the battery "may" catch fire if punctured or shorted too long. (read fire hazard when punctured) Lithium fires are like thermite, you can't put them out, tossing water on it will only make it worse.</p> <p>Then there's the voltage mismatch (unless you're using a DUE). A POL boost converter is needed for best efficiency to get 5-5.2V from a 3.7V cell. And a specialized charging IC is needed so that you don't overcharge/over-rate the current charging the pack. (constant-voltage/constant-current regulator type is needed). I think Adafruit has a lithium breakout board for the 3.7V lithium cell charger, it's for their lilypad stuff i think.</p>
18806
|arduino-mega|
Handling double (8 byte) in Arduino mega 2560?
2015-12-18T16:30:23.107
<p>I am receiving 8 bytes from serial.</p> <p>I want to convert and save in double variable. </p> <p>This is how i tried.</p> <pre><code>union u_data { byte b[4]; double fval; } u; double BytesToDouble (byte b8,byte b7,byte b6,byte b5,byte b4,byte b3,byte b2,byte b1) { u.b[0] = b1; u.b[1] = b2; u.b[2] = b3; u.b[3] = b4; u.b[4] = b5; u.b[5] = b6; u.b[6] = b7; u.b[7] = b8; return u.fval; } </code></pre> <p>But i am getting 0.00. Because here double size is 4 bytes.</p> <p>Is there is any other way to do this?</p> <p>Thanks</p>
<p>avr-gcc doesn't support <a href="https://en.wikipedia.org/wiki/Double-precision_floating-point_format" rel="nofollow">binary64</a>. You can use 8 bytes to treat it as an opaque data type, but attempting to manipulate it beyond manually converting to/from binary32 will be naught but pain.</p>
18825
|c++|arduino-ide|library|esp8266|time|
NTP Client Library. Set sync provider pointing to public class function. Possible?
2015-12-18T22:54:46.193
<p>I am trying to develop a NTP client library for ESP8266/Arduino to make adding NTP sync an easier task.</p> <p>Basically, I've thought about a constructor as <strong><code>NTPClient(String host, int interval);</code></strong> and a <strong><code>NTPClient.begin()</code></strong> function to register sync function.</p> <p>My problem is with that registering.</p> <p>I have a public function: <strong><code>time_t ntpClient::getNtpTime()</code></strong> that connects to NTP server, decodes the response and returns a <code>time_t</code> variable.</p> <p>Then, inside <strong><code>boolean ntpClient::begin()</code></strong> function I try to run <strong><code>setSyncProvider(ntpClient::getNtpTime)</code></strong>. I've also tried to use <strong><code>setSyncProvider(this-&gt;getNtpTime)</code></strong>.</p> <p>I get a compile error here:</p> <pre><code>ntpClient.cpp:In member function 'boolean ntpClient::begin() ntpClient.cpp:79:39: error: cannot convert 'ntpClient::getNtpTime' from type 'time_t (ntpClient::)() {aka long int (ntpClient::)()}' to type 'getExternalTime {aka long int (*)()} setSyncProvider(ntpClient*:getNtpTime) Error compiling project sources </code></pre> <p>What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?</p>
<blockquote> <p>What could I do to allow registering this function as sync provider to hide NTP internals to my sketches?</p> </blockquote> <p>The function should be a static member function. A "normal" member function does not have the right prototype as there is a hidden parameter ("this"). </p> <pre><code>static time_t getNtpTime(); </code></pre> <p>To solve this you need a <a href="https://sourcemaking.com/design_patterns/singleton" rel="nofollow">single-ton</a> (an instance of the client class) that the static function can use. </p> <pre><code>class NTPClient { public: NTPClient() ... { ... s_client = this; } time_t getNtpTime(); ... static time_t getNtpTime() ( return (s_client-&gt;getNtpTime()); } ... protected: static NTPClient* s_client; ... }; ... NTPClient::s_client = NULL; ... NTPClient ntpClient; ... setSyncProvider(NTPClient::getNtpTime) </code></pre> <p>Alternatively a global function and a known instance:</p> <pre><code>class NTPClient { ... }; extern NTPClient ntpClient; ... time_t getNtpTime() { return (ntpClient.getNtpTime()); } ... setSyncProvider(getNtpTime) </code></pre> <p>Cheers!</p>
18838
|arduino-yun|
Arduino Christmas light project with dimmer
2015-12-19T13:35:17.033
<p>I have an existing project using an Arduino Yun that controls Christmas lights with relays to turn them on/off. There are currently 13 separate rows of lights on the (60 foot) tree, each plugged into a wall wart that's controlled by its own relay.</p> <p>I'm considering adding the ability to dim the lights, so I wanted to figure out the best way to do it. The lights can all be dimmed "in unison" - there's no need for 13 seperately controlled dimmers. But I have to be mindful not to cause any "buzzing" in the audio equipment on stage where the tree is.</p> <p>I've read about PWN, zero cross, and other terms and saw the zero cross tail from <a href="http://powerswitchtail.com" rel="nofollow">powerswitchtail.com</a> that seem useful in the typical project. I'd like to be able to pull this off with no more than 2 "dimmers" for the whole project, if possible.</p> <p>Where do I start, and how do I do it?</p>
<p>I can think of a couple of ways to approach this:</p> <ol> <li><p>Use a DMX dimmer, something like <a href="http://smile.amazon.com/American-Dp-415-Channel-Dimmer-Pack/dp/B000FVZUMM" rel="nofollow">this 4-channel dimmer</a>, or</p></li> <li><p>Use an household <a href="http://smile.amazon.com/X10-RWS17-WS12A-Decorator-Dimmer/dp/B00022OCE6" rel="nofollow">X10 dimmer</a>.</p></li> </ol> <p>DMX is used for stage lighting and there is some information on <a href="http://playground.arduino.cc/Learning/DMX" rel="nofollow">controlling DMX devices with an Arduino in the Playground</a> where there is also some <a href="http://playground.arduino.cc/DMX/DMXShield" rel="nofollow">information on the hardware interface and shields</a>, it looks pretty simple. DMX is a differential RS485 interface.</p> <p>X10 is used for home automation, the signaling is done over the AC line. There is some information on <a href="https://www.arduino.cc/en/Tutorial/X10" rel="nofollow">using X10 and an Arduino library</a> in the Tutorials.</p> <p>Both seem like viable approaches, if you're working in a theater it is likely that they might already have DMX equipment and it would be as simple as hooking up to the gear in the house. Then you'd only need to add a shield or build the interface hardware.</p>
18842
|arduino-uno|sensors|motor|mpu6050|h-bridge|
How to connect an L293D and an MPU6050 to run together?
2015-12-19T19:38:47.167
<p>I'm wondering how to connect the L293D (H-bridge) and an MPU 6050.</p> <p>I'm using 1 Arduino Uno, 2 DC motors, 1 MPU6050 and an L293D.</p> <p>When I tried this, I got some sparks/smoke from the breadboard and none of the motors where running. I only used a 9v battery, not 12v.</p> <p><img src="https://i.stack.imgur.com/uGD8u.png" alt="mpu 6050 and l293d"></p> <p>Here's the L293D: </p> <p><img src="https://i.stack.imgur.com/rl1MH.jpg" alt="l293d"></p> <p>MPU 6050 wiring: int-digital 2, SDA-A4, SCL-A5, GND-GND, VDD-Vss</p> <p>L293D wiring: Vss-VDD, Input4-Digital 5, Output4-Motor, Output3-Motor, Input3-Digital 6, Enable2-5V, Enable1-5V, Input1-Digital 9, Output1-motor, Output2-motor, Input2-Digital 10, Vs-12V battery.</p>
<p>I don't really se anything wrong with the wiring, atleast your diagram seems to be in order. only thing I would ad is give the pin 8 a ceramic capacitor to ground</p> <p>but There is a few possible issues you can check.</p> <p>1 -the sparks make me think that you had a Loose connection at the spark site on the breadboard, maybe the IC was not properly pushed Down in the breadboard, this happens alot, try Again and make sure the IC is complete inserted.</p> <p>2 - if this does not work You might have destroyed the first L293 or the breadboard tracks but if you have more than one try to see if a replacement or movement of the old ic does the trick</p> <p>3 - the motors are to large, and so the current drawn is to high for the L293 to handle and caused thermal shutdown of the L293, a very high current drain will also occur if the motor is stalled. Anyway add some current limiting resistors and see what happends.</p> <p>4 - if the motor hums without moving then it is because Both the forward and reverse input eg. 1 and 2 is enabled simultaneously.</p> <p>5 - the code is not appended, so that cannot be verfified, but the MPU 6050 is correctly installed</p>
18854
|serial|
Why is setup() executed twice at runtime?
2015-12-20T07:50:54.377
<p><strong>Code:</strong></p> <pre><code>void setup() { Serial.begin(9600); Serial.println("hello"); } void loop() { } </code></pre> <p><strong>Output:</strong></p> <pre><code>hello hello </code></pre> <p>Why does <code>hello</code> print twice?</p>
<p>It isn't, it's displaying the previous message from when you didn't have the Serial Monitor open yet, plus the new message caused by the Arduino resetting from the Serial Monitor being opened.</p> <p>If you put a longer message in there you'll probably see the first line get cut off and then the full line.</p>
18857
|serial|
Can I run a loop in setup()
2015-12-20T08:49:58.327
<p>Are loops not allowed in setup()? The following doesn't print anything inside the <code>for</code> loop to the serial terminal</p> <p><strong>Code:</strong></p> <pre><code>void setup() { Serial.begin(9600); Serial.println("Ping"); for (int i = 0; i &gt;= 10; i++) { Serial.println(i); Serial.println("Pong"); } } void loop() { } </code></pre> <p><strong>Output:</strong></p> <pre><code>Ping </code></pre>
<p>You could (and I occasionally do) write your entire program in the <code>setup()</code> function. <code>Setup()</code> and <code>loop()</code> are constructs provided for your convenience, but they aren't necessary. In C/C++ compiled programs, it conventional for the C run-time code to call <code>main()</code>, and for <code>main()</code> to be written by the programmer.</p> <p>It is conventional within the Arduino IDE world to bury the complicated stuff to let new user get productive quickly with a gentle learning curve. That includes a pre-written <code>main()</code> that provides the calls to <code>setup()</code> and <code>loop()</code> for you. </p> <p>The following <code>main()</code> function is typical of a number of pre-written Arduino <code>main()</code> functions, but you don't have to use the pre-written one; you can supply your own. It will need to call <code>init()</code>, and Arduino library function that prepares the hardware and software environment into a known state; after that you're good to go.</p> <pre><code>/* * main.cpp * * Created on: Dec 13, 2011 * Author: jrobert */ #include "WProgram.h" int main(void){ init(); setup(); for(;;) loop(); } extern "C" void __cxa_pure_virtual() { while (1) ; } </code></pre>
18860
|power|arduino-leonardo|rgb-led|
Different behavior than in simulator: 5V pin works instead of GND. Why is that?
2015-12-20T11:57:08.003
<p>I use <a href="http://123d.circuits.io" rel="nofollow noreferrer">this simulator</a> to check if what I want to do works. This is how it looks like:</p> <p><a href="https://i.stack.imgur.com/ZUyqx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZUyqx.png" alt="enter image description here"></a></p> <p>I've recently realised that I've connected my RGB LED to 5V pin instead of GND like on schema. It worked perfectly that way (led worked and chanaged colors). When I connected it back to GND pin, it didn't worked.</p> <p>When I went back to simulator and changed things to those that worked physically (using 5V pin) it didn't worked, but GND did.</p> <p>Why do you think there are some differences? Can I use 5V pin instead of GND if it works? </p> <p>My Arduino: Arduino Leonardo.</p>
<p>The RGB LED's are available with common cathode and common anode. That determines whether you connect the common pin to ground or to +5.</p> <p>In your schematic you likely mismatched the selected part to what you actually have. If you have the opposite type of LED as planned, just reverse the connection as you did. You are not alone in this type of mistake. <a href="http://forum.arduino.cc/index.php?topic=22413.0" rel="nofollow">see similar whot? here</a></p> <p>A digital multimeter with a diode test mode would be very useful here. The DMM would quickly measure the polarity of the diode tell you which lead connects to positive and which to ground. </p> <p>But did it really work correctly? Don't you also see that you have to write LOW to the digital output to make the LED light up?</p>
18862
|oscillator-clock|input|
Input clock limit
2015-12-20T12:41:34.943
<p>If you use an external oscillator, and divide-by-8 internally, can you apply up to 160MHz on PB6? For example, can I use my 50MHz oscillator to clock my 328p @ 6250KHz? Note: when I say oscillator I don't mean resonator or crystal</p>
<p>No! 20 MHz max (Please see <a href="http://www.atmel.com/images/doc8161.pdf" rel="nofollow">8.8 External Clock, pp. 34</a>). The 50MHz clock could be divided by 8 with a <a href="http://www.nxp.com/documents/data_sheet/74HC_HCT393.pdf" rel="nofollow">counter</a> or the 150MHz clock by 16 with a <a href="https://www.fairchildsemi.com/datasheets/74/74VHC393.pdf" rel="nofollow">faster counter</a>. </p> <p>Cheers!</p>
18869
|arduino-uno|ir|
#define macro not in scope when i try to use IR library
2015-12-20T19:36:26.930
<p>My code keeps saying that that Button_8 and the rest of the #define macros are out of scope.</p> <pre><code>#include &lt;IRLib.h&gt; #include &lt;Servo.h&gt; #define MY_PROTOCOL SONY #define RIGHT_ARROW 0xfd50af //Move several clockwise #define LEFT_ARROW 0xfd10ef //Move servo counterclockwise #define SELECT_BUTTON 0xfd906f //Center the servo #define UP_ARROW 0xfda05f //Increased number of degrees servo #define DOWN_ARROW 0xfdb04f //Decrease number of degrees servo moves #define BUTTON_0 0xfd30cf //Pushing buttons 0-9 moves to fixed positions #define BUTTON_1 0xfd08f7 // each 20 degrees greater #define BUTTON_2 0xfd8877 #define BUTTON_3 0xfd48b7 #define BUTTON_4 0xfd28d7 #define BUTTON_5 0xfda857 #define BUTTON_6 0xfd6897 #define BUTTON_7 0xfd18e7 #define BUTTON_8 0xfd9867 #define BUTTON_9 0xfd58a7 IRrecv My_Receiver(11);//Receive on pin 11 IRdecode My_Decoder; long Previous; Servo myservo2; Servo myservo; void setup() { myservo.attach(8); myservo2.attach(3); My_Receiver.enableIRIn(); } void loop() { if (My_Receiver.GetResults(&amp;My_Decoder)) { My_Decoder.decode(); if(My_Decoder.decode_type==MY_PROTOCOL) { if(My_Decoder.value==0xFFFFFFFF) My_Decoder.value= Previous; if(My_Decoder.value == Button_9) { myservo.write(0); myservo2.write(180); } else if(My_Decoder.value == Button_8) { myservo.write(180); myservo2.write(180); } } } } </code></pre> <p>when i use a switch statement instead of the 4 and 5 if statement like so:</p> <pre><code>switch(My_Decoder.value) { case Button_8: //do something; break; </code></pre> <p>it works, but i dont know why.</p>
<p>C++ is case-sensitive. <code>Button_8</code> is different from <code>BUTTON_8</code>.</p>
18872
|led|c|
Arduino C, Led > binary alternative all lights
2015-12-20T21:29:25.487
<p>I'm trying to alternatively have a random int generate a binary number with 4 lights. </p> <p>This is my current code, However, it seems that all the lights(leds) go on, I don't think the minus option works. As in, it won't take a value from the currently randomized digit. (randombinary = randombinary - x)</p> <p>I also tried just "randombinary - x"</p> <hr> <pre><code>const int button = 2; const int redone = 13; const int redtwo = 8; const int greenone = 12; const int greentwo = 7; int randomnumber = 0; int randombinary = 0; void setup() { pinMode(13, OUTPUT); pinMode(12, OUTPUT); pinMode(7, OUTPUT); pinMode(8, OUTPUT); pinMode(2, INPUT); } void loop() { delay(1000); int randomnumber = (1, 15); randombinary = randomnumber; if (randombinary &gt;=8){ digitalWrite(redone, HIGH); randombinary = randombinary - 8; } else { digitalWrite(redone, LOW); } if (randombinary &gt;=4){ digitalWrite(greenone, HIGH); randombinary = randombinary - 4; } else { digitalWrite(greenone, LOW); } if (randombinary &gt;=2){ digitalWrite(redtwo, HIGH); randombinary = randombinary - 2; } else { digitalWrite(greentwo, LOW); } if (randombinary &gt;=1){ digitalWrite(greentwo, HIGH); randombinary = randombinary - 1; } else { digitalWrite(greentwo, LOW); } } </code></pre> <p>Would appreciate any help!</p>
<p>Code review (one possible solution can be found below) </p> <ul> <li>Absolute numbers in the code, like 15 as the limit for the random numbers are generally considered harmful. It would be better to give all absolute numbers a constantsname and use these throughout. The OP code did not use the constants for the pins, for instance. </li> <li>Writing similar pieces of code in a row makes maintenance hard. Therefore, group similar items in any kind of list, like an array, and iterate over them. </li> <li>Functions should have expressive names clearly stating what is going on inside. </li> <li>Functions should be short and concise, ideally having only a few lines. </li> </ul> <p>Try something along these lines: </p> <pre><code>// setting the number of bits to analyze, corresponding pins and corresponding powers of two. // the latter is here for instructional purposes although it is redundant. const int numberOfBits = 4; const int randLimit = 15; // 2^(1+numberOfBits)-1 actually; int ledPins[numberOfBits] = {13, 8, 12, 7}; int bitValue[numberOfBits] = {8, 4, 2, 1}; // the powers of two void turnOffAllLeds () { Serial.println ("turning all off"); for (int i = 0; i &lt; numberOfBits; i++) { digitalWrite (ledPins[i], LOW); } } void selectivelyTurnOnLeds(int value) { turnOffAllLeds (); // now for each bit, check if it is set in the value, if yes: turn on corresponding led for (int i = 0; i &lt; numberOfBits; i++) { if ((value &amp; bitValue[i]) &gt; 0) { digitalWrite (ledPins[i], HIGH); } } } void setup() { for (int i = 0; i &lt; numberOfBits; i++) { pinMode (ledPins[i], OUTPUT); } } void loop() { selectivelyTurnOnLeds (random (randLimit)); delay (1000); } </code></pre> <p>P.S. When posting a question, please also post what your code is supposed to do. If it were not for a lazy prechristmas workday, I would not have taken the time to reverse engineer your code. </p>
18876
|arduino-uno|motor|lcd|c|esp8266|
Arduino DC motor causes disturbance. What can cause it?
2015-12-20T23:32:23.047
<p>I tried to fix this problem the whole weekend but, after no success I decided to post it here. I would really appreciate any help.</p> <p><strong>The problem</strong></p> <p>The Wi-Fi module activates the DC motor and lets it run for 3 seconds, but when the DC motor stops after that 3 seconds, the Wi-Fi module and display don't respond anymore. It only works once. (After I push the reset button the same thing happens.)</p> <p><strong>Question</strong></p> <p><strong>What causes this disturbance? Any advice on my circuit?</strong> (I included a Fritzing Diagram because I am bad at drawing schematics)</p> <p><a href="https://i.stack.imgur.com/BREkf.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BREkf.jpg" alt="Fritzing Diagram"></a></p> <pre><code>#include &lt;SoftwareSerial.h&gt; #include &lt;LiquidCrystal.h&gt; LiquidCrystal lcd(12, 11, 5, 4, 3, 2); SoftwareSerial ESP8266(9, 8); // RX = 8 en TX = 9 #define DEBUG true boolean FAIL_8266 = false; int LED = 13; // led op 13 int secondeAan = 3000; String my_AP_SSID = "myID"; String my_AP_Pass = "myPass"; void setup() { // -- stel led in -- pinMode(LED, OUTPUT); // -- lcd scherm -- lcd.begin(16, 2); lcd.clear(); lcd.setCursor(0, 1); do { ESP8266.begin(115200); // start communicatie met esp8266 //Wait Serial Monitor to start while (!Serial); lcd.clear(); lcd.print("--- Start ---"); ESP8266.print("AT\r\n"); delay(500); if (ESP8266.find("OK")) { FAIL_8266 = false; sendData("AT+RST\r\n", 4000, DEBUG); sendData("AT+CWMODE=3\r\n", 2000, DEBUG); sendData("AT+CWJAP=\"" + my_AP_SSID + "\",\"" + my_AP_Pass + "\",9,4\r\n", 2000, DEBUG); sendData("AT+CIFSR\r\n", 2000, DEBUG); sendData("AT+CIPMUX=1\r\n", 2000, DEBUG); sendData("AT+CIPSERVER=1,80\r\n", 2000, DEBUG); } else { lcd.clear(); lcd.setCursor(0, 1); lcd.print("Module have no response."); delay(500); FAIL_8266 = true; } } while (FAIL_8266); } void loop() { // Get the number of bytes (characters) available for reading from the serial port if (ESP8266.find("+IPD,")) { lcd.clear(); lcd.print("Nieuwe connectie"); // -- sluit connectie -- motorToggle(); sendData("AT+CIPCLOSE=0\r\n", 100, DEBUG); sendData("AT+CIPCLOSE=1\r\n", 100, DEBUG); sendData("AT+CIPCLOSE=2\r\n", 100, DEBUG); } } void motorToggle () { digitalWrite(LED, HIGH); lcd.clear(); lcd.print("eten gegeven"); delay(secondeAan); digitalWrite(LED, LOW); delay(200); } String sendData(String command, const int timeout, boolean debug) { String response = ""; ESP8266.print(command); // send the read character to the esp8266 long int time = millis(); while ( (time + timeout) &gt; millis()) { while (ESP8266.available()) { char c = ESP8266.read(); response += c; } } if (debug) { lcd.clear(); lcd.print(response); } return response; } </code></pre>
<p>Thanks for the help everyone. I fixed it by using Capacitors. They suppress the noise that the dc motor produces. I found my information <a href="https://www.pololu.com/docs/0J15/9" rel="noreferrer">here</a></p> <p><a href="https://i.stack.imgur.com/dATTj.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/dATTj.jpg" alt="enter image description here"></a></p>
18882
|serial|arduino-nano|
Issue with Serial PINs (RX/TX) on Arduino
2015-12-21T12:51:54.937
<p>I have an issue with an Arduino Nano.</p> <p>I want to communicate with it through the Serial-Port. Meaning I want to send and receive Serial commands. With USB and the "Serial Monitor" this works nice. Now I have connected the COM-Port of the PC with Adruinos Digital Pins 0 and 1 (RX and TX) and a GND PIN. (3 Cables total).</p> <p>Here is a minimal example of my Code:</p> <pre><code>void setup() { Serial.begin(9600,SERIAL_8N1); Serial.println("Start"); } void loop() { Serial.println("Hello World"); delay( 1000 ); } </code></pre> <p><strong>The Serial Monitor says:</strong></p> <pre><code>Start Hello World Hello World Hello World Hello World ... </code></pre> <p><strong>Putty however says:</strong></p> <pre><code>β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’:: β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’*β–’β–’ β–’Rβ–’β–’β–’tβ–’*β–’β–’β–’Rβ–’β–’β–’tβ–’* </code></pre> <p>Putty is connected with - BaudRate: 9600 - Data Bits: - Stop Bits: 1 - Parity: None - Flow Control: None</p> <p>What is wrong here?</p> <p>Update: The PC has a 9-pin D socket (<a href="http://www.airyear.com/images/products1/202711.jpg" rel="nofollow">Image</a>) This is connected to a RS232 to RJ45 connector (<a href="http://ecx.images-amazon.com/images/I/41BucionchL._SY300_.jpg" rel="nofollow">image</a>) From the RJ45-Cable I used the Brown, Blue, and White/Green Cable to connect with the Arduino</p>
<p>RS232 is not TTL. You need a level converter. For more details see <a href="https://www.sparkfun.com/tutorials/215" rel="nofollow">https://www.sparkfun.com/tutorials/215</a>. </p>
18886
|rfid|
RFID tag "location identification"
2015-12-21T15:29:46.063
<p>Can an RFID tag be used to identify a room? For example, I walk into a room, and the RFID receiver tells me that I am in say, the living room. Would it be possible for a tag to ping back the signal from a distance of 10ft? Or is there a similar technology like RFID that can extend to a much greater range? </p>
<p>There are newer long range RFID solutions. You can do a google search on "Ultra Long-Range UHF Wireless RFID Sensors" for more information, but almost all of these systems are still proprietary (i.e. I'm not aware of any hobbyist breakout-boards based around UHF tags yet).</p> <p>The Disney MagicBands are an exact use-case of your question: Their magic bands use a combination of 13MHz RFID tags, and a new UHF active tag (it requires a small battery). They use them to collect data on how people flow through their Walt Disney World facility. What bathrooms see the most activity, and when, for example. There is actually a pretty decent amount of information available about the technology used in the Disney Magicbands if you're curious about the technology.</p>
18895
|bluetooth|system-design|
How Master and Slave concept works with Bluetooth?
2015-12-21T23:53:58.490
<p>From what I understand the master has primary control over the slaves and communicates with them. A master must always be present as well, and can be connected to (up to) 7 slaves. </p> <p><strong>Question</strong> </p> <ul> <li>If I have 2 arduinos with Bluetooth communicating with each other from within a radius of 80 meters or less, which arduino do I set as the <strong>master</strong> and which do I set as the <strong>slave</strong>? (what dictates which one should be set as master, etc.)</li> </ul> <p>I want both arduinos to be able to transmit data to one-another (where neither has privilege over the other), so in my mind this is more like two slaves communicating. Both devices have the same controls on them and will effect the other devices the exact same way.</p> <ul> <li>How does the <strong>communication</strong> process work exactly, and how should more arduinos be addressed if they are to be added with similar privileges?</li> </ul>
<p>Well, master/slave concept for Bluetooth resides on the protocol, not in the communications. On few words, this means Bluetooth Master is who has the ability to initiate connection with a peripheral (or slave), but onces connected both master and slave basically can interchange information without restriction (limited by application). If your bluetooth module or implementation has a SPP (serial port profile <a href="https://developer.bluetooth.org/TechnologyOverview/Pages/SPP.aspx" rel="nofollow">https://developer.bluetooth.org/TechnologyOverview/Pages/SPP.aspx</a>) once the master finds and connect to the slave, information can flow in both ways like a chat (actually, chat application is the most common usage example of bluetooth modules)</p>
18896
|arduino-mega|
What does "Arduino compatible" mean?
2015-12-22T00:02:21.757
<p>I wanted to buy an Arduino (ATmega) 2560 (8 Bit MCU) via Amazon. But there was no Arduino visible. There was only a </p> <ul> <li><a href="http://www.amazon.de/SainSmart-Mega2560-ATmega2560-ATMEGA8U2-cable/dp/B00FLL8OZG/ref=sr_1_1?ie=UTF8&amp;qid=1450723952&amp;sr=8-1&amp;keywords=arduino%20mega" rel="nofollow noreferrer">SainSmart 2560</a> and</li> </ul> <p><img src="https://i.stack.imgur.com/2FJHj.png" alt="SainSmart 2560 image"></p> <ul> <li><a href="http://www.amazon.de/SunFounder-ATmega2560-16AU-Board-compatible-Arduino/dp/B00D9NA4CY/ref=sr_1_1?s=computers&amp;ie=UTF8&amp;qid=1450738573&amp;sr=1-1&amp;keywords=sunfounder%202560" rel="nofollow noreferrer">SunFounder 2560</a></li> </ul> <p><img src="https://i.stack.imgur.com/ZsfiF.png" alt="SunFounder 2560 image"></p> <p>On both websides (SainSmart and SunFounder) there is the information that they are Arduino compatible. But all three boards (Atmel-orginal, SainSmart, SunFounder) do not look similar... There are differences. Is it possible to buy one of those boards without:</p> <ul> <li>checking the datasheet differences</li> <li>having problems with the Arduino Ethernet Shield !?</li> </ul> <p>So, what is <strong>compatible</strong> ?</p>
<p>The other answer seem to focus on "compatible" meaning "works with the IDE" but that's not what they mean here. "Compatible" in this context means "clone of the original".</p> <p>You can count on these boards being functionally identical. The microprocessor and pinout are the same, which is what a shield cares about. The peripheral circuitry might vary slightly, but that's not a big deal. They might (as mentioned) have a different USB-Serial chip but that won't cause any issues once you install the appropriate drivers on your PC.</p>
18903
|arduino-uno|esp8266|
Connecting ESP8266 with Arduino Uno - WiFi shield not present
2015-12-22T07:09:42.733
<p>I have an Arduino Uno and ESP8266. I want to connect and control an LED from a web server. I made a connection referring to this:</p> <p><a href="https://i.stack.imgur.com/KYbW1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KYbW1.png" alt="enter image description here"></a></p> <p>I uploaded the <a href="https://www.arduino.cc/en/Tutorial/WiFiWebServer" rel="nofollow noreferrer">WifiWebServer</a> code to the Arduino, and applied my router's credentials.</p> <pre><code>char ssid[] = "Router SSID"; // your network SSID (name) char pass[] = "Router's WPA Password"; ` </code></pre> <p>I'm getting a "Wifi Shield not present" message from the Serial Monitor. I even tried giving external 3.3v power supply to my ESP8266 module, but no change. What am I missing here? Can someone help me fix this issue? </p>
<p>For the esp you must use an external 3.3v power source (300 mA or more), and a logic level converter for the esp Rx (arduino Tx is in 5v logic).</p>
18909
|library|lcd|display|
How to drive a 4bit GLCD?
2015-12-22T12:12:44.107
<p>i've got a huge (about 6 x 23 cm) graphics LCD. I used my multimeter and the datasheet the LCD driver chips (6 x KS0104 and 2 x KS0103) to get the pinout. It has the following pins: GND, M, FCS (not 100% shure), CL1, CL2, D0-3, VDD and a ground for the metal part.</p> <p>My problem is that i dont know how i can drive a 4bit GLCD with an Arduino because i didnt found a library which can do this (e.g. OpenGLCD supports only the KS0104 which is an 8 bit controller)</p>
<p>@MikaelPatel answered your question in the comments:</p> <blockquote> <p>That gives a total of 54K pixels. And with 4-bit per pixel, two pixels in a byte, 27K byte to store a packed off-screen bitmap. Even an Arduino Mega would have too little memory for that. This might explain why there are no supporting library for that device.</p> </blockquote>
18910
|serial|class|
serialEvents within a class
2015-12-22T12:41:30.500
<p>My .ino looks roughly like this</p> <pre><code>#include "command.h" Command command; void setup() { } void loop() { } </code></pre> <p>command.h</p> <pre><code>class Command { public: Command(); }; </code></pre> <p>command.cpp</p> <pre><code>#include &lt;Arduino.h&gt; #include "command.h" Command::Command() { Serial.begin(9600); } void serialEvent() { while (Serial.available() &gt; 0) { char inChar = (char)Serial.read(); Serial.print(inChar); } } </code></pre> <p>The serial events don't seem to be happening. It works normally if I move the code out of the class.</p>
<p>@slash-dev "...Also, using SerialEvent is no better than doing the polling in loop()." Are you sure about that? SerialEvent (and especially the ones on Teensy3) use hardware interrupts which can be handled in the midst of other operations; even delay() does not block interrupts (<a href="http://playground.arduino.cc/Code/AvoidDelay" rel="nofollow">http://playground.arduino.cc/Code/AvoidDelay</a>). It's hard to imagine multiple serial streams running at 100 kbaud or better (test reported in PJRC forum) and handling each character in the main loop even if that was all your program did. And why would you want to? There are good reasons interrupts exist.<br> <strong>Update</strong>: I'm not allowed to "comment" without 50 reputation. Thanks for the commit link... I can't imagine why HardwareSerial would not use interrupts... that is the default on all other platforms we've used for years.</p>
18920
|analogwrite|rgb-led|
RGB Led - mixing colors using analogWrite
2015-12-22T20:41:11.353
<p>Currently I'm controlling an RGB LED with my Arduino Nano.</p> <p>I'm mixing the colors using analogWrite</p> <p>Though, the LED's don't light up at all for low analogwrite values and the difference between the levels is not visible (to me).</p> <p>I'm using 100 Ohms resistors between the LED's, using a 680Ohms didn't seem to make a difference.</p> <p>Analogwrite is working by toggling the LED's fast (PWM)? So not by lowering voltage? This is why I think it's weird that they don't light up at all, on low write values.</p> <p>My sketch below:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; int r, g, b = 0; String command = ""; const byte rxPin = 11; const byte txPin = 10; SoftwareSerial blueTooth (rxPin, txPin); void handleCommand() { r = rgbFromCommand("r=",";"); g = rgbFromCommand("g=",";"); b = rgbFromCommand("b=",";"); if(r != -1){ analogWrite(A2,r); } if(g != -1){ analogWrite(A1,g); } if(b != -1){ analogWrite(A0,b); } } int rgbFromCommand(String prefix, String postfix) { int idx = command.indexOf(prefix); int endIdx = command.indexOf(postfix,idx); if(idx&gt;=0 &amp;&amp; endIdx&gt;=0){ idx+=2; return command.substring(idx,endIdx).toInt(); } return -1; } void setup() { pinMode(rxPin,INPUT); pinMode(txPin,OUTPUT); Serial.begin(9600); blueTooth.begin(9600); } void loop() { if (Serial.available() &gt; 0) { // read the incoming byte: char incomingByte = Serial.read(); if(incomingByte == '\n'){ handleCommand(); command = ""; }else{ command += incomingByte; } } if(blueTooth.available() &gt; 0){ // read the incoming byte: char incomingByte = blueTooth.read(); if(incomingByte == '\n'){ handleCommand(); command = ""; }else{ command += incomingByte; } } } </code></pre>
<p>Analog pins aren't PWM pins. Instead you have to use the pins marked with a <code>~</code></p> <p>Pins that aren't PWM pins will be off with a value of 0-127 and on with a value between 128 and 255.</p>
18928
|arduino-uno|wifi|sketch|memory-usage|sram|
Clearing SRAM in loop()
2015-12-23T00:31:09.983
<p>Very broad question here. I don't know exactly what the problem is but I'll edit this post as we narrow down the possibilities.</p> <p>I think I'm running into memory constraints.</p> <p>I'm running a sketch that records two temperature values every 60 seconds and transmits them to an AWS RDB via wifi. It works well for about two hours then stops. I don't know if it's a memory constraint but I suspect that it is. What other common problems (often overlooked by newbies) can cause a sketch to end after a couple hours of run-time?</p> <p>Is there a simple way to add an instruction to a loop to clear the SRAM?</p> <p>Arduino UNO + WiFi 101</p> <p>Edit #1 12/24/2015:<br>It's the WiFi board. It happily remains connected to my phone's hotspot but only lasts an hour or two on my home network. Working on root cause...any ideas are welcome!</p> <p>Edit #2 12/25/2015:<br>Tried to Wifi.disconnect() and reconnect with no luck. Why do some networks kick the board off while others work just fine? Will look into the watchdog.</p>
<p>The problem was solved with a "soft restart" loop. Posts #10 and #11 are all I needed: <a href="http://forum.arduino.cc/index.php?topic=49581.0" rel="nofollow">http://forum.arduino.cc/index.php?topic=49581.0</a></p>
18931
|arduino-uno|attiny|
Small, Power-Efficient wireless communication with ATTiny85
2015-12-23T01:47:04.167
<p>For a project that I'm working on I need an extremely small, power efficient wireless device (could be radio, or some other interface) to network between a series of ATTiny85s and a larger Arduino. The communication range only needs to be about 1 foot, max. I'm currently using wired I2C, so it would be excellent if someone could suggest a radio or another device that can use the two digital pins previously occupied by the SCK and SDA lines on the ATTiny. I have those two, along with one extra digital pin available for use.</p> <p>This device needs to be extremely small - <a href="http://www.miniinthebox.com/upgraded-2-4ghz-nrf24l01-wireless-transceiver-module-for-arduino-black_p683437.html" rel="nofollow">this common NRF24L01</a> package is too big and its SPI interface uses too many pins.</p> <p>Thanks for your help.</p>
<p>I've also had good results with using the <a href="https://mchr3k.github.io/arduino-libs-manchester/" rel="nofollow">Mchr3k - Arduino Manchester Encoding</a> library with those 315mhz RF kits. It has support for ATTiny85 as well.</p>
18935
|arduino-uno|ethernet|
Arduino hangs after less than a minute, but not on USB
2015-12-23T10:17:49.683
<p>I have arduino uno + ethernet shield + 9V/200mA adapter. I am trying to send some data with HTTP connection. When it's connected to USB it works perfectly, but when I plugged out USB, hangs (after less than a minute, it stops pinging).</p> <p>I have tried <a href="http://forum.freetronics.com/viewtopic.php?t=176" rel="nofollow noreferrer">this</a>:</p> <pre><code>EthernetClient.cpp int EthernetClient::connect(IPAddress ip, uint16_t port) { if (_sock != MAX_SOCK_NUM) return 0; // i changed to -1 as suggested on previous link for (int i = 0; i &lt; MAX_SOCK_NUM; i++) { uint8_t s = socketStatus(i); if (s == SnSR::CLOSED || s == SnSR::FIN_WAIT || s == SnSR::CLOSE_WAIT) { _sock = i; break; } } </code></pre> <p>and also example from library <code>Examples-library-WebClientRepeating</code>, but I get the same problem as in my code. Is my adapter too weak?</p> <p>This code is from Example WebClientRepeating:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; // fill in your Domain Name Server address here: IPAddress ip(193, 77, 60, 66); IPAddress subnet(255, 255, 255, 0); IPAddress gateway(193, 77, 60, 7); IPAddress myDns(193, 77, 60, 213); EthernetClient client; char server[] = &quot;www.arduino.cc&quot;; //IPAddress server(64,131,82,241); unsigned long lastConnectionTime = 0; // last time you connected to the server, in millisecond const unsigned long postingInterval = 10L * 1000L; // delay between updates, in milliseconds // the &quot;L&quot; is needed to use long type numbers void setup() { // start serial port: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // give the ethernet module time to boot up: delay(1000); // start the Ethernet connection using a fixed IP address and DNS server: Ethernet.begin(mac, ip, myDns, gateway, subnet); // print the Ethernet board/shield's IP address: Serial.print(&quot;My IP address: &quot;); Serial.println(Ethernet.localIP()); } void loop() { if (client.available()) { char c = client.read(); Serial.write(c); } // if ten seconds have passed since your last connection, then connect again and send data: if (millis() - lastConnectionTime &gt; postingInterval) { httpRequest(); } } // this method makes a HTTP connection to the server: void httpRequest() { // close any connection before send a new request. // This will free the socket on the WiFi shield client.stop(); // if there's a successful connection: if (client.connect(server, 80)) { Serial.println(&quot;connecting...&quot;); // send the HTTP PUT request: client.println(&quot;GET /latest.txt HTTP/1.1&quot;); client.println(&quot;Host: www.arduino.cc&quot;); client.println(&quot;User-Agent: arduino-ethernet&quot;); client.println(&quot;Connection: close&quot;); client.println(); // note the time that the connection was made: lastConnectionTime = millis(); } else { // if you couldn't make a connection: Serial.println(&quot;connection failed&quot;); } } </code></pre> <p><strong>EDIT 1:</strong> Also when I plug USB in its start working with 9V power adapter.</p>
<p>It may be that, for some reason, the library thinks Serial communication is working, but when the buffer of unsent characters gets full, it hangs waiting to complete a Serial.print() or Serial.println().</p> <p>So, try commenting out all use of Serial. </p> <p>For example change</p> <pre><code> Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } </code></pre> <p>to </p> <pre><code> /* Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } */ </code></pre> <p>and <code>Serial.println(...);</code> to <code>// Serial.println(...);</code></p> <p>This might happen if the system is started with USB working, and then USB is unplugged.</p>
18937
|programming|c|
Combine bits from two ports into a single byte
2015-12-23T11:16:05.577
<p>I'm attempting to read the values of 8 pins at a time into a byte. </p> <p>The obvious answer to this seems to be the Port registers, however with the way the Arduino is wired, I'd have to split my read across two registers. </p> <p>In this case, I need a way to combine the lower 5 bits of PORTB with the upper 3 bits of PORTD into a single byte. </p> <p>For example, this is the physical layout with the data lines I'm attempt to read/write to and their corresponding port assignments.</p> <pre><code> SCSI DB7 DB6 DB5 DB4 DB3 DB2 DB1 DB0 | | | | | | | | PB4 PB3 PB2 PB1 PB0 PD7 PD6 PD5 AVR </code></pre> <p>From what I can gather I need to use some shift operators to achieve this, perhaps something like:</p> <pre><code>hi = PORTB &amp; 3; lo = PORTD &gt;&gt; 3; </code></pre> <p>But I'm unsure if that's correct and then how I would combine them.</p> <p>Is it possible to write a macro to make getting and setting this byte easier?</p> <p>Is there a good learning resource on bit manipulation like this?</p>
<p>Assuming PORTB and PORTD are correctly giving unsigned char values:</p> <pre><code>result = (PORTB &lt;&lt; 3) | (PORTD&gt;&gt;5) </code></pre> <p>would do it.</p> <p>As a macro: </p> <pre><code>#define SCSIBITS ((PORTB &lt;&lt; 3) | (PORTD&gt;&gt;5)) </code></pre> <p>Then use like this: </p> <pre><code>result = SCSIBITS </code></pre> <p>To make it clearer which specific bits are being used, write: </p> <pre><code>#define SCSIBITS (((PORTB &amp; B00011111) &lt;&lt; 3) | ((PORTD &amp; B11100000) &gt;&gt; 5))) </code></pre> <p>It should be easier to see that the lower 5 bits of PORTB, and the upper 3 bits of PORTD are being used.</p> <p>In the general case, where the values being manipulated are not unsigned char (should not be a problem in this specific case, but may be helpful to know), you might write: </p> <pre><code>#define SCSIBITS ((unsigned char)((PORTB &amp; B00011111) &lt;&lt; 3) | ((PORTD &amp; B11100000) &gt;&gt; 5))) </code></pre> <p>or: </p> <pre><code>#define SCSIBITS ((((unsigned char)PORTB &amp; B00011111) &lt;&lt; 3) | (((unsigned char)PORTD &amp; B11100000) &gt;&gt; 5))) </code></pre> <p>Here are a few links to bit-manipulation tutorials:<br> <a href="https://www.hackerearth.com/notes/bit-manipulation/" rel="nofollow">https://www.hackerearth.com/notes/bit-manipulation/</a><br> <a href="http://www.cprogramming.com/tutorial/bitwise_operators.html" rel="nofollow">http://www.cprogramming.com/tutorial/bitwise_operators.html</a><br> <a href="http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm" rel="nofollow">http://www.tutorialspoint.com/ansi_c/c_bits_manipulation.htm</a> </p>
18940
|programming|c|
Compare const char * to const char
2015-12-23T13:23:31.513
<p>Using ArduinoJson I have assigned a value such as;</p> <pre><code>const char* id = root["id"]; </code></pre> <p>in the original JSON id was "1"</p> <pre><code>if (strcmp(id, "1") == 0) { // this executes } </code></pre> <p>I have an array of structs that I wish to compare the id against. The struct looks like;</p> <pre><code>typedef struct { char id[2]; .... } Device; </code></pre> <p>I assign an id (1-9) into the struct id by</p> <pre><code>_cmd.id[0] = '0' + (++DevicesPtr); _cmd.id[1] = '\0'; Devices[DevicesPtr-1] = _cmd; </code></pre> <p>where _cmd is of type Device. Devices is an array with up to 8 entries Now I try to find a match in the devices using the JSON id</p> <pre><code>for (byte i = 0; i &lt; DevicesPtr; i++) { if (strcmp(Devices[i].id, id) == 0) { // This code does not execute } } </code></pre> <p>I can't seem to get a match I have also tried (Devices[i].id == id)</p>
<p>You can't compare a char and a string.. How can you compare apples and bananas?</p> <p>Now, you have two ways to do your job.</p> <p>1) do as @Mikael Patel suggests, so convert your <code>id</code>s into strings. This is fine because it will allow you to deal with multiple chars ids.</p> <p>2) a more efficient way to do this (note that this works with just SINGLE CHARS IDS) is the following one:</p> <pre><code>if (strlen(id) == 1) { for (byte i = 0; i &lt; DevicesPtr; i++) { if (Devices[i].id == id[0]) { // This code will execute if ids match } } } </code></pre> <p>Note that id should be exactly 1 char long, otherwise the whole comparison as you thought is meaningless</p> <p>With this solution you don't need multibyte id char in the struct definition, so you can just define</p> <pre><code>typedef struct { char id; .... } Device; </code></pre> <p>and, in the code, </p> <pre><code>_cmd.id = '0' + (++DevicesPtr); Devices[DevicesPtr-1] = _cmd; </code></pre>
18944
|arduino-nano|voltage-level|
Arduino Nano gives 7V on the 5V PIN!
2015-12-23T15:36:52.393
<p>I have an Arduino Nano which is Powered by an external Power supply. This is connected with VIN and GND. The voltmeter says, there are <code>12,12 V</code></p> <p>I have some components connected on the 5V PIN, which altogether draw max. <code>100mA</code> Since some of the components are not working anymore, I started measuring...</p> <p>I have disconnected everything, but the Arduino Nano Power supply. (<code>12,12V</code>)</p> <p>When I now measure GND and the 5V PIN, the Voltmeter says <strong>6,97V!</strong> I guess this is why my components are giving up. </p> <ul> <li>But why are there <code>6,97 Volts</code> all of the sudden? </li> <li>Is my Arduino broken now? </li> <li>Can I fix this?</li> <li>How can this happen?</li> </ul>
<p>Of course the 5V regulator on the nano can be faulty. Another possibility is the 5V decoupling capacitor. If it goes open circuit the regulator will oscillate and the mean output voltage will be near half the input voltage. Most regs have a minimum decoupling cap value specified.</p>
18951
|signal-processing|
FFT (or similar) library for the Arduino
2015-12-23T23:26:14.357
<p>I'd like to build a "low fidelity" spectrum analyzer to run on an Adafruit Trinket Pro. My primary goal is to intrigue my seven year-old niece with something that can be hacked. The plan is to pick up sound from a violin with a mic and use a set of 5 or 6 NeoPixels to represent octaves and use color for amplitude.</p> <p>My first pass at this used <a href="http://www.instructables.com/id/Arduino-Frequency-Detection" rel="nofollow">Amanda Ghassaei's frequency detection code</a>. It kind of worked, but seemed to be having problems with complex waveforms. After doing some more reading and looking at simple spectrum analyzers it seems that I'd do better using something like a FFT to collect the frequency information. It also seems that that might be stretching the capability of an Arduino…</p> <p>Are there any FFT libraries that run well on the Arduino (over a range of about 200 to 4000 Hz)? Or are there other approaches that might work better?</p>
<p>I havent used any of the libraries to make the FFT for my personal project, due to complexity. Instead I bought a spectrum chip, which returns 7 frequencies: MSGEQ7 ( 63Hz, 160Hz, 400Hz, 1kHz, 2.5kHz, 6.25kHz and 16kHz ).</p> <p>Otherwise if you are very keen on using a library, <a href="http://wiki.openmusiclabs.com/wiki/ArduinoFFT" rel="nofollow">this one</a> is very famous and fast for Arduino processors.</p> <p>But again, if you dont need to have a precise band and the MSGEQ7 is good enough to detect what you want, go for it. </p>
18954
|library|attiny|
Creating a library for attiny85 out of working program
2015-12-24T01:03:09.773
<p>Apologies if this is the wrong sub-forum, the involvement of ATTiny and arduino places this into a strange category. Please correct me if I should post elsewhere.</p> <p>It is important for this to be a library as small kids will be using this program and hardware for their own projects. Its kind of a rip on the LOLshield but it involves a lot more steps to integrate more lessons all at once.</p> <p>My whole program takes 8 bytes of information and converts it to data for a shift register driving two multiplexers all driving an 8x8 LED matrix. It can also use multiple of these packets to make a slide show. I have it in a working state right now and would like to turn it into a library for easy use. I am a bit lost in this step as I had to create an interrupt timer and this makes it more complicated than the tutorial on the arduino website covers.</p> <p>Also if someone could point me to a library for ATTiny85 that makes calling a timer interrupt easy then the rest of this project will likewise become easier.</p> <p>Any help would be great! I will be continuing to look on online resources and will update should I figure it out.</p>
<blockquote> <p>I had to create an interrupt timer ...</p> </blockquote> <p>Be warned that there are things you should not do in interrupts, like delays, serial printing, etc. </p> <hr> <h2>Code</h2> <p>In the interests of answering the question though, this works:</p> <pre class="lang-C++ prettyprint-override"><code>// ATMEL ATTINY 25/45/85 / ARDUINO // Pin 1 is /RESET // // +-\/-+ // Ain0 (D 5) PB5 1| |8 Vcc // Ain3 (D 3) PB3 2| |7 PB2 (D 2) Ain1 // Ain2 (D 4) PB4 3| |6 PB1 (D 1) pwm1 // GND 4| |5 PB0 (D 0) pwm0 // +----+ ISR (TIMER1_COMPA_vect) { digitalWrite (4, ! digitalRead (4)); //toggle D4 (pin 3 on chip) } void setup() { pinMode (4, OUTPUT); // chip pin 3 // Timer 1 TCCR1 = bit (CTC1); // Clear Timer/Counter on Compare Match TCCR1 |= bit (CS10) | bit (CS13); // prescaler of 256 OCR1C = 123; // what to count to (zero-relative) TIMSK = bit (OCIE1A); // interrupt on compare } // end of setup void loop() { // other code here } </code></pre> <hr> <p>You can tweak the time delay by changing both the prescaler and the counter in OCR1C. The prescaler gives you coarse tuning, which gets you into the ballpark of the delay time. The timer then counts up to give you the final delay.</p> <hr> <h2>Prescaler values</h2> <p>From the datasheet:</p> <p><a href="https://i.stack.imgur.com/8kPDF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8kPDF.png" alt="ATtiny85 timer 1 prescalers"></a></p> <p>In my case I chose a prescaler of 256 which is or'ing together CS10 and CS13.</p> <p>The delay is then:</p> <pre class="lang-C++ prettyprint-override"><code>125 ns * 256 * 124 = 3.968 ms </code></pre> <p>Where 256 is the prescaler and 124 is what we are counting to. This is assuming an 8 MHz clock which gives a clock period of 125 ns.</p> <hr> <h2>Flashing more slowly</h2> <p>If you put an LED on pin 3 and want to <strong>see</strong> the flashing, you need it much slower. For example:</p> <pre class="lang-C++ prettyprint-override"><code>TCCR1 |= bit (CS10) | bit (CS11) | bit (CS12) | bit (CS13); // prescaler: 16384 </code></pre> <p>That toggles the pin every 254 ms, which is visible.</p> <hr> <h2>Warning</h2> <p>On this chip Timer 1 is an 8-bit timer, so you cannot put more than 255 into OCR1C.</p> <hr> <h2>More information</h2> <ul> <li><a href="http://www.gammon.com.au/timers" rel="nofollow noreferrer">Timers</a></li> <li><a href="http://www.gammon.com.au/interrupts" rel="nofollow noreferrer">Interrupts</a></li> </ul>
18955
|arduino-leonardo|midi|
How to send a pitch bend MIDI message using arcore?
2015-12-24T01:15:03.937
<p>I'm new to MIDI and started playing with an Arduino Leonardo and <a href="https://github.com/rkistner/arcore" rel="nofollow">arcore</a>. Based on the example code, I can easily send <code>noteOn/noteOff/controlChange</code> messages, but I can't seem to send a pitch bend message.</p> <p>Having a look at <a href="http://www.onicos.com/staff/iz/formats/midi-event.html" rel="nofollow">this table</a>:</p> <pre><code>0xE0 Chan 1 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE1 Chan 2 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE2 Chan 3 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE3 Chan 4 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE4 Chan 5 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE5 Chan 6 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE6 Chan 7 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE7 Chan 8 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE8 Chan 9 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xE9 Chan 10 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xEA Chan 11 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xEB Chan 12 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xEC Chan 13 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xED Chan 14 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xEE Chan 15 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) 0xEF Chan 16 Pitch wheel range Pitch wheel LSB (0-127) Pitch wheel MSB (0-127) </code></pre> <p>I've tried to send a message like so:</p> <pre><code>MIDIEvent pitchwheel = {0xe0, 127,127}; MIDIUSB.write(pitchwheel); </code></pre> <p>but this didn't work and I'm not sure what I'm missing/doing wrong.</p> <p>Any hints/tips will be helpful.</p>
<p>arcore creator Ralf Kistner provided the <a href="https://github.com/rkistner/arcore/issues/19" rel="nofollow">answer</a>:</p> <pre><code>// The pitch bend value is a 14-bit number (0-16383). 0x2000 (8192) is the default / middle value. // First byte is the event type (0x0E = pitch bend change). // Second byte is the event type, combined with the channel. // Third byte is the 7 least significant bits of the value. // Fourth byte is the 7 most significant bits of the value. void pitchBendChange(byte channel, int value) { byte lowValue = value &amp; 0x7F; byte highValue = value &gt;&gt; 7; MIDIEvent event = {0x0E, 0xE0 | channel, lowValue, highValue}; MIDIUSB.write(event); } </code></pre>
18959
|arduino-ide|uploading|mac-os|
ERROR: Timed out waiting for Arduino 101 - anything I can do?
2015-12-24T09:41:29.290
<p>I just received an Arduino 101 so I did the following in a wave of excitement...</p> <ol> <li>Connected the USB cable between it and my Macbook Pro</li> <li>Started the Arduino IDE version <code>1.6.7</code></li> <li>Wrote a little bit of code</li> <li>Selected <code>Tools | Boards | Boards Manager...</code> and installed the <code>Intel Curie Boards</code> as per <a href="https://www.arduino.cc/en/Guide/Arduino101">Getting Started</a></li> <li>Selected <code>Tools | Board: "Arduino 101"</code> </li> <li>Selected <code>Tools | port: "/dev/cu.usbmodemFA141 (Arduino 101)"</code> </li> <li>Selected <code>Sketch | Upload</code></li> </ol> <p>I was expecting something amazing, but I got the error:</p> <pre><code>Starting upload script Payload: /var/folders/jr/5rmqcrqj58103d4p1f6_3sjr0000gn/T/build7c6ce067b9e8a57f9917c651ec494989.tmp/orientation.ino.bin Waiting for device... ERROR: Timed out waiting for Arduino 101. </code></pre> <p>Is there anything I can do to debug this or did I miss a step perhaps?</p> <p>(I tried the good ol' turn it off and on again, including shutting the IDE down).</p>
<p>I was really persistent to look for ways on how to fix the Arduino/Genuino 101 Timeout Error, I searched different forums and read a lot of suggestions on how to fix the error, but still all failed, I know some of the 101 users already bricked their 101 or other just left it behind. We are all aware that the Arduino 101 is already discontinued and even support is already stopped, Hence this little but powerful microcontroller is still out there and probably used by the some. Anyhow, to be straight to the point I finally I discovered the fix for the error. Notice that when you insert your 101 to the USB plug it will read and install the device, checking it in the device manager will show the Arduino/Genuino 101 in &quot;Other Devices&quot; and a new COMPort (COMX) is added, then you install the Arduino IDE (regardless of the version), then install the Arduino 101 Board thru &quot;Board Manager&quot;, the manager will install the Arduino 101 but it will not notify you that the driver for Arduino 101 is not installed due to error. So in short we are assuming that the driver for Arduino 101 is successfully installed. This is where the error lies. The software driver &quot;dpinst-amd64&quot; is not digitally signed and Windows is blocking to install unsigned drivers. So what's the fix? The fix here is still to install the &quot;dpinst-amd64&quot; since it is the driver needed to recognize your 101, the trick here is you need to install it in other way, not in your regular PC operation. You need to access the &quot;disable signature enforcement&quot; under the startup options (not safe mode). This startup mode will enable you to install unsigned drivers (I trust this Intel Curie driver since it was downloaded with the board). After installation restart your PC to its regular startup and plug-in again your Arduino/Genuino 101, this time the PC will now recognize the microcontroller and you can now upload sketches without the time out error.</p> <p>For a step by step procedure:</p> <ol> <li>Access Update and Security&gt;Recovery&gt;Advanced Startup</li> <li>Your computer will eventually restart and will bring you to the Advanced Startup, access Troubleshoot&gt;Startup Settings. Your PC will restart again and options for the startup will display, choose number 7 &quot;disable signature enforcement&quot;</li> <li>Your PC will start. Locate &quot;dpinst-amd64.exe&quot; in C:&gt;Users&gt;YOUR USERNAME&gt;AppData&gt;Local&gt;Arduino15&gt;packages&gt;Intel&gt;hardware&gt;arc32&gt;2.0.4(latest version)&gt;drivers&gt;dpinst-amd64</li> <li>During installation a message will prompt if you want to install the unsigned driver, just click install.</li> <li>After installation restart your PC and your Arduino/Genuino 101 is good to go.</li> <li>To confirm that your Arduino/Genuino 101 is installed go to Device Manager and you will see that the Arduino/Genuino 101 is not anymore in the Other Devices.</li> </ol> <p>I hope this will help. :D I will try to make a video about this fix. :D Thanks!</p> <p>Regards,</p> <p>Raf</p>
18963
|avr|mac-os|avr-toolchain|
How to program AVR in Mac OS X?
2015-12-24T13:37:20.007
<p>In our college we are using a module developed by IIT Bombay (called FIREBIRD V[ver 5]). It has ATmega2560 and ATmega8 microcontrollers (master and slave) with bootloader.</p> <p>The staff uses AVR Studio for programming. But since AVR Studio is supported only on Windows (and I have a Mac), I was looking for AVR programming in Mac. I downloaded Crosspack AVR. But I don't know how to proceed after this point. Also I downloaded TextWrangler (because I was told auto-suggestion is not available in TextEdit).</p> <p>Also I have downloaded the Arduino IDE, and I don't know what is required or how to configure it to program AVR microcontrollers.</p> <p>I searched on the web and nothing is clear (mostly they all depend on something to do with terminal and the command line).</p> <p>I don't have Xcode installed in my Mac (I saw a relatively easy tutorial on how to set up Xcode for this purpose) and the file is 4GB. I am trying to work around using Xcode, but if it's the only nice way do let me know!</p> <p>Pertinent suggestions would be helpful.</p>
<p>First, install and get familiar with version 1.6.x of the Arduino IDE. Then, under the sketchbook directory, within <code>hardware/nex/avr/</code> (create the directories if they don't exist) create the following files:</p> <h3>boards.txt:</h3> <pre><code># NEX Robotics Fire Bird V # Only ATmega2560@14.7456MHz supported for now nexfirebirdv2560m14.name=Fire Bird V ATMEGA2560 @ 14.7456 MHz nexfirebirdv2560m14.upload.tool=avrdude nexfirebirdv2560m14.upload.protocol=avr109 nexfirebirdv2560m14.upload.maximum_size=129024 nexfirebirdv2560m14.upload.maximum_data_size=8192 nexfirebirdv2560m14.upload.speed=115200 nexfirebirdv2560m14.bootloader.low_fuses=0xFF nexfirebirdv2560m14.bootloader.high_fuses=0xDA nexfirebirdv2560m14.bootloader.extended_fuses=0xFD nexfirebirdv2560m14.build.mcu=atmega2560 nexfirebirdv2560m14.build.f_cpu=14745600L nexfirebirdv2560m14.build.core=arduino:arduino # This is not the real variant, but it will get the board running nexfirebirdv2560m14.build.variant=arduino:mega </code></pre> <h3>platform.txt:</h3> <pre><code>name=NEX Robotics Fire Bird V version=0.0.0 </code></pre> <p>I have verified that an empty sketch will build, but do not have the hardware to test uploading. The <code>upload.protocol</code> value may need to be changed to <code>avr910</code> or <code>arduino</code> if the current value doesn't work. Make sure to restart the IDE after any changes to the configuration files.</p> <p>Further improvements that can be done include:</p> <ul> <li>A real variant for the specific board</li> <li>Support for the on-board ATmega8 (for now just use one of the slave firmwares uploaded with avrdude)</li> <li>Support for the other AVR boards</li> <li>Support for the 8051 and ARM boards</li> </ul>
18971
|arduino-mega|arduino-ide|servo|
Arduino Servo Free Rotation
2015-12-24T19:42:16.147
<p>I have a project where I use 22 servos. I attach all 22 of the servos in the setup and in the loop, I use <code>myservo.write()</code> command to make a particular servo move to a particular position. </p> <p>The problem here is that, all the other servos become stiff at this point of time, even though I am not writing any value to those servos. By stiff I mean that the servo is holding at a particular random value. Which for most of the 22 servos is at or near 90Β°. </p> <p>My question is how can I make a particular servo move, while allowing all the other servos to freely rotate. I think that when I attach a servo the program prevents the free rotation of the servo. </p> <p>I was wondering if the signal to one of the servos is leaking to other servos because of an issue with wiring, but this is not the case. The other servos become stiff only when I attach them to the pins which have been "attached" as a servo in the program. </p>
<p>When you <code>attach</code> a servo the Arduino starts generating the PWM waveform for its currently selected angle. When you <code>write</code> to the servo you just change the current angle and the waveform changes to match. That waveform is constantly being generated from the moment the servo is attached, and will always be generated. That is how servos work. They are not really designed to be back-driven by the load turning the cogs - it is the role of the servo to do the driving, not to be driven. </p> <p>Depending on the servo you might actually damage the mechanics by driving it backwards like that.</p> <p>The only way you can stop the servo from being actively driven is to detach the pin from the servo system so that it doesn't think there is a servo there any more.</p>
18975
|arduino-pro-mini|
Can I use my phone's charger to connect arduino M0 pro R3 with computer?
2015-12-24T20:35:28.767
<p>I found out that the arduino M0 pro R3 needs either micro HDMI or micro USB.</p> <p>Since I don't have any micro USB or HDMI adapters, can I use the Samsung galaxy USB/micro adapter to connect?</p>
<p>Echoing what Gerben said, in order to wrap up this question:</p> <ul> <li><p>If the Samsung cable has a micro-usb on one end, and a usb-a on the other side, then I don't see why not. </p></li> <li><p>You just want to power it, not connect it to a PC? A regular USB port only supplies upto 500mA, so 1.5A is plenty.</p></li> <li><p>The allowed input voltage range for this pin is 6-20 V. sourceβ€Œβ€‹. So your 12v adapter is also fine.</p></li> </ul>
18985
|class|
Class is not tracking changes to a private field
2015-12-25T06:54:45.110
<p>I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object. This is the main sketch</p> <pre><code>#include "command.h" #include "widget.h" Command command; Widget widget; void setup() { command.init(); widget.init(command); } void loop() { command.update(); } </code></pre> <p>command.h</p> <pre><code>#include "Arduino.h" #ifndef Command_h #define Command_h typedef struct { char id; char name[20]; } Device; class Command { public: Command(); void init(); void registerDevice(Device _cmd); void update(); private: Device Devices[20]; byte DevicesPtr = 0; }; #endif </code></pre> <p>command.cpp</p> <pre><code>#include &lt;Arduino.h&gt; #include "command.h" #define DEVICES_MAX 9 Command::Command() { DevicesPtr = 0; Device Devices[DEVICES_MAX]; } void Command::init() { Serial.begin(9600); } void Command::update(){ Serial.print( DevicesPtr ); Serial.println( " devices registered" ); delay(500); } void Command::registerDevice(Device _cmd) { _cmd.id = '0' + (++DevicesPtr); Devices[DevicesPtr] = _cmd; Serial.print("Devices registered "); Serial.println(DevicesPtr); } </code></pre> <p>widget.h</p> <pre><code>#include "Arduino.h" #include "command.h" class Widget { public: static void init(Command _command); private: }; </code></pre> <p>widget.cpp</p> <pre><code>#include "widget.h" #include "command.h" void Widget::init(Command _command) { Device device; strcpy(device.name, "Widget #1"); _command.registerDevice(device); } </code></pre>
<p>It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference. </p> <p>This is call-by-value (the incoming command is not updated, a copy is passed as parameter):</p> <pre><code>void Widget::init(Command _command) ... widget.init(command); </code></pre> <p>This is call-by-reference (a pointer to command is passed as parameter):</p> <pre><code>void Widget::init(Command* _command) { __command-&gt;registerDevice(...); } ... widget.init(&amp;command); </code></pre> <p>Alternative syntax is:</p> <pre><code>void Widget::init(Command&amp; _command) { _command.registerDevice(...); } ... widget.init(command) </code></pre> <p>Cheers!</p>
18997
|programming|i2c|
Where am I supposed to get an I2C BUFFER_LENGTH defined?
2015-12-25T18:51:49.497
<p>I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:</p> <pre><code>Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope </code></pre> <p>How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case? </p>
<p>BUFFER_LENGTH is set in <a href="https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/I2Cdev/I2Cdev.h" rel="nofollow">I2Cdev.h</a> depending on the target. BLE nano is not directly supported (what I can see). </p> <p>Cheers!</p>
18998
|programming|
Capacitive "keys" press event registration issues
2015-12-25T20:17:09.540
<p>Seeing as this is my first post I would like to thank everyone ahead who take their time to delve into my whimsical code, whoever you may be, be merciful ;)</p> <p>For one of my uni projects, I would like to make a physical interface that can be operated via touch "keys" that rely on the human capacitance effect. I have relentlessly researched it (as much as feasible in my time as a student for this project) and even created a working prototype with 4 unique keys. </p> <p>As you will see in my code below, I am using the capacitiveSensor.h library, which I could unfortunately not find much documentation about other than a few videos and tutorials that build upon it. </p> <p>I tried deciphering the workings of it by looking at its code to see if I can manipulate it for my own biddings but quickly realized it is beyond my skill to understand.</p> <p>The problem I am facing right now is that while the touch keys work, they trigger each other because of the capacitance build up when one of the keys is being pressed or when the hand is close to other keys while pressing a key. </p> <p>Essentially, I am looking for an algorithm that will reduce processing time &amp; effort for the Arduino as the one I have implemented below slows it down way too much to be of any use for my project.</p> <p>Sorry for the long post, here is my current code:</p> <pre><code>#include &lt; CapacitiveSensor.h &gt; #include &lt; pitches.h &gt; CapacitiveSensor cs_4_2 = CapacitiveSensor(4, 2); // 10M resistor between pins 4 &amp; 2, pin 2 is sensor pin, add a wire and or foil if desired CapacitiveSensor cs_4_3 = CapacitiveSensor(4, 3); // 10M resistor between pins 4 &amp; 6, pin 6 is sensor pin, add a wire and or foil CapacitiveSensor cs_4_5 = CapacitiveSensor(4, 5); // 10M resistor between pins 4 &amp; 8, pin 8 is sensor pin, add a wire and or foil CapacitiveSensor cs_4_6 = CapacitiveSensor(4, 6); # define COMMON_PIN 4 // send pin # define CAP_THRESHOLD 450 // overall threshold # define NUM_OF_KEYS 4 // Number of keys that are on the keyboard # define noteDur 50 // duration of note # define BUZZER_PIN 12 // The output pin for the piezo buzzer # define noMulti 0.9 // incremental factor per key # define overkill 5 // register no touch after this cap factor is exceeded // This macro creates a capacitance "key" sensor object for each key on the piano keyboard: # define CS(Y) CapacitiveSensor(COMMON_PIN, Y) CapacitiveSensor keys[] = { CS(2), CS(3), CS(5), CS(6) }; void setup() { Serial.begin(57600); // Turn off autocalibrate on all channels: for (int i = 0; i &lt; NUM_OF_KEYS; ++i) { keys[i].set_CS_AutocaL_Millis(0xFFFFFFFF); } } void loop() { // needs to be repeated here to work in THIS scope long sensor01 = cs_4_2.capacitiveSensor(30); // pin 2 is cap sensor, pin 4 is "common send" long sensor02 = cs_4_3.capacitiveSensor(30); long sensor03 = cs_4_5.capacitiveSensor(30); long sensor04 = cs_4_6.capacitiveSensor(30); Serial.println(""); Serial.print("key1"); Serial.print("\t"); Serial.print("key2"); Serial.print("\t"); Serial.print("key3"); Serial.print("\t"); Serial.print("key4"); Serial.println(""); Serial.print(keys[0].capacitiveSensor(CAP_THRESHOLD)); Serial.print("\t"); Serial.print(keys[1].capacitiveSensor(CAP_THRESHOLD)); Serial.print("\t"); Serial.print(keys[2].capacitiveSensor(CAP_THRESHOLD)); Serial.print("\t"); Serial.print(keys[3].capacitiveSensor(CAP_THRESHOLD)); // algo for key 1 if (keys[0].capacitiveSensor(CAP_THRESHOLD) &gt; CAP_THRESHOLD &amp;&amp; keys[1].capacitiveSensor(CAP_THRESHOLD) &lt; keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[2].capacitiveSensor(CAP_THRESHOLD) &lt; keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[3].capacitiveSensor(CAP_THRESHOLD) &lt; keys[0].capacitiveSensor(CAP_THRESHOLD) * noMulti) { Serial.print("key pressed on sense1"); Serial.println(""); tone(BUZZER_PIN, NOTE_A7, noteDur); } // algo for key 2 else if (keys[1].capacitiveSensor(CAP_THRESHOLD) &gt; CAP_THRESHOLD &amp;&amp; keys[0].capacitiveSensor(CAP_THRESHOLD) &lt; keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[2].capacitiveSensor(CAP_THRESHOLD) &lt; keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[3].capacitiveSensor(CAP_THRESHOLD) &lt; keys[1].capacitiveSensor(CAP_THRESHOLD) * noMulti) { Serial.print("key pressed on sense2"); Serial.println(""); tone(BUZZER_PIN, NOTE_B7, noteDur); } // algo for key 3 else if (keys[2].capacitiveSensor(CAP_THRESHOLD) &gt; CAP_THRESHOLD &amp;&amp; keys[1].capacitiveSensor(CAP_THRESHOLD) &lt; keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[0].capacitiveSensor(CAP_THRESHOLD) &lt; keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[3].capacitiveSensor(CAP_THRESHOLD) &lt; keys[2].capacitiveSensor(CAP_THRESHOLD) * noMulti) { Serial.print("key pressed on sense3"); Serial.println(""); tone(BUZZER_PIN, NOTE_C7, noteDur); } // algo for key 4 else if (keys[3].capacitiveSensor(CAP_THRESHOLD) &gt; CAP_THRESHOLD &amp;&amp; keys[1].capacitiveSensor(CAP_THRESHOLD) &lt; keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[2].capacitiveSensor(CAP_THRESHOLD) &lt; keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti &amp;&amp; keys[0].capacitiveSensor(CAP_THRESHOLD) &lt; keys[3].capacitiveSensor(CAP_THRESHOLD) * noMulti) { Serial.print("key pressed on sense4"); Serial.println(""); tone(BUZZER_PIN, NOTE_D7, noteDur); } } </code></pre>
<p>You might experiment with the code shown at the end of this answer. It is fairly responsive, in the sense that readings are taken reasonably quickly (several per millisecond), which should leave a good deal of time available for other processing.</p> <p>In this code, all of the pins that are on the same port are sampled at the same time. For example, pins 2,3,5,6 on an Uno are all on port D so their four pads can be tested all at the same time. But if the pins list includes pins from <code>k</code> different ports, sampling will take up to <code>k</code> times as long as when sampling from a single port. For example, on a Mega2560, pins 2, 3, 5 are on port E and pin 6 is on port H, so this code's execution time when processing buttons on pins 2,3,5,6 is about twice as long on a Mega as on an Uno.</p> <p>[<em>Edit:</em> For Uno port-to-pin assignments, see an <a href="https://www.google.com/search?hl=en&amp;site=imghp&amp;tbm=isch&amp;source=hp&amp;biw=1095&amp;bih=625&amp;q=uno+pinout&amp;oq=uno+pin&amp;gs_l=img.1.0.0l3j0i30j0i5i30l6.2233.4374.0.6513.7.7.0.0.0.0.70.453.7.7.0....0...1ac.1.64.img..0.7.451.lq4psgGuNr0" rel="nofollow noreferrer">Arduino Uno Pinout Diagram</a>. On such diagrams, labels like <code>ADC0 PCINT8 14 A0 23 PC0</code> show the Arduino digital pin reference number (eg, 14), analog pin label (eg, A0), its various functional designations (ADC0, PCINT8, and PC0, meaning analog input pin 0, pin-change-interrupt pin 8, and bit 0 of port C), and the physical pin number (23). For hardware level information about Uno ports, see <a href="http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf" rel="nofollow noreferrer">Atmel's document #8271</a>. Use Google images similarly to find other-model diagrams, eg <a href="https://www.google.com/search?hl=en&amp;site=imghp&amp;tbm=isch&amp;source=hp&amp;biw=1095&amp;bih=625&amp;q=uno+pinout&amp;oq=uno+pin&amp;gs_l=img.1.0.0l3j0i30j0i5i30l6.2233.4374.0.6513.7.7.0.0.0.0.70.453.7.7.0....0...1ac.1.64.img..0.7.451.lq4psgGuNr0#hl=en&amp;tbm=isch&amp;q=mega+2560+pinout" rel="nofollow noreferrer">Mega 2560 pinouts</a>.]</p> <p>You may need to tune some of the constants to fit your own circuitry or switch-function requirements. I'm not able to tell from the question what resistor sizes you are using or what your circuit is. For preliminary tuning, enable the <code>secondly()</code> function and disable <code>testChange()</code> functions. If your circuit is similar to that shown below but uses higher resistances, you may need to increase <code>nsamp</code>, <code>IsHighCount</code>, and <code>preSamp</code>.</p> <p>Here is the general idea of circuitry I used: <a href="https://i.stack.imgur.com/tpwfx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tpwfx.jpg" alt="enter image description here"></a></p> <p>In the above, "Drive" refers to pin 4. "Sense 1" ... "Sense j" (with j=4) refer to pins 2, 3, 5, 6, as in your example code. The capacitors illustrated are tape-covered aluminum-foil pads, eg 22 x 44 mm and the resistors are 440 KΞ© each (two 220 KΞ©'s in series). Those resistor values produce an RC time constant of a few dozen microseconds when a button isn't touched, and a couple hundred microseconds when a button is touched.</p> <p>Here is some example output:</p> <pre><code>2 on 199 7587 2 off 179 7702 1 on 196 10798 1 off 154 10802 1 on 253 10900 1 off 180 10924 2 on 219 18097 2 off 166 18134 3 on 214 21105 3 off 155 21385 3 on 227 24312 3 off 72 24535 </code></pre> <p>In that output, the first column is switch number. The last column is the current reading of <code>millis()</code> at time of printing. The third column is total counts accrued from 12 sets of contact readings. The simple-minded on/off algorithm used in the <code>testChangeA()</code> function is that a contact is on when its 12-sample count exceeds 180. One could also add calibrations, adaptive threshholds, debouncing, etc to the code.</p> <p>Here is the code (which was run on an Uno, but I tested most of it on a Mega also, and it should run ok on other Arduinos as well since the direct port accesses are computed via functions like <code>portInputRegister</code>, <code>portModeRegister</code>, etc in <code>countPins7()</code> setup before it calls <code>portSampler7()</code> to run the test.</p> <pre class="lang-c prettyprint-override"><code>/* Via serial port, tell the current time when capacitive readings on various digital pins show a button has been "pressed" or "released". JW - 25 Dec 2015 See eg refs at http://playground.arduino.cc/Code/CapacitiveSensor and http://www.arduino.cc/en/Reference/PortManipulation and http://garretlab.web.fc2.com/en/arduino/inside/arduino/Arduino.h/digitalPinToPort.html */ #include &lt;Streaming.h&gt; // provides nicer syntax for printing // Set upper size on pins count per sample; #samples saved per reading; // #samples tossed; threshold for Button-is-on; #samples per set; etc enum { nbits=8, nsamp=40, preSamp=1, SettleDown=90 }; enum { IsHighCount=15, SampleSets=12, IsHighTotal=IsHighCount*SampleSets }; void setup() { Serial.begin(115200); // initialize serial port } //----------------------------------------------------------- // portSampler7(): Sample a port nsamp times and return the results. // Inputs: drivePin, portCode, pinsMask, preWait. Constant nsamp. // Output: array of nsamp samples. // This version takes 8 cycles per sample, and as inputs switch // on after about one RC time constant, on a 16MHz Arduino an // m-count result (that is, a bit clear in m of the nsamp readings) // suggests RC is about m/2 + preWait/2 us. void portSampler7(uint8_t drivePin, uint8_t portCode, uint8_t pinsMask, uint8_t preWait, uint8_t *samples) { volatile uint8_t *pin, *port, *ddr; // pin, port, and ddr are pointers to registers with volatile // contents: input port, output port, direction register. pinMode(drivePin, OUTPUT); digitalWrite(drivePin,LOW); pin = portInputRegister (portCode); // eg points to PIND port = portOutputRegister(portCode); // eg points to PORTD ddr = portModeRegister (portCode); // eg points to DDRD *port &amp;= ~pinsMask; // Turn off our pins *ddr |= pinsMask; // Make our pins be outputs, briefly for (uint8_t i=0; i&lt;SettleDown; ++i) *pin; // Delay to let pins settle low *ddr &amp;= ~pinsMask; // Make our pins be high-impedance inputs digitalWrite(drivePin,HIGH); // Turn on driver pin for (uint8_t i=0; i&lt;preWait; ++i) *pin; // Baseline Delay for (uint8_t i=0; i&lt;nsamp; ++i) // Take and store nsamp readings samples[i] = *pin; } //----------------------------------------------------------- /* Sample a pins-list and report results in counts array. Eg, pinsList can look like "2,3,4,5,6" or "2,4,5,12,9,23,17,7" etc. A list may contain digits and commas only. Pins may be listed in any desired order. Elements of counts will be in list-order. Eg, in the "2,3,4,5,6" example, counts[0] is the count for pin 2, counts[1] is the count for pin 3, etc. A larger count implies longer rise time and larger capacitance. Use preWait to suppress baseline-level counts (and to reduce sample array size) by waiting a while before beginning to sample. */ uint8_t countPins7(uint8_t drivePin, char *pinsList, uint8_t *counts, uint8_t preWait) { uint8_t pnum, pomask, pocode, potem, i, j, mul; uint8_t sampl[nsamp], pim[nbits], pat[nbits], bout=0, nat=0, pcon; char *c, cc; int usedPorts=0; // To track which ports are done for (c=pinsList, counts[0]=pcon=0; *c; ++c) // Zero the counts array if (*c &lt; '0' || *c &gt; '9') counts[++pcon] = 0; // In each pass, group bit numbers by port and sample the port while (nat&lt;pcon) { // Each loop pass sets one bit in usedPorts pnum = pocode = pomask = bout = pcon = 0; c = pinsList; while ((cc=*c++)) { // Loop until c is at end of string if ('0' &lt;= cc &amp;&amp; '9' &gt;= cc) { pnum = 10*pnum + cc - '0'; if ( *c &lt; '0' || *c &gt; '9') { // See if pin # is complete potem = digitalPinToPort(pnum); // Get port #, in range 1 to 12 if (!(usedPorts &amp; (1&lt;&lt;potem))) { // Is potem's port already done? if (!pocode) // If pocode not set, set it pocode = digitalPinToPort(pnum); if (pocode == potem) { // Process pin if it's in current port pomask |= (pim[bout] = digitalPinToBitMask(pnum)); pat[bout++] = pcon; // Save location of pin's bit in results } } pnum = 0; // Clear # accumulator ++pcon; // Count pin numbers } } } // Now pomask is a mask for all bits to be read from port pocode // and we are ready to sample current port portSampler7(drivePin, pocode, pomask, preWait, sampl); usedPorts |= 1&lt;&lt;pocode; // Mark the port finished // Count up # of zeroes (ie rise times) in sampled bits for (j=0; j&lt;bout; ++j) { int count; uint8_t m=pim[j]; for (count=i=0; i&lt;nsamp; ++i) count += sampl[i] &amp; m; counts[pat[j]] += nsamp - count/m; } nat += bout; // Count number of pins done so far } return pcon; // Return # of pins processed } //----------------------------------------------------------- // secondly() will report counts at start-of-second void secondly() { uint8_t counts[nbits], j, nc; if (millis()%1000) return; // Wait for start-of-second nc = countPins7(4, "2,3,5,6", counts, preSamp); Serial &lt;&lt; "Counts: "; for (j=0; j&lt;nc; ++j) // Marshal output Serial &lt;&lt; counts[j] &lt;&lt; " "; Serial &lt;&lt; " t=" &lt;&lt; millis() &lt;&lt; endl; while ((millis()%1000)==0) {}; // Await end-of-millisecond } //----------------------------------------------------------- uint8_t ostate[nbits] = {0}; void testChange1() { uint8_t counts[nbits], j, nc, s; nc = countPins7(4, "2,3,5,6", counts, preSamp); for (j=0; j&lt;nc; ++j) { s = counts[j] &gt; IsHighCount; if (s ^ ostate[j]) { Serial &lt;&lt; j &lt;&lt; (s? " on " : " off ") &lt;&lt; counts[j] &lt;&lt; " " &lt;&lt; millis() &lt;&lt; endl; ostate[j] = s; } } } //----------------------------------------------------------- void testChangeA() { uint8_t counts[nbits], j, k, nc, s; int sumcount[nbits]={0}; for (k=0; k&lt;SampleSets; ++k) { nc = countPins7(4, "2,3,5,6", counts, preSamp); for (j=0; j&lt;nc; ++j) { sumcount[j] += counts[j]; } } for (j=0; j&lt;nc; ++j) { s = sumcount[j] &gt; IsHighTotal; if (s ^ ostate[j]) { Serial &lt;&lt; j &lt;&lt; (s? " on " : " off ") &lt;&lt; sumcount[j] &lt;&lt; " " &lt;&lt; millis() &lt;&lt; endl; ostate[j] = s; } } } //----------------------------------------------------------- // Take samples of rise times at designated pins. When a pin's // time changes from small to large, report rising edge; or // when it changes from large to small, report falling edge. void loop() { //secondly(); //testChange1(); testChangeA(); } </code></pre>
19018
|arduino-mega|shields|arduino-yun|
arduino beginner documentation help
2015-12-26T19:19:13.897
<p>I plan to buy these 2 products to begin to play with arduino to learn.</p> <ol> <li><a href="http://www.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html" rel="nofollow">Board with LCD touch</a></li> <li><a href="http://www.banggood.com/Iduino-Yun-Shield-Expansion-Module-Board-Compatible-Arduino-p-979882.html" rel="nofollow">Yun board expansion</a></li> </ol> <p>I have a mega 2560 which i bought with a starter kit and i love to play with. I have not played with the shield yet. I understand some shields can be used together, some not. and some with modification on the board and in the code. </p> <p>I can't find pins specification for the touch screen and the support on the website doesn't respond. </p> <p>If some one can help me find specifications for the touch screen, or help me choose some shields that will allow me to use a USB host, wifi, and a touchscreen it will be nice.</p> <p>Thanks all.</p>
<p>The <a href="http://m.banggood.com/UNO-R3-ATmega328P-Board-2_4-Inch-TFT-LCD-Screen-Module-For-Arduino-p-945755.html" rel="nofollow">link you posted</a> describes a TFT LCD Touch screen unit with the SPFD5408 controller, referenced in <a href="http://m.instructables.com/id/How-to-use-24-inch-TFT-LCD-SPFD5408-with-Arduino-U/" rel="nofollow">this Instructable</a> for use with the Mega. You might start there and migrate to the Yun once you get the screen working. </p>
19019
|hardware|
Re-use smartphone/tablets parts like a camera
2015-12-26T21:47:45.837
<p>For learning and hacking purposes, I plan to study and use parts from smartphones and tablets like Galaxy or iPhone. They are really efficient and pretty cheap...</p> <p>Did anybody do this before? If yes, can anybody tell me what kind of connector is this one on the galaxy camera, <a href="https://www.ifixit.com/Store/Parts/Galaxy-Tab-S-10-5-Front-Facing-Camera-Wi-Fi/IF252-001-1" rel="nofollow">Galaxy Tab S 10.5 Front Facing Camera (Wi-Fi)</a>, and whether it can be found for attaching it to an Arduino project? </p> <p>Edit: Someone else asked a similar question here, <a href="http://forum.arduino.cc/index.php?topic=269272.0" rel="nofollow">How to reuse quality camera from old / broken phone</a>.</p>
<p><em>(summary of comment thread)</em></p> <p>I <strong>strongly recommend</strong> against trying to use any of these smartphone camera replacement parts. While they are cheap, this is because the signal they output is nigh impossible for you to use, even if you knew its specifications, which is unlikely given proprietary parts often have proprietary, non-public protocols. Even if you did have it, you'd likely have to implement a linux kernel extension for Raspberry Pi yourself to support it. Far more work than it's worth.</p> <p>If you actually want to do image processing, there is a clear recommendation: <strong>the Raspberry Pi camera interface</strong>. RasPis have a special flex socket on the board for a camera, and you can buy cameras which work with the <code>raspivid</code> etc. commands included in raspbian with no extra setup. This allows you to use OpenCV or similar image processing libraries, or write your own, without having to worry about bitbanging obscure camera protocols.</p> <p>No-name camera boards can be bought from eBay or similar sites for less than US$20, and they support 30fps 5 MP image/video capture to the Raspberry Pi natively and easily. Just search for &quot;Raspberry Pi camera&quot;.</p> <h3><em>However...</em></h3> <p>If you're <em>really</em> sure you're up to the challenge of hacking a proprietary camera module, you'll want to do thorough research finding the exact protocol specifications for these camera chips first, and try to find ones that are the most common, for the highest chance of compatibility, and likelihood of others having made progress on using them. Good luck!</p>
19024
|gsm|
What phone carriers are available in the USA that are compatible with a sim900 breakout board
2015-12-27T00:04:18.363
<p>I was wondering what carriers are compatible with a sim900 breakout board. I know it needs a GSM network (AT&amp;T,T-mobile,?) but what networks can I use? </p> <p>It needs a 850/ 900/ 1800/ 1900 MHz frequency to work but who offers that frequency? I personally could not find what frequency cell phone companies offered. From how I understand it is that T-Mobile definitely will work.I have heard several different answers about companies like AT&amp;T and I have seen discussion about sprint (which I don't understand because they are a CDMA carrier). </p> <p>I have also heard that there are other carriers (Vondafone, nextel,Ting) that might be more cost effective for people like me who are only going to be using the text messaging.</p> <p>Can someone please set me straight on who I can use. </p>
<p>SIM900 should be compatible with both AT&amp;T and T-Mobile. T-Mobile uses 1900Mhz for 2G and AT&amp;T uses 850Mhz and 1900Mhz. Although both carriers are upgrading to 4G, they still support 2G devices. My personal experience is that most quadband 2G devices still work with AT&amp;T and T-Mobile and there is no technical reason why SIM900 shouldn't work. However, there can be issues with incompatible data plans that are compatible only with their own devices. You need to be careful when selecting the contract and buying the sim card.</p> <p>Nextel and Ting uses Sprint's network which is CDMA and thus wouldn't work. However Vodafone seems to be using T-Mobile's network and may work. </p>
19025
|interrupt|isr|timing|
Hardware Interrupt Triggered Randomly
2015-12-27T07:30:02.693
<p>So there is this pretty generic part of my project that involves triggering an ISR that will flip a boolean value. I have set up the software side like so: </p> <pre class="lang-c prettyprint-override"><code>void setup() { attachInterrupt(digitalPinToInterrupt(2), displayConvergence, FALLING); } void loop() { if(flashConvergence) { //Do stuff that takes several seconds delay(3000); flashConvergence = false; } } void displayConvergence() { if (!flashConvergence) { flashConvergence = true; } } </code></pre> <p>The schematic is as follows:</p> <p><img src="https://i.stack.imgur.com/ZE3pg.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fZE3pg.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>But the behavior of my circuit surprised me as the pin interrupt would get triggered randomly at a frequency at (guessing here) 3 times a second. </p> <p>Weird, I thought. I fiddled around and found that when the boost converter's 180V is not connected to any load, the interrupt service triggers as expected, as in it starts working correctly. So I thought perhaps the issue was some noise introduced by the boost converter. </p> <p>I modified the circuit by adding a capacitor across the switch: </p> <p><img src="https://i.stack.imgur.com/adfpO.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fadfpO.png">simulate this circuit</a></sup></p> <p>I tried 1 uF at first, but that didn't help and neither did 10 uF. However, when I tried 100 uF (I thought decoupling capacitors are usually 0.1uF to 1 uF, is the value I am using too big?), things seem to be working as expected with the exception that when I hold the switch in the closed position for a long time, then let it go back in the open position, the interrupt service can be triggered randomly for a short period right after I let go of the switch. </p> <p>Is my initial assumption that the ISR is triggering randomly due to EMI from the boost converter correct? Perhaps there are other causes I am not looking at? Is there a way to make this work 100% (as in solve the issue right after the switch is put in the open position)? </p> <p>Thanks for the help!</p>
<p>It has come to my attention I never posted a followup to this but I was actually able to solve this problem by shielding the wire going from the switch to the arduino. The switch's wire was about 2 to 3 inches long and I wrapped aluminum foil around it, which shielded the signal from what I suspected was EMI induced by the switching converters.</p> <p><a href="https://i.stack.imgur.com/MWI5S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MWI5S.png" alt="Poor Man&#39;s EMI Shielding"></a></p>
19028
|arduino-uno|bluetooth|communication|mac-os|
How to Send Live Sensor Data to iOS Custom Apps with BLE
2015-12-27T16:22:59.653
<p>I am looking for a Bluetooth Low Energy (BLE) device that could send live sensor data from Arduino to iOS custom apps, not the app that is already in the app store. I would like to create my own apps to receive the sensor data. Or are there any other ways to achieve it? </p>
<p>I would expect this to be pretty straight forward. Off hand, I can't think of anything that would be a major roadblock to creating your iOS apps. It seems like there are two problems you'll need to solve:</p> <ol> <li>Finding a BLE chip that is relatively easy to integrate with an Arduino, and</li> <li>Selecting the tools that you'll use on the iOS side to develop your app.</li> </ol> <p>Since I haven't done this my self, I started off looking on the Arduino side – mostly because it seemed like the problems there would be larger. I searched on Google using the terms:</p> <p><code>aruduino ble</code></p> <p>I found quite a few candidates that look promising, here are some of the better ones:</p> <ul> <li><p><a href="https://www.adafruit.com/product/1697" rel="nofollow">Bluefruit LE - Bluetooth Low Energy (BLE 4.0) - nRF8001 Breakout - v1.0</a> – I put this one on the top of my list because the price is pretty reasonable (&lt; $20 US) and Adafruit tends to do a good job of supporting their products with tutorials and at least a basic library that demonstrates the functionality of the device.</p></li> <li><p><a href="http://redbearlab.com/bleshield/" rel="nofollow">Redbear Labs</a> - I don't know anything about Redbear, but they do well in Google searches and appear to have several products, including a BLE shield, that might do what you want.</p></li> <li><p><a href="http://bleduino.cc" rel="nofollow">BLEduino</a> - this is a Kickstarter, and while it looks interesting, a <em>very</em> quick investigation didn't reveal a source where you can buy one.</p></li> </ul> <p>The choice of devices will partly depend on what your ultimate goal is. Something like the BLEduino will give you an all-in-one package to build your project around. The downside of this is that you may be spending money on functionality that you don't need/want to duplicate. A breakout board like the Bluefruit LE gives you a smaller device and possibly more flexibility at the expense a bit more work to get up and running.</p> <p>Next you'll need to select development tools. I started by searching with the terms:</p> <p><code>ble swift ios</code></p> <p>I got a number of promising results, including:</p> <ul> <li><a href="http://www.raywenderlich.com/85900/arduino-tutorial-integrating-bluetooth-le-ios-swift" rel="nofollow">Arduino Tutorial: Integrating Bluetooth LE and iOS with Swift</a></li> <li><a href="https://developer.apple.com/bluetooth/" rel="nofollow">Apple: Bluetooth for Developers</a></li> <li><a href="https://learn.adafruit.com/introduction-to-bluetooth-low-energy" rel="nofollow">Adafruit - Introduction to Bluetooth Low Energy</a></li> </ul> <p>These first three look like good starting points for "getting your bearings," the following two are specific to actual boards.</p> <ul> <li><a href="https://learn.adafruit.com/getting-started-with-the-nrf8001-bluefruit-le-breakout" rel="nofollow">Getting Started with the nRF8001 Bluefruit LE Breakout</a></li> <li><a href="https://github.com/RedBearLab/iOS" rel="nofollow">RedBearLab/iOS</a></li> </ul>
19038
|arduino-uno|analogread|voltage-level|safety|
Measuring voltage on an analog pin - What do I need to know about amperage?
2015-12-28T15:42:50.857
<p>I'd like to measure the voltage at a test point on a stepper motor driver chip with an arduino. The voltage at this point controls the amperages to the phase coils and is adjusted to trim the driver.</p> <p>I have a common ground with the driver already, I'd like to wire the drivers v-ref point to an analog input to drive an LCD showing the output amp number so I can adjust the driver.</p> <p>The issue I am worried about is that with the hardware I have to test with a properly trimmed driver is pushing 0.84A.</p> <p>Is this safe to do without killing the arduino board? </p>
<p>Yes. The only thing you need to be concerned about is the voltage. It needs to be less than the Arduino Vcc.</p> <p>The voltage sense circuit (analog inputs) typically have a high impedance and should draw a negligible current from the circuit being sensed. I didn't have much luck finding the actual spec for any of the AVR chips, but I did find <a href="https://electronics.stackexchange.com/questions/67171/input-impedance-of-arduino-uno-analog-pins">this answer to the question</a> on Electronics.StackExchange – where they say "hard to tell, the specs are incomplete, but 10 KΞ© seems like a reasonable guesstimate/assumption" (I paraphrase). The reasoning is interesting and worth a read.</p>
19043
|home-automation|
Link to an project for remotely turning off light switch?
2015-12-27T13:07:20.277
<p>I want to build a contraption using an arduino that allows me to turn off my light from across the room. I plan to use a solenoid to move the lights switch up and down. I'm sure I'll have some specific questions later on but to start with, has anybody made or seen a similar project? All I'm really looking for is a link to a project (unless you're willing to give advice/suggestions). Thanks!</p>
<h3>MicroBot Push: a robotic finger for your buttons...</h3> <p><a href="https://i.stack.imgur.com/64zRC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/64zRC.png" alt="enter image description here"></a></p> <p><a href="https://www.indiegogo.com/projects/microbot-push-a-robotic-finger-for-your-buttons#/" rel="nofollow noreferrer">https://www.indiegogo.com/projects/microbot-push-a-robotic-finger-for-your-buttons#/</a></p> <h3>The Robotoic Light Switch</h3> <p><a href="https://i.stack.imgur.com/k7xM7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/k7xM7.jpg" alt="enter image description here"></a></p> <p><a href="http://hackaday.com/2015/11/06/the-robot-light-switch/" rel="nofollow noreferrer">http://hackaday.com/2015/11/06/the-robot-light-switch/</a></p> <h3>Wifi controlled light switch</h3> <p><a href="https://i.stack.imgur.com/20BQY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/20BQY.png" alt="enter image description here"></a></p> <p><a href="https://hackaday.io/project/5141-wifi-controlled-light-switch" rel="nofollow noreferrer">https://hackaday.io/project/5141-wifi-controlled-light-switch</a></p>
19049
|atmega328|analogread|adc|
Arduino Uno ADC behavior in free running mode
2015-12-28T23:14:50.467
<p>I'm using my ATmega328P to sample an analog signal in free running mode. The ADC clock frequency is set to Γ·128. I've read that a single analog conversion lasts 13 clock cycles. I would like to know if the number of clock cycles changes if I make the ADC trigger an interrupt after every conversion (ADIE bit set to one). Or will the ADC still use 13 clock cycles and start again on the 14th?</p> <p>If ADIE is set to zero (no interrupts) will the result of the conversion still be written to ADCL and ADCH? And at what time of the 13 clock cycles is this result written to those registers? This is important to me so I can calculate how much time I have to read those registers.</p> <p>Would it be possible to set ADIE to zero and instead use a timer interrupt to read ADCL and ADCH every ~1 millisecond. Or am I missing something important?</p>
<p>You may want to take a look at Amanda Ghassaei's <a href="http://www.amandaghassaei.com/projects/arduinodsp/" rel="nofollow">tutorials on Arduino DSP techniques</a> or the <a href="http://wiki.openmusiclabs.com/wiki/ArduinoFHT" rel="nofollow">FFT/FHT</a> code at the Open Music Labs. Both use the Arduino ADC in free running mode. Amanda's code uses interrupts, the Open Music Lab code sits in a tight loop waiting for the conversion to complete.</p> <p>Based on the Open Music Lab code I can say, yes, the conversion is still written to ADCL and ADCH regardless of the interrupt setting in ADIE. I can't tell from your question how concerned you are about cycle counts, but I don't think you'd see a significant change using interrupts (I'd expect it to be zero). But using interrupts you'll take a hit as you enter and return from the ISR.</p> <p>As I mentioned in the comment, take a look at Amanda Ghassaei's code. She toggles pin 12 which creates a spike in the trace if you have a scope attached to pin 12 (or a logic analyzer). That will give you a very easy way to determine the actual time to handle the conversion.</p>
19059
|serial|arduino-nano|
Problem with serial driver for CH340G board
2015-12-29T07:52:04.267
<p>I bought a <code>USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino</code> and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1</p> <p>The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded <a href="http://www.wch.cn/download/CH341SER_MAC_ZIP.html" rel="nofollow">http://www.wch.cn/download/CH341SER_MAC_ZIP.html</a></p> <p>Most of the instructions were in Chinese, but the driver <code>CH341SER_MAC.ZIP θ΅„ζ–™η±»εž‹οΌšεΊ”η”¨θ΅„ζ–™ θ΅„ζ–™ε€§ε°οΌš250KB θ΅„ζ–™η‰ˆζœ¬οΌš1.1 ζ›΄ζ–°ζ—Άι—΄οΌš2013-12-25</code> seemed to install, but I cannot seem to find any <code>/dev/tty</code> and Arduino can't see any serial ports.</p> <p>Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)</p>
<p>On MacOS Sierra it kept crashing the OS, but version 1.3 works on MacOS Sierra. </p> <p>Found here: <a href="https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver" rel="nofollow">https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver</a></p>
19064
|arduino-mega|
Use of additional i/o ports in Arduino Mega
2015-12-29T10:51:09.793
<p>I'm a newbie in Arduino and I bought an Arduino Mega instead of the Uno. I want to know what the so-called additional i/o pins do. Are they the same with PWM and SPI? What can they do?</p>
<p><strong>Firstly some background info on the Arduino Mega:</strong></p> <p>I haven't used the Mega, but I've used the Uno, and have worked with a variety of ATmega microcontrollers.</p> <p>First thing you need to know is that the Arduino Mega (or any other Arduino) is a board that uses the Atmel ATmega microcontrollers. The specific microcontroller used on the Mega is the <strike>ATmega1280</strike> ATmega2560.</p> <p>So if you are keen to learn more about your Arduino, a good place would be to look at the datasheet of the microcontroller itself. Just google <strike>ATmega1280</strike> ATmega2560 datasheet. </p> <p>However this might be a fair bit complicated, since you are new to the Arduino and microcontroller world. </p> <p>A good place to start would be the Arduino website itself (but I suppose you've already looked at it).</p> <p><strong>Now, regarding your question:</strong></p> <p>I'm not sure what you are referring to as "additional i/o pins", but here's a quick rundown on what I/O pins are and used for.</p> <p>As you may know I/O pins are used by the microcontroller to talk to the outside world. On the ATmega chips, most of these are GPIOs (General Purpose I/Os) that can be programmed to receive or send digital signals. Of these GPIOs some are used for PWM, and some may be used for some communication protocol. And of course there are analog input &amp; reference pins, voltage supply, ground etc.</p> <p>You can find all this information in the datasheet I linked above. </p> <p>If you are curious how Arduino has routed the pins, you can have a look at the <a href="https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf" rel="nofollow noreferrer">schematic of the Arduino Mega</a> here.</p> <p>If you also have a look at the Arduino website, they have a very good description on what each pin does: <a href="https://www.arduino.cc/en/Main/arduinoBoardMega" rel="nofollow noreferrer">Arduino Mega</a>.</p> <p>Look at "Inputs and Outputs".</p>
19069
|serial|python|
Python PySerial with Arduino fails byte check
2015-12-29T12:22:23.490
<p>I'm struggling with my first steps with Python and PySerial. I have one Arduino which reads impulses from an electricity power meter, passes the counts over to another Arduino over an RF link and then sends the data over to an Raspberry Pi. The Arduino to Arduino communication works well. However the last step of passing this to the RPi fails. </p> <p>The MeterValue from the Arduino side is an unsigned Long (32 bits) and therefore split in 4 pieces of 8-bit transmissions plus a frame start and frame end:</p> <pre><code>[0x01] Frame start [0xMeterValueByte0] [0xMeterValueByte1] [0xMeterValueByte2] [0xMeterValueByte3] [0x04] Frame end </code></pre> <p>This is my Arduino code continuously sent to the RPi in debug purpose : </p> <pre><code>void loop() { //static test loop Serial.write(0x01); //start frame Serial.write(0x00); Serial.write(0x00); Serial.write(0x02); Serial.write(0x04); //end frame delay(3000); } </code></pre> <p>This is my Python code:</p> <pre><code>Import serial ser = serial.Serial('/dev/ttyACM0',9600) print("Connected to: " + ser.portstr) inputbuffer=[] inputbuffer = [0 for i in range(10)] while True: if ser.inWaiting() &gt; 0: inputbuffer = ser.read(1) print "Byte received" print "Inputbuffer[0]: " + hex(ord(inputbuffer[0])) j = inputbuffer[0] print "j= " + hex(ord(j)) </code></pre> <p>This check of the "j" parameter somehow fails:</p> <pre><code> if (j == 0x1): #look for start of frame print "Start found\n" print "Filling buffer\n" while ser.inWaiting() &lt; 5: #hold here until 5 bytes arrived pass #proceed here inputbuffer +=ser.read(5) #read 5 bytes if inputbuffer[5] == 4: #check that the message has frame end RXval = inputbuffer[1] RXval |= (inputbuffer[2] &lt;&lt; 8) RXval |= (inputbuffer[3] &lt;&lt; 16) RXval |= (inputbuffer[4] &lt;&lt; 24) print "RXval: ", RXval else: print "RX error, no frame end\n" inputbuffer = [] </code></pre> <p>This is the Python output: </p> <pre><code>Connected to: /dev/ttyACM0 Byte received Inputbuffer[0]: 0x1 j= 0x1 Byte received Inputbuffer[0]: 0x0 j= 0x0 Byte received Inputbuffer[0]: 0x0 j= 0x0 Byte received Inputbuffer[0]: 0x2 j= 0x2 Byte received Inputbuffer[0]: 0x4 j= 0x4 </code></pre> <p>And then it repeats. Obviously the Python code doesn't realize j == 1. How should I handle the checking of the received bytes?</p>
<p>I think the problem is that you can't count ;)</p> <p>Spot the difference:</p> <pre><code>0: [0x01] Frame start 1: [0xMeterValueByte0] 2: [0xMeterValueByte1] 3: [0xMeterValueByte2] 4: [0xMeterValueByte3] 5: [0x04] Frame end </code></pre> <p>and: </p> <pre><code>0: Serial.write(0x01); //start frame 1: Serial.write(0x00); 2: Serial.write(0x00); 3: Serial.write(0x02); 4: Serial.write(0x04); //end frame </code></pre> <p>Your receiver is looking for a pattern of 6 bytes, but your Arduino sketch is only sending a pattern of 5 bytes.</p> <p>Your check for the start character is simple enough - you solved it fine a few lines above:</p> <pre><code>print "j= " + hex(ord(j)) </code></pre> <p>But you forgot to do something similar for the check:</p> <pre><code>if (j == 0x1): </code></pre> <p>That should really be:</p> <pre><code>if (ord(j) == 0x1): </code></pre>
19074
|gsm|
SIM800 or SIM900 library for Arduino
2015-12-29T19:19:21.450
<p>I have a SIM 800L module which I am using to send /receive SMS calls.</p> <p>I just wanted to know whether there is any library suitable for the SIM800 for arduino. I don't need GPRS functionality . I see mostly the arduino shield library but not sure whether it works with the SIM800 module bought from aliexpress.</p> <p>Can someone help me in get me a library which can be used for the SIM800 .I have tried a lot but not getting a simple library for the same.</p> <p>Actual Issue :</p> <p>I am able to make it work with the AT commands using the Serial3 in the arduino MEGA. But when i started integrating with the existing project of ESP8266 and DS3231 somehow the Serial3 read() is not working properly. I tested with Serial3.readString()/ Serial3.read() and all. The CNMI for the SIM800 is 2,3,0,0 which is to direct the incoming message to the Terminal. If my project is having a simple loop with only Serial3.read, then all messages contents are read properly. If I include the other Serial2 readings which is for the ESP8266, then I am not able to read the full messages from Serial3.I have tried with timer to read serial from the Serial3 for 3-5 secs but now way it is working.</p>
<p>Most likely, the Serial3 buffer is being overrun because you are not reading fast enough. That is why when you use a simple loop, everything works and you get the whole message; very little time passes between reads. The simplest solution to this is to increase the size of the Serial buffer to, maybe, 256 bytes. Search for <code>HardwareSerial.h</code> in your Arduino installation and look for the <code>#define</code>d variable <code>SERIAL_RX_BUFFER_SIZE</code> in the file near the top. Change its value to 256 and save. This should provide enough buffer space to store the entire SMS until you read it. Alternatively you could change your CNMI settings to push only SMS notifications, which are a lot smaller in size, to the Arduino. Then you can parse the notifications, extract the SMS index and then request the SMS from the SIM800 using the index whenever you wish, making sure to read quickly (you will need to craft a <code>while</code> loop to do this efficiently, with timeouts and all). </p>
19078
|serial|softwareserial|
HardwareSerial - check for overflow
2015-12-29T20:00:46.137
<p>The SoftwareSerial library has a built-in <a href="https://www.arduino.cc/en/Reference/SoftwareSerialOverflow" rel="noreferrer">Overflow</a> function, but the <a href="https://www.arduino.cc/en/Reference/Serial" rel="noreferrer">Serial</a> library does not. Is there a simple way to check for a data buffer overflow on a hardware serial port?</p>
<p>A look at <code>HardwareSerial_private.h</code> shows incoming bytes are always read (interrupt-based), regardless of what your code is doing. So we can't set up a hardware interrupt to notify us when the chip's RX register has overflowed, because such an interrupt would depend on overflow flags but these flags never become set because, like I said, bytes are always read. It also shows that while all incoming bytes are read, not all are added to the 64-byte Serial buffer i.e. a byte may be read but if the buffer is full, nothing else happens; it is simply read to clear hardware flags. So the only (direct) way I can think of is to constantly poll <code>Serial.available()</code> in <code>loop()</code> to check if the number of bytes available for reading is equal to 64. If this condition yields TRUE, then you may safely conclude that the Serial buffer is full and about to overflow. This should suffice:</p> <pre><code> void loop(){ //your code if (Serial.available() == SERIAL_RX_BUFFER_SIZE){ // Just to be general, 64 bytes in most cases //buffer is overrun, do what u will } } </code></pre> <p>You could make some changes to <code>HardwareSerial_private.h</code> to get something like the overflow() method of SoftwareSerial. The relevant lines are:</p> <pre><code> if (i != _rx_buffer_tail) { _rx_buffer[_rx_buffer_head] = c; _rx_buffer_head = i; } </code></pre> <p>The snippet above ensures that the current write position is not equal to the tail of the ring buffer (i.e. if we are about to overwrite a character in the buffer), before writing the incoming byte to the buffer. An <code>else</code> block could be added to set some global variable to indicate overflow. This global variable would have to be cleared when <code>Serial.read()</code> is called.</p>
19087
|arduino-uno|
How do I connect multiple pinhole cameras and take photos and video at the press of a button?
2015-12-30T01:39:17.823
<p>I am trying to set up a 4 cameras which can take videos/photos at the press of a button.</p> <p>Things which I will need:</p> <ol> <li>4 micro cameras(the ones which are very small in size) with good shutter speed and sensor. The cameras will often travel at 20 to 30mph. So I guess good shutter speed is needed. </li> <li>2 Push buttons. One will start and stop taking pictures really fast, and the other will do the same for video </li> <li>Battery which can last atleast taking 5 images/1 min of video recording.</li> <li>4 Microsd cards and the connectors. Is there anyway I would be able to set up a common adapter to all these cards, so when connected to a computer it will show up as 4 different drives?</li> </ol> <p>So I think I can make the set up using this: <a href="http://www.arducam.com/" rel="nofollow">http://www.arducam.com/</a> But can it take images really fast. I couldn't see any information regarding this. It should be able to take like 4 images per second. Also it would be awesome if this set up can somehow support taking videos.</p> <p>Now another thing I need is a push button which will start taking the photos and stop taking it.</p> <p>This whole thing should operate from a battery.</p> <p>Mostly I want to know is the list of products which will work or the specs to look for when choosing the products. Also I would like to know if this is the best way to go for a project like this. This thing will be more like a toy, so I don't want to use really expensive parts for this. Also I don't want a gopro. I want to make this whole set up myself.</p> <p>Let me know if you need to know more details about this. </p>
<p>Arduinos and Cameras do not mix well at all. It's all down to the sheer quantity of data involved in pictures.</p> <p>Take for instance a typical VGA image - 640x480 pixels at 24-bit (3 byte) colour depth. One single picture requires 640x480x3 = 921600 bytes just to store it.</p> <p>Add to that the fact that most small cameras include hardware JPEG compression which the Arduino really has no hope of being able to handle, and you just can't do anything with it.</p> <p>Most camera modules use a system called <a href="http://mipi.org/specifications/camera-interface" rel="nofollow">CSI-3</a> (Camera Serial Interface version 3) for streaming the raw data from the CCD elements into the target. That allows for high speed data transfer of the whole frame at a speed that is able to support video. If you think about video as 25 frames per second, and raw data, that means that the data is being transferred from the CCD elements in total at arouns 22 MiB/s - there is absolutely no way that an Arduino can deal with that kind of data. So cameras that attach to an Arduino have their own controller chip that compresses the image to JPEG and streams it out through a much slower interface - typically RS232. All the Arduino can then do is tell the camera "Take a picture for me" at which point an image is captured and compressed, and then the Arduino receives the JPEG data through serial (slowly) and stores it on an SD card (also slowly). It can't do anything else with it.</p> <p>To crunch those numbers - assume that the compressed VGA image from the camera's processor chip is 100,000 bytes (I took a typical photo, scaled it to 640x480 and saved it with 90% JPEG compression and it was roughly that size). At 9600 baud you get 960 bytes per second. 100,000 / 960 = 104 seconds.</p> <p>That is how long it would take to transfer one single image through the Arduino.</p> <p>If the camera has a higher speed UART, say 115200 baud (11520 Bps), that would then give you 100,000/11,520 = 8.7 seconds. </p> <p>So no, using an Arduino to control cameras in that way just isn't possible.</p> <p>Instead you need a system that can talk CSI-3 directly - something with a direct camera connection, such as the Raspberry Pi. Another alternative is any embedded computer with enough processing power and USB ports to connect cheap USB webcams to. Again the Raspberry Pi would do - especially the newer version 2 with the quad core processor.</p>
19089
|arduino-uno|gps|
GPS library for Proteus
2015-12-30T02:25:45.940
<p>I am working on a project in which I have to connect my Arduino with a GPS module. In this project I need to get longitude, latitude, time and date from the GPS module and need to send these values via USB to a computer.</p> <p>On this computer, I am going to design software in Microsoft Visual Studio 2010, which will receive this data and display it on a map. </p> <p>Now, before designing it in hardware, I want to simulate it on Proteus. I have searched in Proteus but there's no GPS module in it, so does anyone know any GPS module library for Proteus?</p>
<p>If you will be using the computer to interface, <strong>you don't really need Arduino in the middle</strong>.</p> <p>You can hook the GPS module to the computer using a USB-UART bridge like one below:</p> <p><a href="https://i.stack.imgur.com/769N1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/769N1.jpg" alt="USB to serial"></a></p> <p>The usual GPS modules (ebay or other hobby stores) output NMEA sentences over their serial port. Check the datasheet of your GPS module for the baud rate and the RX/TX pins. Connect the RX and TX lines of your GPS to the USB-serial module and you should be able to see NMEA output on a terminal emulator (set to right baud).</p> <p>Once you see NMEA sentences over a terminal emulator, you can parse those in your application directly (bypassing terminal emulator) instead of using an Arduino.</p>
19096
|library|arduino-galileo|ubuntu|
WARNING: Category '' in library *any library* is not valid. Setting to 'Uncategorized'
2015-12-30T12:38:06.490
<p>I'm using Ubuntu 14.04 with arduino Galileo and the newest arduino IDE from arduino.cc and every time I compile I got this warnings with <em>any library</em> in place of EEPROM, SD, Wire, Wifi and a lot of others.</p> <p>When I check the boards manager I got the following:</p> <p>Invalid library found in /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire: /home/User/.arduino15/packages/Intel/hardware/i586/1.6.2+1.0/libraries/Wire </p> <p>Anyone knows how to solve this?</p>
<p>As sated above you need to "Edit or add library.properties to that folder so that you specify a valid category."</p> <p>This link has some good info on the structure of the file: <a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification" rel="nofollow noreferrer">https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification</a></p> <p>From that link:</p> <p>library.properties file format</p> <p>The library.properties file is a key=value properties list. Every field in this file is UTF-8 encoded. The available fields are:</p> <pre><code>**name** - the name of the library version - version of the library. Version should be semver compliant. 1.2.0 is correct; 1.2 is accepted; r5, 003, 1.1c are invalid **author** - name/nickname of the authors and their email addresses (not mandatory) separated by comma "," **maintainer** - name and email of the maintainer **sentence** - a sentence explaining the purpose of the library **paragraph** - a longer description of the library. The value of sentence always will be prepended, so you should start by writing the second sentence here **category** - if present, one of these: "Display", "Communication", "Signal Input/Output", "Sensors", "Device Control", "Timing", "Data Storage", "Data Processing", "Other" **url** - the URL of the library project, for a person to visit. Can be a github or similar page as well architectures - a comma separated list of architectures supported by the library. If the library doesn’t contain architecture specific code use β€œ*” to match all architectures **dot_a_linkage** - (available from IDE 1.6.0 / arduino-builder 1.0.0-beta13) when set to true, the library will be compiled using a .a (archive) file. First, all source files are compiled into .o files as normal. Then instead of including all .o files in the linker command directly, all .o files are saved into a .a file, which is then included in the linker command. **includes** - (available from IDE 1.6.10) a comma separated list of files to be added to the sketch as #include &lt;...&gt; lines. This property is used with the "Include library" command in the IDE. If the property is undefined all the headers files (.h) on the root source folder are included. </code></pre>
19097
|xbee|
Can't make Wee serial WiFi work with Arduino Uno
2015-12-30T14:02:58.727
<p>I'm trying to plug a <a href="http://wiki.iteadstudio.com/Wee_Serial_WIFI_Module" rel="nofollow noreferrer">Wee serial WiFi</a> module on my Arduino Uno, through an <a href="https://hackspark.fr/fr/xbee-shield.html" rel="nofollow noreferrer">XBee shield</a> .</p> <p><a href="https://i.stack.imgur.com/GsC52.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GsC52.jpg" alt="Wee in XBee shield"></a></p> <p>I'm simply trying to make work <a href="https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/examples/ConnectWiFi/ConnectWiFi.ino" rel="nofollow noreferrer">the example from the library</a>.</p> <p>All I get is</p> <pre><code>setup begin FW Version: to station err Join AP failure setup end </code></pre> <p>The code i'm using :</p> <pre><code>#include &lt;SoftwareSerial.h&gt; #include &lt;doxygen.h&gt; #include &lt;ESP8266.h&gt; SoftwareSerial mySerial(3, 2); /* RX:D3, TX:D2 */ ESP8266 wifi(mySerial); #define SSID "yuflowoffice" #define PASSWORD "cashless" void setup(void) { Serial.begin(9600); mySerial.begin(115200); Serial.print("setup begin\r\n"); Serial.print("FW Version: "); Serial.println(wifi.getVersion().c_str()); if (wifi.setOprToStation()) { Serial.print("to station ok\r\n"); } else { Serial.print("to station err\r\n"); } delay(1500); if (wifi.joinAP(SSID, PASSWORD)) { Serial.print("Join AP success\r\n"); Serial.print("IP: "); Serial.println(wifi.getLocalIP().c_str()); } else { Serial.print("Join AP failure\r\n"); } Serial.print("setup end\r\n"); } void loop(void) { } </code></pre> <p>What can I do?</p>
<p>A look at <a href="https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h" rel="nofollow">https://github.com/itead/ITEADLIB_Arduino_WeeESP8266/blob/master/ESP8266.h</a> shows that when you pass a <code>SoftwareSerial</code> object to the ESP8266 constructor, a default baud rate of 9600 is also passed to it. Also, the library source file shows that, in the constructor, the <code>begin()</code> method of the <code>SoftwareSerial</code> object you passed (myserial) is called with 9600 baud. Thus, this line in your code:</p> <pre><code> mySerial.begin(115200); </code></pre> <p>is a duplicate, albeit one with a different baud rate, thus rendering the constructor's call of <code>mySerial.begin()</code> useless, since your call comes after the constructor's. If you are certain that 115200 is the right baud rate for the hardware, then you should get rid of the line above and instead pass the baud rate to the constructor like this:</p> <pre><code> ESP8266 wifi(mySerial, 115200); </code></pre> <p>Replace 115200 with any baud rate you discover to be the right one for the AT commands. You also need to uncomment the line in ESP8266.h in your library:</p> <pre><code> //#define ESP8266_USE_SOFTWARE_SERIAL </code></pre> <p>and then save, since you are using SoftwareSerial to communicate with the module.</p>
19105
|library|
Basic usage of Nick Gammon's Regexp library
2015-12-31T00:48:37.100
<p>I am using the following code modified from the examples. I get the count of matches but the actual value is not displayed</p> <pre><code>#include &lt;Regexp.h&gt; void setup() { Serial.begin(115200); MatchState ms; char buf [100]; char buf2 [100] = "The quick brown fox jumps over the lazy wolf"; ms.Target (buf2); unsigned int count = ms.MatchCount ("[aeiou]"); Serial.print ("Found "); Serial.print (count); Serial.println (" matches."); for (int j = 0; j &lt; count; j++) { Serial.print ("Capture number: "); Serial.println (j, DEC); Serial.print ("Text: '"); Serial.print (ms.GetCapture (buf, j)); Serial.println ("'"); } } void loop(){} </code></pre>
<p>You haven't defined any capture groups in your regexp.</p> <p>The regexp <code>[aeiou]</code> will <em>match</em> any of those characters, but it won't <em>capture</em> them. To capture you need to define a <em>capture group</em> which is a sequence of tokens surrounded by parenthesis. For instance:</p> <pre><code>([aeiou]) </code></pre> <p>In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of <em>e u i o o u o e e a o</em>.</p> <p>The reason why matching and capturing are two completely different things is so you can do things like <code>[aeiou]([aeiou])</code> which would capture the second vowel in a two vowel sequence. In your example it would match the <em>ui</em> of <em>quick</em> and capture just the <em>i</em>.</p>
19124
|led|
Why is 1020 steps used for crossfading colors on an RGB LED?
2015-12-31T11:20:23.213
<p>I'm looking into how to smoothly crossfade between colors on an RGB LED with the Arduino and I've found this piece of code for doing it: <a href="https://www.arduino.cc/en/Tutorial/ColorCrossfader" rel="nofollow">https://www.arduino.cc/en/Tutorial/ColorCrossfader</a></p> <p>I understand all parts of the code except for one thing. The values for red, green and blue are changed incrementally through 1020 steps, because 255*4 = 1020. But WHY 4? There are 3 colors, and 255 * 3 = 765. So why not 765 steps?</p>
<p>For my transition between colors I used arrays during the setup to collect the main transitions (bigger jumps between RGB values) then during the loop I used a series of <code>analogWrite()</code> commands essentially splitting the jumps by a 16th, for example starting at <code>255, 0, 0</code> the next array value was <code>223, 0, 0</code> in the loop it went from <code>255, 0, 0</code> to <code>253, 0, 0</code> to <code>251, 0, 0</code> finally landing the last loop value of <code>225, 0, 0</code> before starting the loop over at the next array value of <code>223, 0, 0</code>. It's important to realize what colors transition into others and what the corresponding RGB values are of that transition. </p> <p>Tomorrow I'll post my code, it's a bit messy as it was more proof of concept that starting with a distinct plan.</p>
19127
|avr|
AVR - How to know that there is collision between stack and heap or the memory has filled?
2015-12-31T20:23:08.197
<p>I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?</p>
<blockquote> <p>I am using the dynamic memory in AVR microcontroller, so How to know that there is collision between stack and heap or if the memory has been filled?</p> </blockquote> <p>The first thing that happens is that malloc() will return NULL saying that memory could not be allocated. The <a href="http://www.nongnu.org/avr-libc/user-manual/malloc.html" rel="nofollow noreferrer">AVR heap implementation</a> has a few safety measures. One is to check that there is a minimum margin (__malloc_margin) between end of the heap and the top of the stack. This can be adjusted by the application. </p> <p><a href="https://i.stack.imgur.com/Lc5uw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Lc5uw.png" alt="Heap-Stack"></a></p> <p>Typically the minimum margin should be able to hold <a href="http://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_ramoverlap" rel="nofollow noreferrer">the largest stack usage</a> (typically deepest function call tree with the largest local variables usage) plus largest ISR stack usage. </p> <p>If the stack runs into the heap the memory block/s at the end of the heap is/are corrupted. What happens depends on the type of data structure. </p> <p>Not checking NULL return from malloc() gives some interesting errors on the AVR as the <a href="https://gcc.gnu.org/wiki/avr-gcc#Register_Layout" rel="nofollow noreferrer">processors registers</a> are memory mapped. NULL points to R0. </p> <p><a href="https://i.stack.imgur.com/RxwSL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RxwSL.jpg" alt="AVR Memory Map"></a></p> <p>A good rule of thumb when using malloc() in small scale embedded systems is 1) avoid it, 2) allocate memory with malloc() during the setup(). All other dynamic memory need be allocated temporary on stack and only for the processing.</p>
19140
|battery|
How to build circuit to switch to other power source if primary source dies?
2016-01-01T03:31:10.607
<p>I would like to have a backup battery connected to a device that requires an uninterrupted power supply, like an Arduino or Raspberry Pi, so that if my primary power source (USB plug) gets pulled, the device will switch to being powered by the battery.</p> <p>I need a solution that I can either build on a breadboard or buy for only a couple dollars. Does anyone know a solution? I'm assuming this is a common need and think I perhaps am not searching with the correct key words.</p> <p>Edit:</p> <p>I would like to add that I may also use 4AA batteries and a DC-DC step down module to produce 5V exactly to power a 5V device, so I'm looking for a solution that accepts 5V. Assume the device, let's say Raspberry Pi, takes 5V, the power supply is 5V, and the battery backup is 5V.</p>
<p>Your $2 budget rules out some of the more-effective possible solutions, such as using an actual UPS (uninterruptible power supply) system. </p> <p>One affordable approach is to connect the plus side of a 3.7 V lithium-polymer battery through a Schottky diode [such as MBR0520, SS14, 1N5819] to the +5 V line of an Arduino board. (I haven't looked at Raspberry Pi schematics and don't know if this will apply there.) Hook the minus side of the battery to Arduino ground.</p> <p>Ideally, the battery voltage less the voltage drop through the diode (say .4–.5 V) should be just less than the voltage that USB supplies. Ie, just under 5 V if you have a 5 V board, or just under 3.3 V for a 3.3 V board. Note, most 3.3 V Arduino systems are specified to run at 8 MHz rather than 16. There's a good chance a 5 V Arduino running at 16 MHz would continue to run ok when powered by about 3.3 V, but it's out of spec.</p> <p>If your battery voltage exceeds 5 V you won't be able to make the connection quite so directly. Besides certain risks of damage (see eg Method #5 and Method #8 of <a href="http://www.rugged-circuits.com/10-ways-to-destroy-an-arduino/" rel="nofollow noreferrer">10 Ways to Destroy An Arduino</a>) there will be the practical matter that the higher battery voltage will cause its power to be used preferentially to the USB power, thus discharging the battery so that it won't act as a backup.</p> <p><em>Edit:</em> The question-edit says the system uses 5 V, and seems to suggest the primary 5V power supply uses 4 AA batteries and a DCDC converter.</p> <p>If the DCDC converter is a step-down <a href="https://en.wikipedia.org/wiki/Buck_converter" rel="nofollow noreferrer">buck converter</a> it will go out of regulation when the input voltage from the four AA's goes below 5 V, which is 1.25 V per cell.</p> <p>As you can see from the following graph, if the discharge rate of a typical alkaline cell is 100 mA, it still has about half its power left when its voltage goes below 1.25 V. To fully use up the alkaline batteries, you could use a <a href="https://en.wikipedia.org/wiki/Buck%E2%80%93boost_converter" rel="nofollow noreferrer">buck-boost converter</a> or could test if your buck converter just passes the voltage on through, as opposed to shutting down when the input voltage is low.</p> <p><a href="https://i.stack.imgur.com/JN2dL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JN2dL.png" alt="alkaline AA-battery discharge curve"></a></p> <p>(Note, the AA-battery discharge curves shown above and below are from the <a href="http://www.powerstream.com/AA-tests.htm" rel="nofollow noreferrer">powerstream.com's β€œAA tests” web page</a>.)</p> <p>For the backup battery, where you also want 5 V output, an economical possibility is use of four AA NiMH cells, with nominal voltage 1.2 V per cell. However, initial voltage officially can exceed 1.4 V per cell, giving 5.6 V total:</p> <p><a href="https://i.stack.imgur.com/nL7mz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nL7mz.png" alt="NiMH AA-battery discharge curve"></a></p> <p>A Schottky diode in series will bring that down to say 5.2 V, an acceptable level for powering a 5 V system. But if the primary supplies 5.0 V, the backup will end up discharging slightly until its output voltage goes below that of the primary. If that's acceptable, fine. Otherwise, you could use a diode like 1N4001, with 0.7 to 0.8 volts of drop at 0 to 150 mA output. Instead of losing some backup power at first (due to higher backup than primary voltage) you will lose some at the end, due to backup voltage going too low slightly sooner. That won't be a problem, however, if you restore the primary supply and recharge the backups in time to prevent over-discharge damage to the backup batteries.</p>
19142
|arduino-leonardo|nrf24l01+|
RF24 tranceivers: trouble with two way communication
2016-01-01T06:01:52.763
<p>I am using RF24 modules with my two Arduinos Leonardo with the <a href="https://github.com/maniacbug/RF24" rel="nofollow">RF24</a> library. My goal is to be able to press a button on the first Arduino which will light up an LED on the second Arduino, and be able to press a button on the second Arduino to light up an LED on the first Arduino. I was easily able to figure this out as a one-way transmission with the first Arduino only transmitting and the second only receiving, but I am unable to make it a two-way transmission, where each Arduino can transmit and receive at the same time.</p> <p>This is my code so far:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;nRF24L01.h&gt; #include &lt;RF24.h&gt; #include &lt;RF24_config.h&gt; int msg[1]; RF24 radio(9,10); const uint64_t pipe = 0xE8E8F0F0E1LL; const uint64_t pipe2 = 0xF0F0F0F0AA; void setup(void){ Serial.begin(57600); pinMode(A0, INPUT); radio.begin(); radio.openWritingPipe(pipe); radio.openReadingPipe(1,pipe2); } void loop(void){ int charToSend[1]; charToSend[0] = digitalRead(A0); if (!radio.write(charToSend,1)) {Serial.println('didn\'t send');} radio.startListening(); if (radio.available()){ bool done = false; done = radio.read(msg, 1); Serial.println(msg[0]); digitalWrite(13, msg[0]); } radio.stopListening(); radio.powerDown(); delay(10); radio.powerUp(); } </code></pre> <p>But the <code>radio.write()</code> is returning false and therefore not sending.</p>
<p>The main thing that I can see wrong with your sketch is that the logic of your methodology is backwards.</p> <p>You are spending most of your time either with the radio asleep, or not in listening mode, so it can not receive anything.</p> <p>Instead you need to spend all your time in listening mode waiting for messages to arrive, and only when the button changes state do you want to switch off listening mode and send a packet to the other end. As soon as you have done that you then go back to listening.</p> <p>You can't listen while the radio is powered down, so using <code>powerDown()</code> and <code>powerUp()</code> is just nonsense.</p>
19150
|arduino-uno|i2c|lcd|
I2C LCD displaying weird characters
2016-01-01T20:37:47.090
<p>I have connected an LCD with an I2C backpack to my Arduino Uno but it prints the wrong characters. The weird thing is that it worked fine for a while and when I updated the code (but didn't change anything to do with the LCD) it started displaying the wrong characters. This happened earlier today too. That time, reinstalling the LiquidCrystal library worked, but it doesn't now.</p> <p>Does anyone know what might be the problem so I can fix it permanently?</p> <p>The LCD's SDA and SCL are connected to A4 and A5 respectively and I'm running this code:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;LiquidCrystal_I2C.h&gt; LiquidCrystal_I2C lcd(0x27,20,4); // set the LCD address to 0x27 for a 16 chars and 2 line display void setup() { lcd.init(); lcd.backlight(); lcd.setCursor(0,0); lcd.print("Hello, world!"); } void loop() { } </code></pre> <p>and this is what's displayed on the screen:</p> <p><a href="https://i.stack.imgur.com/Y9l43.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y9l43.jpg" alt="some random characters"></a></p>
<p>I experienced this while using a STM32f429 discovery board, and I found out there are two reasons that this happens. </p> <ol> <li>when using a fast microcontroller (180 MHz clock), if you send I2C packet consecutive LCD may not be that fast to understand it and as James said in other post LCD may lose some packet and get confused. To cope with that you have to put a delay between your packet.</li> <li>If you reset your MCU board while your LCD is writing something without cutting off power, LCD may get first nibble but lose the second 4bit nibble and interprets your initialize data as second nibble data to show on LCD and simply get confused. If LCD had something like software reset it could help but I did not find anything in datasheet. Though I think there is a hardware walkaround </li> </ol> <p><a href="https://i.stack.imgur.com/6f2NO.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6f2NO.gif" alt=" LCD I2C module based PCF8574 Schematic"></a></p> <p>if you could disconnect K in 8050 transistor and connect LCD Ground to that point then you could disconnect and connect LCD power just by toggle P3 pin through PCF8574 IC when you are initializing your LCD.actually you will lose some control over LCD backlight. you can consider R/W pin too because almost all firmware just write on LCD and simply lower this pin. I bring the purpose schematic in below</p> <p><a href="https://i.stack.imgur.com/slzHn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/slzHn.png" alt="modified schematic"></a></p> <p>in Module simply disconnect ground pin from module and LCD and in LCD board connect K pin to ground as i put the image here</p> <p><a href="https://i.stack.imgur.com/jPhpr.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jPhpr.jpg" alt="disconnect Ground PIN"></a></p> <p><a href="https://i.stack.imgur.com/t0UBC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/t0UBC.jpg" alt="connect Baklight Kathode to Ground PIN"></a></p> <p>in your Code When you are Initializing write 0xF7 in I2C and Delay for 200 ms then write 0 for and delay 100 ms then do your other Initialization Sorry for bad English</p>
19155
|usb|
Observing USB Gamepad with Arduino?
2015-12-30T16:06:12.593
<p>I have a gamepad which I want to treat as a sensor for my Arduino board. I want Arduino to trigger a certain action based on button pushes from the gamepad. Different buttons, different actions.</p> <p>The gamepad comes with a USB connector. I cut the the USB cable open, solder it with pluggable pins which are then connected to a breadboard. I supply the gamepad with 5V power from Arduino and connect the USB's Data+ to Arduino's analog input pin (A0). Please check the images below.</p> <p>I thought by observing the voltage coming from the gamepad's Data+ pin, I can probably determine if a button is being pushed. However, the observable input voltage in Arduino's A0 do not produce any meaningful difference between button push and release.</p> <p>My question: Is it possible to detect Gamepad's button pushes with this arrangement? If it's possible, where do you think I'm doing wrong?</p> <p><a href="https://i.stack.imgur.com/hEZRk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hEZRk.jpg" alt="USB Gamepad and Arduino"></a></p> <p><img src="https://i.stack.imgur.com/V6e4s.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fV6e4s.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p>
<p>USB devices make a serial communication, a series of packets of bits are sent and received, which is not beyond your power to learn and talk with. Using a USB Host shield or a chip would be easier (and more costly), but doing it yourself will be much more fun and educational.</p> <p>Surprisingly, for some USB devices (like a keyboard) you need to poll the data. Nothing will be sent to the host automatically. To find out the protocol they speak, you need to connect the game-pad to a PC and monitor the signals.</p> <p>Also you need to monitor both D+ and D- signals, they are both used.</p> <p>Here is a wonderful video by Ben Eater about the USB Keyboards where he goes deep into monitoring the signals and the protocol, can be a good start for your project: <a href="https://www.youtube.com/watch?v=wdgULBpRoXk" rel="nofollow noreferrer">https://www.youtube.com/watch?v=wdgULBpRoXk</a></p>
19162
|programming|arduino-ide|sketch|adafruit|
uint8_t etc as color variable
2016-01-02T01:46:25.080
<p>I am very new to coding and I am attempting to teach myself the best I can. I have no prior knowledge of coding and am filling in the blanks via YouTube and forums alike. One place I keep getting hung up on is what seems to be an unsigned integer. </p> <p>I have tried to figure out how these work (assignment and such) to no avail. I was wondering if anyone could offer some insight for me or at the least a link that gets specific for the Arduino.</p> <p>I see them used as uint8_t, uint16_t, and uint_32 in various places. Am I correct that it is an unsigned integer? Meaning it is a whole positive number only. </p> <p>The code I have attached is from Adafruit's article on multi-tasking. I am trying to adapt my sketch for millis() over delay().</p> <pre><code> uint32_t Color1, Color2; // What colors are in use uint16_t TotalSteps; // total number of steps in the pattern uint16_t Index; // current step within the pattern </code></pre> <p>For instance: on the variable declarations they use these for the color. I will need to change the colors, but have only seen them expressed in RGB. They are in every sketch I see, but I am struggling to answer this question on my own. Thanks in advance for any help.</p>
<p>If you search for information about C types on the internet, there will be much help to find, but effectively you are correct. One format of integer types in C take the form:</p> <p><code>uint</code> / <code>int</code>: Signed or unsigned integer. Unsigned integers are stored in simple binary representation, and signed integers are stored in <a href="https://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow noreferrer">two's complement</a> form.</p> <p><code>8</code> / <code>16</code> / <code>32</code> / <code>64</code>: The number of bits to store the value. This means the number of possible values is 2<sup><em>x</em></sup> where <em>x</em> is the number of bits.</p> <p><code>_t</code>: Simply a suffix to indicate that it is a type name, not a variable.</p> <hr /> <h2>Colour storage</h2> <p>Colours are generally stored as three components: <em>red</em>, <em>green</em> and <em>blue</em> (or sometimes four, adding <em>alpha</em>, the degree of transparency).</p> <p>If each component is given an unsigned byte to be stored (so it has a value from 0–255), then the total colour size is 24 bits. However, 24 bit integers are not a standard size, so the next bigger size is selected, 32-bit. This also allows room for an alpha component if necessary, but otherwise the spare 8 bits are unused.</p> <h3>For example:</h3> <pre><code>| 00000000 | 00000000 | 00000000 | 00000000 | = 32 bits | red | green | blue |alpha/empty| </code></pre>
19168
|sd-card|datalogging|
What happens when there's no space left on SD card?
2016-01-02T03:27:11.913
<p>I'm coding a data logger and I would like to know what happens if there are no bytes remaining to be written using SD library, ie, if the SD card is full of data. The logging would just stop or I would get some nasty error?</p>
<p>Open-source is just great. Lets have a look at the source code for SD. <a href="https://github.com/arduino/Arduino/blob/master/libraries/SD/src/utility/SdFile.cpp#L1164" rel="nofollow">Here</a> is what happens on write of a block. </p> <pre><code>/** * Write data to an open file. * * \note Data is moved to the cache but may not be written to the * storage device until sync() is called. * * \param[in] buf Pointer to the location of the data to be written. * * \param[in] nbyte Number of bytes to write. * * \return For success write() returns the number of bytes written, always * \a nbyte. If an error occurs, write() returns -1. Possible errors * include write() is called before a file has been opened, write is called * for a read-only file, device is full, a corrupt file system or an I/O error. * */ </code></pre> <p>The source code shows that blocks are allocated from the free list and if there are no more blocks the function will return an error. </p>
19176
|arduino-uno|assembly|
How fast is an Arduino?
2016-01-02T07:12:59.610
<p>Can an Arduino Uno calculate the time that an assembly instruction will take in nanoseconds, not microseconds? I don't want to use a PC, because the calculation will be more accurate using an Arduino, as the processor won't be running other tasks.</p> <p>If the Arduino can't, is there any way to improve it, or any other open source hardware that can do?</p>
<blockquote> <p>I just want to know how much time (in nanosecond example: 14 microsecond and 145 nanosecond ) it'll take for a CMP instruction comparing 2 strings, because in theory it will take less time if the two strings doesn't match.</p> </blockquote> <p>You can set up a hardware timer (eg. Timer 1) with a prescaler of one, so that each "tick" counts one clock cycle. Thus it can time to a resolution of 62.5 ns if running at 16 MHz.</p> <p>Then you could read the timer, do your target instruction (eg. compare two strings) and then read the timer again. The difference in counts will be the time (in units of 62.5 ns).</p> <p>I have a <a href="http://www.gammon.com.au/timers" rel="nofollow">page about timers</a> which might help you get started.</p> <hr> <blockquote> <p>... calculate the time that an assembly instruction will take ...</p> </blockquote> <p>Generally speaking the C++ compiler does a good job of generating code. You won't necessarily make things faster by writing in assembler and you might make it slower, because compiler-writers know various tricks which you might not.</p>
19180
|arduino-uno|arduino-mega|usb|mac-os|
Arduino Uno R3 (with Atmega 16u2) and MAC OSX 10.11 (El capitan) not working
2016-01-02T11:23:25.487
<p>I have Chinese copy of arduino which uses ATmega16u2 (at least that's what is written on the chip itself). When connected, it is visible in system information under USB section:</p> <blockquote> <p>Communication Device:</p> <p>Product ID: 0x0043<br> Vendor ID: 0x2341<br> Version: 0.01<br> Serial Number: 75237333636351600270<br> Speed: Up to 12 Mb/sec<br> Manufacturer: Arduino (www.arduino.cc)<br> Location ID: 0x1a140000 / 6<br> Current Available (mA): 1000<br> Current Required (mA): 100<br> Extra Operating Current (mA): 0<br> Built-In: Yes</p> </blockquote> <p>But it doesn't show up in arduino program ports.</p> <p>I've searched a lot, and it seems that people mostly had problems with arduinos on CH340 chips. I also have one such arduino, but it works properly after installing signed drivers as <a href="http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html" rel="nofollow">described here</a>.</p> <p>Are there any solutions for atmega 16u2 chips?</p> <p>My system:</p> <ul> <li>OS X El Capitan 10.11.2 (15C50) (hackintosh if it changes anything).</li> <li>Arduino Uno R3 (chinese copy)</li> <li>Arduino soft version 1.6.7</li> </ul> <p>Additional info: I've tried connecting Arduino Mega 2560 with Atmega16u2 chip and it also doesn't work </p> <p>Info I've got using Nick's awesome program:</p> <pre><code>Atmega chip detector. Written by Nick Gammon. Version 1.17 Compiled on Jan 8 2016 at 21:35:08 with Arduino IDE 10607. Attempting to enter ICSP programming mode ... Entered programming mode OK. Signature = 0x1E 0x94 0x89 Processor = ATmega16U2 Flash memory size = 16384 bytes. LFuse = 0xFF HFuse = 0xD9 EFuse = 0xF4 Lock byte = 0xFF Clock calibration = 0x56 Bootloader in use: No EEPROM preserved through erase: No Watchdog timer always on: No Bootloader is 4096 bytes starting at 3000 Bootloader: 3000: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 3010: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 3020: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF ... MD5 sum of bootloader = 0x6A 0xE5 0x9E 0x64 0x85 0x03 0x77 0xEE 0x54 0x70 0xC8 0x54 0x76 0x15 0x51 0xEA No bootloader (all 0xFF) First 256 bytes of program memory: 0: 0x90 0xC0 0x00 0x00 0xA9 0xC0 0x00 0x00 0xA7 0xC0 0x00 0x00 0xA5 0xC0 0x00 0x00 10: 0xA3 0xC0 0x00 0x00 0xA1 0xC0 0x00 0x00 0x9F 0xC0 0x00 0x00 0x9D 0xC0 0x00 0x00 20: 0x9B 0xC0 0x00 0x00 0x99 0xC0 0x00 0x00 0x97 0xC0 0x00 0x00 0x48 0xC4 0x00 0x00 30: 0x0C 0xC4 0x00 0x00 0x91 0xC0 0x00 0x00 0x8F 0xC0 0x00 0x00 0x8D 0xC0 0x00 0x00 40: 0x8B 0xC0 0x00 0x00 0x89 0xC0 0x00 0x00 0x87 0xC0 0x00 0x00 0x85 0xC0 0x00 0x00 50: 0x83 0xC0 0x00 0x00 0x81 0xC0 0x00 0x00 0x7F 0xC0 0x00 0x00 0x02 0xC1 0x00 0x00 60: 0x7B 0xC0 0x00 0x00 0x79 0xC0 0x00 0x00 0x77 0xC0 0x00 0x00 0x75 0xC0 0x00 0x00 70: 0x73 0xC0 0x00 0x00 0x71 0xC0 0x00 0x00 0x6F 0xC0 0x00 0x00 0x6D 0xC0 0x00 0x00 80: 0x6B 0xC0 0x00 0x00 0x69 0xC0 0x00 0x00 0x67 0xC0 0x00 0x00 0x65 0xC0 0x00 0x00 90: 0x63 0xC0 0x00 0x00 0x61 0xC0 0x00 0x00 0x12 0x01 0x10 0x01 0x02 0x00 0x00 0x08 A0: 0x41 0x23 0x43 0x00 0x01 0x00 0x01 0x02 0xDC 0x01 0x09 0x02 0x3E 0x00 0x02 0x01 B0: 0x00 0xC0 0x32 0x09 0x04 0x00 0x00 0x01 0x02 0x02 0x01 0x00 0x05 0x24 0x00 0x01 C0: 0x10 0x04 0x24 0x02 0x06 0x05 0x24 0x06 0x00 0x01 0x07 0x05 0x82 0x03 0x08 0x00 D0: 0xFF 0x09 0x04 0x01 0x00 0x02 0x0A 0x00 0x00 0x00 0x07 0x05 0x04 0x02 0x40 0x00 E0: 0x01 0x07 0x05 0x83 0x02 0x40 0x00 0x01 0x04 0x03 0x09 0x04 0x32 0x03 0x41 0x00 F0: 0x72 0x00 0x64 0x00 0x75 0x00 0x69 0x00 0x6E 0x00 0x6F 0x00 0x20 0x00 0x28 0x00 Programming mode off. </code></pre> <p>Fuses info:</p> <pre><code>Atmega fuse calculator. Written by Nick Gammon. Version 1.10 Compiled on Jan 8 2016 at 22:19:34 with Arduino IDE 10607. Attempting to enter programming mode ... Entered programming mode OK. Signature = 0x1E 0x94 0x89 Processor = ATmega16U2 Flash memory size = 16384 LFuse = 0xFF HFuse = 0xD9 EFuse = 0xF4 Lock byte = 0xFF Clock calibration = 0x56 Hardare Boot Enable..................... [X] Debug Wire Enable....................... [ ] External Reset Disable.................. [ ] Enable Serial (ICSP) Programming........ [X] Watchdog Timer Always On................ [ ] Preserve EEPROM through chip erase...... [ ] Boot into bootloader.................... [ ] Divide clock by 8....................... [ ] Clock output............................ [ ] Bootloader size: 4096 bytes. Start-up time: SUT0: [ ] SUT1: [ ] (see datasheet) Clock source: low-power crystal. Brownout detection at: 3.0V. </code></pre>
<p>There is complete documentation on Arduino website, I followed the steps and I was able to install driver</p> <p><a href="https://support.arduino.cc/hc/en-us/articles/4408887452434-Flash-USB-to-serial-firmware-in-DFU-mode" rel="nofollow noreferrer">https://support.arduino.cc/hc/en-us/articles/4408887452434-Flash-USB-to-serial-firmware-in-DFU-mode</a></p>
19187
|rs485|
Interfacing Gammon's RS485 with computer
2016-01-02T15:43:33.170
<p>I'm using the non-blocking RS485 Gammon's library for Arduino (as shown at <a href="http://www.gammon.com.au/forum/?id=11428" rel="nofollow">http://www.gammon.com.au/forum/?id=11428</a>) to handle the communication between some arduinos. Now I'm having trouble to add a Raspberry Pi (or otherwise a non-arduino platform) to the network.</p> <p>How can I integrate the Gammon's protocol in a python or processing software?</p>
<p>Open-source and Web-search is just great. <a href="https://github.com/Sthing/Nick-Gammon-RS485" rel="nofollow">This</a> might be what you are looking for. </p> <p>Cheers!</p>
19188
|arduino-uno|rgb-led|
Decision maker loop problem
2016-01-02T16:03:24.260
<p>Today, I've started a decision maker, using a Arduino UNO R3, a button and a RGB led. This project makes a decision for you (yes, no, or maybe) when you don't know your own decision about something.</p> <p>The code I used in the project is the following one (written by me): </p> <pre><code>#define out OUTPUT #define in INPUT #define H HIGH #define L LOW int red = 2; int green = 3; int blue = 4; int randomValue = 0; int button = 5; int buttonState = 0; void setup(){ pinMode(red, out); pinMode(green, out); pinMode(blue, out); pinMode(button, in); } void loop(){ buttonState = digitalRead(button); if(buttonState == H){ randomValue = random(0,4); if(randomValue == 1){ digitalWrite(red, H); delay(200); digitalWrite(red, L); clear(); } if(randomValue == 2){ digitalWrite(green, H); delay(200); digitalWrite(green, L); clear(); } if(randomValue == 3) { digitalWrite(blue, H); delay(200); digitalWrite(blue, L); clear(); } } } </code></pre> <p>The connections are correct, and the code also. The problem is: when I push the button, the LED starts showing random colors, and what I want is for the LED to show one color per push.</p> <p>What can I do?</p>
<p>There is one basic concept that you are lacking. At the moment you are looking to see <em>if</em> the button is pressed, not <em>when</em> the button has been pressed.</p> <p>Instead of just looking to see if it is HIGH you need to look if it <em>was</em> LOW but is <em>now</em> HIGH. It's that transition from LOW to HIGH that you need to use as your trigger for when to set the LED colour, and that means remembering the state of the button the last time you went through the loop.</p> <pre><code>buttonState = digitalRead(button); if (buttonState != oldButtonState) { oldButtonState = buttonState; if(buttonState == H) { // Do your stuff } } </code></pre> <p><code>oldButtonState</code> is defined the same as <code>buttonState</code>.</p>
19209
|avr|uart|
In UART, what mechanism sets the "new data received" flag back to 0?
2016-01-03T11:01:00.107
<p>I was reading <a href="http://www.embedds.com/programming-avr-usart-with-avr-gcc-part-1/" rel="nofollow">documentation on UART on AVR</a> and it looks simple: when a flag (bit <code>RXC0</code> of register <code>UCSR0A</code>) is set to 1, it means the micro controller has new data for you, and you read this from register <code>UDR0</code>.</p> <p>But something boggles my mind: How does the micro controller know that we have read the data? Or, in other words, after it received the first byte on UART, the flag is set to 1, but when is it set back to 0?</p>
<p>The ATmega328p data-sheet describes the setting of RXCn:</p> <h3>Bit 7 – RXCn: USART Receive Complete</h3> <blockquote> <p>This flag bit is set when there are unread data in the receive buffer and cleared when the receive buffer is empty (i.e., does not contain any unread data). If the Receiver is disabled, the receive buffer will be flushed and consequently the RXCn bit will become zero. The RXCn Flag can be used to generate a Receive Complete interrupt (see description of the RXCIEn bit).</p> </blockquote> <p>The hardware seems to keep a register the size of the receive buffer. Incremented when received and decremented when read. It is only one level so the size is 0..1, i.e. one bit.</p> <p>Actually there is two registers; one for possible incoming data and one for the latest data until read.</p> <p>Cheers!</p> <p>More details in <a href="http://www.atmel.com/images/doc8161.pdf" rel="nofollow noreferrer">ATmega328p data-sheet, chap. 19 USART0</a></p>
19210
|arduino-uno|programming|electronics|pid|
How does the PID controller actually work?
2016-01-03T11:21:26.343
<p>Preferably PID functions on an Arduino uno or any other examples. I have been researching but many of the the websites really do not explain it. </p> <p><strong>P.S is there an algorithm for a PID? Thanks</strong></p>
<p>I, also, didn't get the idea behind PID from just reading Wikipedia. After some videos/tutorials, I believe the best way to explain it is:</p> <p><strong>What is PID</strong></p> <p>PID is an algorithm. It involves three factors which can be adjusted to tune a signal.</p> <p>It is often used in servo's (and things like thermostates, basic signal controllers)</p> <p><strong>Imagine this</strong></p> <p>The servo will be used in the practical examples.</p> <p>A servo has: - a current position (signal) - the position you want the servo to be in (goal signal) - a speed (PID output signal)</p> <p>The PID output signal/algorithm makes sure that the servo reaches it's goal.</p> <p><strong>In short:</strong></p> <p>PID is an algorithm that can adjust a signal towards an setpoint. Or correct it for that matter. It regulates how much you have to adjust the signal, without getting serious overshoot, or oscillation around the setpoint.</p> <p><strong>Detail:</strong></p> <p>P stands for proportional.</p> <p>Which means that the further the servo is from it's setpoint, the more speed we want to/can give it. So that we're faster towards the set point. This also means that we slow down as we near the set point. Of course you can multiply each of these rules with a factor, to achieve a better balance.</p> <p>I stands for integrating.</p> <p>It basically comes down to the fact that it constantly keeps adding to the signal, depending on how long there is a difference between the current point and set point. This is so that if P is still a little slow, it adds some speed over time.</p> <p>D stands for differentiating</p> <p>It's less commonly used. (Wikipedia) The D factor reacts on the speed of the change in value. Or speed of change in setpoint (Dutch wikipedia is not 100%, comment if neccesary :) )</p> <p>These factors / the algorithm provides a smooth regulation of various systems, hence that's why it is so adjustable.</p> <p>It can be used for balancing quadcopters or making your house comfortably warm (without sudden changes, or too slow changes)</p> <p><strong>Why?</strong></p> <p>How would you balance a quadcopter? If it shifts to one side, you don't want to fully reverse the throttle. It'll make it wobble, since you get a lot of overshoot. Controlling things can be hard, PID is an known working algorithm for those cases. But you have to adjust the factors right to adjust it to your specific system. (They all react differently, or have to react differently).</p>
19216
|arduino-uno|led|arduino-ide|audio|
Audio Visualizer (not working properly)
2016-01-03T17:06:14.583
<p><strong>Parts</strong> </p> <ul> <li>Arduino Uno R3 (Atmega328 - assembled)</li> <li>Adafruit Bicolor LED Square Pixel Matrix with I2C Backpack</li> <li>Electret Microphone Amplifier - MAX4466 with Adjustable Gain</li> <li>Half-size Breadboard</li> <li>Breadboarding wires</li> </ul> <p><strong>Description</strong><br> I have been following the build guide for the "Piccolo Music Visualizer" on the Adafruit website (<a href="https://learn.adafruit.com/piccolo?view=all" rel="nofollow">https://learn.adafruit.com/piccolo?view=all</a>), using all of the same components and code (following the guide exactly as shown). I first tested the 8x8 matrix to see if it was working properly, and it works beautifully. The problems started when I wired up the electret microphone... </p> <p>In regard to how I wired this to the breadboard, I followed the example for the R3 on the Adafruit guide (since that's my current version): </p> <p><strong>Note</strong><br> The files (code) used for this project are found here: (<a href="https://github.com/adafruit/piccolo" rel="nofollow">https://github.com/adafruit/piccolo</a>). The ffft file is supposed to be saved to the library (this worked for me). The Piccolo file is supposed to be saved to the Sketchbook (this did not work for me - kept giving error messages when trying to reference it). I instead copied the code found in the Piccolo file, and saved it as a new sketchbook file. Let me know if this might be the cause of the problem. This is my first arduino project, so I am still trying to figure out how the IDE works.</p> <p><strong>Problem</strong><br> The electret microphone is supposed to pick up audio and the LED matrix should display a waveform based on the loudness and frequency of the audio. Instead, I only have 2 bars on the bottom left lighting up (the effect is static - wont respond to volume or frequency changes). Oddly, when pulling out the microphone from the breadboard, the waveform begins displaying as it should, but in a glitchy/unstable form. I figured the problem was with the adjustable gain on the microphone, but no matter how much I adjust the screw only the 2 bars are affected and still static (when adjusted to the left only green LED, in middle is green and orange, to the right is red/orange/green on the matrix).</p> <p>A little confused as to what the problem could be... is the microphone broken, code malfunctioning, wiring incorrect, etc.</p> <p><strong>Pictures to reference</strong> (DropBox link)<strong>:</strong><br> - <strong><em>See comment below for link</em></strong> (must have <em>10 rep</em> to use more than <em>2 links</em> in post)<br> (zip file contains <strong>3</strong> pictures: "<em>wiring</em>", "<em>when_on</em>", "<em>pulling_out_mic</em>")<br> Photos are over 2MB so I couldnt upload here.</p>
<p>It sounds like a dry joint; the fact that the LED matrix seems to work 'better' when you're fiddling with the microphone board makes me think that the problem lies entirely with that little board.</p> <p>Try adding more solder; the more the merrier.</p>
19217
|gps|
Can I use a GPS from old Garmin with an Arduino?
2016-01-03T14:13:45.170
<p>I'm working on an Arduino project, and I'd like to add GPS functionality. I could buy a GPS module, but those are expensive. I had an old Garmin Forerunner 305 lying around, so I took it apart and took a peek inside. There are two PCBs - one connected to a screen and one to the GPS. In addition, there was a battery and a small part for charging.</p> <p>I'd like to know if it is possible to connect this GPS to my Arduino, and if so, how?</p> <p>Edited: To make my question more precise,</p> <p>-I see the pins in the top right of the picture. How do I connect those to my Arduino? Is there any specific kind of wire? Because the pins are too small for standard wires.</p> <p>-Once I connect it, how do I figure out the voltage requirements and pin layout? I tried googling the GPS model, but nothing helpful came up. What kind of scope should I put on it?</p> <p>The two pictures below show only the GPS part of the inside of the watch. <a href="https://i.stack.imgur.com/CMrCK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CMrCK.jpg" alt="The GPS PCB"></a></p> <p><a href="https://i.stack.imgur.com/VsdzK.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VsdzK.jpg" alt="The other side of the GPS"></a></p>
<p>Yes, interfacing with arduino, PC, ESP8266, whatever, easy peasy. Simple to breakout the serial comms off the Garmin, and whether or not you want to use a logic level shifter (Depending on your RS-232 logic requirements), easy too implement.</p> <p>I've got a whole bunch of old Garmins (and some new ones) interfaced with some cheapy ESP8266's so I can share the GPS output (All of it. Not just the x,y,z position data), with multiple devices.</p> <p>I'd be willing to share the code, wiring if you wish.</p>
19228
|communication|
Sending 5 Led pixel values to arduino , is this a good way?
2016-01-04T18:27:20.060
<p>I wanted to install a 5 LED strip underneath my PC's front panel. I want to send color over PC so it can change when i open different apps, with temperature or etc!</p> <p>So all I think the best way to do this is to just use Arduino to set the LED Values!</p> <p>But I have had some troubles creating a good communication protocol for this, I've been just simply sending 45 digits (15 3 digit numbers) to my Arduino with serial. here's code: Arduino :</p> <pre><code>#include "Adafruit_NeoPixel.h" #include "WS2812_Definitions.h" #define PIN 4 #define LED_COUNT 5 struct pixel { int R = 0; int B = 0; int G = 0; }; Adafruit_NeoPixel leds = Adafruit_NeoPixel(LED_COUNT, PIN, NEO_GRB + NEO_KHZ800); char count = 1; int pixelNumber = 0; struct pixel tempPixel; //struct pixel Pixels[LED_COUNT]; void setup() { Serial.begin(9600); Serial.println("Init"); leds.begin(); // Call this to start up the LED strip. clearLEDs(); // This function, defined below, turns all LEDs off... leds.show(); // ...but the LEDs don't actually update until you call this. } void loop() { if(Serial.available() &gt; 0) { if(count == 1) { tempPixel.R = PC_Receive(); } else if (count == 2) { tempPixel.G = PC_Receive(); } else if (count == 3) { tempPixel.B = PC_Receive(); count = 0; setPixelColor(pixelNumber, tempPixel); Serial.println(pixelNumber); leds.show(); // Pixels[pixelNumber] = tempPixel; if(++pixelNumber &gt;= LED_COUNT) { pixelNumber = 0; } } count++; } // if(pixelNumber == 0) { // for(int i = 0; i &lt; LED_COUNT; i++ ) { // setPixelColor(i, Pixels[i]); // } // // leds.show(); // } } void setPixelColor(int a, struct pixel P) { leds.setPixelColor(a, P.R, P.G, P.B); } char PC_Receive() { int result = 0; while(Serial.available() == 0); result += ((int)Serial.read() - '0') * 100; while(Serial.available() == 0); result += ((int)Serial.read() - '0') * 10; while(Serial.available() == 0); result += ((int)Serial.read() - '0'); Serial.println(result); return result; } void setColourRgb(unsigned int red, unsigned int green, unsigned int blue) { for(int i = 0; i &lt; LED_COUNT; i++) { leds.setPixelColor(i, red, green, blue); } leds.show(); } </code></pre> <p>And here's PC's dirty code in python:</p> <pre><code>import serial import time import random class Pixel: def __init__(self, R, G, B): self.R = R self.G = G self.B = B def clearAll(): for i in range(0,5): ser.write("000000000") def sendPixel(pixels): for i in range(0,5): ser.write(str(pixels[i].R).zfill(3)) ser.write(str(pixels[i].B).zfill(3)) ser.write(str(pixels[i].G).zfill(3)) ser = serial.Serial('/dev/ttyACM2', 9600) little = [0,0,0,0,0] for i in range(0,5): little[i] = Pixel(0,255,50) sendPixel(little) time.sleep(0.5) clearAll() </code></pre> <p>the problem is it isn't stable, i think i should just use an \n at end or send back OK or something to confirm it, but that would make it slow if i did it for each value! (and checking only once after all 5 leds are send would mean sending more values until i receive the ok and clearing and sending them again!)</p> <p>Can you recommend me a better way?</p> <p>Thanks!</p> <p>EDIT: Just wanted to say! it's almost done! It does change color when i open chrome, and i think at 115200 baud rate it's fast enough to not notice a delay (although at 9600 i felt like it's slower then my (xxx/xxx/xxx....) protocol but it's better and works at 115200</p> <p>i will add some basic functions to my python side and add a rainbow effect I will also add GPU temperature and etc... it's not going to be really hard on linux but windows, im not sure :D</p>
<p>I would recommend a similar solution as DaveX with a small modofication.</p> <p>If you bitmask your LEDS, and leave room for a possible additional 3, you can mask any combination of them in the space of 00-FF. then you could send to the arduino a single string of 0xFFFFFFFF FF(LED bitmask),FF(Red value), FF(Green Value), FF(Blue Value).</p> <p>so LED 1 {<code>00000001</code> =<code>01</code>} all red {<code>FF0000</code>} would be <code>0x01FF0000</code></p> <p>LED 2 and 4 {<code>00001010</code> =<code>0A</code>} all green {<code>00FF00</code>} would be <code>0x0A00FF00</code></p> <p>LED 5 and 1 {<code>00010001</code> =<code>11</code>} all blue {<code>0000FF</code>} would be <code>0x110000FF</code></p> <p>ALL LEDS off would be <code>0xFF000000</code></p> <p>All LEDS onn full white would be <code>0xFFFFFFFF</code></p>
19234
|arduino-uno|programming|lcd|
Print string and integer LCD
2016-01-04T19:55:14.847
<p>How do I print a string and integer on an LCD? Here is what I have tried:</p> <pre><code>int number = 2; int result = (number + number); lcd.print(number, DEC + " plus " + number, DEC + " equals " + result, DEC); </code></pre> <p>And the result is an error. When I try:</p> <pre><code>lcd.print(number + "look"); </code></pre> <p>or</p> <pre><code>lcd.print("1234 " + number); </code></pre> <p>Then the result on the LCD is "34 ", as it deleted the first two numbers!</p> <p>I want it to print:</p> <p>1234 2</p> <p>Please help! Thanks!</p>
<pre><code>int a=0; float b=10.01; char str[16]; sprintf(str,"a=%d, b=%.2f, c=%d", a, b, 2); // use sprintf() to compose the string str lcd.print(str); </code></pre> <p>The output will be 'a=0, b=10.01, c=2'</p>
19236
|rf|
panstamp device signature is random
2016-01-04T16:24:55.860
<p>I Have 2<a href="http://panstamp.com" rel="nofollow">panstamp</a>. I can program the first but not the second with the arduino program.</p> <p>When I upload the sketch (a simple blink) on the second, I got this </p> <pre> Reading | ################################################## | 100% 0.03s avrdude: Device signature = 0x004e22 avrdude: Expected signature for ATmega328P is 1E 95 0F Double check chip, or use -F to override this check. avrdude done. Thank you. </pre> <p>And if I retry, I got this.</p> <pre> Reading | ################################################## | 100% 0.03s avrdude: Device signature = 0x81f014 avrdude: Expected signature for ATmega328P is 1E 95 0F Double check chip, or use -F to override this check. avrdude done. Thank you. </pre> <p>The device signature is not the same anymore ... I've changed the wire and re-open arduino program. But it don't change, the device signature change (often 0xE1E1E1). I've check the connection between the ATmega and the wire and everything is ok.</p> <p>Is the Panstamp broken ? or should I do a kind of factory reset?</p>
<blockquote> <p>Is the Panstamp broken ?</p> </blockquote> <p>Sounds like it. If one works, and the other does not, using the same wiring, it looks like you have a faulty one.</p> <blockquote> <p>or should I do a kind of factory reset?</p> </blockquote> <p>You can't really "factory reset" a chip like that. Possibly there is a problem with the fuses. You may be able to explore further here:</p> <p><a href="https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board">Have I bricked my Arduino Uno? Problems with uploading to board</a></p>
19243
|programming|c++|
>> << and -> Syntax in arduino
2016-01-05T00:18:54.003
<p>I was trying to follow <a href="https://www.arduino.cc/en/Tutorial/SPIEEPROM" rel="nofollow">this</a> tutorial and came across <code>&gt;&gt;</code>. What exactly does this do? </p>
<p><code>&gt;&gt;</code> is right shift a value by a certain number of bits. <code>&lt;&lt;</code> is left shift a value by a certain number of bits. <code>-&gt;</code> is accessing a member of a class or struct that is referenced by a pointer.</p> <h1>Right Shift and Left Shift</h1> <p>If you have a binary number <code>0b00010000</code> and right shift it two bits you get <code>0b00000100</code>. The C notation for that is <code>val &gt;&gt; 2</code>. The same for left shift - <code>val &lt;&lt; 2</code> would result in <code>0b01000000</code>.</p> <h1>Pointers and members</h1> <p>Normally when you access a member of a class or struct you use <code>.</code>, such as <code>Serial.println()</code>. However it is possible to make a <em>pointer</em> to a class instance, and when you do you need to access the members with <code>-&gt;</code> instead of <code>.</code> - such as <code>mySerial-&gt;println()</code>. This arrow notation serves as syntactic sugar: <code>mySerial-&gt;println()</code> is interpreted as <code>(*mySerial).println()</code>. The parentheses are necessary because the dereferencing operator <code>*</code> has a lower order of precedence compared to the dot <code>.</code> operator.</p>
19250
|sound|piezo|
Push-Pull tone code
2016-01-05T07:55:49.113
<p>I wanted to use a piezo sounder to sound an alarm in an application. Testing indicated that <code>tone()</code> was not very loud.</p> <p>I could use some external circuitry to swing the pins Β±5V but as I have plenty of spare pins, it seemed feasible to use 2 pins driven in anti-phase to increase the power by 4.</p> <p>I looked at the source <code>Tone.cpp</code> but the code is somewhat intimidating. Before I start to modify it I was wondering if anyone else has already done something like this.</p>
<p>Yes, Tim Eckel has already published a library "toneAC" on the Arduino website at <a href="http://playground.arduino.cc/Code/ToneAC" rel="nofollow">http://playground.arduino.cc/Code/ToneAC</a></p> <p>All of the syntax is there too.</p>
19251
|arduino-uno|power|led|
constant current or constant voltage power supply to use with RGB shield with high power LEDs
2016-01-05T09:33:07.927
<p>So, I got an arduino uno and a <a href="https://www.reichelt.de/Erweiterungsboards/ARDUINO-SHD-RGB/3/index.html?ACTION=3&amp;GROUPID=6669&amp;ARTICLE=148933&amp;OFFSET=16&amp;" rel="nofollow">RGB shield from velleman</a> for christmas because I mentioned I might want to do a project with high power LEDs - a neat surprise, but now I have to use it (: The shield can do PWM on an external power supply and this can be wired through to the high power LEDs itself. I aim to power about 10W of LED light in total, with different colors in order to make good use of the board. Can I go for Option 1? If not, what would you advise? </p> <p><strong>Option 1</strong></p> <p>As <a href="http://www.ebay.com/itm/1W-3W-High-Power-cool-warm-white-3000k-4000k-10000k-30000k-LED-20mm-star-pcb-/321471559197?var=&amp;hash=item4ad932b61d:m:m9FF_32EUKYGAQ_1yJ7jQFA" rel="nofollow" title="for example...">high power LEDs</a> need a constant current, I am inclined to connect a <a href="http://www.ebay.com/itm/High-Power-350mA-10W-LED-Driver-Board-DC-Boost-5-32V-Wide-Input/161047962520?_trksid=p2047675.c100005.m1851&amp;_trkparms=aid%3D222007%26algo%3DSIC.MBE%26ao%3D1%26asc%3D20131003132420%26meid%3D095402a042fa472d9944387cbdd4ee36%26pid%3D100005%26rk%3D3%26rkt%3D6%26sd%3D141700678280" rel="nofollow" title="for example">constant current supply</a> as the external supply of the board (assuming all channels' LEDs need the same current).</p> <p><em>Update</em>: I talked to an electrician and a constant current supply typically works on a PWM basis; putting this in series with the PWM of the shield is not smart.</p> <p><strong>Option 2</strong></p> <p>Alternatively I could connect a standard constant voltage supply and make sure that the current is within limits: </p> <ul> <li>One option would be to use <em>resistors</em>; but, with 12V DC and 350mA I would need like 33 Ohm resistance dissipating 4 Watts of power, which is inefficient. </li> <li>Alternatively there are <a href="http://www.ebay.com/itm/350-MA-Constant-current-LED-driver-with-PWM-control-up-to-10-off-1W-led-/311494471358?hash=item4886846ebe:g:E6EAAOSwwE5WWP1A" rel="nofollow" title="for example">DC voltage to constant current LED drivers</a> which will take care of the constant current for me; I could put those at the exits of the shield for the LEDs. They supposedly have a better conversion efficiency than the resistors, but I do have any knowledge about their performance with PWM as input; but I have serious doubts they would like that type of input. Furthermore, these drivers also often have PWM capabilities. This kind of module would render the shield functionality largely useless. </li> </ul>
<p>Your thinking and reasoning is pretty much spot on.</p> <p>The board you have is basically a trio of high current low side switches. So yes, you need <em>something</em> to limit the current, and as you have noted resistors are not going to be very efficient.</p> <p>The best way to drive high power LEDs is, as you know, with constant current. However, you need a constant current source <em>per LED channel</em>, not one single one for the whole board. That means three individual constant current sources, each providing the right current for the LEDs you are driving on that channel.</p> <p>It's possible to roll your own cheap constant current sources using LM317T linear voltage regulators (<a href="http://diyaudioprojects.com/Technical/Current-Regulator/" rel="nofollow">http://diyaudioprojects.com/Technical/Current-Regulator/</a>). It's a cheap option, though pretty much as in-efficient as using resistors, just easier to deal with the heat sinking. Note that on the LM317T the tab is live, so you must use three separate heat sinks for each channel.</p> <p>My personal preference though is to use PWM capable constant current sinks. My favourite is the <a href="http://www.onsemi.com/PowerSolutions/product.do?id=CAT4101" rel="nofollow">CAT4101</a> which can deal with up to 1A per channel (more if you parallel them) and uses a single resistor to set the current. It has a PWM input that you can drive direct from an Arduino's PWM pin. Of course, as you note, that then makes your nice shield redundant. </p>
19276
|arduino-uno|c++|
Menu system without libraries
2016-01-06T11:29:38.353
<p>I was wondering if there are a way to do a menu system for arduino UNO using buttons and without libraries.</p> <p>I tried to do it by myself but the code was too long and heavy.</p> <p>I don't want full code, just a pseudo-code idea and how does it works.</p> <p>I know there are libraries that to this, but I want to practise C++.</p> <p>Thanks!</p>
<p>Interactive menus are certainly not a "simple" task. That is why people use libraries.</p> <p>Whatever you try you will end up with complex code - either long winded with lots of duplication, or somewhat cryptic with lots of pointers, arrays, and structures. Not an easy task for a beginner in C++.</p> <p>How I would set about it would involve the following things:</p> <ol> <li>A structure that defines a menu entry, including pointers to one of: sub-menu array, numeric variable (including max/min limits), option array, function to execute.</li> <li>Arrays of the above structure to define each menu</li> <li>Array or linked list of "breadcrumbs" through the menu to track where you are and go back up properly</li> <li>Functions to display and navigate the menu arrays on an LCD.</li> </ol> <p>All of that uses fairly advanced C coding techniques, especially when it comes to managing all the pointers, etc.</p> <p>The "simpler", though more long winded way, would be to write individual functions for each menu and sub-menu, but that would make your program incredibly long and prone to have errors when duplicating (copy/paste) code.</p>
19285
|programming|
Explanation for micros function
2016-01-06T16:37:17.370
<p>I was trying to understand the working of micros() function internally and I had a look at the function in Arduino.h</p> <p>This is the code:</p> <pre><code>unsigned long micros() { unsigned long m; uint8_t oldSREG = SREG, t; cli(); m = timer0_overflow_count; #if defined(TCNT0) t = TCNT0; #elif defined(TCNT0L) t = TCNT0L; #else #error TIMER 0 not defined #endif #ifdef TIFR0 if ((TIFR0 &amp; _BV(TOV0)) &amp;&amp; (t &amp; 255)) m++; #else if ((TIFR &amp; _BV(TOV0)) &amp;&amp; (t &amp; 255)) m++; #endif SREG = oldSREG; return ((m &lt;&lt; 8) + t) * (64 / clockCyclesPerMicrosecond()); } </code></pre> <p>Can someone please explain me what this line is doing :</p> <pre><code> if ((TIFR0 &amp; _BV(TOV0)) &amp;&amp; (t &amp; 255)) m++; </code></pre>
<p>Since at the start of this function interrupts have been disabled by the <code>cli()</code> function it is possible that the timer <code>TCNT0</code> has overflowed yet this <em>event</em> has not been processed and included in the value of <code>timer0_overflow_count</code> that has been read into <code>m</code>. Therefore the line that you are asking about is checking for this condition and incrementing the local copy <code>m</code> if necessary before using it to calculate the number of microseconds since startup.</p>
19292
|arduino-uno|
LCD does not work with if condition
2016-01-06T20:57:19.207
<pre><code>#include &lt;LiquidCrystal.h&gt; #include &lt;Wire.h&gt; LiquidCrystal lcd(2, 3, 4, 5, 11, 12);// initialize the library with the numbers of the interface pins int pirPin = 7; //Variable that will receive the digital signal from the sensor int LEDgreen = 6; //LED addressed to the digital pin 6 int speaker = 8; //speaker addressed to the digital pin 7 int buttonPin = 9; // the pin that the pushbutton is attached to void setup(){ pinMode(buttonPin, INPUT);// Initialize the button pin as an input: pinMode(pirPin, INPUT); // declares variable pirPin as an input pinMode(LEDgreen, OUTPUT); // declares variable LEDgreen as an output pinMode(speaker, OUTPUT); // declares variable speaker as an output lcd.begin(16, 2); // turn on the cursor: lcd.cursor(); Serial.begin(9600); } void loop(){ int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin: int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal if(buttonState == LOW){ if(digitalRead(pirPin) == LOW){ /*The LED Blinks once with the command digitalWrite the LED keeps turned on after blink during the motion cycle*/ digitalWrite(LEDgreen, HIGH); delay(1000); digitalWrite(LEDgreen, LOW); delay(500); digitalWrite(LEDgreen, HIGH); /*speaker plays frequency, the number 7 is the digital pin, the second number is the frequency played and the third number is the sound duration we repeated this command with different frequency and varying the time in order to create a pleasant sound */ tone(4,261,300); delay(200); tone(4,329,300); delay(200); tone(4,392,600); delay(200); tone(4,329,300); delay(200); tone(4,392,300); delay(200); tone(4,493,600); delay(200); tone(4,392,300); delay(200); tone(4,493,300); delay(200); tone(4,294,600); delay(200); lcd.setCursor(0,0); lcd.print(" Motion "); // Print a message to the LCD. lcd.setCursor(0,1); lcd.print(" Detected "); } else if(digitalRead(pirPin) == HIGH) { digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected lcd.setCursor(0,0); lcd.print("No Motion "); lcd.setCursor(0,1); lcd.print(" Detected "); } } else if(buttonState == HIGH) { if(digitalRead(pirPin) == LOW) { digitalWrite(LEDgreen, HIGH); delay(1000); digitalWrite(LEDgreen, LOW); delay(500); digitalWrite(LEDgreen, HIGH); tone(4,261,300); delay(200); tone(4,329,300); delay(200); tone(4,392,600); delay(200); tone(4,329,300); delay(200); tone(4,392,300); delay(200); tone(4,493,600); delay(200); tone(4,392,300); lcd.setCursor(0,0); lcd.print(" Motion "); lcd.setCursor(0,1); lcd.print(" Detected &amp; door "); } else if(digitalRead(pirPin) == HIGH) { digitalWrite(LEDgreen, LOW); // Turn off the LED in the case where no motion is detected tone(4,329,300); delay(200); tone(4,392,300); delay(200); tone(4,493,600); delay(200); tone(4,392,300); lcd.setCursor(0,0); lcd.print("No Motion "); lcd.setCursor(0,1); lcd.print(" Detected but door "); } } delay(2000); // wait for 1 seconds before compare again } </code></pre>
<p>This is a summary of your basic loop logic:</p> <pre><code>void loop() { int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin: int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal if (buttonState == LOW) { if (digitalRead(pirPin) == LOW) { // buttonState is LOW // pirPin is recently read as LOW // ... Motion Detected ... } else if (digitalRead(pirPin) == HIGH) { // buttonState is LOW // pirPin is recently read as HIGH // ... No Motion Detected ... } } else if (buttonState == HIGH) { if (digitalRead(pirPin) == LOW) { // buttonState is HIGH // pirPin is recently read as LOW // ... Motion Detected &amp; Door ... } else if (digitalRead(pirPin) == HIGH) { // buttonState is HIGH // pirPin is recently read as HIGH // ... No Motion Detected but Door ... } } delay(2000); // wait for 1 seconds before compare again } </code></pre> <p>However, this is bad code:</p> <pre><code>if (digitalRead(pirPin) == LOW) { // ... Motion Detected ... } else if (digitalRead(pirPin) == HIGH) { // ... No Motion Detected ... } </code></pre> <p>because each time the digitalRead(..) function is called, it can give a different value. So even though your intention is clear, this code won't work the way you expect. Consider what happens if the first digitalRead(pirPin) is high, so digitalRead(pirPin)==LOW is false, but then the second digitalRead(pirPin) is low, so digitalRead(pirPin)==HIGH is also false. Then neither block of code runs. Instead, use:</p> <pre><code>if (digitalRead(pirPin) == LOW) { // ... Motion Detected ... } else { // ... No Motion Detected ... } </code></pre> <p>Or since you already sampled it at the start of the loop with <code>int pirVal = digitalRead(pirPin);</code>, simplify the logic as:</p> <pre><code>void loop() { int buttonState = digitalRead(buttonPin);// Read the pushbutton input pin: int pirVal = digitalRead(pirPin); //read the digital value from the pirPin and store the value in the local variable pirVal if (buttonState == LOW) { if (pirVal == LOW) { // buttonState is LOW // pirPin is LOW // ... Motion Detected ... } else { // buttonState is LOW // pirPin is HIGH // ... No Motion Detected ... } } else { // buttonState is HIGH if (pirVal == LOW) { // buttonState is HIGH // pirPin is LOW // ... Motion Detected &amp; Door ... } else { // buttonState is HIGH // pirPin is HIGH // ... No Motion Detected but Door ... } } delay(2000); // wait for 1 seconds before compare again } </code></pre> <p>By the way, if you're using the Arduino IDE, you can easily clean up the indentation to make these control structures easier to see, by using Tools | Auto Format.</p>
19294
|c++|string|memory-usage|
What is the memory expense of creating a String from a char array?
2016-01-06T23:35:32.300
<p>I'm writing a little API for processing email messages in Arduinos. Obviously, I need to keep memory use down, but I also want to allow the end user to use the String functions (like indexOf) to search for particular content in emails.</p> <p>My logic uses char arrays (so that memory is statically allocated). If my end user converts a char array to a String (so that they can easily see if an email subject startsWith() a particular word) will this result in doubling the character memory used? .. or will the String class simply include a pointer to the original char array (and just add some cruft)?</p> <p>What would be the best-practice in this kind of situation?</p>
<p>[I'm a year late but this or a related question gets asked often enough, I think it's worth another answer.]</p> <p>With a Mega, there's enough memory to <em>consider</em> doing what you propose <strong><em>if</em></strong> we make some assumptions and modifications:</p> <ol> <li><p>We know or can accept a maximum size of a string, above which, memory allocation will fail, detectably (the allocator returns a NULL pointer and the object handles the failure gracefully);</p></li> <li><p>We use a non-fragmenting allocation method - statically allocated buffer pools of one or more fixed sizes - that are allocated and returned intact. No splitting or merging will take place. A given request will be filled with a buffer of the requested size or larger, if one is available.</p></li> <li><p>Either the String object is modified to only use the new allocator or the system '<em>new()</em>' is replaced by it.</p></li> </ol> <p>The obvious disadvantages are:</p> <ul> <li>The entire heap will not be eaten up by a fragmented memory pool. ("Heap" is that space between the statically allocated memory and dynamically growing and shrinking stack. When the stack and heap meet, your application fails).</li> <li>You'll need to know something about your application's memory needs to plan the buffer pools.</li> <li>You'll have to plan to prevent or handle allocation failure.</li> </ul> <p>In exchange, you get:</p> <ul> <li>The allocator won't crash your system.</li> <li>The String object's programming advantages become available.</li> <li>You'll write better code since you had to think about and plan for its needs rather than let a dumb and fragmenting allocator blindly consume the heap.</li> </ul>
19301
|sensors|current|electricity|
ACS712 sensor reading for AC current
2016-01-07T06:56:00.530
<p>I'm trying to track down a clearly/simply articulated piece of code to take a reading from the <a href="http://www.allegromicro.com/~/media/Files/Datasheets/ACS712-Datasheet.ashx?la=en" rel="nofollow">ACS712 current sensor</a> (link to download PDF data sheet).</p> <p>I understand that these sensors are noisy, and that reading AC current is quite different to DC current.</p> <p>After looking at a range of examples in a variety of forums etc., I've based the following on <a href="http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/" rel="nofollow">http://henrysbench.capnfatz.com/henrys-bench/acs712-arduino-ac-current-tutorial/</a></p> <pre><code>void ac_read() { int rVal = 0; int maxVal = 0; int minVal = 1023; int sampleDuration = 100; // 100ms uint32_t startTime = millis(); // take samples for 100ms while((millis()-startTime) &lt; sampleDuration) { rVal = analogRead(A0); if (rVal &gt; maxVal) maxVal = rVal; if (rVal &lt; minVal) minVal = rVal; } // Subtract min from max to determine the peak to peak range // 1023 = the max value we'll get on the input (1024, zero indexed) // 5.0 = 5v total on adc input double volt = ((maxVal - minVal) * (5.0/1023.0)); // div by 2 is to calculate RMS from peak to peak // 0.35355 is factor to calculate RMS from peak to peak // see http://www.learningaboutelectronics.com/Articles/Voltage-rms-calculator.php double voltRMS = volt * 0.35355; // x 1000 to convert volts to millivolts // divide by the number of millivolts per amp to determine amps measured // the 20A module 100 mv/A (so in this case ampsRMS = voltRMS double ampsRMS = (voltRMS * 1000)/100; Serial.println(ampsRMS); } </code></pre> <p>I unfortunately don't have sufficient test equipment at present to validate this, but I'm getting a value of around 8.9 for a 2300W device, which afaict is roughly accurate (based on this calculator <a href="http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm" rel="nofollow">http://www.rapidtables.com/calc/electric/Watt_to_Amp_Calculator.htm</a>).</p> <p>Is anyone able to confirm the above makes sense/is logical/sane? Is there anything obviously incorrect?</p>
<p>Measuring the peak-to-peak current and scaling the result will get you an answer which will at least go up and down with the magnitude of your average AC current, so yes it is NOT incorrect. As you suggested it will be sensitive to noise from the sensor - in fact as you are taking the highest and lowest single readings the noise will always cause the measurement to be higher than actual.</p> <p>However, I think you could do better. Given that the code is already having to take many samples (basically as fast as it can) for 100mS (which will sample 5 cycles of the waveform if it is 50Hz and 6 if it is 60Hz, depending on where you are in the world), then you could actually do the maths to measure the RMS value and by basing this on all of the signal the effect of the noise will be reduced.</p> <p>You need to know the ADC reading when there is no current <code>rZero</code> (which should be around 511 but could be off a bit due to offset errors) - you could measure this with nothing connected to calibrate the sensor, or take a long term average even with the AC signal present.</p> <p>As the henrysbench tutorial points out it is important that the Arduino samples the signal at a high enough frequency (say 1000Hz - hence 100 samples for your 100mS sample duration)- the count of the number of times that the while loop executes <code>sampleCount</code> will confirm if this still the case even with the extra computation time of this code.</p> <p>Also if you increase the sample time please be careful that the <code>unsigned long rSquaredSum</code> can't overflow, but I would avoid use of doubles within the while loop as they will definitely slow it down a LOT.</p> <pre><code>void ac_read() { int rVal = 0; int sampleDuration = 100; // 100ms int sampleCount = 0; unsigned long rSquaredSum = 0; int rZero = 511; // For illustrative purposes only - should be measured to calibrate sensor. uint32_t startTime = millis(); // take samples for 100ms while((millis()-startTime) &lt; sampleDuration) { rVal = analogRead(A0) - rZero; rSquaredSum += rVal * rVal; sampleCount++; } double voltRMS = 5.0 * sqrt(rSquaredSum / sampleCount) / 1024.0; // x 1000 to convert volts to millivolts // divide by the number of millivolts per amp to determine amps measured // the 20A module 100 mv/A (so in this case ampsRMS = 10 * voltRMS double ampsRMS = voltRMS * 10.0; Serial.println(ampsRMS); } </code></pre>
19304
|electronics|input|
Industrializing Arduino - 24V io? (Electronics)
2016-01-07T08:58:15.860
<p>I would like to make an arduino board that is capable of handling 24V i/o.</p> <p>Powering the Arduino would be done through either a linear or switching regulator of some sort. Low amperages, so efficiency isn't the main problem.</p> <p>For input: 24v to 5v input scaling could be created with a voltage divider. </p> <p>As far as I know, there will never run a high current into the arduino? So the power loss is minimal?</p> <p>For output: 5v to 24v can be easily achieved using a MOSFET? Since this will ramp up the possible load (higher amperages) given that I'm using a 24v supply/separate line.</p> <p>So I could choose to make half the I/O only input and half only output.</p> <ol> <li>Could I combine the MOSFET and voltage divider, and in what way?</li> <li>Are my "assumptions" about the I/O correct, or are there beter ways of handling it?</li> <li>What other things should I think of? Over voltage protection? Polarity inversion? Protection against too high currents?</li> </ol>
<p>This is a pretty old post but I'm sure people still search this topic from time to time. If what you are after is making an arduino into the plc replacement of sorts, look at these links. I've done these tasks and they worked pretty easyily for me. When you compare the cost of a plc to these alternatives, you won't find a new plc for the same price:</p> <p><a href="https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/" rel="nofollow noreferrer">https://www.universal-solder.ca/product/canaduino-plc-mega328-programmable-logic-controller-electronics-diy-kit-for-arduino-nano-included/</a></p> <p>and</p> <p><a href="https://www.visuino.com/" rel="nofollow noreferrer">https://www.visuino.com/</a> - A visual ide</p>
19315
|arduino-micro|op-amp|
Amplification of microphone circuit
2016-01-07T17:45:17.960
<p>I am getting constant values and I need to know the amplification of the circuit. I believe that amplification = R8/R6 though I am not sure.<a href="https://i.stack.imgur.com/pL7jh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pL7jh.jpg" alt="enter image description here"></a></p>
<p>You are mostly correct Diana. The gain of an OP-Amp would normally be R8 divided by R6. </p> <p>However, what needs to be recognized is that in your circuit, the resistance of R3 and the microphone get entangled with your R6. </p> <p>The resistance (impedance of your microphone) is in series with R6. R3 also comes into play, but I will ignore it here (subject of another question on amplifiers). </p> <p>So, since R of microphone is in series with your R6, your gain (amplification) will be slightly less than you have calculated. </p> <p>The old 741 Op-Amp won't work very well (probably not at all) with a single ended power supply of 5 volts. Although you have done a good job of biasing the non-inverting input (+) at 2.5 volts. </p> <p>The 741 output can't get near the +5 volts, nor can it get near ground. Try a better Op-Amp such as MCP6002. Look at how the output of the MCP6002 can approach the rails (your power supply and ground).</p>
19316
|servo|
Why does my Arduino freezes when i turn a servo
2016-01-07T11:26:18.777
<p>I have a Servo Motor and an Arduino Uno.</p> <p>I used the Arduino to run a servo motor. The code was very simple. It was to just Turn it 90 Deg Anti-Clockwise when a switch is pressed and Turn back to its original position (90 Deg Clockwise).</p> <p>The servo had 3 pins. 1. V+ 2. Ground 3. Data</p> <p>I connected the V+ to the Arduino's 5v Output. And the Ground to the Arduino's GND pin. I connected the Data to Digital Pin 3. </p> <p>When ever this script runs, The servo turns a little and then stops. It stops because the arduino froze and It wont do anything. I pressed the Reset button and it does nothing. I plugged off the Servo and the Power Supply and replugged the Power and it works.</p> <p>The power source was a battery pack with 4x 1.5 Volts batteries in it. Maybe there was a problem with this?</p> <p>Do anyone know what might be the problem here? Any Answer will be Appriciated. Thanks.</p>
<p>You said that you were using 4x 1.5v batteries. That would make a total of 6 volts. The current that those batteries can supply is also little. </p> <p>The Recommended Input Range is 7-12 volts. And the Limit is 6-20 volts.</p> <p>You were supplying it with 6 Volts which is at the very limit of the Input Voltage Range. When the motor runs, the Voltage might have dropped and made the arduino freeze.</p> <p>The fix is to supply the arduino with another source such as a benchtop supply that can supply more than 8 volts.</p>
19331
|current|input|
What is the Maximum Current an Arduino can Supply?
2016-01-08T04:09:45.817
<p>I was wondering how much my Arduino I/O pin can output when it is set at <strong>Output</strong> and is at <strong>High</strong>.</p> <p>I am using an <strong>Arduino Uno R3</strong>.</p> <p>Thanks in Advanced.</p>
<p>40.0mA.</p> <p>The Arduino UNO Digital IO pins are connected directly to the IO pins on the ATMEGA328P processor.</p> <p>From page 299 of the <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=0ahUKEwi3p_GkrpnKAhWEQyYKHVBiCJUQFggjMAA&amp;url=http%3A%2F%2Fwww.atmel.com%2Fimages%2Fatmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet_complete.pdf&amp;usg=AFQjCNEfBUXFG85G6huz6IpUbv0LQqhvGQ&amp;sig2=9zwktRebt6GXlhApMf7Zzg" rel="noreferrer">data sheet</a> for that processor...</p> <p><a href="https://i.stack.imgur.com/Brff1.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Brff1.jpg" alt="enter image description here"></a></p> <p>Note that there is also a total current limit for all output pins combined, and that the voltage starts to drop as the current goes up. </p>
19341
|power|arduino-yun|usb|
Power Supply Problem with Arduino YΓΊn: Using a long USB cable
2016-01-08T11:25:35.220
<p>I want to use an Arduino YΓΊn as a kind of outdoor weather station. I want to supply the power for the YΓΊn with a 5V USB-Charger. Using a normal USB cable everything works fine. But as the weather station shall be far from the next power socket, I made the USB cable about 10 meters longer. Now the YΓΊn does not power up any more.</p> <p>Has anybody an idea why?</p> <p>Should I use a 12 V power supply and a 7805 power converter instead?</p>
<p>The USB specification limits the length of a cable between two devices to 5 meters. When you make a longer cable, you're going out of spec, which means it is not guaranteed to work anymore.</p> <p>Since you're only supplying power, the issue is (as you have guessed) the voltage drop in the cable. However, the voltage drop will depend on how much current Arduino is consuming at any given moment. Supplying it with a higher voltage without a converter is dangerous, because it will lead to overvoltage you won't be able to control.</p> <p>I'd suggest trying <a href="https://raspberrypi.stackexchange.com/questions/39066/usb-cables-why-are-some-of-them-bad-for-raspberry-pi/39080">better cables</a> first: thicker and stiffer cables have thicker wires, and may have less voltage drop. You can also make your own cable (provided you can solder) using only two thick wires for power.</p> <p>The ultimate solution, like you said yourself, is to deliver higher voltage over the wire (12V would do) and install a power converted (12V to 5V) near your Arduino. That way, the voltage drop in 5V line will be small, and the voltage drop in 10m 12V line will be compensated by the converter. Actually, the intermediate voltage may be higher: you can simply drop a mains line (220V or whatever you have) to your weather station and place the same USB charger near the Arduino.</p>
19346
|bluetooth|
Can an Arduino act as a GATT Server (Bluetooth LE)
2016-01-08T14:43:14.857
<p>I know it's pretty standard to set up an Arduino system as a BLE client, and use something like an app running on a smartphone as the GATT server, which receives the data and does something with it.</p> <p>In my scenario I have a BLE sensor that is not connected directly to the Arduino system, and I want the Arduino to be able to respond to the sensor output (a wearable accelerometer) and, for example, initiate various lighting sequences depending on the data being received.</p> <p>I would prefer not to introduce a third component (ie: mobile device as GATT server) into the equation. I'd like for the Arduino to listen to the remote device's services and characteristics, analyze the incoming data and then make some decisions about what LEDs to illuminate based on that analysis.</p> <p>Can an Arduino run as a GATT server? </p>
<p>An ESP32 module (Arduino IDE compatible) can act as both a GATT Client and Server, and there are module examples for each of these, as well as github projects. </p>
19352
|arduino-uno|
Arduino recieving binary
2016-01-08T17:52:16.210
<p>I was wondering if Arduino digital pin can receive binary data. For example, I might want one Arduino to send another Arduino a binary code. If the code is <code>01</code> it would turn a red led on, if it was <code>11</code> it would turn green on, etc. I would like to do this so that I don't have to use a lot of digital pins. Is this possible with Arduino or not?</p>
<p>As Majenko says, it is easily possible to implement using bit banging. Assuming that you want to write your own protocol, you need to distinguish between the end of one data packet and the start of another. This could be done by having all of the packets the same length (as in your example with length 2) or using a form of <a href="https://en.wikipedia.org/wiki/Huffman_coding" rel="nofollow">Huffman coding</a> where only the external nodes of the state tree are results so you know when a full packet has been received.</p> <p>Using a standard serial or I2C protocol would also work. With serial you would be able to communicate via a serial emulator on a USB port so you could test with a computer.</p>
19357
|servo|
Automatic/manual door lock with servo
2016-01-08T21:03:28.513
<p>I'm building an automatic door lock, which is moved by a servo ( <a href="http://rads.stackoverflow.com/amzn/click/B00MPW2N6K" rel="nofollow noreferrer" title="this one">this one</a> ). However, I want to still make it possible to open the lock manually, but it's not possible if the servo is attached to the lock mechanism.</p> <p>Do you have ideas on how to go around this problem?</p> <p>Here's a diagram of the lock mechanism</p> <p><a href="https://i.stack.imgur.com/HlkLP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HlkLP.png" alt="Lock mechanism diagram"></a></p>
<p>So it's actually the worm gear that is causing your problem, since that can't be reverse driven by the cogs.</p> <p>The simplest option, I think, would be to have the middle cog normally separated from the worm gear and only re-engage it when you need to drive the mechanism with the servo. You could maybe use a second servo to move it into the right place, or maybe a solenoid, or something along those lines. Have it slide along a short track or slot with a spring to ensure it disengages when the solenoid is released.</p>
19359
|sensors|algorithm|
Compute yaw from magnetometer and accelerometer
2016-01-08T23:27:29.243
<p>I use an Arduino and a 9 DOF sensor (gyroscope, accelerometer and magnetometer) and I'm trying to use the pitch, roll and yaw that the sensor gives me to rotate an object in unity.</p> <p>I managed to correctly compute pitch and roll (the z and x axis in unity) from the accelerometer but it seems that I can't get the Yaw right. By that I mean that when I rotate my sensor pitch or roll it rotates my yaw too, in a weird way.</p> <hr> <p><em>Code in the arduino to get the heading</em></p> <pre><code>void getHeading(void) { heading=180*atan2(Mxyz[0],Mxyz[1])/PI; if(heading &lt;0) heading +=360; } void getTiltHeading(void) { //float pitch = asin(-Axyz[0]); //float roll = asin(Axyz[1]/cos(pitch)); float pitch = atan( Axyz[0] / sqrt( Axyz[1] * Axyz[1] + Axyz[2] * Axyz[2] ) ); float roll = atan( Axyz[1] / sqrt(Axyz[0] * Axyz[0] + Axyz[2] * Axyz[2])); float xh = Mxyz[0] * cos(pitch) + Mxyz[2] * sin(pitch); float yh = Mxyz[0] * sin(roll) * sin(pitch) + Mxyz[1] * cos(roll) - Mxyz[2] * sin(roll) * cos(pitch); float zh = -Mxyz[0] * cos(roll) * sin(pitch) + Mxyz[1] * sin(roll) + Mxyz[2] * cos(roll) * cos(pitch); tiltheading = 180 * atan2(yh, xh)/PI; if(yh&lt;0) tiltheading +=360; } </code></pre> <p><em>Pitch and roll</em></p> <pre><code> float _Pitch = (float)(180 / Math.PI * Math.Atan( m_ResultX / Math.Sqrt( m_ResultY * m_ResultY + m_ResultZ * m_ResultZ ) ) ); float _Roll = (float)(180 / Math.PI * Math.Atan(m_ResultY / Math.Sqrt(m_ResultX * m_ResultX + m_ResultZ * m_ResultZ))); float _Yaw = (float)(m_TiltHeadingResult); </code></pre> <p>Don't hesitate to ask for details.</p>
<p>I don't know how all your sensor's axis are lined up, but it looks like you should level the magnetometer readings by rotating them by <code>-pitch</code> and <code>-roll</code> to get back to the global reference frame, instead of rotating the magnetometer readings by the positive angles.</p> <p>However, The pitch and roll angles in the code are both relative the horizon, not a set of euler angles that define a rotation between two states; because of this, they do not compose to rotate the magnetometer back into the global xy frame like I assume the equations are trying to do. The code is also only using <code>atan</code> for pitch and roll instead of <code>atan2</code>, so their range is only 180 degrees.</p> <p>You need to make sure the rotation matrix you multiply your magnetometer reading by is based on the same conventions as the equations you use to get pitch and roll from the accelerometer, and that it cancels the observed rotation.</p> <p>To do this correctly, I recommend you read into <a href="https://en.wikipedia.org/wiki/Euler_angles" rel="nofollow">euler angles</a>. You might also try searching around for a good library that handles 9-DOF sensor fusion for you.</p>
19378
|arduino-uno|array|
Why I cannot change array values even if a statement is successfully called? TFT Touch Screen
2016-01-09T08:43:56.090
<pre><code>#include &lt;Adafruit_GFX.h&gt; // Core graphics library #include "LGDP4535.h" // Hardware-specific library #include &lt;zTouchScreen.h&gt; #define BOXSIZE 40 // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF LGDP4535 tft; // Using the shield, all control and data lines are fixed #define YP A3 // must be an analog pin, use "An" notation! #define XM A2 // must be an analog pin, use "An" notation! #define YM 9 // can be a digital pin #define XP 8 // can be a digital pin // You need to calibrate to fit your LCD #define TS_MINX 930 #define TS_MINY 903 #define TS_MAXX 142 #define TS_MAXY 117 #define PENRADIUS 3 #define MINPRESSURE 10 #define MAXPRESSURE 1000 int matrix[2][3]; // Initial Declaration int array[3] TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); // array = start with 1 but the variable read start with 0 String ButtonAction[9]={"a", "b", "c", "d", "e", "f", "g", "h", "i"}; boolean ActiveMenu=true; void setup(void) { Serial.begin(9600); tft.reset(); tft.begin(); ts.InitVariable(3, 240, 320, TS_MINX, TS_MAXX, TS_MINY, TS_MAXY, MINPRESSURE, MAXPRESSURE); tft.fillScreen(BLACK); DrawIt(CYAN, "draw"); DrawIt(BLACK, "text"); } void loop() {//SOME OTHER STUFF} unsigned long DrawIt(uint16_t color, String CurrentAction) { int timedcycle=0; if (CurrentAction == "text") { int matrix[2][3]={{25,150,265},{45,100,155}}; int array[3]={3,3,3}; tft.setRotation(3); tft.setTextColor(BLACK); tft.setTextSize(1); Serial.println("Text Columns"); } else if (CurrentAction == "draw") { int matrix[2][3]={{260,140,20},{40,150,95}}; int array[3]={3,3,3}; } Serial.println(CurrentAction); for(int j=0; j&lt;3; j++) { for(int i=0; i&lt;array[j]; i++) { if (CurrentAction == "draw") { if (timedcycle == 7) { tft.fillCircle(100, 160, 15, WHITE); } else { tft.fillRect(matrix[1][j], matrix[0][i], 20,40, color); } } else if (CurrentAction == "text") { if (timedcycle == 4) { true; //tft.fillCircle(100, 160, 15, WHITE); } else { tft.setCursor(matrix[0][j], matrix[1][i]); tft.println(ButtonAction[timedcycle]); } } timedcycle++; } } } </code></pre> <p>So as you can see I'm trying to draw some things in a TFT Touch Screen. Everything seems to be working but no matter what I do I can't change the array value. </p> <p>If I initialize the array variable with a predetermined value it won't change even if the statement is called correctly. I can see that it runs over serial but the array still doesn't change.</p> <p>I suppose there's something wrong but I can't pinpoint what it is! Thanks in advance!</p>
<p>It's because you are defining a <em>new</em> array every time, not modifying the existing one.</p> <pre><code>int matrix[2][3]={{25,150,265},{45,100,155}}; </code></pre> <p>That line doesn't assign new values to the existing <code>matrix</code> array, instead it creates a new array called <code>matrix</code> which only exists within the current scope - that is, within the <code>{...}</code> defined by the <code>if</code> that it is within.</p> <p>Instead you either need to assign values directly to the existing matrix array on a slice-by-slice basis (you cannot use <code>{...}</code> to assign them in bulk):</p> <pre><code>matrix[0][0] = 25; matrix[0][1] = 150; ... etc ... </code></pre> <p>Alternatively, since the values are static, you can pre-define the different matrices in the global scope and then switch between them. This can be done with the right kind of pointer. For instance:</p> <pre><code>int textMatrix[2][3] = {{260,140,20},{40,150,95}}; int (*matrix)[3]; void whateverTheFunctionIs() { if (whatever...) { matrix = textMatrix; } } </code></pre> <p>In that example <code>matrix</code> is a pointer to an array of pointers, which is basically what a 2D array is internally. It starts off by not being assigned to anything at all - it's just "dangling in the breeze". When the <code>if</code> in your function is triggered the address that the <code>matrix</code> pointer points to is changed to that of the <code>textMatrix</code> 2D array, so any access to <code>matrix[x][y]</code> will be identical to accesses to <code>textMatrix[x][y]</code>.</p>
19385
|arduino-uno|
Arduino loading variables from an SD card
2016-01-09T13:19:49.457
<p>Hello I have made a small game using and Arduino Uno and a Nokia 5110 screen. I use bitmaps to draw the images onto the screen. The problem is that bitmaps take up a lot of space and I can only use up to three bitmaps before running out of space. Is it possible to use an SD card to store the bitmaps on and have a method in the Arduino code to load a bitmap at a certain time, like when a button is pushed?</p>
<p>Typically a bitmap for the Nokia 5110 (PCD8544) requires 504 bytes of memory (48*84/8). A bitmap as a initiated global variable will be stored in program memory, transfered to data memory on startup and then to the device (when drawn). Three bitmaps will use up 1.5 Kbyte. This is the limit for the Arduino Uno as an additional bitmap will require all data memory.</p> <p>The first trick that can be used is to define the bitmaps in <a href="http://www.nongnu.org/avr-libc/user-manual/pgmspace.html" rel="nofollow">program memory</a> with the attribute PROGMEM and when needed <a href="http://www.nongnu.org/avr-libc/user-manual/pgmspace_8h.html" rel="nofollow">transfer</a> to a buffer (504 byte) in data memory (and then to the device).</p> <pre><code>void * memcpy_P (void *, const void *, size_t) </code></pre> <p>The second trick is to transfer the bitmap directly from the program memory to the device. This may be supported by the library. If not the bitmap draw function will need to be updated to explicitly read program memory. </p> <p>The upper limit for the bitmaps is now the size of the program memory (30 Kbyte, 60 bitmaps).</p> <p>Cheers!</p>
19387
|arduino-uno|
Arduino and reading from multiple USB connections
2016-01-09T14:51:06.700
<p>I'm sending up a high-altitude balloon with an onboard <a href="https://mightyohm.com/blog/products/geiger-counter/" rel="nofollow">Mighty Ohm Geiger Counter</a> and some other sensors, all of which will be managed by an R Pi B+. I'll collect and store the data with the R Pi; all of that's fine.</p> <p>In order to track and recover it, I'm using the HABDuino shield on an Arduino. It uses the APRS system and sends back short messages, giving the altitude, internal temp, my callsign, and coordinates. I'd like to add the Geiger counter's data to that, but I'll need to get it from the R Pi. </p> <p>Currently, I'm using an FTDI Friend to connect the Gieger counter to the R Pi, and getting the data from the serial port. I see <a href="http://www.seeedstudio.com/recipe/166-basic-pi-lt-gt-arduino-communication-over-usb.html" rel="nofollow">here</a> that I can connect the Arduino and Pi vai USB, but... since there's already a USB connection to the Gieger counter, will there be a conflict? Is that something that I can work around? </p> <p>Thanks for the help!</p>
<p>The FTDI should be showing up as <code>/dev/ttyUSB0</code> on the Pi.</p> <p>If you connect an Arduino as well it will show up as <code>/dev/ttyACM0</code>.</p> <p>If you don't have enough USB sockets then just add a USB hub.</p>
19397
|power|sd-card|
Why can I power an SD card reader from a digital pin?
2016-01-09T21:03:13.863
<p>I'm trying to understand the power requirements of an SD card. I have a cheap breakout board from eBay that includes built-in level shifters, so I can plug it in directly to my Arduino. I provide power from one of the digital pins, and it works. This doesn't make sense to me, as I thought an SD card reader should draw upwards of 50-100 mA, well over the capacity of an individual digital pin on the Arduino. However, at least one <a href="https://www.cooking-hacks.com/documentation/tutorials/arduino-micro-sd" rel="nofollow noreferrer">SD card manufacturer</a> does this as well, so I'm not making this up.</p> <p>I have checked, and the data is written no problem. I have connected an ammeter between the Arduino and the SD reader, and it never jumps above 3 mA? The only problem I have is when I switch from using the USB cable (connected to my computer) for power to a battery pack, the SD card starts acting erratically. Which makes sense, if it's not getting enough current.</p> <p>What I'm wondering is why it <em>ever</em> works when connected to a digital output pin? Clearly I'm missing something important.</p> <p>Edit: The reason why I thought they required a lot of current: I've seen comments like this on a number of <a href="https://learn.adafruit.com/adafruit-micro-sd-breakout-board-card-tutorial/look-out" rel="nofollow noreferrer">tutorials</a>: </p> <blockquote> <p>One is that they are strictly 3.3V devices and the power draw when writing to the card can be fairly high, up to 100mA (or more)! </p> </blockquote> <p>Edit2: @dlu answer lead me to investigate the voltage I was sending to the SD card reader, which turns out to have been the problem. I was supplying the Vin pin with 5.2V, which was regulated down to 4V, presumably too low for the 5V-3.3V step-down at the SD card. Moving the battery power to the 5V pin corrected this. This also introduces some new risk, as the board is now <a href="https://arduino.stackexchange.com/questions/4458/what-are-the-5v-and-vin-pins-for">receiving unregulated power</a>. But that is another problem.</p> <p>Edit3: And finally, answering my original question: I found a note on the <a href="https://www.adafruit.com/product/254" rel="nofollow noreferrer">Adafruit product pag</a>e for a similar breakout that indicates:</p> <blockquote> <p>Onboard 5v->3v regulator provides 150mA for power-hungry cards</p> </blockquote> <p>So despite only drawing 3mA of current from the Arduino pin, the actual SD card is supplied with > 100mA from the regulator.</p>
<p>I just tested a SD card in an adapter (with level shifters). Without any activity the SD card is only drawing around 0.5 mA. So that is in the capability of an output pin.</p> <p>Doing a directory list appears to use a maximum of 7 mA, so that is OK.</p> <p>Writing a file used a maximum of <strong>54.3 mA</strong>, which is exceeding the absolute maximum ratings for an output pin (40 mA - recommended only 20 mA for continuous current).</p> <p>Now you may say that "it works" but the question is: for how long? Exceeding absolute maximum ratings is a path to damaging your processor.</p> <p>If you want to turn the SD card on and off from time to time, to reduce power, I suggest you arrange to switch the 5V line (and not use a digital output). For example from this <a href="http://www.gammon.com.au/forum/?id=12106" rel="nofollow noreferrer">page about a low-power temperature sensor</a> I have this schematic:</p> <p><a href="https://i.stack.imgur.com/vGoJg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vGoJg.png" alt="Power switching MOSFET"></a></p> <p>The MOSFET there switches a 5V line on and off under program control.</p> <p>That particular design includes a SD card, and that particular gadget has been working for a couple of years now.</p> <p>Photo of hardware:</p> <p><a href="https://i.stack.imgur.com/eECeL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eECeL.png" alt="Temperature and humidity sensor"></a></p>
19399
|c|
Correct solution for "multiple definition of" compile error
2016-01-09T21:16:22.037
<p>I'm in the process of trying to take <a href="https://github.com/tdicola/CloudThermometer/tree/master/CloudThermometer" rel="nofollow">this demo sketch</a> and extract the necessary bits into a modular library that can be included in other sketches.</p> <p><a href="https://github.com/maketronica/Adafruit_CC3000_Dynamodb/tree/2ed5c6c8e251be4c0993ed0a1d68a85abe71d62d" rel="nofollow">Here's where I'm at so far</a>.</p> <p>Here's <a href="https://github.com/maketronica/cc3000test/blob/d22022cb76c2dbc92547a1ce7bca0fe97e106a6b/cc3000test.ino" rel="nofollow">the test sketch</a> that I'm including it in.</p> <p>However, when I try to compile it right now, I'm getting...</p> <pre><code>libraries/Adafruit_CC3000_Dynamodb/sha256.cpp.o: In function `Sha256Class::init()': /home/me/sketchbook/libraries/Adafruit_CC3000_Dynamodb/sha256.cpp:33: multiple definition of `Sha256Class::init()' sketch/sha256.cpp.o:sketch/sha256.cpp:33: first defined here </code></pre> <p>I've been programming for years in other languages, but I'm not all that experienced in C. I'm sure I'm doing something completely stupid, but I can't figure out what it is.</p> <p>I'm also aware that this code still needs a lot of cleanup work in general. Right now I'm just trying to work toward a basic MVP that works so that I start gradually cleaning things up and making it more OOP one step at a time.</p>
<p>You have an old copy of the sha256 files lingering in the build folder. These will have been output at some point in the past and never been cleaned up since they have been deleted from the IDE.</p> <p>It is probably a bug in the IDE that doesn't remove the old files.</p> <p>Restarting the IDE will cure the problem and allow you to compile.</p>
19403
|c|
Few questions related to programming microcontrollers
2016-01-09T23:30:10.390
<p>I'm learning "Arduino" (I don't have previous knowledge of microcontrollers). I have few questions:</p> <ol> <li><p>What is the difference between programming a microcontroller in C and programming in "Arduino?"</p></li> <li><p>Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?</p></li> <li><p>I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? What are differences between various microcontrollers which can be used with this board?</p></li> <li><p>If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer? </p></li> </ol> <p>That's it :)</p>
<blockquote> <p>What is the difference between programming a microcontroller in C and programming in "Arduino?"</p> </blockquote> <p>The default language is C++, but you can program in C. Thus the difference is "not much".</p> <blockquote> <p>Is it a good idea for beginners to start programming microcontrollers in Arduino and then start learning to program in C?</p> </blockquote> <p>Ah, if you program the Arduino you will be learning C. So "goodness" doesn't really enter into it.</p> <blockquote> <p>I have Arduino Uno with an Atmega328P-PU microcontroller. What are some other microcontrollers which can be used with this board? </p> </blockquote> <p>You could conceivably remove the chip and replace it with an Atmega168P. I'm not sure why you would want to.</p> <blockquote> <p>What are differences between various microcontrollers which can be used with this board?</p> </blockquote> <p>RAM, program memory (flash) size, and EEPROM size.</p> <blockquote> <p>If a microcontroller is already programmed, can we download the program from it to a PC and edit it in Arduino IDE? Or it is like a .exe on a PC, once compiled we can't get source, all we can do is reverse engineer?</p> </blockquote> <p>No. Like a PC, you can't get the source back. The compiler is a good, highly optimized one. The generated code won't look like the source.</p>
19414
|arduino-uno|esp8266|
Can't send HTTP request using ESP8266 and Arduino Uno
2016-01-10T14:29:50.787
<p>I have an Arduino Uno and for Wifi an ESP8266.</p> <p>My ESP8266 Firmware is</p> <pre><code>AT+GMR AT version:0.40.0.0(Aug 8 2015 14:45:58) SDK version:1.3.0 Ai-Thinker Technology Co.,Ltd. Build:1.3.0.2 Sep 11 2015 11:48:04 </code></pre> <hr> <pre><code>baund = 115200, Both NL &amp; CR </code></pre> <p>Server -- www.linysoft.com</p> <p>The URL I want to send is either: <code>http://www.linysoft.com/arduino/?light=off</code> OR <code>http://www.linysoft.com/arduino/?light=on</code>.</p> <p>Depending on to the link I send the result should be either ==> on or ==> off on the page <code>http://www.linysoft.com/arduino/light.json</code>.</p> <p>Now I want to send an HTTP request (Weblink - <code>http://www.linysoft.com/arduino/?light=on</code>) so it can write according to that link "on" in the <code>light.json</code> page.</p> <p>The AT command I am sending (my wifi module is connected to my wifi automatically):</p> <pre><code>WIFI CONNECTED WIFI GOT IP AT+CWMODE=1 OK AT+CIPMUX=1 OK AT+CIPSTART=0,"TCP","www.linysoft.com",80 0,CONNECT OK AT+CIPSEND=0,200 OK &gt; </code></pre> <p>Here I am getting a problem after this > I can't send <code>**GET /arduino/?light=on**</code>. I also tried <code>GET /arduino/?light=on HTTP/1.0\r\n</code>.</p> <p>After putting this line in the textbox, I press the Enter button or Send Button, but nothing happens.</p> <p>It is stuck here > for some time. And then it shows me:</p> <pre><code>OK &gt; 0,CLOSED </code></pre> <p>Pin Connection</p> <pre><code>ARDUINO UNO ESP8266 RX --------------&gt; TX TX --------------&gt; RX VCC--------------&gt; 3.3 CH_PD ----------&gt; 3.3 GND -------------&gt; GND </code></pre>
<p>I was having same problem and this one solved the problem that after you get a '>' sign then write</p> <p>GET <a href="http://linysoft.com/arduino?light=on" rel="nofollow noreferrer">http://linysoft.com/arduino?light=on</a> HTTP/1.0\r\n\r\n(or if you are directly writing this on serial monitor then press enter key twice and then wait for somemoment like 2-3 sec in this case dont put \r\n\r\n)</p> <p>If this didnt worked then try GET <a href="http://linysoft.com/arduino/?light=on" rel="nofollow noreferrer">http://linysoft.com/arduino/?light=on</a> HTTP/1.0\r\n\r\n</p> <p>But in this I guess you need to specify arduino.php or arduino.html whichever type you have and too you have to take care the cipsend should be the byte no of get request excluding \r\n\r\n and add 4 to it because we are too sending \r\n\r\n these are 4 character</p> <p>I hope this will surely work for you </p>