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
16188
|arduino-uno|rgb-led|
Verify RGB Led Cube equipment
2015-09-19T11:28:49.523
<p>I'm preparing <a href="http://www.ebay.com/cln/stancheg/rgb-led-cube/234958035011" rel="nofollow">this</a> kit on eBay to create the following instructable - <a href="http://www.instructables.com/id/4x4x4-RGB-LED-Cube/" rel="nofollow">http://www.instructables.com/id/4x4x4-RGB-LED-Cube/</a> But I have doubts about 0.1uF and 22pF capacitors since the once on eBay are 50v. Also MOSFETs - instructable uses IRF9531 but the ones I found on eBay are IRF9540N. Is the equipment I added on eBay compatible with instructable?</p>
<p>For a crystal with 20pF load capacitance you need 40pF capacitors.</p> <p>The formula used is:</p> <ul> <li>Cx1 = Cx2 = 2(CL - Cpara)</li> </ul> <p>CL is 20pF and Cpara is the parasitic capacitance of the circuitry involved. Under most amateur circumstances that can be ignored.</p>
16194
|esp8266|
ESP8266 failure to connect to router
2015-09-19T15:57:20.720
<p>I'm trying to get a ESP8266 board with 2x4 pins to work. I'm connecting it to an Olimexino 32u4 (Leonardo-compatible), configured to use 3.3V. This simple snippet I use to transfer everything to the PC (CH_PD is connected to D8, /RST to D9):</p> <pre><code>void setup() { pinMode(8, OUTPUT); pinMode(9, OUTPUT); digitalWrite(8, LOW); digitalWrite(9, LOW); delay(2000); // initialize both serial ports: Serial.begin(9600); Serial1.begin(115200); delay(10000); digitalWrite(9, HIGH); digitalWrite(8, HIGH); } void loop() { // read from port 1, send to port 0: if (Serial1.available()) { int inByte = Serial1.read(); Serial.write(inByte); } // read from port 0, send to port 1: if (Serial.available()) { int inByte = Serial.read(); Serial1.write(inByte); } } </code></pre> <p>When launching, I see following output:</p> <pre><code>&lt;"random" bytes&gt; Ai-Thinker Technology Co. Ltd. invalid </code></pre> <p>Performing a reset shows more:</p> <pre><code>AT+RST OK ets Jan 8 2013,rst cause:2, boot mode:(3,6) load 0x40100000, len 1396, room 16 tail 4 chksum 0x89 load 0x3ffe8000, len 776, room 4 tail 4 chksum 0xe8 load 0x3ffe8308, len 540, room 4 tail 8 chksum 0xc0 csum 0xc0 2nd boot version : 1.4(b1) SPI Speed : 40MHz SPI Mode : QIO SPI Flash Size &amp; Map: 8Mbit(512KB+512KB) jump to run user1 @ 1000 ŒÂÕ�MEM CHECK FAIL!!! äsl�‚rô Ai-Thinker Technology Co. Ltd. invalid </code></pre> <p>The mode is set to station:</p> <pre><code>AT+CWMODE? +CWMODE:1 OK </code></pre> <p>Listing the access points works fine:</p> <pre><code>AT+CWLAP +CWLAP:(3,"ap-1",-91,"01:23:45:67:89:ab",1) +CWLAP:(3,"ap-2",-88,"cd:ef:01:23:45:67",2) +CWLAP:(3,"ap-3",-74,"89:ab:cd:ef:01:23",11) OK </code></pre> <p>But logging in to my Fritzbox router fails (WPA2):</p> <pre><code>AT+CWJAP="ap-2","mypassword" WIFI CONNECTED +CWJAP:1 FAIL WIFI DISCONNECT </code></pre> <p>First I thought the reason is the low signal, but even moving directly beside the Fritzbox shows the same result (though with higher signal value in <code>AT+CWLAP</code>).</p> <p>I've tried nearly everything, e.g. <code>AT+CWMODE=3</code>, <code>AT+RST</code>, <code>AT+RESTORE</code>). Nothing changes. When using a wrong password, I'm getting no "WIFI CONNECTED" messages at all.</p> <p>Could it be a power problem (that the Olimexino can't provide up to 200mA at the 3.3V line?</p> <p>Connecting from my smartphone to the ESP8266 in one of its access point modes (2 or 3) works fine. If there were power problems, wouldn't then the access point mode fails as well?</p>
<p>I had this same problem and spent an embarrassing number of hours trying to fix it before coming across this post. </p> <p>I did a <code>AT+RESTORE</code> followed by <code>AT+UART_DEF=9600,8,1,0,0</code> since, as expected, my module expected communication on 115200 after the restore.</p> <p>Then... as if by magic, everything works now... </p> <pre><code>AT+CWJAP="ssis","pwd" WIFI CONNECTED WIFI GOT IP ! </code></pre> <p>I really don't know what was wrong that the <code>RESTORE</code> fixed... I must have screwed up the module by experimenting with various commands somehow.</p>
16195
|ethernet|
Connect my arduino with ethernet shield to new router
2015-09-19T17:07:26.590
<p>I just changed the router for my webserver and I'm having trouble to connect my arduino with the LAN. I'm using a router which uses Zhone technology, and I've been working with NetGear for a while without problems. The procedure I've done so far is:</p> <ol> <li>Connect the arduino with the ethernet and run the DhcpAdressPrinter example</li> <li>Once I got the adress, in my case 192.168.1.125 I run the WebServer example, using the IP assigned by the DHCP.</li> <li>In the serial monitor, I see it has started the program with the correct IP.</li> </ol> <p>Problem: WHEN PUTTING THE IP INTO A BROWSER, NOTHING CHARGES</p> <p>More info:</p> <ul> <li>In my router page (192.168.1.1) I can see that each ethernet port has assigned a MAC adress, I don't really understand why. </li> <li>I also can see that the arduino has been successfully added to the DHCP with the IP assigned and the MAC adress that I wrote on the code</li> <li>Finally, add that I've read in another website that sometimes the problem is due to the fact that the router just let the access to some specific MAC adress, but i'm not sure. </li> </ul> <p>Any help will be apreciated! Thanks!</p>
<p>Finally, I was capable to solve it by just creating a port forwarding with the IP that was assigned by the DCHP. It looks like my router for security reasons don't let you comunicate with other devices within the lan, so it's necessary to open a port and access the device through it!</p>
16200
|power|hardware|electronics|system-design|
safety for power electronics
2015-09-20T10:43:44.467
<p>I'm quite new to Arduino. I have build a number of projects successfully, like potentiometers, serial communication, DAC, sensors, motors etc. </p> <p>I use a laptop to power my Arduino project and Atmel Studio to program and upload to the Arduino. I have created a project with 2 motors and I have successfully used a separate power supply (a transformer) to power the motors.</p> <p>Now I want to continue my experiments but I'm afraid of the possibility to cause any problem to my laptop.</p> <p>When I made the circuit with the 2 power sources (laptop for the Arduino, transformer for the motors) I had to connect the 2 grounds together.</p> <p>So my question is that:</p> <p><em>Can someone explain me or point me to some information about power electronics so to be absolutely sure that I won't cause any problem to the laptop?</em></p> <p>Should I use optocouplers, or diodes etc? Is there a way to avoid the 2 grounds connection? What is the reason to connect both grounds (of the 2 power supplies) in the first place? </p>
<p>Connecting the grounds together is required since without that there would be no circuit for the current to flow through. Take this simple block diagram for instance:</p> <p><a href="https://i.stack.imgur.com/0uyFv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0uyFv.png" alt="enter image description here"></a></p> <p>In the top diagram there are two complete circuits - the green one (Arduino's 5V power) and the blue one (device's 12V power). The communication between the Arduino and the Device can't happen because there is no circuit (red).</p> <p>In the bottom diagram the red circuit has been completed by joining the grounds together. That means that the current has some way to get back to where it came from (which current always <em>has</em> to do) so the signals you send can actually get through.</p> <p>To avoid having to connect the grounds together you need something called <em>Galvanic Isolation</em>. This involves using some method that is not electricity to connect the two circuits together. That could be using light in the form of an opto-coupler, or magnetism in the form of a transformer, or even something even more physical like a relay. In that situation you have an arrangement like this:</p> <p><a href="https://i.stack.imgur.com/G9hvY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G9hvY.png" alt="enter image description here"></a></p> <p>The ground connection that was part of the red circuit above has now been sliced in half (red and orange now) and the isolation device is responsible for passing the signal from one side to the other.</p> <p>Galvanic isolation is highly desirable when:</p> <ul> <li>You are controlling a different <em>type</em> of current (e.g., using DC to switch AC)</li> <li>You are working with voltages considerably higher than your drive voltage (e.g., switching mains)</li> <li>You have different ground potentials (e.g., you have a long distance connection)</li> </ul>
16204
|c++|class|gcc|
How to loop over objects or pass object to function?
2015-09-20T14:59:10.593
<p>I'm not sure if this is more of an C++ question, but I've looked up both and still have no idea. </p> <p>I have a sketch which controls 6 stepper motors using the AccelStepper library and in order to shorten the code, I would like to simply loop over them, or pass them to a function individually. They are all initialised with different parameters and then placed in an array. </p> <p>However I get the error "conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested" or "conversion from ‘SomeClass (*)()’ to non-scalar type ‘SomeClass’ requested" depending on what I try. </p> <p>I've got experience with C and Java, not much C++ and I thought it would be a straightforward array of pointers, but I can't get the right combination. </p> <p>I've made a cut down version that I try to compile with gcc to demonstrate either approach. I've removed all attempts at pointers with &amp; or * to explain what I want:</p> <pre><code>SomeClass classA(); SomeClass classB(); // error: conversion from ‘SomeClass()’ to non-scalar type ‘SomeClass’ requested SomeClass things[2] = {classA, classB}; int init(class SomeClass thing) { std::cout &lt;&lt; "Setting up thing "; thing.setFoo(100); } int main() { for (int i=0; i &lt; 2; i++) { things[i].setFoo(100); } // could not convert ‘classA’ from ‘SomeClass (*)()’ to ‘SomeClass’ init(classA); return 0; } </code></pre> <p>And just for completeness my class files which are simplified versions of the AccelStepper class:</p> <p>SomeClass.h:</p> <pre><code>#include &lt;stdlib.h&gt; class SomeClass { public: SomeClass(); void setFoo(float foo); }; </code></pre> <p>SomeClass.cpp:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;string&gt; #include &lt;iostream&gt; #include "SomeClass.h" SomeClass::SomeClass() { } void SomeClass::setFoo(float foo) { std::cout &lt;&lt; "foo "; } </code></pre> <p>I hope someone doesn't mind explaining what is probably really simple and obvious! :) </p>
<p>There's a couple of fundamental errors in your sketch. Mainly your construction of your class instances:</p> <pre><code>SomeClass classA(); SomeClass classB(); </code></pre> <p>Those are taken as functions that return a SomeClass object, not SomeClass constructors. Instead they should just read:</p> <pre><code>SomeClass classA; SomeClass classB; </code></pre> <p>As for the rest, you are much better off using pointers to the classes - it makes passing them around so much easier. For instance, your array would look like this:</p> <pre><code>SomeClass *things[2] = {&amp;classA, &amp;classB}; </code></pre> <p>That is an array of pointers to the objects. It just stores the addresses that they are at, rather than duplicating the objects into new objects within the array.</p> <p>Your loop would then run like this:</p> <pre><code>for (int i=0; i &lt; 2; i++) { things[i]-&gt;setFoo(100); } </code></pre> <p>Note the use of <code>-&gt;</code> instead of <code>.</code> because you are using a pointer to the object.</p> <p>Similarly your <code>init()</code> function would be like this:</p> <pre><code>int init(SomeClass *thing) { Serial.println("Setting up thing"); thing-&gt;setFoo(100); } init(&amp;classA); </code></pre> <p>However, if you're never going to use the contents of your array with it you could use a reference instead of a pointer:</p> <pre><code>int init(SomeClass &amp;thing) { Serial.println("Setting up thing"); thing.setFoo(100); } init(classA); </code></pre> <p>That performs the same job as a pointer but leaves you with what looks like a real object rather than a pointer to the object - in fact it's just aliased the object name to a new one at the same address so you can still access it the same using <code>.</code></p>
16205
|arduino-pro-mini|
Arduino Delivering less power
2015-09-20T15:30:12.173
<p>I connected 4x716 Coreless DC Motors on pin 13,12,11,10 and 1xGY-521 to Arduino Pro Mini 328, 5v but speed of propellers is not enough to produce enough torque to lift the quad whereas when i connect then directly to 3.3v LiPo battery the quad has lift but because of no flight control it moves randomly. </p> <p>I checked the voltage of pin 13,12... they have output as 0.5-0.6v, I think this is the reason quad is not lifting. </p> <p>I am using following code </p> <pre><code>// MPU-6050 Short Example Sketch // By Arduino User JohnChi // August 17, 2014 // Public Domain #include&lt;Wire.h&gt; const int MPU=0x68; // I2C address of the MPU-6050 int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ; int p1 = 13; int p2 = 12; int p3 = 11; int p4 = 10; void setup(){ Wire.begin(); Wire.beginTransmission(MPU); Wire.write(0x6B); // PWR_MGMT_1 register Wire.write(0); // set to zero (wakes up the MPU-6050) Wire.endTransmission(true); pinMode(p1, OUTPUT); pinMode(p2, OUTPUT); pinMode(p3, OUTPUT); pinMode(p4, OUTPUT); digitalWrite(p1, 0); analogWrite(p2, 0); analogWrite(p3, 0); analogWrite(p4, 0); Serial.begin(9600); } void loop(){ Wire.beginTransmission(MPU); Wire.write(0x3B); // starting with register 0x3B (ACCEL_XOUT_H) Wire.endTransmission(false); Wire.requestFrom(MPU,14,true); // request a total of 14 registers AcX=Wire.read()&lt;&lt;8|Wire.read(); // 0x3B (ACCEL_XOUT_H) &amp; 0x3C (ACCEL_XOUT_L) AcY=Wire.read()&lt;&lt;8|Wire.read(); // 0x3D (ACCEL_YOUT_H) &amp; 0x3E (ACCEL_YOUT_L) AcZ=Wire.read()&lt;&lt;8|Wire.read(); // 0x3F (ACCEL_ZOUT_H) &amp; 0x40 (ACCEL_ZOUT_L) Tmp=Wire.read()&lt;&lt;8|Wire.read(); // 0x41 (TEMP_OUT_H) &amp; 0x42 (TEMP_OUT_L) GyX=Wire.read()&lt;&lt;8|Wire.read(); // 0x43 (GYRO_XOUT_H) &amp; 0x44 (GYRO_XOUT_L) GyY=Wire.read()&lt;&lt;8|Wire.read(); // 0x45 (GYRO_YOUT_H) &amp; 0x46 (GYRO_YOUT_L) GyZ=Wire.read()&lt;&lt;8|Wire.read(); // 0x47 (GYRO_ZOUT_H) &amp; 0x48 (GYRO_ZOUT_L) Serial.print("AcX = "); Serial.print(AcX); Serial.print(" | AcY = "); Serial.print(AcY); Serial.print(" | AcZ = "); Serial.print(AcZ); Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53); //equation for temperature in degrees C from datasheet Serial.print(" | GyX = "); Serial.print(GyX); Serial.print(" | GyY = "); Serial.print(GyY); Serial.print(" | GyZ = "); Serial.println(GyZ); digitalWrite(p1, HIGH); analogWrite(p2, 250); analogWrite(p3, 255); analogWrite(p4, 255); delay(333); } </code></pre>
<p>Atmega328 output pins are rated at 40 mA absolute-maximum current, and the 328's total current through Vcc and ground pins is 200 mA absolute max. Eg, see table 29.1 in the Atmega328 specs.</p> <p>Although <a href="http://www.quadkopters.com/product/diy-kit/716-coreless-dc-motor-high-speed-x-4/" rel="nofollow">some sources</a> rate a high-speed 716 coreless dc motor at 40 mA, <a href="http://www.seeedstudio.com/depot/37V-50000RPM-Small-Coreless-Motor-716-p-1884.html" rel="nofollow">other sources</a> rate it at 100 mA. In either case, it exceeds normal I/O pin capability. You should use FETs or other drivers between Arduino output pins and the motors rather than trying to drive the motors directly from digital output pins.</p> <p><em>Edit:</em> Regarding the comment, “But most projects i've seen don't use any drivers, Why so ?” I replied:</p> <blockquote> <p>Perhaps they are using slightly higher voltage to the Pro Mini, eg 3.7 V up to 5 V, which after accounting for voltage drop in the i/o pin circuits may deliver enough voltage to the motors. Note that a driverless circuit ie direct drive from the i/o pins operates the 328 out of its safe operating area (SOA), but it may be close enough to the safe area to usually work.</p> </blockquote> <p>For example, some of the 716-based quadcopter pages I looked at say they used 4.2 V LiPo batteries. Also note, 716 seems to be a fairly generic motor designation; it refers to the motor's 7 mm diameter and 16 mm length. As a generic designation it has been used for several different motors, some of which produce less power. For example, in <a href="http://www.rcgroups.com/forums/showthread.php?t=1710948&amp;page=35" rel="nofollow">thread #1710948</a> on rcgroups.com, people refer to different RPMs, less lift, etc. for various motors, and the importance of shaving grams off of the copter's weight to allow it to fly.</p> <p>Another item that matters when drawing high current from an Atmega328 is which ports are used; and for some devices, it matters whether drive is high-side or low-side, ie whether current is sourced or sunk. The Atmega328 spec sheet (Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf) says “Each output buffer has symmetrical drive characteristics with both high sink and source capability”, but for several kinds of drivers less voltage is lost with low-side drive than with high-side. Ie, you could try connecting the motor's V+ lead to Vcc and its V- lead to the i/o pin, and inverting the on-off logic in the sketch. (I don't know if this will make any difference at all in how well things work.) </p> <p>Regarding which ports are used, the footnotes to Table 30-1, “Common DC characteristics”, spell out various combinations of ports where total current draw must not exceed a limit (100 mA in some cases, 150 mA in others). On the Uno and Pro-Mini, digital outputs marked 10 through 13 (as used for motor control in the question's sketch) are port B Atmega pins, with a footnoted total-current limit for the group. If you move two of the motor drives to outputs marked 2...4 or D2...D4, then a different total-current limit will apply. (Again, I don't know if this will make any difference at all in how well things work.) Refer to Table 30-1 footnotes for details.</p> <p>As noted in Gerben's comment, having <a href="https://en.wikipedia.org/wiki/Flyback_diode" rel="nofollow">flyback-diodes</a> for the motor circuits is a good idea. This consists of placing power diodes across the motors, cathode to V+, anode to V-, to prevent energy stored in the motor's inductance from producing extreme i/o pin voltages each time the motor is turned off.</p> <p><em>Edit 2:</em> Regarding “which diode, FET to use and where [to] learn about them”, <a href="http://www.electronics-tutorials.ws/transistor/tran_7.html" rel="nofollow">electronics-tutorials.ws</a> is an accurate and helpful presentation about FET digital circuits. In particular, see the section called “An example of using the MOSFET as a switch”. </p> <p>Which FETs to consider depends in part on your electronic-circuits fabrication skills. Note that surface mount devices (SMD parts) usually weigh less than other versions of parts, which is important for a lightweight quadcopter. However, some people find SMD parts difficult to work with. In my opinion, the main difficulty is holding parts in their proper places while soldering them, due to small size. (Eg, a SOT-23 SMD transistor package is on the order of 3mm x 2mm x 1mm, and a diode may be half as big.) If you have good soldering skills and a way to hold parts in place while soldering, you should be ok, either using a printed circuit board or air-wiring parts using wire-wrap wire (ie, 30 AWG wire, about 0.25mm diameter).</p> <p>Some typical logic-level-input SMD FETs are shown in <a href="http://www.mouser.com/Search/Refine.aspx?N=1323043&amp;Keyword=logic+level+mosfet&amp;Ns=Pricing|0&amp;FS=True" rel="nofollow">mouser.com's online catalog</a>. Note that in that list, RDS_on decreases a bunch as unit price increases slightly. For example, the <a href="http://www.mouser.com/ProductDetail/Fairchild-Semiconductor/FDN359BN_F095/?qs=sGAEpiMZZMshyDBzk1%2fWiwbr802GNVlLdK7ZHbmE8eQ%3d" rel="nofollow">FDN359BN</a> would have under 0.1 ohm resistance when operated with Vcc = 3.7 V and currents &lt; 100 mA. Voltage drop running a 40 mA motor should be about 4 millivolts.</p> <p>Some typical SMD Schottky diodes also are shown in <a href="http://www.mouser.com/Semiconductors/Discrete-Semiconductors/Diodes-Rectifiers/Schottky-Diodes-Rectifiers/_/N-ax1mj?P=1yzxl0uZ1yrhh8nZ1z0z5meZ1z0xoywZ1z0sou6Z1yzolw2Z1z0z5mmZ1yzteijZ1z0j8z5Z1yztawsZ1z0z4y2Z1yx5tfjZ1yrgsggZ1z0z7utZ1z0z458Z1yzolt6Z1yzsp1rZ1yzsbarZ1yuythpZ1yzspgbZ1z0z4yl" rel="nofollow">mouser.com's online catalog</a>. I think even the cheapest of these would work ok. Of course you'll need to adapt all these suggestions to your own skills, sources of parts supply, and budget.</p>
16207
|serial|
To know the state of USB (Serial) connection (connected or not connected)
2015-09-20T15:36:05.993
<pre><code>if (Serial.available()) { digitalWrite(7, HIGH); } else { digitalWrite(7, LOW); } </code></pre> <p>It doesn't seem to be so simple. My testing LED turns on when the USB connection with another program is established, but it doesn't turn off (LOW) when that program exits.</p>
<blockquote> <p>How about having the other program send data to Arduino and Arduino knowing the connection is lost when new data isn't received? I have no idea what Arduino code would do that but just an idea.</p> </blockquote> <p>That sounds simple enough.</p> <pre class="lang-C++ prettyprint-override"><code>const unsigned long MESSAGE_TIMEOUT = 10UL * 1000; // 10 seconds void setup () { Serial.begin (115200); while (!Serial) ; // wait for Serial to become active Serial.println ("Starting"); } // end of setup unsigned long lastMessage; void processInput () { while (Serial.available ()) { char c = Serial.read (); // do something with the data } // end of while loop } // end of processInput void loop () { if (Serial.available ()) { lastMessage = millis (); // remember when we last got input processInput (); // now handle the input } if (millis () - lastMessage &gt;= MESSAGE_TIMEOUT) { // we don't seem to be receiving data } } // end of loop </code></pre>
16215
|serial|arduino-nano|python|
make Arduino tell when the Python program stops reading from the Serial (crash, etc)
2015-09-20T17:36:46.200
<p>Here's the Arduino code:</p> <pre><code>void setup() { Serial.begin(9600); pinMode(7, INPUT_PULLUP); } void loop() { int val = digitalRead(7); if (val == HIGH) { Serial.print("1"); } else { Serial.print("0"); } Serial.println(""); // new line } </code></pre> <p>Python code:</p> <pre><code>import time import serial # setup Arduino USB communication try: arduinoSerialData = serial.Serial('com3', 9600) except: # not connected/damaged pass while True: if arduinoSerialData.inWaiting() &gt; 0: datastr = arduinoSerialData.readline() print datastr time.sleep(1) </code></pre> <p>WHat I want to add is, if Python program exits, or crashes, let the Arduino know somehow. More specifically turn on a LED in pin 8.</p>
<p>There is no way to know if the connection has closed or not, you can only know if the connection <em>was</em> working at some point in the past.</p> <p>Your communication protocol as shown is only <em>half duplex</em> (i.e., it's only one way - the Arduino sends to Python but never the other way around) which simplifies things somewhat.</p> <p>There are a number of strategies you can employ in your case, and any number of them can be combined to create a system as robust (and complex) as you like.</p> <p>First you would need to make your protocol <em>full duplex</em>. This is, you need your Python program to be able to send information to the Arduino. Since you aren't doing that at the moment the implementation of it can be in any way you like. </p> <p>One method you can use is called <a href="https://en.wikipedia.org/wiki/Keepalive" rel="nofollow">Keepalive</a>. In this system the Python program will periodically send an "I am here" message to the Arduino. The Arduino receives these messages and remembers when the last one was (hint: use the <code>millis()</code> function). If a message hasn't been received for more than a pre-defined timeout period the link is assumed to be dead.</p> <p>Another method which is good if you are sending data very regularly from the Arduino to the Python program is to use a system of <em>acknowledgements</em>. In this situation every bit of data sent to the Python program is followed by the Python replying with an "I got that" message. If the Arduino doesn't get that response after sending its data within a certain timeout period (can be much shorter than for a keepalive timeout) then the link is assumed to be dead.</p> <p>Wrapped around both these methods you can add an "I have arrived" and an "I am leaving" message. These are sent by the Python program when it starts and just before it's about to exit so the Arduino knows when the link <em>should</em> be alive and when it <em>shouldn't</em>. If it gets an "I am leaving" message then it knows that it shouldn't care whether it gets any acknowledgement or keepalive messages, so it doesn't need to think about timeouts. Only after it has received an "I have arrived" message should it start caring.</p> <p>So for instance your protocol, with all these things implemented, might look like this (<code>&gt;&gt;</code> = message from Arduino to Python, <code>&lt;&lt;</code> is message from Python to Arduino):</p> <pre><code>&gt;&gt; 1 &gt;&gt; 1 &gt;&gt; 1 &gt;&gt; 0 &gt;&gt; 0 &gt;&gt; 1 &lt;&lt; A - I have arrived &gt;&gt; 1 &lt;&lt; Y - Yes, I got that &gt;&gt; 1 &lt;&lt; Y - Yes, I got that &gt;&gt; 0 &lt;&lt; Y - Yes, I got that &lt;&lt; K - keepalive - we know the link is alive and working. &gt;&gt; 0 &lt;&lt; Y - Yes, I got that &gt;&gt; 1 &lt;&lt; Y - Yes, I got that (Program crashes now.) &gt;&gt; 1 *no Y received - assume connection is closed* &gt;&gt; 1 ... etc ... </code></pre> <p>In this instance the 0 and 1 are what you are sending at the moment. A is an "I have <strong>A</strong>rrived" message, Y is a "<strong>Y</strong>es I got that" message, K is a "<strong>K</strong>eepalive" message, and if the program had exited cleanly an L would have been an "I am <strong>L</strong>eaving" message.</p> <p>Keeping the messages simple (single characters) means it's really easy for the Arduino to parse those messages and work out what is going on.</p> <p>There is a certain amount of balancing act to be performed when implementing your system between how often you are sending data and how long you are willing to wait for a valid response or message to flag the connection closed. </p> <p>Expanding your existing example program to incorporate these messages might look like:</p> <pre><code>unsigned long lastKA = 0; unsigned long lastSent = 0; boolean isConnected = false; void setup() { Serial.begin(9600); pinMode(7, INPUT_PULLUP); } void loop() { // Check the timeouts if we are connected if (isConnected) { // First check to see if the Keepalive timeout has passed if (millis() - laskKA &gt; 5000) { // 5 second keepalive timeout) isConnected = false; } // If we have sent data... if (lastSent &gt; 0) { // ... check that we got a response in time if (millis() - lastSent &gt; 100) { // 100ms Y timeout isConnected = false; } } } // If we are connected then send some data if (isConnected) { int val = digitalRead(7); if (val == HIGH) { Serial.print("1"); } else { Serial.print("0"); } Serial.println(""); // new line // and set the timer for the response lastSent = millis(); } // Now process incoming messages. if (Serial.available()) { int c = Serial.read(); // If the message is an A then turn on the connection and // treat it as a Keepalive as well. if (c == 'A') { // Arrived isConnected = true; lastKA = millis(); // If it's a Leaving message then turn off the connection. } else if (c == 'L') { // Leaving isConnected = false; // If it's a Keepalive then reset the timer. } else if (c == 'K') { // Keepalive lastKA = millis(); // A Y acknowledgement will disable the sent timer. } else if (c == 'Y') { // Yes lastSent = 0; // Cancel the sent timer } } } </code></pre>
16218
|arduino-mega|pwm|hardware|analogwrite|
AnalogWrite custom voltage
2015-09-20T20:41:59.720
<p>I want to get a low voltage on output pin of Arduino mega. I have connected Pin 46 to A3, and wrote 120 value to 46 port. Expected was to get 2-3v on A3 input pin. Instead I always get 1023 values as input. Am I doing something wrong ?</p> <pre class="lang-C++ prettyprint-override"><code>void setup(){ Serial.begin(9600); pinMode(46, OUTPUT); pinMode(A3,INPUT); } void loop(){ analogWrite(46,120); Serial.println(analogRead(A3)); } </code></pre>
<p>The analog outputs aren't real analog outputs, they are PWM.</p> <p>That means that they rapidly switch from OFF to ON and back to OFF again. The analog value is the ration of OFF time to ON time, known as the <em>Duty Cycle</em>.</p> <p>You can convert that rapid switching to a real voltage by passing the signal through a <em>low pass filter</em>. The simplest form is the RC filter:</p> <p><a href="https://i.stack.imgur.com/YALYT.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YALYT.png" alt="enter image description here"></a></p>
16227
|arduino-uno|lcd|analogread|communication|analogwrite|
Sending a value from one arduino to another
2015-09-21T07:18:15.620
<p>I wonder if it is possible to send a value from one arduino to another. </p> <p>Basically, I have one arduino measuring let's say weight, but I want to display that value using an lcd in another arduino. Is it possible to send the value to a pin using analogwrite or digital write in the arduino doing the measurement and use analogread/digitalread at the other arduino making the display? </p> <p>I do not know if this is possible but what is attractive is that one can have several arduino making weight measurements, all showing up in the display of just one central one...</p>
<p>You could have the LCD Arduino be an I2C master and all the weighing Arduinos be slaves. There's an example of master/slave communication and wiring here: <a href="https://www.arduino.cc/en/Tutorial/MasterReader" rel="nofollow">https://www.arduino.cc/en/Tutorial/MasterReader</a>.</p> <p>I2C supports up to 128 devices and the wiring is very simple.</p>
16239
|arduino-uno|serial|bluetooth|wireless|
Is it possible to create an electromagnetic wave using PWM?
2015-09-21T18:52:39.603
<p>What would be the simplest way of making an Arduino emit EM waves using PWM (or without)? Theoretically, oscillating a current through a wire would result in an electromagnetic wave, but I don't know if this is possible using an Arduino and if so, how?</p>
<p>I had a toy project a while ago that generated AM radio. </p> <hr> <h2>Code</h2> <p>Code for Uno or any Atmega328 based boards:</p> <pre class="lang-C++ prettyprint-override"><code>const byte ANTENNA = 9; void setup() { // set up Timer 1 TCCR1A = bit (COM1A0); // toggle OC1A on Compare Match TCCR1B = bit (WGM12) | bit (CS10); // CTC, no prescaler OCR1A = 9; // compare A register value to 10 (zero relative) } // end of setup void loop() { pinMode (ANTENNA, OUTPUT); delay (500); pinMode (ANTENNA, INPUT); delay (300); } // end of loop </code></pre> <hr> <h2>Wiring</h2> <p>Plug a wire into digital pin 9:</p> <p><a href="https://i.stack.imgur.com/qHyEP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qHyEP.jpg" alt="AM radio"></a></p> <hr> <h2>Theory</h2> <p>The 16 MHz clock is divided by 10 (that is, 1.6 MHz) and that is used to toggle pin 9 at that rate, giving a frequency of 800 kHz, since one toggle turns the output on, and second toggle turns it off.</p> <p>Then by turning the output pin on and off slowly you effectively have "keyed" output.</p> <p>Obviously this would not have a long range, but you could amplify the output signal.</p> <hr> <blockquote> <p>What does the timer code do?</p> </blockquote> <p>It's a bit easier to understand if you look at the datasheet. I did a summary for Timer 1 (and the other two timers on the Atmega328) a while back.</p> <h2>Timer 1</h2> <p><a href="https://i.stack.imgur.com/TflBq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TflBq.png" alt="Timer 1 chart"></a></p> <p>The lines assigning to TCCR1A and TCCR1B set various bits as per the chart / datasheet. Then OCR1A is the value that the timer counts to, zero-relative, so it counts to 10.</p> <p>The prescaler is set to 1, so each "tick" is 1/16000000 of a second (62.5 ns). Count 10 of them and you have 625 ns per tick. The timer is configured to toggle an output pin automatically. Since it takes two toggles (on and off) for one frequency "cycle" the period is 1.250 µs. The inverse of that is 800000. Thus the output frequency is 800000 Hz (800 kHz).</p>
16240
|i2c|
What is the I2C address of a sensor?
2015-09-21T18:57:28.310
<p>I have connected BMP180 sensor:</p> <p><a href="https://i.stack.imgur.com/lWCYy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lWCYy.png" alt="enter image description here"></a></p> <p>to Arduino and was able to read its values with appropriate samples (from <a href="https://github.com/adafruit/Adafruit-BMP085-Library" rel="nofollow noreferrer"><code>Adafruit BMP085 Library</code></a> and <a href="https://github.com/adafruit/Adafruit_BMP085_Unified" rel="nofollow noreferrer"><code>Adafruit BMP085 Unified</code></a>).</p> <p>Apparently, this sensor is sending information via <a href="https://en.wikipedia.org/wiki/I%C2%B2C" rel="nofollow noreferrer">I2C bus</a>.</p> <p>However, I2C protocol assumes addresses of connected devices.</p> <p>What are addresses in my case? How to know and/or change them?</p> <p>Is it possible to connect several BMP180 to a single Arduino?</p>
<p>From the datasheet:</p> <blockquote> <p><strong>4.2 Device and register address</strong> </p> <p>The BMP085 module address is shown below. The LSB of the device address distinguishes between read (1) and write (0) operation, corresponding to address 0xEF (read) and 0xEE (write). </p> </blockquote> <p>With the Wire library you divide that by 2 (because it handles the read/write bit) so the address for using with Wire is:</p> <pre class="lang-C++ prettyprint-override"><code>0xEE / 2 = 0x77 </code></pre> <p>Which is mentioned in the Adafruit library:</p> <pre class="lang-C++ prettyprint-override"><code>#define BMP085_I2CADDR 0x77 </code></pre> <blockquote> <p>Is it possible to connect several BMP180 to a single Arduio?</p> </blockquote> <p>You can certainly connect <strong>two</strong> of them. From the datasheet:</p> <blockquote> <p>There is an easy way to connect two BMP085 to the same I2C bus: You can use the XCLR input of BMP085 to set one BMP085 part silent while you communicate with the other BMP085 part via I2C and vice versa. The signals can be provided by two digital outputs of the microcontroller, or one digital output and one inverter. </p> </blockquote> <p>If you have access to the XCLR input (the Adafruit board broke it out, I can't tell with the board in your photo) you could use that method. Otherwise do what some of the other answers suggested, and use an I2C multiplexer.</p>
16244
|arduino-uno|hardware|system-design|wireless|
Fog Machine - On Command
2015-09-21T21:20:12.110
<p>I work with a marching band, and we want to use fog machines for a particular part of the show. I know how to code/program in Arduino, however I am not great in the electrical and technical end. I own two fog machines, and the issue is that we need them to start fogging on command without delay (at least not a long delay, just not early and not late). We cannot exactly stop the show in the middle of a competition to say "wait, the fog is coming soon." We also need them to stop fogging on command.</p> <p>I have read this article, <a href="http://www.instructables.com/id/Motion-Triggered-Fog-Machine/step1/The-Relay/" rel="nofollow">Motion Triggered Fog Machine</a> and it seems simple enough, however, I do not need or want it to work with a motion sensor. I suppose the easiest way you could help me is to either point me to a tutorial or tell me how to modify that tutorial to my own needs.</p>
<p>Perhaps use a small wireless board like the NRF24L01 (available for around $1 each on eBay). Have one at the fogging machine, similar to the Instructable, but instead of a sensor, you turn the machine on and off when a command arrives. For example, send "0" to turn it off and "1" to turn it on. There are examples with the <a href="http://tmrh20.github.io/RF24/index.html" rel="nofollow noreferrer">NRF24L01 library</a>.</p> <p><a href="https://i.stack.imgur.com/4AmYT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4AmYT.jpg" alt="NRF24L01 module"></a></p> <p>Then you have an Arduino in the wings nearby where you press a switch when you need to turn the fogging machine on (this would transmit the signal).</p>
16261
|rfid|
Memory organisation of MIFARE 1K
2015-09-22T14:58:41.813
<p>I'm trying to use a MIFARE 1K RFID card with RC522 RFID reader/writer for my college project. I'm trying to understand about memory organization of MIFARE 1K.A documentation() that supplied with a RFID Arduino library() says like this. I will very appreciate if someone explain me this portion clearly.</p> <blockquote> <p>The MIFARE Classic 1K offers 1024 bytes of data storage, split into 16 sectors; each sector is protected by two different keys, called A and B. Each key can be programmed to allow operations such as reading, writing, increasing valueblocks, etc. MIFARE Classic 4K offers 4096 bytes split into forty sectors, of which 32 are same size as in the 1K with eight more that are quadruple size sectors. MIFARE Classic mini offers 320 bytes split into five sectors. For each of these card types, <strong>16 bytes per sector</strong> are reserved for the keys and access conditions and can not normally be used for user data. Also, the very first 16 bytes contain the serial number of the card and certain other manufacturer data and are read only. That brings the net storage capacity of these cards down to 752 bytes for MIFARE Classic 1k, 3440 bytes for MIFARE Classic 4k, and 224 bytes for Mini. It uses an NXP proprietary security protocol (Crypto-1) for authentication and ciphering.</p> </blockquote> <p>Accordind to above quote,</p> <blockquote> <p>For each of these card types, <strong>16 bytes per sector</strong> are reserved for the keys and access conditions and can not normally be used for user data. Blockquote</p> </blockquote> <p>Explain how to divide 1024 bytes like this.It has 16 sectors.So,total memory should be 16*16=256 bytes.This is impossible. Please explain this.</p>
<p>There is also an excellent graphic of the various mifare card layouts, that someone has put together: <a href="https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png" rel="nofollow">https://upload.wikimedia.org/wikipedia/commons/thumb/3/39/MiFare_Byte_Layout.png/220px-MiFare_Byte_Layout.png</a></p>
16265
|wifi|esp8266|
Esp8266 Arduino smart connect
2015-09-21T15:26:00.583
<p>Below i have an example of a temperature sensor.What i need to be able to set the username an password dynamically before connecting to my home router.It would ask me for the ssid and password for example.example. Ive seen a couple of posts about this with no definitive code to show how it would work.If anyone has experience with this could they comment here please.</p> <pre><code>#include #include #include #define ONE_WIRE_BUS 8 OneWire oneWire(ONE_WIRE_BUS); DallasTemperature sensors(&amp;oneWire); #define SSID "[YOUR_SSID]" #define PASS "[YOUR_PASSWORD]" #define IP "184.106.153.149" // thingspeak.com String GET = "GET /update?key=[THINGSPEAK_KEY]&amp;field1="; void setup() { Serial.begin(9600); sensors.begin(); Serial.println("AT"); delay(5000); if(Serial.find("OK")){ connectWiFi(); } } void loop(){ sensors.requestTemperatures(); float tempC = sensors.getTempCByIndex(0); tempC = DallasTemperature::toFahrenheit(tempC); char buffer[10]; String tempF = dtostrf(tempC, 4, 1, buffer); updateTemp(tempF); delay(60000); } void updateTemp(String tenmpF){ String cmd = "AT+CIPSTART=\"TCP\",\""; cmd += IP; cmd += "\",80"; Serial.println(cmd); delay(2000); if(Serial.find("Error")){ return; } cmd = GET; cmd += tenmpF; cmd += "\r\n"; Serial.print("AT+CIPSEND="); Serial.println(cmd.length()); if(Serial.find("&gt;")){ Serial.print(cmd); }else{ Serial.println("AT+CIPCLOSE"); } } boolean connectWiFi(){ Serial.println("AT+CWMODE=1"); delay(2000); String cmd="AT+CWJAP=\""; cmd+=SSID; cmd+="\",\""; cmd+=PASS; cmd+="\""; Serial.println(cmd); delay(5000); if(Serial.find("OK")){ return true; }else{ return false; } } </code></pre>
<p>I have cobbled together, from the library examples, a program to log temperature and humidity to an MQTT server. The SSID/password, MQTT server and port, and the MQTT publish path can all be set at run time. Once they are set, the device will remember and re-use the settings next time it boots.</p> <p>I am using the Arduino IDE to program an ESP8266-01. It, in turn, talks to a DHT11 sensor for temperature and humidity data.</p> <p>The program is found at <a href="https://github.com/PabluskiNC/TempHumidityLogger" rel="nofollow">https://github.com/PabluskiNC/TempHumidityLogger</a></p> <pre><code> #include &lt;FS.h&gt; //this needs to be first, or it all crashes and burns... #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); #include &lt;ESP8266WiFi.h&gt; //https://github.com/esp8266/Arduino //needed for library #include &lt;DNSServer.h&gt; #include &lt;ESP8266WebServer.h&gt; #include &lt;WiFiManager.h&gt; //https://github.com/tzapu/WiFiManager #include &lt;ArduinoJson.h&gt; //https://github.com/bblanchon/ArduinoJson #include &lt;PubSubClient.h&gt; WiFiClient espClient; PubSubClient client(espClient); long mqtt_lastMsg = 0; char mqtt_msg[50]; int mqtt_value = 0; //define your default values here, if there are different values in config.json, they are overwritten. char mqtt_server[40]; char mqtt_port[6] = "1883"; char mqtt_topic[34] = "OutTopic"; //flag for saving data bool shouldSaveConfig = false; //callback notifying us of the need to save config void saveConfigCallback () { Serial.println("Should save config"); shouldSaveConfig = true; } void setup() { // put your setup code here, to run once: Serial.begin(115200); Serial.println(); //clean FS, for testing //SPIFFS.format(); //read configuration from FS json Serial.println("mounting FS..."); if (SPIFFS.begin()) { Serial.println("mounted file system"); if (SPIFFS.exists("/config.json")) { //file exists, reading and loading Serial.println("reading config file"); File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { Serial.println("opened config file"); size_t size = configFile.size(); // Allocate a buffer to store contents of the file. std::unique_ptr&lt;char[]&gt; buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonBuffer jsonBuffer; JsonObject&amp; json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { Serial.println("\nparsed json"); strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); strcpy(mqtt_topic, json["mqtt_topic"]); } else { Serial.println("failed to load json config"); } } } } else { Serial.println("failed to mount FS"); } //end read // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); WiFiManagerParameter custom_mqtt_topic("topic", "mqtt topic", mqtt_topic, 32); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; //set config save notify callback wifiManager.setSaveConfigCallback(saveConfigCallback); //set static ip //wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0)); //add all your parameters here wifiManager.addParameter(&amp;custom_mqtt_server); wifiManager.addParameter(&amp;custom_mqtt_port); wifiManager.addParameter(&amp;custom_mqtt_topic); //reset settings - for testing //wifiManager.resetSettings(); //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% //wifiManager.setMinimumSignalQuality(); //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds //wifiManager.setTimeout(120); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name //here "AutoConnectAP" //and goes into a blocking loop awaiting configuration if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(5000); } //if you get here you have connected to the WiFi Serial.println("connected...yeey :)"); //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); strcpy(mqtt_topic, custom_mqtt_topic.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); DynamicJsonBuffer jsonBuffer; JsonObject&amp; json = jsonBuffer.createObject(); json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; json["mqtt_topic"] = mqtt_topic; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } json.printTo(Serial); json.printTo(configFile); configFile.close(); //end save } client.setServer(mqtt_server, stringToNumber(mqtt_port)); client.setCallback(callback); Serial.println("local ip"); Serial.println(WiFi.localIP()); dht.begin(); } int stringToNumber(String thisString) { int i, value, length; length = thisString.length(); char blah[(length + 1)]; for (i = 0; i &lt; length; i++) { blah[i] = thisString.charAt(i); } blah[i] = 0; value = atoi(blah); return value; } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i &lt; length; i++) { Serial.print((char)payload[i]); } Serial.println(); // Switch on the LED if an 1 was received as first character if ((char)payload[0] == '1') { digitalWrite(BUILTIN_LED, LOW); // Turn the LED on (Note that LOW is the voltage level // but actually the LED is on; this is because // it is acive low on the ESP-01) } else { digitalWrite(BUILTIN_LED, HIGH); // Turn the LED off by making the voltage HIGH } } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); Serial.print(mqtt_server); Serial.print(":"); Serial.print(mqtt_port); Serial.print("..."); // Attempt to connect if (client.connect("ESP8266Client")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish(mqtt_topic, "Reconnected"); // ... and resubscribe //client.subscribe("inTopic"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } } void loop() { // put your main code here, to run repeatedly: float h = dht.readHumidity(); float t = dht.readTemperature(); if (isnan(t) || isnan(h)) { Serial.println("Failed to read from DHT"); } else { Serial.print("Temp:"); Serial.print(t); Serial.print( "*C Humidity:"); Serial.print(h); Serial.println("%"); if (!client.connected()) { reconnect(); } client.loop(); //long now = millis(); //if (now - mqtt_lastMsg &gt; 2000) { // lastMsg = now; // ++mqtt_value; char temp[7]; dtostrf(t,4,2,temp); //convert float to char snprintf (mqtt_msg, 50, "%s C", temp); // Serial.print("Publish message: "); // Serial.println(msg); // client.publish(mqtt_topic, msg); //} char pub_topic[34]; strcpy(pub_topic,mqtt_topic); strcat(pub_topic,"/temperature"); client.publish( pub_topic , mqtt_msg); Serial.print("Publish: "); Serial.print(pub_topic); Serial.print(" , "); Serial.println(mqtt_msg); dtostrf(h,4,2,temp); //convert float to char snprintf (mqtt_msg, 50, "%s %", temp); strcpy(pub_topic,mqtt_topic); strcat(pub_topic,"/humidity"); client.publish(pub_topic,mqtt_msg); Serial.print("Publish: "); Serial.print(pub_topic); Serial.print(" , "); Serial.println(mqtt_msg); } delay(5000); } </code></pre>
16280
|serial|c++|arduino-pro-mini|
Waiting for an AT command to complete
2015-09-23T11:09:58.313
<p>I'm looking for a way to wait for a response from an AT command to return OK or CONNECTED or whatever the command returns when it's true.</p> <p>I can check if the serial is available, but that means I have to manually guess what time between commands to give them time to connect or start.</p> <p>Function:</p> <pre><code>void ModemCommand(String command) { //Send command to modem mySerial.println(command); Serial.println(command); delay(100); while (!mySerial.available()) { //Wait for Response from modem Serial.println(F("No response yet")); delay(1000); } while (mySerial.available()) { Serial.write(mySerial.read()); //Print response from modem } Serial.println(""); //Linefeed after reponse delay(10); } </code></pre> <p>Code example:</p> <pre><code>ModemCommand(F("ATE0")); //Turn on echo ModemCommand(F("AT+CFUN=1")); //Turn modem functions on waitSec(8,F("turning on Modem functions")); ModemCommand(F("AT+CGREG?")); //GSM attached? ModemCommand(F("AT+CSQ")); //Signal Quality ModemCommand(F("AT+CSTT=\"internet\"")); //Set APN ModemCommand(F("AT+CIICR")); //Connect to APN GPRS waitSec(8,F("connecting to APN GPRS")); ModemCommand(F("AT+CIFSR")); //Get IP </code></pre> <p>Does anybody know how to do this?</p>
<p>The most you can do is define a certain amount of time between received characters, after which you can decide that there's nothing more to be read from the modem. Of course, the time taken for processing is longer for certain commands (and some provide no response at all, until you've completed entering their payload, like TCPSEND, in which case you should simply use <code>mySerial.write()</code> to send said payload, and not your function), but once a response is ready and its first character is available, a timeout of 1 second between characters should be sufficient, for any reasonable baud rate. Something like this:</p> <pre><code>#define TIMEOUT 1000 void modem_command(String command){ mySerial.println(command); Serial.println(command); while (mySerial.available() == 0); // wait for first char unsigned long lastRead = millis(); // last time a char was available while (millis() - lastRead &lt; TIMEOUT){ while (mySerial.available()){ Serial.write(mySerial.read()); lastRead = millis(); // update the lastRead timestamp } } // No need for extra line feed since most responses contain them anyways } </code></pre> <p>Of course, you can always alter <code>TIMEOUT</code> based on your findings.</p>
16284
|led|pwm|
Light multiple RGB Led Strips from same 3 RGB PWM outputs
2015-09-23T18:38:19.543
<p>I need to control about 6 RGB Led Strips from an Arduino Board. The problem is that i need 3 PWM outputs for each led strip, but each will have probably the same colors. I was wondering if i could put two strips receiving a signal from the same PWM output, then i would have to use half the PWM outputs but send the same signal for each pair of strips.</p> <p>The scheme i found is this one:</p> <p><a href="https://learn.adafruit.com/system/assets/assets/000/002/693/medium800/led_strips_ledstripbjt.gif?1396785837" rel="nofollow noreferrer"><img src="https://learn.adafruit.com/system/assets/assets/000/002/693/medium800/led_strips_ledstripbjt.gif?1396785837" alt="arduino schematic" /></a></p> <p>And what i want is something like this: <a href="https://i.stack.imgur.com/yokZr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yokZr.png" alt="enter image description here" /></a></p> <p>Is this possible? What should i modify to make it work?</p> <p>Thanks in advance.</p>
<p>You have few options:</p> <ol> <li><p>do as you represented in the drawing: it should work, as I expect the transistors to not load too much the input.</p></li> <li><p>add a <a href="http://www.digikey.com/product-search/en/integrated-circuits-ics/logic-buffers-drivers-receivers-transceivers/2556308" rel="nofollow">logic buffer</a> inbetween the arduino and the driver stage</p></li> <li><p>use other pins from the arduino for driving the additional strips and bitbang the PWM, instead of using the HW blocks</p></li> </ol> <p>Whether the solution you propose (1) will work or not depends entirely on the max current that each PWM pin can output vs the total load from the 3 transistors it will have to drive.</p>
16286
|input|
Arduino Analog Input Oscillating
2015-09-23T20:02:07.137
<p>I'm making a simple Infrared detector using a thermopile. I have a few extra capacitors than what that schematic says. I'm currently following another, but this is the gist.</p> <p>Schematic and Breadboard- <a href="https://i.stack.imgur.com/cvHXe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/cvHXe.jpg" alt="Breadboard and Schematic"></a></p> <p><strong>I can add breadboard picture if needed. I don't have 10 points in this Stack so I can't post more than 2.</strong></p> <p>I'm using a 9V battery through a 24v - 5v regulator (had one around) to power my op amp and schematic. The signal from the OPAMP will be between 0-5V so voltage hasn't damaged the Arduino Uno. The final project will be something like: output > A then power green, A &lt; output &lt; B power yellow, B &lt; output red.</p> <p>The issue is that I'm getting an oscillating value from my Serial Monitor that goes from 0 to 1023 (or I have a conversion to change it back to output voltage. So 0V to 5V. See code).</p> <p>It does this oscillation when I have the board connected to any of the AX pins (X=0-5) or nothing plugged in at all (I understand it will output weird numbers with the pin floating).</p> <p><strong>I had a picture of the serial monitor but I don't have 10 points to add more than 2 pictures. Please see image below</strong></p> <p>I know that the output from the OPAMP works because when I use a VoltMeter to read the output, it works fine. 0.3XXV when no flame, 5V when flame is directly on top of my theromopile. <a href="https://i.stack.imgur.com/rIZ78.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/rIZ78.jpg" alt="Serial Monitor and VM"></a></p> <p>Would anyone happen to have a suggestion to why the Arduino is acting this way? The volt meter reading is directly out of the Op amp pin 1. <strong>no more than 2 links. AD822 op amp</strong></p> <p>Here's my code before adding if statements for the LED's. It was incorrect.</p> <pre><code>int TP=A2; // Assign Thermopile to pin A2 int val; // Declare readValue Variable float Voltage; // Declare real world voltage variable - Float = in between variable int ledG = 11; int ledY = 12; int ledR = 13; void setup() { pinMode(TP,INPUT); // Declare Thermopile pin as input pinMode(ledG, OUTPUT); pinMode(ledR, OUTPUT); pinMode(ledY, OUTPUT); Serial.begin(9600); // Start your Serial Port } void loop() { val = analogRead(TP); // Read Thermopile pin and place value into readValue Voltage = (5./1023.)*val; // To do "floating point math" have a "." //after the number. If not, it will return real number (5/1023 = 0) according to Arduino Serial.println(Voltage); // Print readValue to Serial Monitor delay(100); // Delayed output to 1/4 a second } </code></pre>
<p>It seems you haven't connected the circuit ground to the Arduino ground. This is essential to complete the circuit between your breadboard and the Arduino. Without the ground connection the electrons that you send to the Arduino have no way of getting back again.</p> <p>Here's a couple of diagrams that I drew for another question which deals with the Arduino driving a remote device, but the theory holds true no matter which way around it is.</p> <p><a href="https://i.stack.imgur.com/gFtVI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gFtVI.png" alt="enter image description here" /></a></p> <p>In that diagram the red arrows (<em>not the aerial display team I hasten to add</em>) represent the connection between your breadboard circuit and the Arduino. Without the ground connection there is no circuit, and a circuit is always needed for current to flow (and hence your signal). With the ground connection the red arrows become a loop which allows the current to flow and transfer your signal.</p>
16290
|sensors|c++|power|analogread|rf|
Is there a away to transmit sensor signal over RF without Arduino?
2015-09-24T06:31:16.523
<p>I would like to place analog sensor in a place, that is impractical to reach with a wire. But it looks like an overkill to use a separate small Arduino board to read and transmit sensor signal to main Arduino board at a close range (~1 m). </p> <p>Is there a cheap practical way to setup such sensor signal broadcast over RF without using Arduino board? Something that could work for considerable duration with a small tablet like battery?</p>
<p>I would recommend investigating the ESP8266 modules. Many people use them as a WiFi interface to an Arduino, but they are also capable of being used completely standalone.</p> <p>You can pick up a cheap module and program it using a readily available USB to TTL UART adapter using the ESP8266 plugin to the Aduino IDE.</p> <p><a href="https://github.com/esp8266/Arduino" rel="nofollow">https://github.com/esp8266/Arduino</a></p> <p>It's like having an Arduino and a WiFi interface all embedded in one chip, and the modules are tiny too - perfect for embedding in a project.</p> <p>There are many different modules available, some with more pins than others for IO. The best one is the NodeMCU since it has the programming interface built in (go for version 1.0 not version 0.9 since it has better IO options), but the higher end ESP8266 modules on carrier boards (ESP-12, etc) are as good, if a little harder to work with.</p>
16292
|arduino-uno|i2c|wire-library|float|
Sending and receiving different types of data via I2C in Arduino
2015-09-24T08:00:39.833
<p>I have found a few good tutorials on how to send and receive data via I2C in connected arduinos. My limitation is now how to transmit different types of data like for instance, long, float, etc. Right now the communication via I2C using the wire library only allows transmission of numbers between 0 and 255. How can one transmit different types of numbers?.</p> <p>In my code a master receives three types of data from the slave, and it send data of a fourth variable to the slave.</p> <p>here is the code for the master</p> <pre><code>#include &lt;Wire.h&gt; const int SLAVE_ADDRESS = 8; //Slave arduino ID int table[]={0,0,0}; //the data will be transmited via table as to allow different data to be transfer. void setup () { Wire.begin (); Serial.begin (9600); // start serial for output } // end of setup void loop() { Wire.requestFrom(SLAVE_ADDRESS, 3);// request 3 bytes from slave device #8 for(int i=0;i&lt;3;i++)//organizes the data from the slave in the table { int c = Wire.read(); // receive a byte as character table[i]=c; } //displays the data Serial.print('\n'); Serial.print(table[0]); Serial.print('\t'); Serial.print(table[1]); Serial.print('\t'); Serial.print(table[2]); Serial.print('\n'); delay (500); // transmit just this variable to the slave int Work=1; Wire.beginTransmission (8); Wire.write (Work); Wire.endTransmission (); } </code></pre> <p>here is the code for the slave</p> <pre><code>#include &lt;Wire.h&gt; int table[]={0,0,0}; int Work=0; void setup() { Wire.begin(8); // join i2c bus with address #8 Wire.onRequest(requestEvent); // register event Wire.onReceive(receiveEvent); // register event } void loop() { int x=120; int y=1200;// gets converted to an strange # because is larger than 255 int z=3; table[0]=x; table[1]=y; table[2]=z; } void requestEvent() { uint8_t Buffer[3]; Buffer[0]=table[0]; Buffer[1]=table[1]; Buffer[2]=table[2]; Wire.write(Buffer,3); } void receiveEvent(int howMany) {Work = Wire.read();} </code></pre>
<p>Use the 'I2C_Anything' library, available <a href="https://github.com/nickgammon/I2C_Anything" rel="nofollow noreferrer">here</a>. I use it in all my I2C projects. It is extremely simple and works great. Here's the entire .h file</p> <pre><code>// Written by Nick Gammon // May 2012 #include &lt;Arduino.h&gt; #include &lt;Wire.h&gt; template &lt;typename T&gt; unsigned int I2C_writeAnything (const T&amp; value) { Wire.write((byte *) &amp;value, sizeof (value)); return sizeof (value); } // end of I2C_writeAnything template &lt;typename T&gt; unsigned int I2C_readAnything(T&amp; value) { byte * p = (byte*) &amp;value; unsigned int i; for (i = 0; i &lt; sizeof value; i++) *p++ = Wire.read(); return i; } // end of I2C_readAnything </code></pre>
16296
|arduino-uno|
Using an Arduino as a electrical mains switch
2015-09-24T10:55:17.627
<p>How do I make an electrical switch using Arduino, that when it receives signal (wirelessly or through a LAN port) to switch off it disconnects the switch and then again told to turn on turns the switch on? </p> <p>The main problem I am facing is that I need to give a 5V output to turn off the transmission between two wires having voltage rating of 230V.</p>
<p>You need to use <a href="https://en.wikipedia.org/wiki/Relay" rel="nofollow">Relays</a>. There all kind of relays.</p> <p>Regular and Solid state ... for controlling a Regular Relay using Arduino you will need a transistor (so you will able to provide the right current to the relay to close a circle)</p> <p>There are a lot of guides for Arduino and Relays (for <a href="http://www.instructables.com/id/Arduino-Controlled-Relay-Box/" rel="nofollow">example</a>)</p>
16303
|arduino-uno|wifi|
Linking Arduino With Twitter
2015-09-24T14:11:21.420
<p>My project is having Arduino with my WiFi shield connect to Twitter and look for any messages that other users have tweeted at me that contain a certain color, (I.E. @myTwitterHandle I want red) and then changes an RGB LED to become that color. </p> <p>I have been searching online for different methods, and found a few different solutions which I could use as a starting point. However, these apparently call to an old Twitter API that is not supported anymore (support stopped mid 2013).</p> <p>One solution I came across was to use node-red as well as MQTT. I am not too familiar with these programs.</p> <p>Does anyone know how to have Arduino parse a twitter account for mentions containing certain strings and have it print to LED? Any help with be appreciated </p>
<p>The new Twitter 1.1 API requires OAuth authorization over SSL, for which Arduino is under-powered.</p> <p>You will need to write a proxy application, which would parse the tweets and then send a RGB color value to your Arduino.</p> <p>You should split your project into three parts.</p> <ol> <li><p>Retrieving tweets with the <a href="https://dev.twitter.com/overview/documentation" rel="nofollow">Twitter API</a>.<br> You can get some library to do it for you.</p></li> <li><p>Communicating with your Arduino.<br> Just try to send an arbitrary color to your Arduino over internet.</p></li> <li><p>And finally joining first two pieces of code together.</p></li> </ol> <p>And if you get stuck somewhere, you can always ask for help here on StackExchenge.</p>
16304
|programming|sensors|c++|library|
Querying streaming sensor data on the Arduino board
2015-09-24T14:18:27.240
<p>I am new to Arduino and this forum, so please forgive me if I am asking something really trivial and stupid.</p> <p>I have an Arduino board which collects sensor readings from an MPU6050 sensor (acceleration+gyroscope). The next step for me would be to process these data directly on the board. I want to somehow store N last sensor values and then query this set (collection, vector, array, whatever you call it) to fetch certain values. This set will be constantly updated with new values, whereas older values will be pushed out, so that only the most up-to-date values are stored in the set. For example, I want to know if the acceleration exceeded 10 m/s in the last minute.</p> <p>In the literature this kind of set with most recent values is sometimes called <em>window</em> - this approach allows limiting an unbounded sequence of constantly generated tuples to a bounded bag and then apply traditional SQL-like query operators. For example, Oracle has come with <a href="http://docs.oracle.com/cd/E16764_01/doc.1111/e12048/intro.htm" rel="nofollow noreferrer" title="CQL">CQL</a> - an engine and a query language for handling streaming data.</p> <p>Before I start implementing this, I am wondering if there is a similar (and, of course, much simpler) library for Arduino? If not, which data structure should I use to implement such functionality?</p> <p>Also, my intention is to query not just individual values, but certain patterns and sequences - e.g., I want to know if the acceleration first decreased and then increased again (something similar to the WHERE condition of an SQL query). Does it look realistic to implement with Arduino?</p>
<p>It sounds like you are after my Average library:</p> <ul> <li><a href="https://github.com/MajenkoLibraries/Average" rel="nofollow">https://github.com/MajenkoLibraries/Average</a></li> </ul> <p>It allows you to store a rolling set of data where you get to "push" values into it and the oldest one drops off the end. (It's implemented internally using a circular buffer).</p> <p>You can then do various forms of analysis on the data - get the <em>mean</em> average, the <em>mode</em> average, calculate the standard deviation, find the maximum and minimum values of the set, and even access individual entries within the set.</p> <p>It's a fully templated library, so you can use it with any numerical data type (float, double, int, long, etc).</p>
16308
|serial|python|
Serial.readString() - how does it work exactly?
2015-09-24T14:53:45.417
<p>Someone posted a solution for a problem I had which used Serial.read() .Why doesn't readString() seem to work though? From the docs it seems it reads the data as a String object which would make things a bit cleaner.</p> <p>But here's my Python code:</p> <pre><code>import serial arduinoSerialData = serial.Serial('com7', 9600, timeout=0) while True: arduinoSerialData.write('ALIVE\r\n') </code></pre> <p>And Arduino code:</p> <pre><code>void setup() { Serial.begin(9600); pinMode(13, OUTPUT); } void loop() { if (Serial.readString() == "ALIVE") { digitalWrite(13, HIGH); } else { digitalWrite(13, LOW); } } </code></pre> <p>If this was right, the green LED on the Arduino would light up when the Python program would run, but it doesn't. What is Serial.readString() expecting that it doesn't get? I even tried <code>if (Serial.readString().startsWith("ALIVE"))</code> instead, as well as <code>arduinoSerialData.flush()</code> before <code>arduinoSerialData.write()</code></p>
<p><code>readString()</code> will read characters from the serial (or other Stream) device until a timeout occurs. That timeout is, by default, 1 second. It is only appropriate to use <code>readString()</code> if your data is arriving in chunks with a minimum time between each chunk.</p> <p>It is more appropriate to use <code>readStringUntil()</code> which will read characters from the serial device until <em>either</em> it times out, <em>or</em> it receives a certain character. It is most common to use either the line feed (<code>\n</code>) or carriage return (<code>\r</code>) characters as the end of string marker. You must, of course, ensure that your sending program sends the string terminated in the right way.</p> <p>However, that all said, you really should avoid using String objects when possible, since the constant creation and destruction of temporary objects all over the place can make a real mess of your heap.</p> <p>It is far better to learn to use character arrays and fill them using <code>Serial.read()</code>. A tutorial I wrote for that is here:</p> <ul> <li><a href="http://hacking.majenko.co.uk/reading-serial-on-the-arduino" rel="nofollow">http://hacking.majenko.co.uk/reading-serial-on-the-arduino</a></li> </ul>
16312
|serial|arduino-nano|
Is the Serial buffer going from Arduino to PC and from PC to Arduino different?
2015-09-24T16:11:43.723
<p>I'm both sending and receiving strings to Arduino from my Python program on the PC and the opposite. I don't check by code if one is finished before doing the other. Are they seprate buffers, or is it just pure luck my program has been running fine until now and each program has been reading the right string ?</p>
<p>There shall be separate buffers for Tx and Rx (in Arduino Serial library). The actual buffer size may vary, <strike>but shall be around 8-16 bytes and there is also hardware buffer in MCU</strike>. Please try to increase serial baudrate, if possible.</p> <p><strong>UPD:</strong> In HardwareSerial.h:</p> <pre><code>#if (RAMEND &lt; 1000) #define SERIAL_TX_BUFFER_SIZE 16 #else #define SERIAL_TX_BUFFER_SIZE 64 #endif .... unsigned char _rx_buffer[SERIAL_RX_BUFFER_SIZE]; unsigned char _tx_buffer[SERIAL_TX_BUFFER_SIZE]; </code></pre> <p><strike>It seems for Atmega328 the buffers are 16 bytes each</strike></p> <p><strong>UPD:</strong> As Nick pointed, for Atmega328:</p> <pre><code>#define RAMEND 0x8FF /* Last On-Chip SRAM Location */ </code></pre> <p>So the buffers are 64 byte each.</p>
16314
|arduino-uno|electronics|
Arduino circuit diagram help
2015-09-24T18:09:22.717
<p>I'm new to the arduino and to EE in general. I've built the basic examples and a, now trying to get a deeper understanding of what the physics is doing. As such, I'd like some help in understanding the diagram here:</p> <p><a href="https://www.arduino.cc/en/Tutorial/Blink" rel="nofollow">https://www.arduino.cc/en/Tutorial/Blink</a></p> <p><strong>Question 1:</strong></p> <p>Specifically,it seems that the flow is going from Pin 13 to Ground. Is the diagram using the conventional flow or the electron flow approach. </p> <p>Specifically, is it the <em>electrons</em> flowing from Pin 13 to ground or does the diagram show protons flowing? It seems that its showing the electron flow as the diagram has the anode attached to the resistor so the electrons flow from the pin to the resistor to the positive end (anode) of the LED.</p> <p><strong>Question 2:</strong> This is about bread boards, like one shown here:</p> <p><a href="https://www.google.com/search?q=arduino+breadboard&amp;biw=1696&amp;bih=988&amp;tbm=isch&amp;tbo=u&amp;source=univ&amp;sa=X&amp;ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&amp;q=breadboard&amp;imgrc=KwnTrtjnYJdB1M%3A" rel="nofollow">https://www.google.com/search?q=arduino+breadboard&amp;biw=1696&amp;bih=988&amp;tbm=isch&amp;tbo=u&amp;source=univ&amp;sa=X&amp;ved=0CFEQsARqFQoTCIjsw5WhkMgCFdWYiAodttcKIw#tbm=isch&amp;q=breadboard&amp;imgrc=KwnTrtjnYJdB1M%3A</a></p> <p>1) Would I connect Pin 13 (or say the 5V pin) to the + (the red line). Then I would connect the blue line (the -) to the ground on the arduino? Do I need to connect the blue line? </p> <p>2) Also, is it again the electron flow notation so that from Pin 13, the electrons flow to the + (red), then to one of the lettered columns and then to whatever component I have?</p> <p>Thank you for your help! I realize these are basic questions but I want to go a little beyond building the examples and start trying things out myself. As such I want to make sure I'm getting the theory behind it right!</p>
<p>The thing to remember about electrons is they are a negative charge. That means that the direction of current flow (positive charge) is opposite to the direction of flow of the actual electrons (negative charge). Picture it like those "compression jams" you get on the motorway (freeway) where cars that are travelling too close together have to slam their breaks on to avoid running into each other. The one at the front slams its breaks on briefly then carries on. The one behind has to do the same, and so on and so forth. You then get a wave effect travelling in the opposite direction to the direction of travel of cars as they slam their breaks on in turn. The cars are moving forwards, but the compression jam is moving backwards. Similar in a circuit - the electrons are moving forward, but the charge is moving backwards. </p> <p>Another way to visualize it is as a bubble in a pipe of stationary water. The bubble moves in one direction, but in order for it to do that the water has to flow past the bubble in the opposite direction.<sup>*</sup></p> <p>So the current flows out of pin 13 through the LED and to ground, but the electrons themselves are actually flowing from ground through the LED and in to pin 13 (where they eventually return back to ground through the power supply).</p> <p>For how the IO pin works it's best to picture it as a pair of switches - one connected to Vcc and one connected to GND. For instance, this is the LED wired up with the IO pin set to HIGH:</p> <p><a href="https://i.stack.imgur.com/gWOUn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gWOUn.png" alt="enter image description here"></a></p> <p>You can see that S1, being on, forms a circuit between the battery and the LED to allow the current to flow.</p> <p>When the IO pin is set to LOW the circuit looks a bit like this:</p> <p><a href="https://i.stack.imgur.com/Atfxx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Atfxx.png" alt="enter image description here"></a></p> <p>You see that S1 is now turned off, and S2 is turned on. the connection from that battery is now broken, and current can't flow.</p> <p>But, you ask, what is the point of S2 here? It doesn't actually do anything. No, not in that circuit it doesn't. But consider if you re-arrange the circuit to be like this:</p> <p><a href="https://i.stack.imgur.com/uaV1O.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uaV1O.png" alt="enter image description here"></a></p> <p>Now it's S2 that is controlling the connection to the battery. S1 is now the redundant switch.</p> <p>This leads to some terminology.</p> <p>When S1 is closed the IO pin is said to <em>source</em> current since it is pretty much connected directly to the positive power source.</p> <p>When S2 is closed instead the IO pin is said to <em>sink</em> current since it is connected to ground, so current can "sink" down to ground through it.</p> <p>As far as breadboards are concerned - they are just collections of metal strips that are used to join wires and component leads together in whatever way you need to. There is no one part of it that is any different to any other, and there is nothing that says you must use this bit in a certain way, or that bit in another way.</p> <p>Your typical breadboard has sprung metal clips that are arranged in this pattern:</p> <p><a href="https://i.stack.imgur.com/u220p.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u220p.png" alt="enter image description here"></a></p> <p>You can use any collection of holes for any purpose you choose.</p> <p>That said, normally the blue (or black) marked line of holes down each side is used for ground, and the red line of holes is used for power. As both sides of the board are separate it is possible to use different voltages on each side, or the same voltage on both sides, etc. That can be especially useful when you're working on a circuit that has, say, +3.3V and +5V in it. Another common split usage is for a positive voltage on one side and a negative voltage on the other - common when working with op-amps. Just remember which is which.</p> <hr> <p><sup>*</sup> This is a complete lie, but it's as close as you need to know at this point in your education. <a href="https://en.wikipedia.org/wiki/Lie-to-children" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Lie-to-children</a></p>
16315
|hardware|
atmega16 in Arduino Board
2015-09-24T12:59:18.570
<p>I had a very common question. Why a additional MEGA used in most of the Arduino Boards. Arduino board Mega2560 also have a MEGA16U2 controller on board which i think is used for programming via USB. Is there any other specific usage of atmega16 on arduino board. </p> <p>Thanks</p>
<p>It's an ATmegaU2, which has USB hardware and handles the USB communication. It passes the hex file on to the bootloader in the main microcontroller. That is its only job.</p>
16330
|accelerometer|
Hardware to measure velocity via string/wire attatchment? beginner
2015-09-25T03:09:21.167
<p>This is a broad question but I want advice on what type of hardware I should look for to make a device that could measure the velocity of an object attached via a string/wire to some sort of rotary wheel.</p> <p>The purpose of this is to attach it to a barbell and measure mean-velocity for weightlifting atheletes.</p> <p>I'm a software engineer by trade but know nothing about hardware. I will obviously need to start with simple projects to learn, but I would like to know which hardware I should lean towards buying, so I don't have to re-buy anything?</p>
<p>You can use a dog lead (or replace it with a fishing line). I made one my self. I used a rotary encoder and a dog lead, an Arduino board Paralax, and Excel.</p> <p>It will use interrupts. Once the wire is triggered, the Arduino will send to Excel time and distance traveled. Once the weight goes down distance and time will be printed too, however distance will run in a minus direction. Later just press one button in Excel and each set of lifts will appear on the desktop. I can see my lift speed, power generated, distance travelled and so on.</p> <p><a href="https://i.stack.imgur.com/8lhAU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8lhAU.png" alt="Excel example"></a></p>
16334
|serial|led|electronics|
help with 7- segment display
2015-09-25T07:03:14.473
<p>I'm playing with a 7 segment display.</p> <p>The following works on my breadboard:</p> <pre><code>5V -&gt; 330 Ohm Resistor (same row, row 9) 330 Ohm Resistor -&gt; Com Port (row 9 to row 15) h led (the dot/row 17) -&gt; ground rail </code></pre> <p>I get the dot to light up.</p> <p>However, the following does not light up:</p> <pre><code>5V -&gt; h led (the dot/row 17) Com Port -&gt; 330 Ohm Resistor (Row 15 -&gt; row 38). 330 Ohm Resistor to negative rail (row 38 -&gt; negative rail) </code></pre> <p>I realize that the row numbers are meaningless -- things just need to be on the same row. I've included them to make it easier to visualize.</p> <p>So basically, if the circuit goes:</p> <p>5V -> Resistor -> Com, then I can use the ground wire to light up any part I want.</p> <p>If the circuit goes Com -> Resistor to Ground, I can't use the 5V to light up any part. </p> <p>I'm not sure why given that all the stuff is in serial?</p>
<p>Because you have a common-anode display and you're trying to use it as a common-cathode display. LEDs, like all diodes, only conduct freely in one direction.</p>
16347
|arduino-mega|c++|arduino-ide|ethernet|datalogging|
How do I connect Arduino directly to MySQL server using the URL?
2015-09-25T20:30:09.740
<p>I started a project with my Arduino Mega 2560 that gets some values from sensors. I'm using MySQL Connector, <a href="https://launchpad.net/mysql-arduino" rel="nofollow noreferrer">https://launchpad.net/mysql-arduino</a>, and this library allows me to connect to a server using the IP address, and it worked on localhost.</p> <p>This is the code:</p> <pre><code>/* Setup for all libraries */ #include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; #include &lt;sha1.h&gt; #include &lt;mysql.h&gt; #include &lt;OneWire.h&gt; /* Setup for Ethernet Library */ byte mac_addr[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xB3, 0x05 }; // MAC address must be unique; this is the Ethernet shield address IPAddress server_addr( 177, 156, 122, 113 ); // Server addr /* Setup for all others variables */ int DS18S20_Pin = 2; // Temperature sensor float temperature; float placasTensao; float placasCorrente; float geradorEolicoTensao; float geradorEolicoCorrente; float bateriaTensao; float bateriaTemp; float correnteSaidaControlador; float correnteSaidaConsumo; OneWire ds(DS18S20_Pin); // On digital pin 2 /* Setup for the Connector/Arduino */ Connector my_conn; // The Connector/Arduino reference /* Setup for connection and all variables of the database */ char user[] = ""; char password[] = ""; char INSERT_SQL[1000]; char temperature_convt[10], placasTensao_convt[10], placasCorrente_convt[10], geradorEolicoTensao_convt[10], geradorEolicoCorrente_convt[10], bateriaTensao_convt[10], bateriaTemp_convt[10], correnteSaidaControlador_convt[10], correnteSaidaConsumo_convt[10]; void setup(){ Ethernet.begin(mac_addr); Serial.begin(9600); delay(1000); } void loop(){ temperature = getTemp(); convert(temperature, temperature_convt); snprintf(INSERT_SQL, "INSERT INTO data.data VALUES (%s, 1, 1, 1, 1, 1, 1, 1, NULL)", temperature_convt); sendData(); delay(20000); } // Convert a float variable to string void convert(float data, char *value){ dtostrf(data, 7, 3, value); } // Saves all data on database void sendData(){ Serial.println("Connecting..."); if (my_conn.mysql_connect(server_addr, 3306, user, password)){ delay(500); Serial.println("Starting SQL!"); Serial.println(INSERT_SQL); my_conn.cmd_query(INSERT_SQL); Serial.println("Query Success!"); my_conn.disconnect(); Serial.println("\n"); } else { Serial.println("Connection failed!"); Serial.println("Make sure all cables are properly connected!\nIf they are, restart the Arduino!\n"); } } // Returns the temperature from one DS18S20 in degree Celsius float getTemp(){ byte data[12]; byte addr[8]; if (!ds.search(addr)) { // No more sensors on chain, reset search ds.reset_search(); return -1000; } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return -1000; } if ( addr[0] != 0x10 &amp;&amp; addr[0] != 0x28) { Serial.print("Device is not recognized"); return -1000; } ds.reset(); ds.select(addr); ds.write(0x44,1); // Start conversion, with parasite power on at the end byte present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad for (int i = 0; i &lt; 9; i++) { // We need 9 bytes data[i] = ds.read(); } ds.reset_search(); byte MSB = data[1]; byte LSB = data[0]; float tempRead = ((MSB &lt;&lt; 8) | LSB); // Using two's complement float TemperatureSum = tempRead / 16; return TemperatureSum; } </code></pre> <p>Now, how can I connect to a server using the URL? Is there a library like MySQL Connector that allows me to use the URL instead of the IP address?</p> <p>All I want is to do exactly the same thing that I'm doing with MySQL Connector, but using the URL of the server instead of the IP address.</p>
<p>The easiest, just git 'er done, way would be to do an nslookup on the domain, get the IP address and just hard code that into your source. It's not the most robust solution, as it's possible for the IP address to change over time. However, it's highly likely the IP address won't change frequently.</p> <pre><code>&gt; nslookup google.ca Server: 64.59.144.93 Address: 64.59.144.93#53 Non-authoritative answer: Name: google.ca Address: 216.58.193.67 </code></pre> <p>If you need it to be more robust, you would need the Arduino to perform the dns lookup to resolve the IP address. This looks like it would do the job: </p> <p><a href="https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h" rel="nofollow noreferrer">https://github.com/esp8266/Arduino/blob/master/libraries/Ethernet/src/Dns.h</a></p>
16348
|arduino-uno|arduino-mega|c++|arduino-leonardo|spi|
How do you use SPI on an Arduino?
2015-09-26T01:06:58.590
<p>With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:</p> <ul> <li>How does SPI work?</li> <li>How fast is SPI?</li> <li>How do I connect between a master and a slave?</li> <li>How do I make an SPI slave?</li> </ul> <hr> <p><em>Please note: This is intended as a reference question.</em></p>
<p>Thank you for the information.</p> <p>Mr. Nick Gammon said</p> <blockquote> <p>However the Leonardo and ProMicro don't expose the SS pin and thus cannot be used as an SPI slave.</p> </blockquote> <p>but I could use ProMicro and Leonardo as SPI slave devides by wiring SS signal.</p> <p>Reference: <a href="https://asukiaaa.blogspot.com/2023/05/atmega32u4-as-spi-slave.html" rel="nofollow noreferrer">https://asukiaaa.blogspot.com/2023/05/atmega32u4-as-spi-slave.html</a></p> <p><a href="https://i.stack.imgur.com/3Gds3m.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Gds3m.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/dgLeJm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dgLeJm.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/mHf3sm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mHf3sm.jpg" alt="enter image description here" /></a> <a href="https://i.stack.imgur.com/PIwCZm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PIwCZm.jpg" alt="enter image description here" /></a></p>
16352
|c++|voltage-level|adc|
Measure Vcc using 1.1V bandgap
2015-09-26T10:24:59.570
<p>For an battery driven application I want to measure the Vcc (using an Atmega 32u4). That is my code:</p> <pre><code>int readBandGap() { ADMUX = (B01 &lt;&lt; REFS0) // VCC | (0 &lt;&lt; ADLAR) // right-adjusted result | (B011110 &lt;&lt; MUX0) // 1.1V ; // switch off any ADC conversion ADCSRA &amp;= ~(1 &lt;&lt; ADEN); // enable ADC ADCSRA |= 1 &lt;&lt; ADEN; // start ADC ADCSRA |= 1 &lt;&lt; ADSC; // wait until finished while (bit_is_set(ADCSRA, ADSC)); // first read low, then high! uint8_t low = ADCL; uint8_t high = ADCH; // switch off any ADC conversion ADCSRA &amp;= ~(1 &lt;&lt; ADEN); return (high &lt;&lt; 8) | low; } void setup() { Serial.begin(9600); } void loop() { int value = readBandGap(); float vcc = 1.1 * 1023 / value; Serial.print(value); Serial.print(" "); Serial.println(vcc); delay(1000); } </code></pre> <p>My Olimexino 32u4 board has the ability to switch the voltage between 5V and 3.3V. There are two strange things: </p> <ol> <li><p>the first measurement is always significantly different than the later measurements</p></li> <li><p>with 5V I'm getting 450, followed by ~367; with 3.3V I'm getting 422, followed by ~395. I would have expected a higher Vcc resulting in a lower measured value (bandgap should be measured compared to Vcc).</p></li> </ol> <p>Any ideas what is wrong with my approach?</p>
<p>The bandgap voltage reference needs some time to stabilize, after you enable it. See <a href="http://jeelabs.org/2012/05/12/improved-vcc-measurement/" rel="nofollow">http://jeelabs.org/2012/05/12/improved-vcc-measurement/</a> </p> <p>Doing 3 dummy measurements, gives it enough time to do that.</p>
16355
|motor|hardware|robotics|
Dagu Mini Driver Board Issues
2015-09-26T13:34:23.033
<p>I have the Dagu Mini Driver board which is based on the atmega8 and I uploaded the code <a href="http://blog.dawnrobotics.co.uk/2013/11/getting-started-with-the-dagu-arduino-mini-driver-board/" rel="nofollow noreferrer">here</a>. It uploaded perfectly and I wired 4x AA pack to the battery terminals making sure to observe polarity.</p> <p>I then attached two DC motors to the ML and MR pins just like it said in the picture. I turned the board on, making sure the switch was set to on also.</p> <p>The red light lighted up and the blue light flickered for a second. The motors did not move. I tried different motors. To check if it was a corrupt bootloader I tried to upload the hello world blink sketch. That worked perfectly. </p> <p>I got my multi-meter out and tested the wires I was using...all good! Tested the battery...6.31v! That's within specs. I have the jumpers correctly inserted on the D7 - 10 pins. Here's my setup: <a href="https://i.stack.imgur.com/Q5tGn.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Q5tGn.png" alt="http://blog.dawnrobotics.co.uk/wp-content/uploads/2013/11/circuit_diagram.png"></a></p> <p>What in the world could be wrong? The code is supposed to make it turn in a rough square. I checked it over and over and it looks right. Any ideas?</p>
<p>Switching the selector did not help. I received a new one which worked perfectly following the steps from before. Apparently the issue was hardware related, possibly a cold solder joint preventing the motor driver section to work while still letting everything else continue normally.</p>
16365
|attiny|rotary-encoder|
Reading from a KY-040 rotary encoder with Digispark
2015-09-27T17:49:04.570
<p>I have a rotary encoder KY-040 connected to a Digispark like this: </p> <p><a href="https://i.stack.imgur.com/rJiAQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rJiAQ.png" alt="enter image description here"></a></p> <p>CLK go to p0 and and DT go to p2, SW is disconnected for now (it's just a button).</p> <p>I did everything like the instructions here: <a href="http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/" rel="nofollow noreferrer">http://henrysbench.capnfatz.com/henrys-bench/keyes-ky-040-arduino-rotary-encoder-user-manual/</a></p> <pre><code>#include &lt;DigiKeyboard.h&gt; int pinA = 0; // Connected to CLK on KY-040 int pinB = 2; // Connected to DT on KY-040 int encoderPosCount = 0; int pinALast; int aVal; boolean bCW; void setup() { pinMode (pinA,INPUT); pinMode (pinB,INPUT); /* Read Pin A Whatever state it's in will reflect the last position */ pinALast = digitalRead(pinA); Serial.begin (9600); } void loop() { aVal = digitalRead(pinA); if (aVal != pinALast){ // Means the knob is rotating // if the knob is rotating, we need to determine direction // We do that by reading pin B. if (digitalRead(pinB) != aVal) { // Means pin A Changed first - We're Rotating Clockwise encoderPosCount ++; bCW = true; } else {// Otherwise B changed first and we're moving CCW bCW = false; encoderPosCount--; } Serial.println("Rotated: "); if (bCW){ //Serial.println ("clockwise"); DigiKeyboard.sendKeyStroke(KEY_V); //or DigiKeyboard.write("1"); }else{ //Serial.println("counterclockwise"); DigiKeyboard.println("cc"); } Serial.print("Encoder Position: "); Serial.println(encoderPosCount); } pinALast = aVal; } </code></pre> <p>I only changed the pin numbers in the code and the <code>Serial.println (...</code> to any of the following:</p> <pre><code>DigiKeyboard.write("1"); DigiKeyboard.println("1"); DigiKeyboard.sendKeyStroke(KEY_V); </code></pre> <p>All of them didn't do anything when rotating the knob... </p> <p>Any ideas? Maybe the 10K resistors are too much?</p>
<p>Shown below is a KY-040 test program that in my tests doesn't lose any counts and is more accurate than some other software; it picks up the counts between detents as well as those at detents. You may be able to adapt it to your DigiKeyboard ATtiny system.</p> <pre><code>/* roto_jw4.ino -- JW, 29 September 2015 -- * A 4-state state-machine implementation of rotary * encoding for KY-040 rotary knobs. The state-machine picture at * https://e2e.ti.com/support/microcontrollers/hercules/f/312/t/318762 * in a Feb 4, 2014 7:40 PM post by Anthony Seely shows counts * increasing on transitions 10 -&gt; 11 -&gt; 01 -&gt; 00 -&gt; 10 and * decreasing on transitions the other way. Transitions between 00 * and 11 or 10 and 01 are invalid. This code detects valid * transitions by (abOld xor abNew) equaling 1 or 2. It detects * up-count events by the tri-bit value ABA' (where A' is the new * reading on pin A) being equal to 1, 2, 5, or 6 (a bit mask of * 0x66), and down-count events by ABA' being equal to 0, 3, 4, or 7 * (a bit mask of 0x99). * * On a KY-040 unit I tested, there are 30 detent positions per turn. * With this unit the code generates 60 counts per turn, which can be * seen individually as one turns the rotor slowly. Odd counts * appear between detents, even counts at detents. * * Set quadrature-signal pin numbers, via PinA and PinB constants. * Set IPINMODE to INPUT_PULLUP if there are no external pull-ups * on encoder AB pins, else set IPINMODE to INPUT */ enum { PinA=2, PinB=3, IPINMODE=INPUT }; static byte abOld; // Initialize state volatile int count; // current rotary count int old_count; // old rotary count void setup() { pinMode(PinA, IPINMODE); pinMode(PinB, IPINMODE); attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts attachInterrupt(1, pinChangeISR, CHANGE); abOld = count = old_count = 0; Serial.begin(115200); Serial.println("Starting Rotary Encoder Test"); } // On interrupt, read input pins, compute new state, and adjust count void pinChangeISR() { enum { upMask = 0x66, downMask = 0x99 }; byte abNew = (digitalRead(PinA) &lt;&lt; 1) | digitalRead(PinB); byte criterion = abNew^abOld; if (criterion==1 || criterion==2) { if (upMask &amp; (1 &lt;&lt; (2*abOld + abNew/2))) count++; else count--; // upMask = ~downMask } abOld = abNew; // Save new state } void loop() { if (old_count != count) { Serial.print(millis()); Serial.print(" "); Serial.println(count); old_count = count; } } </code></pre> <p>Since some ATtiny's only have one external-interrupt pin, it may be necessary to use two pin-change interrupts instead of two external-interrupt pins. (Six of the pins on an ATtiny45, for example, support pin-change interrupts, and only one is an external-interrupt pin.) Change PinA and PinB to appropriate pin numbers, and replace</p> <pre><code> attachInterrupt(0, pinChangeISR, CHANGE); // Set up pin-change interrupts attachInterrupt(1, pinChangeISR, CHANGE); </code></pre> <p>with </p> <pre><code> enableInterrupt(PinA, pinChangeISR, CHANGE); // Set up pin-change interrupts enableInterrupt(PinB, pinChangeISR, CHANGE); </code></pre> <p>and add the following <code>#include</code> near the beginning:</p> <pre><code>#include &lt;EnableInterrupt.h&gt; </code></pre> <p>To install the .h file for use via the Arduino IDE, unpack an <code>EnableInterrupt</code> zip file (for example, <code>enableinterrupt-0.8.2.zip</code> from <a href="https://bintray.com/greygnome/generic/EnableInterrupt/view#files" rel="nofollow">bintray.com/greygnome</a>) in the directory <code>~/sketchbook/libraries</code>. I think the package works with ATtiny's as well as more-standard Arduinos.</p>
16369
|programming|
RGBs, photoresistors, and delays
2015-09-28T03:10:26.707
<p>I am having a little trouble with a program of mine. My circuit consists of (mainly) an arduino UNO, two RGB LEDs, and a photoresistor. My current code(programmed in c#) operates the hardware as so: When the lights in the room are on, the two LEDs alternate blue/off once per second in a loop. When the lights are off, or the photoresistor is not sensing any light, both LEDs turn on, and stay on, red. My code:</p> <pre><code>int prPin = A0; void setup() { pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(prPin,INPUT); Serial.begin(9600); } void loop() { int prVal = analogRead(prPin); Serial.write(prVal); if(prVal&gt;450) { digitalWrite(5,HIGH); digitalWrite(6,HIGH); digitalWrite(7,HIGH); digitalWrite(8,LOW); digitalWrite(9,HIGH); digitalWrite(10,HIGH); delay(1000); digitalWrite(5,LOW); digitalWrite(6,HIGH); digitalWrite(7,HIGH); digitalWrite(8,HIGH); digitalWrite(9,HIGH); digitalWrite(10,HIGH); delay(1000); } else { digitalWrite(5,HIGH); digitalWrite(6,HIGH); digitalWrite(7,LOW); digitalWrite(8,HIGH); digitalWrite(9,HIGH); digitalWrite(10,LOW); delay(10); } } </code></pre> <p>The problem I am having is when the lights turn off, the LEDs will not operate according to the "else" statement/loop until it finishes going through the "if" statement/loop. Any suggestions or answers are appreciated. I'm an open book, so I'll take anything you guys give me.</p>
<p>Instead of the two delays of one second, have the program check if the current time is an even or odd number of seconds.</p> <pre><code>int prPin = A0; void setup() { pinMode(5,OUTPUT); pinMode(6,OUTPUT); pinMode(7,OUTPUT); pinMode(8,OUTPUT); pinMode(9,OUTPUT); pinMode(10,OUTPUT); pinMode(prPin,INPUT); Serial.begin(9600); } void loop() { int prVal = analogRead(prPin); Serial.write(prVal); if(prVal&gt;450) { if( (millis()/1000)%2 == 0 ) // check if even or odd number of seconds have passes since the program started { digitalWrite(5,HIGH); digitalWrite(6,HIGH); digitalWrite(7,HIGH); digitalWrite(8,LOW); digitalWrite(9,HIGH); digitalWrite(10,HIGH); } else { digitalWrite(5,LOW); digitalWrite(6,HIGH); digitalWrite(7,HIGH); digitalWrite(8,HIGH); digitalWrite(9,HIGH); digitalWrite(10,HIGH); } } else { digitalWrite(5,HIGH); digitalWrite(6,HIGH); digitalWrite(7,LOW); digitalWrite(8,HIGH); digitalWrite(9,HIGH); digitalWrite(10,LOW); delay(10); } } </code></pre>
16370
|arduino-uno|programming|c++|analogread|
Identical statements, different outcome
2015-09-28T03:58:58.197
<p>First a little background on me and my project. Most of my programming experience is with PHP and javascript. I have just recently started looking at C and C++ for this Arduino project. My project is a weather station that feeds its data to a web based database in real time. I will be writing the code for a web site that will access this data base and present the data in realtime. I am currently working on the temperature section of my weather station. It is an RTD coupled to a constant current circuit and feeds a varying voltage to analog pin 5 on my Arduino Uno. My problem is with the code. I have a working code but I decided to make it object oriented so that I could reuse it in other projects. Here is the code that works.</p> <pre><code>const unsigned int RTD_PIN = A5; const float MVOLTS_CTS = 4.882813; const float OHMS_DEGREE = 0.3851; const unsigned int SAMPLES = 10; const float MILLI_AMPS = 19.125; unsigned long currentMillis; unsigned long oldMillis = 0; unsigned long timeBetweenSamples = 1000; // milliseconds between samples int measurement[SAMPLES]; int read_index = 0; int total = 0; int average_cts = 0; boolean initialized = false; float degC = 0; float degF = 0; void setup() { Serial.begin(9600); for (int i = 0; i &lt; SAMPLES; i++) { measurement[i] = 0; } } void loop() { // Reset the counter when we go over the // set number of samples if (read_index &gt;= SAMPLES) { read_index = 0; initialized = true; } // only take a measurement if one second has passed currentMillis = millis(); if (currentMillis - oldMillis &gt;= timeBetweenSamples) { // subtract one element from the total total = total - measurement[read_index]; // take a measurement measurement[read_index] = analogRead(RTD_PIN); // add the new measurement back into the total total = total + measurement[read_index]; // take an average of the readings average_cts = total / SAMPLES; // calculate degrees degC = (average_cts * MVOLTS_CTS / MILLI_AMPS -100) / OHMS_DEGREE; degF = degC * 1.8 + 32; // print results only if all elements of measurement[] are filled if (initialized) { Serial.print(degC); Serial.print(" degrees C "); Serial.print(degF); Serial.print(" degrees F "); Serial.println(average_cts); } read_index++; oldMillis = currentMillis; } } </code></pre> <p>And this is the code that doesn't work.</p> <pre><code>#include "Arduino.h" #include "Sensor.h" Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long sampleRate) { sensorPin = analogPin; samples = numSamplesInAverage; _sampleRate = sampleRate; int measurement[samples]; // initialize the measurement array for (int i = 0; i &gt;= samples; i++) { measurement[i] = 0; } } int Sensor::update() { if (read_index &gt;= samples) { read_index = 0; } // only take a measurement if sample rate has been exceeded // and return a rolling average currentMillis = millis(); if (currentMillis - oldMillis &gt;= _sampleRate) { //subtract one element from the total total = total - measurement[read_index]; // take a measurement measurement[read_index] = analogRead(sensorPin); // add the new measurement into the total total = total + measurement[read_index]; // take an average of the readings average_cts = total / samples; // increment the read_index read_index++; oldMillis = currentMillis; return average_cts; } // return false if the sample rate has not expired return false; } </code></pre> <p>It seems like the issue is with this one line of code on line 34.</p> <pre><code>measurement[read_index] = analogRead(sensorPin); </code></pre> <p>When this line has not been remarked out the read_index only goes to 4 before it resets to 0 and it does it at the rate of program execution instead of every second like expected.</p> <p>If this line is remarked out the the read_index is incremented from 0 to 9 once every second as expected.</p> <p>Here is where the read_index is defined.</p> <pre><code>#ifndef Sensor_h #define Sensor_h #include "Arduino.h" class Sensor { public: Sensor(int analogPin, int numSamplesInAverage, unsigned long sampleRate); int update(); private: unsigned int sensorPin; unsigned long currentMillis; unsigned long oldMillis; unsigned long sampleRate; // milliseconds between samples int read_index = 0; int total = 0; int average_cts = 0; int samples; unsigned long _sampleRate; int measurement[]; }; #endif </code></pre> <p>and this is the Arduino sketch that calls update()</p> <pre><code>#include &lt;Sensor.h&gt; Sensor rtd(4, 10, 1000); // instantiate a Sensor object int cts; void setup() { Serial.begin(9600); } void loop() { rtd.update(); Serial.println(rtd.read_index); } </code></pre> <p>can anyone tell me why this works in my procedural code but not the objected oriented code?</p>
<p>I was going to add to Majenko's excellent answer, but what I want to say is too long. :)</p> <hr> <p>Change:</p> <pre><code>int measurement[]; </code></pre> <p>to:</p> <pre><code>int * measurement; </code></pre> <p>and then in the constructor do: </p> <pre><code>measurement = new int [samples]; </code></pre> <p>And check that measurement is not NULL, in case there is not enough memory.</p> <hr> <p>Also, this is wrong in two ways:</p> <pre><code>// initialize the measurement array for (int i = 0; i &gt;= samples; i++) { measurement[i] = 0; </code></pre> <p>It should be:</p> <pre><code>// initialize the measurement array for (int i = 0; i &lt; samples; i++) { measurement[i] = 0; </code></pre> <p>You need to test less than, and you don't test equals (that would initialize one too many).</p> <hr> <p>You should also have a destructor that frees the memory, ie.</p> <pre><code>delete [] measurement; </code></pre> <hr> <blockquote> <p>When would this destructor come into play? How and when should I call it?</p> </blockquote> <p>The destructor is automatically called when an instance of the class is destroyed. This is when you do things like free memory you allocated. You don't call it directly.</p> <p>An example:</p> <pre><code>class Sensor { public: // constructor Sensor(int analogPin, int numSamplesInAverage, unsigned long mysampleRate); // destructor ~Sensor (); // call to update samples int update(); private: unsigned int sensorPin; unsigned long currentMillis; unsigned long oldMillis; unsigned long sampleRate; // milliseconds between samples int read_index; int total; int average_cts; int samples; int * measurement; }; Sensor::Sensor (int analogPin, int numSamplesInAverage, unsigned long mysampleRate) { sensorPin = analogPin; samples = numSamplesInAverage; sampleRate = mysampleRate; read_index = 0; total = 0; average_cts = 0; measurement = new int [samples]; if (measurement == NULL) exit (1); // can't continue // initialize the measurement array for (int i = 0; i &lt; samples; i++) { measurement[i] = 0; } } // end of constructor // destructor Sensor::~Sensor () { delete [] measurement; } // end of destructor </code></pre> <hr> <blockquote> <p>Can you please explain how these two line of code work <code>int * measurement</code> and <code>measurement = new int [samples];</code></p> </blockquote> <p><code>int * measurement</code> creates a pointer to an int (called <code>measurement</code>). However pointers can also point to the start of an array (or indeed, to the middle of an array) of ints. So this variable will hold the start of your array of ints.</p> <p><code>measurement = new int [samples];</code> allocates the memory for this array - in this case "samples" lots of ints.</p> <p>Once the memory is allocated you can treat the pointer as an array, eg.</p> <pre><code>measurement [5] = 42; </code></pre> <p>For more detail about this see <a href="http://c-faq.com/aryptr/aryptrequiv.html" rel="nofollow">So what is meant by the "equivalence of pointers and arrays" in C?</a> and also Google: <code>pointer vs array</code>.</p> <p>Also Google: <code>new</code> and <code>delete</code> with reference to the C++ language.</p>
16371
|arduino-uno|sensors|c|accelerometer|
Interrupt not firing on motion
2015-09-28T05:55:16.683
<p>I'm trying to get <a href="http://www.freescale.com/files/sensors/doc/data_sheet/MMA8452Q.pdf" rel="nofollow">MMA8452Q</a> to trigger an interrupt when motion is detected and wonder if I'm missing something very obvious here.</p> <p>So I setup CTRL_REG4 to 0x0B with</p> <pre><code>void MMA8452Q::setupISR() { writeRegister(CTRL_REG4, 0x0B); } </code></pre> <p>then I setup FF_MT with</p> <pre><code>void MMA8452Q::setupFF_MT() { writeRegister(FF_MT_CFG, 0xF8); writeRegister(FF_MT_THS, 0x0F); writeRegister(FF_MT_COUNT, 0x00); } </code></pre> <p>and I read ISR with</p> <pre><code>#define SRC_PULSE 2 #define SRC_FF_MT 1 byte MMA8452Q::readISR() { byte intStat = readRegister(INT_SOURCE); if (intStat &amp; 0x0B) { readRegister(FF_MT_SRC); return intStat &amp; 0x0B; } else return 0; } void printISR() { byte isr = (accel.readISR() &gt;&gt; 2); if (isr &amp; SRC_PULSE) Serial.print("(ISR) Tap"); else Serial.print("(ISR) No Tap"); Serial.print("\t"); if (isr &amp; SRC_FF_MT) Serial.print("(ISR) Motion"); else Serial.print("(ISR) No Motion"); Serial.print("\t"); } </code></pre> <p>AFAIK, that should already have FF/MT interrupt enabled. Even when I'm getting readings in <code>FF_MT_SRC</code>, I'm not picking up an interrupt in <code>INT_SOURCE</code>.</p> <p>Interrupts are fired on (most) taps, but not on motion at all.</p> <p>Am I missing something here?</p> <p>Thanks</p>
<p>Here's an extract from page 39 of MMA8452Q-rev8.1.pdf, the MMA8452 spec sheet:</p> <p><a href="https://i.stack.imgur.com/4kWQL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4kWQL.jpg" alt="interrupt enable bits"></a></p> <p>Rather than saying <code>writeRegister(CTRL_REG4, 0x0B);</code> in <code>MMA8452Q::setupISR()</code>, try <code>writeRegister(CTRL_REG4, 0xD);</code>. </p> <p>0xB is 1011 in binary, while 0xD is 1101, which turns on INT_EN_FF_MT to enable freefall/motion interrupts.</p> <p>The above should answer your question as asked. The following expands on my earlier comment which said</p> <blockquote> <p>Absent other info, it looks like MMA8452Q::readISR() is not an interrupt processing routine, but instead a routine that polls an interrupt-source register to find out what source would have triggered an interrupt if correctly wired and initialized.</p> </blockquote> <p>"Interrupt" as used in your question (and code) refers to when the MMA8452 signals (via an I1 or I2 output line) that an interrupt-worthy condition has occurred.</p> <p>"Interrupt" as in the question does not refer to an interrupt from the Uno's point of view, because (per diagram) neither of I1 or I2 connects to the Uno.</p> <p>If speed of response becomes important, you may wish to hook I1 or I2 to one of the Uno's Digital Pins With Interrupts, ie pin 2 or 3, as noted in the <a href="https://www.arduino.cc/en/Reference/AttachInterrupt" rel="nofollow noreferrer">AttachInterrupt</a> page at arduino.cc. Then you'd replace the polling loop that now periodically reads the MMA8452's ISR (interrupt status register) to check for set bits, with an interrupt service routine which would set a flag to cause loop() to use Wire.read to get ISR data.</p>
16376
|arduino-uno|
Sketch will not start with external power source
2015-09-28T12:35:37.710
<p>NOOB Question: when my Uno is connected to an external power source it will not start running the uploaded sketch. The Arduino web site says it's because the RX pin is not connected and then gets random data.</p> <p>The site suggests grounding the RX pin using a resistor (granted it suggests a 10K and I used a smaller one ) or connecting it to the TX pin. </p> <p>From <a href="https://www.arduino.cc/en/Guide/Troubleshooting#toc19" rel="nofollow">Why doesn't my sketch start when I power up or reset the Arduino board?</a></p> <blockquote> <p>Most likely because you are sending serial data to the board when it firsts turns on. During the first few seconds, the bootloader (a program pre-burned onto the chip on the board) listens for the computer to send it a new sketch to be uploaded to the board. After a few seconds without communication, the bootloader will time out and start the sketch that's already on the board. If you continue to send data to the bootloader, it will never time out and your sketch will never start. You'll either need to find a way to stop serial data from arriving for the first few seconds when the board powers (e.g. by enabling the chip that sends the data from within your setup() function) or burn your sketch onto the board with an external programmer, replacing the bootloader.</p> </blockquote> <p>From <a href="https://www.arduino.cc/en/Guide/Troubleshooting#toc6" rel="nofollow">Why doesn't my sketch start when I'm powering the board with an external power supply? (Arduino Diecimila or earlier)</a></p> <blockquote> <p>Because the RX pin is unconnected, the bootloader on the board may be seeing garbage data coming in, meaning that it never times out and starts your sketch. Try tying the RX pin to ground with a 10K resistor (or connecting RX directly to the TX pin).</p> </blockquote> <p>Both failed for me. </p> <p>What should I do?</p>
<p>I will add my little drop of experience here... So I am using a display tm1637, having CLK in 6 and DIO in 5. When connecting the Battery (12V 3s lipo 4000mA) to Vin, the arduino will freeze, even connected to the USB, will still freeze.</p> <p>Short version, Moving DIO from 5 to 7 corrected the problem, now i have my device running from USB and or battery with no problem.</p> <p>Long version: after 3 hours of trying different mods, including resistor to RX,TX, to GND, even removing the ch340 chip and connecting Rts and others to GND/VCC.. Nothing, so i decided to move the different devices from One nano to Other but testing after each connection. When the display was connected, the Nano will freeze while running on battery power. So... i moved DIO first to a different pin, and the device started working. I know is a very particular case, but one more thing to try if you are like me, stock without knowing what to do.... moving some pins (maybe skipping 5?)...</p>
16379
|arduino-uno|hardware|gps|
Connect GPS module with GPS antenna SIM39EA to Arduino Uno
2015-09-28T15:50:04.737
<p>I bought a GPS module with GPS antenna SIM39EA online.</p> <p>The manual for the GPS module is here:</p> <p><a href="http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf" rel="nofollow noreferrer">http://www.vis-plus.ee/pdf/SIM39EA_Hardware_Design_V1.00.pdf</a></p> <p>I have an Arduino board. It has 3 ground pin, one Vcc and two input/output pin.</p> <p>I want to know how can I connect this module to Arduino GPS module and get GPS coordinates?</p>
<p>Your data comes back via the GPS's UART port.<br> Use the softserial library to create a second serial port on your Arduino (means you can still use the normal serial to read the console).</p> <p>Then write a program that sucks data from the GPS and squirts it out of the Arduino serial port back to your PC using printf.</p> <p>I only had a quick flick through and didn't see the default serial speed, so start with 9600 and experiment.</p> <p>What should come out is probably a line of comma separated values which is in NEMA format. Google for the specification and you will be able to find out the bits of interest.</p> <p>Hope that helps.</p>
16383
|usb|
How to make an Arduino USB programming circuit?
2015-09-28T06:41:24.407
<p>I am designing a PCB in which I am using the MCU used in <strong><code>Arduino UNO</code></strong> which is <strong><code>Atmega328P</code></strong> and some other components as per my project requirements. I have almost designed the circuit but I am confused with the USB programming part. I want my MCU to be programmed using <strong><code>USB B Type</code></strong> just like we do it in <strong><code>Arduino UNO</code></strong>. My friend suggests me to purchase an <strong><code>Arduino UNO</code></strong> device and program that MCU and then put it in my circuit. But I don't want to do it like this. I have found the <a href="https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf" rel="nofollow"><strong>schematic design</strong></a> but its very confusing. Can anyone help me out with this.? </p>
<p>If you wanted a more permanent option on the board, you could also add a USB to FTDI chip like this: <a href="http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI%2fFT232RL-REEL%2f&amp;qs=D1%2fPMqvA103RC6OU6bKtoA%3d%3d&amp;gclid=CNmDjr7dvssCFYZefgod9jgPeQ" rel="nofollow">http://www.mouser.com/Search/m_ProductDetail.aspx?FTDI%2fFT232RL-REEL%2f&amp;qs=D1%2fPMqvA103RC6OU6bKtoA%3d%3d&amp;gclid=CNmDjr7dvssCFYZefgod9jgPeQ</a> </p>
16390
|c++|wireless|project-critique|
Basic Serial Transmission Protocol
2015-09-28T22:39:11.607
<p>I have a small piece of code here that I hope to run on Arduino. Basically what this code is doing is, it takes a nibble from the user, appends a <code>startbit</code> to it, and transmits the code through a transmitter module. The receiver end receives the bits and checks if <code>startbit</code> is being received. If <code>startbit</code> is not being received, then it prints out whatever was transmitted. If <code>startbit</code> is received, then it doesn't print the startbit, just the nibble all in one line.</p> <p>My question is: is it convention/clever to use the bool array or should I not do that? Second, is there a way to make my code more efficient? Where can I clean it up? Also, is my code legible or very convoluted? </p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;WirelessComm.h&gt; int tx_pin; int rx_pin; WirelessComm::WirelessComm(int rxPin, int txPin) { pinMode(rxPin, INPUT); tx_pin = txPin; rx_pin = rxPin; } int countDigit(long n) { int count = 0; while (n &gt; 0) { n /= 10; count++; } return count; } void getDigit(bool *data, long num) { int cd = countDigit(num); long shift = 1; for (int i = 0; i &lt; cd; i++) { data[i] = (num / shift) % 10; shift *= 10; } } int WirelessComm::writeTx(long nibble) { int i; bool data[11]; // warning: I didn't check for buffer overrun! int32_t startBit = 110101L; // larger than 32767, so cannot be in int if(nibble != 0) { int sbLen = countDigit(startBit); for (int i = 0; i &lt; (int)(sizeof(data) / sizeof(data[0])); i++) data[i] = 0; getDigit(data, startBit); getDigit(data + sbLen, nibble); } else return -1; for(i = 0; i &lt; 10; i++) { if(data[i] == 1) { digitalWrite(tx_pin, HIGH); } else { digitalWrite(tx_pin, LOW); } } return 1; } int WirelessComm::readRx(long nibble) { bool first = 0; bool second = 2; //initially set to some random value bool third = 2; bool fourth = 2; bool fifth = 2; bool sixth = 2; bool counter = 0; bool val = 0; while(true) { first = digitalRead(rx_pin); if(first == 1); { second = digitalRead(rx_pin); if(second == 1) { third = digitalRead(rx_pin); if(third == 0) { fourth = digitalRead(rx_pin); if(fourth == 1) { fifth = digitalRead(rx_pin); if(fifth == 0) { sixth = digitalRead(rx_pin); if(sixth == 1) { while(counter &lt; 4) { val = digitalRead(rx_pin); Serial.print(val); counter++; } Serial.println(); } else Serial.println(first); first = digitalRead(rx_pin); } else Serial.println(first); first = digitalRead(rx_pin); } else Serial.println(first); first = digitalRead(rx_pin); } else Serial.println(first); first = digitalRead(rx_pin); } else Serial.println(first); first = digitalRead(rx_pin); } else Serial.println(first); first = digitalRead(rx_pin); } } </code></pre>
<blockquote> <p>So to clarify, SoftwareSerial uses bit-bang? How are you able to tell? </p> </blockquote> <p>By reading the code. For example, this is how it reads 8 bits. It does a delay (which you don't) for the exact amount of time, and then reads the pin, and "ors" it into the variable which is the assembled byte.</p> <pre class="lang-C++ prettyprint-override"><code>// Read each of the 8 bits for (uint8_t i=0x1; i; i &lt;&lt;= 1) { tunedDelay(_rx_delay_intrabit); DebugPulse(_DEBUG_PIN2, 1); uint8_t noti = ~i; if (rx_pin_read()) d |= i; else // else clause added to ensure function timing is ~balanced d &amp;= noti; } </code></pre> <hr> <p>And to write the 8 bits:</p> <pre class="lang-C++ prettyprint-override"><code>// Write each of the 8 bits for (byte mask = 0x01; mask; mask &lt;&lt;= 1) { if (b &amp; mask) // choose bit tx_pin_write(HIGH); // send 1 else tx_pin_write(LOW); // send 0 tunedDelay(_tx_delay); } </code></pre> <hr> <p>Your rather elaborate nested <code>if</code> just seems complete overkill, when you see how SoftwareSerial does it in half a dozen lines.</p> <hr> <p>Another typo:</p> <pre class="lang-C++ prettyprint-override"><code>if(first == 1); </code></pre> <p>You don't want that semicolon.</p> <hr> <blockquote> <p>Second, is there a way to make my code more efficient?</p> </blockquote> <p>Use loops, like SoftwareSerial does.</p> <blockquote> <p>Also, is my code legible or very convoluted? </p> </blockquote> <p>Very convoluted.</p> <blockquote> <p>Where can I clean it up?</p> </blockquote> <p>I suggest you browse through the SoftwareSerial library for ideas.</p> <p>Meanwhile, HardwareSerial is available, so you don't need to write any of this. For that matter, SoftwareSerial is available too. If you are just doing it to learn, well and good.</p> <hr> <p>You really should read about loops. Whenever I have to do something 8 times I have a loop of 8 (or even for "x" times, a loop of "x"). Unrolling into 8 different variables is just confusing and prone to errors. As you had, before you fixed it, doing <code>if(fourth = 1)</code> instead of <code>if(fourth == 1)</code>.</p>
16392
|arduino-ide|arduino-leonardo|analogread|arduino-pro-micro|
Arduino Pro Micro Analog Pinouts
2015-09-29T05:00:53.473
<p>I have the Arduino Pro Micro and I would like to use all the <strong>analog</strong> pins that I can on it.</p> <p>It currently looks like it has a total of <strong>9 Analog pins</strong> that can be used. <a href="https://i.stack.imgur.com/SEiwb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SEiwb.png" alt="enter image description here"></a></p> <p>A0, A1, A2, A3, A6, A7, A8, A9 and A10.</p> <p>However, I am unsure how to call these pins since all of those are also <strong>digital pins</strong>.</p> <p>Would A0-A3 be defined as:</p> <pre><code>#define analog1 A0; #define analog2 A1; #define analog3 A2; #define analog4 A3; </code></pre> <p>While the other pins would be this?:</p> <pre><code>#define analog5 4; #define analog6 6; #define analog7 8; #define analog8 9; #define analog9 10; </code></pre> <p>Then just call:</p> <pre><code>analogRead(analog1); analogRead(analog2); ..... analogRead(analog8); analogRead(analog10); </code></pre> <p>Would that be the correct way of defining the 9 analog pins?</p>
<p>Assuming you have the <a href="https://github.com/sparkfun/SF32u4_boards" rel="nofollow">Pro Micro core</a>, they are called A0, A1, A2, A3, A6, A7, A8, A9 and A10. There is no need to "special case" the others, since the pins are known as both.</p>
16393
|communication|softwareserial|
How to fix baud rate when hardware capacity has a low limit?
2015-09-29T05:37:53.947
<p>I have a transmitter(simple <a href="http://www.ebay.com/itm/433Mhz-RF-transmitter-and-receiver-kit-for-Arduino-ARM-MCU-WL-/261041100836" rel="nofollow">433 MHz transmitter</a>) connected via digital pins on the Arduino. The receiver is connected to another arduino. Now, I kept that pin on HIGH for 1 second, and it transmits only 1000 ones. But I've seen different example transmitter sketches having baud rates of 1200, 9600, etc. So the situation is, when the transmitter is transmitting at maximum capacity(just HIGH for a whole second), it can only transmit 1000 ones. </p> <p>I am able to read that it only transmits 1000 ones because my receiver just has a simple read function that reads and prints the data. and it prints 1000 ones every second. Give or take one or two. So when you specify a baud rate of 1200, is it useless? how will it transmit 1200 bits/sec? Does the baud rate actually increase the hardware limit or what exactly is going on? Can someone please provide me some insight into this? I'd be glad to clarify this question more if need be. </p>
<p>The transmitter you're using is very basic, and only transmits "on" and "off". As such it is <em>protocol-agnostic</em>. In order to use it effectively we use it with a protocol that uses "on" and "off" as its signalling, but also includes framing information so that we can know when the data flow starts and stops.</p> <p>One such protocol is the UART protocol consisting of 1 start bit, 5 to 9 data bits, an even, odd, or no parity bit, and 1, 1.5, or 2 stop bits, all being generated at a specific rate. This rate is the "baud rate", and must match in both the sending device's and the receiving device's UART in order for them to communicate. This is true whether the devices are connected by a wire, an optical link, or a radio link.</p> <p>The TX and RX pins on an Arduino are connected to a hardware UART which will handle the framing and signal generation for you. The hardware UART(s) can be accessed via <a href="https://www.arduino.cc/en/reference/serial" rel="nofollow"><code>Serial</code></a> on non-USB-native Arduinos as well as <code>Serial1</code>, <code>Serial2</code>, and <code>Serial3</code> on Arduinos where they are present.</p> <p>Additionally, <a href="https://www.arduino.cc/en/Reference/SoftwareSerial" rel="nofollow"><code>SoftwareSerial</code></a> can be used to generate a UART signal on arbitrary pins in software, but you're almost always better off using a hardware UART when possible.</p>
16400
|arduino-galileo|
Enternal Analog Reference mode not compiling in Arduino + Intel Galileo Gen 2
2015-09-29T07:59:49.610
<p>I am trying to use external voltage reference in Intel Galileo gen 2 operating in Arduino mode. </p> <p>So I created a setup code like this:</p> <pre><code>void setup() { // We'll send debugging information via the Serial monitor Serial.begin(9600); // If you want to set the aref to something other than 5v analogReference(EXTERNAL); // use AREF for reference voltage } </code></pre> <p>I selected the board as Intel Galileo Gen 2 in Tools option. When I compiled I am getting the following error:</p> <pre><code>LM35_temp_sensor.ino:21:19: error: 'EXTERNAL' was not declared in this scope </code></pre> <p>But when I change the board to Arduino Uno in Tools option, the program in compiling fine.</p> <p>This means that Intel Galileo Gen 2 does not support external analog voltage reference?</p>
<p>There is no such thing as an external analog reference on the Galileo. If you look at the block diagram that is on the Galiley Arduino.cc page you can clearly see that the Aref pin goes nowhere:</p> <p><a href="https://i.stack.imgur.com/lwFWt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lwFWt.png" alt="enter image description here"></a></p> <p>So no, it won't support the EXTERNAL analog reference function.</p>
16402
|remote-control|
Detect closed shutter
2015-09-29T09:00:36.320
<p>I want to controll some ambient lights in my living room.</p> <p>Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.</p> <p>The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.</p> <p>Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.</p> <p>A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.</p> <p>Edit: What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...</p>
<p>I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1). There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm. (If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)</p>
16422
|project|
Arduino "piston" device
2015-09-30T01:09:28.530
<p>Is there any compact piston-like devices on the market that can apply pressure safely various parts of the head? I can further expound if needed. </p> <p>The ideal size would be something within the 1-2 inch length range </p>
<p>It sounds like this is nothing to do with an Arduino, just a general Electrical/Mechanical engineering question that you want to control from and Arduino. I think you wan a device that when signalled by your Arduino can extend itself by up to 2 inches.</p> <p>If that is right then I think what you are looking for is a Linear Actuator. There are plenty out there and some do handle the small stroke you want, but most of them appear to be 9 to 12V. This means you would require a Darlington transistor or relay to control them from an Arduino.</p> <p>If you require an extremely precise stoke length then I would recommend a stepper motor with a screw axel. This would allow you much finer control over how far you pushed, but it would impose limits on what you could do and how it could be mounted.</p> <ul> <li>Can you provide more details on what you want to move? </li> <li>List item</li> <li>Is it heavy? Do you need lots of Torque?</li> <li>Are you pushing straight or do you need to push in an arc (i.e. a door)? </li> <li>What voltage supplies do you have available? </li> <li>How fast do you want it to move? </li> <li>Do you want it to move exactly the same distance every time?</li> </ul> <p>The more info you can provide the better, but in answer to your original question Yes, it sounds like there might be so you plan is still on the rails.</p>
16435
|c++|string|
Split RGBW hex String into integers
2015-09-30T17:01:15.073
<p>I have a program where the Arduino receives hex Strings that represent a RGBW color (similar to css for example). My goal is to create that color by using pwm, so I need to convert that one hex string into four integer values between 0..255 to use for the pwm. Whats the best/easiest way to do this?</p> <p>Example:</p> <pre><code>void incomingMessage(const MyMessage &amp;message) { // h = hex value // message = e.g. (h) #112233AB redval = ?; // h11 =&gt; 17 greenval = ?; // h22 =&gt; 34 blueval = ?; // h33 = 51 whiteval = ?; //AB = 171 analogWrite(RED_PIN, redval); analogWrite(GREEN_PIN, greenval); analogWrite(BLUE_PIN, blueval); analogWrite(WHITE_PIN, whiteval); } </code></pre>
<p>I don't like using the String class because it can cause memory fragmentation. This would do it by just using C-style strings:</p> <pre><code>byte fromhex (const char * str) { char c = str [0] - '0'; if (c &gt; 9) c -= 7; int result = c; c = str [1] - '0'; if (c &gt; 9) c -= 7; return (result &lt;&lt; 4) | c; } void setup () { Serial.begin (115200); Serial.println (); const char * test = "#112233AB"; byte redval = fromhex (&amp; test [1]); byte greenval = fromhex (&amp; test [3]); byte blueval = fromhex (&amp; test [5]); byte whiteval = fromhex (&amp; test [7]); Serial.println ((int) redval); Serial.println ((int) greenval); Serial.println ((int) blueval); Serial.println ((int) whiteval); } // end of setup void loop () { // whatever } // end of loop </code></pre> <p>Output:</p> <pre><code>17 34 51 171 </code></pre> <p>That does not do any validation (that the string is indeed 9 characters long, and contain hex characters) but I'll leave that for you to do. :)</p>
16438
|arduino-uno|pins|reset|
When the Arduino is in reset mode are the digital pins high impedance?
2015-09-30T19:59:12.673
<p>I have an Arduino (Arduino A) hooked up to an external FRAM chip and I want to be able to pull the Arduino A's reset pin to ground to keep it in a constant reset state. Then I want to hook up another Arduino (Arduino B) up to the same lines going from Arduino A to the external FRAM chip and pull data off of the FRAM chip.</p> <p>I am worried that when I hook Arduino B to the lines running between the FRAM and Arduino A that it will damage Arduino A. If the digital pins are in a high impedance state while I do this though, then it should be fine. I can't find the necessary documentation to figure this out though.</p> <p>All Arduinos involved are Uno Rev 3s.</p> <p>Any help would be appreciated, thanks!</p>
<p>From the ATMEGAxx8 datasheet...</p> <blockquote> <p>11.1 Resetting the AVR</p> <p>... The I/O ports of the AVR are <strong>immediately</strong> reset to their initial state when a reset source goes active. This does not require any clock source to be running.</p> </blockquote> <p>(bold added)</p> <p>Looking over the register descriptions for the Data Direction Registers, all bits have an initial value of <code>0</code>, corresponding to high impedance input.</p> <p>...so it is safe to assume that all IO pins will be in a high impedance state a very short time after the <code>RESET</code> pin goes low.</p> <p>Caveats:</p> <ol> <li><p>The clamping diodes are in-circuit even when pins are in high impedance state, so current will flow if the voltage on the pin is higher than Vcc or lower than Ground (at least until the diode blows up!).</p> </li> <li><p>Some Arduino pins are connected to other things besides just the pin on the MPU. For example, digital pin 13 is connected to ground though a resistor and diode, so current will flow into it if you connect a voltage higher than the threshold for the diode. On the Uno there are also resistors on the RX and TX pins connected to the serial communications link, so current can flow there too.</p> </li> <li><p>The MISO pin can inadvertently become an output while <code>RESET</code> is held low if the Programming Enable command ($AC $53 xx yy) is transmitted over the MOSI &amp; SCK lines. This process is described in <a href="http://www.atmel.com/images/doc0943.pdf" rel="nofollow noreferrer">App Note AVR910</a>.</p> </li> </ol>
16441
|arduino-uno|programming|c++|sketch|
Help with Flappy Bird Sketch
2015-09-30T21:46:50.517
<p>I am compiling the sketch found <a href="https://github.com/huytd/arduino-flappybird" rel="nofollow">here</a>. I just downloaded the .ino and .h files and opened them, so I have not modded the code at all. I keep getting the following error.</p> <pre><code>In file included from flappyDuino.ino:7:0: Sprite.h:3: error: variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))' static unsigned char PROGMEM flappybird_frame_1[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x78, 0x8A, 0x84, 0x8A, 0x82, 0x42, 0x82, 0x3E, 0x44, 0x41,0x38, 0xBE, 0x20, 0x41, 0x18, 0x3E, 0x07, 0xC0 }; ^ In file included from flappyDuino.ino:7:0: Sprite.h:4: error: variable 'flappybird_frame_2' must be const in order to be put into read-only section by means of '__attribute__((progmem))' static unsigned char PROGMEM flappybird_frame_2[] = { 0x03, 0xF0, 0x0C, 0x48, 0x10, 0x84, 0x20, 0x8A, 0x40, 0x8A, 0x40, 0x42, 0x7C, 0x3E, 0x82, 0x41, 0x84, 0xBE, 0x88, 0x41, 0x78, 0x3E, 0x07, 0xC0 }; ^ Sprite.h:5: error: variable 'bar_bottom' must be const in order to be put into read-only section by means of '__attribute__((progmem))' static unsigned char PROGMEM bar_bottom[] = { 0xFF, 0xFF, 0xFF, 0x42, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E }; ^ Sprite.h:6: error: variable 'bar_top' must be const in order to be put into read-only section by means of '__attribute__((progmem))' static unsigned char PROGMEM bar_top[] = { 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x42, 0xFF, 0xFF, 0xFF }; ^ variable 'flappybird_frame_1' must be const in order to be put into read-only section by means of '__attribute__((progmem))' </code></pre> <p>I'd appreciate any help. </p>
<p>The arrays need to be tagged with the keyword <code>const</code>. It is possible that the original sketch was written using an earlier version of the IDE that you are using (or a later version?) and your version requires the <code>const</code> keyword whereas the author's doesn't.</p> <p>Basically any arrays that are <code>PROGMEM</code> need the word <code>const</code> adding to them. For instance, lines that start:</p> <pre><code>static unsigned char PROGMEM ... </code></pre> <p>need changing to:</p> <pre><code>static const unsigned char PROGMEM ... </code></pre>
16447
|arduino-mega|display|components|
Are there any ePaper modules that are bigger than 2.7 inches for arduino
2015-09-30T23:43:06.320
<p>I am looking for a large ePaper Display for the Arduino. The issue is is that I cannot seem to find one any larger than 4.5 inches in size. That will be compatible with arduino. Even with a controller board. </p> <p>Are there any companies that sell controller boards for these displays? Is there anyone who can manufacture these epd displays upon request?</p> <p>I am looking to take this project to a pcb board after I prototype it so do I need to build my own controller? If what parts would you need? Is it easy for a designer with intermediate capability? </p> <p>I can find all kinds of display like at <a href="http://www.pervasivedisplays.com/" rel="nofollow">pervasivedisplays.com</a> and <a href="http://mouser.com" rel="nofollow">Mouser.com</a></p> <p>The end goal is to create a Arduino based project that I can score skeet with to keep track of my average score. </p>
<p>I would suggest you to start the other way: find a sw stack that is known to work and check if any of the controllers/displays it already supports fits your needs. This is how I would do it.</p> <p><a href="http://ugfx.org/platforms" rel="nofollow">Here</a> is a starting point.</p>
16450
|power|hardware|arduino-pro-mini|system-design|electricity|
Powering arduino and 12V Fan from same supply
2015-10-01T10:42:19.457
<p>I have found a relatively small 12V switching power supply that I want to build into my device, using it to power both the Arduino Pro Mini and a couple of 12V cpu fans.</p> <p>Am I correct in assuming that I can have the Arduino RAW pin and Fan+ on the same power supply lead? Or do I need to protect the Raw pin in any way? Also, I need to power 2x cpu fans, can this be done with one transistor or do I need one for each fan?</p> <p>If I stay within the Current specs of my supply (6A) could I keep adding other 12V components on the same +lead as in the diagram below? <a href="https://i.stack.imgur.com/st4Or.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/st4Or.png" alt="enter image description here"></a></p>
<p>Sounds fine.</p> <p>You can connect the two fans in <strong>parallel</strong>, as long as they don't use more than 5A combined, as that is the maximum of the TIP120. Though you definitely need to attach a heatsink to the TIP120, if you are using a largish amount of current. Though in that case, I'd suggest using a MOSFET instead of a Darlington Transistor (TIP120), as MOSFETs don't heat up that much.</p> <p>The diode is not needed if you use the TIP120, as there is already a diode inside the package.</p> <p>Since you are using 12V as a power supply, the voltage regulator has to convert 7v into heat. Depending on the amount of current you use, this could result in the voltage regulator getting very hot. If you are only powering the ATMega328 and maybe some LEDs from the 5v line, you'll be fine. Just don't connect something like a 5v fan.</p>
16455
|sensors|temperature-sensor|
How can BMP180 measure a temperature too?
2015-10-01T15:02:35.490
<p>I got the following device</p> <p><a href="https://i.stack.imgur.com/HNSIF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HNSIF.png" alt="enter image description here"></a></p> <p>(sorry for imperfect focus)</p> <p>and found, that it can measure not only pressure, but also a temperature too. The code was taken from common sketches for Adafruit BMP085 and they were working. I checked, that temperature value rises if I touch sensor with finger.</p> <p>Simultaneously, on <a href="https://www.bosch-sensortec.com/en/homepage/products_3/environmental_sensors_1/bmp180_1/bmp180" rel="nofollow noreferrer">Bosch site for BMP180</a> I can't find any notes it can measure temperature, only pressure.</p> <p>How can it be?</p> <p>1) Bosch's BMP180 has undocumented feature to measure a temperature</p> <p>2) The device on picture has additional component to measure temperature</p> <p>3) The device on picture has completely different sensor, which has the name of "BMP180" just by coincidence.</p> <p>4) Something else....</p>
<p>See, for example, <a href="https://github.com/adafruit/Adafruit_BMP085_Unified" rel="nofollow">Adafruit BMP085 library</a> (it's work with BMP180 too), function</p> <pre><code>void Adafruit_BMP085_Unified::getTemperature(float *temp) </code></pre> <p>in file Adafruit_BMP085_u.cpp line 330</p>
16459
|arduino-mega|power|pins|hardware|debugging|
Mega pin stuck high after driving optocoupler
2015-10-01T15:45:46.053
<p>I have an Arduino Mega which is driving a board. On the board is a quad optocoupler (K847PH). Pins 42 - 45 of the Arduino are each attached to the Anode of a opto. The cathode goes to ground through a 50ohm resistor. I've used multiple boards and have had no issues with this part of the circuitry so far. I recently attached a new board (same circuit) and began testing. I noticed I had ~1.1V on pin 1 of the opto (Anode). After some debugging I checked the voltage coming out of the Arduino to that pin (42 on the Mega) and noticed it was 5V. I ran a new sketch to drive and hold the voltage low but the voltage remains at 5V.</p> <pre><code>void setup() { pinMode(42, OUTPUT); digitalWrite(42, LOW); } void loop() { digitalWrite(42, LOW); } </code></pre> <p>Looking at the schematic of the Mega it appears pin 42 is directly connected to the ATMEGA1280-16AU. Is there anything I can do to fix the Mega? Should I just replace the ATMEGA1280-16AU? Is there something I can probe to check? It does appear there is > 1Mohm of isolation between pin 42 and the 5V rail.</p>
<p>Re “Is there anything I can do to fix the Mega?”, if the condition persists when trying it after removing power from the Mega and discharging it, probably not. (Aside from not using that pin.)</p> <p>Note, the IR LEDs in the K847PH are rated at 60 mA max each, and typically drop 1.25 volts at 50 mA current. If you drive them with 5 V through a 50Ω resistor, typical current will be 3.75/50 = 75 mA, which exceeds K847PH ratings and Mega2560 ratings (typically 40 mA max, 20 mA working). Consider using a 125Ω or more resistor, to stress the Mega pins at 30 mA or less.</p> <p>(From Fig. 8 - Collector Current vs. Forward Current, in the K847PH data sheet, you might be ok with 10 to 20 mA current through the IR LEDs.)</p>
16467
|arduino-uno|sensors|
Using a state machine
2015-10-01T22:53:47.160
<p>I'm trying to get a strip of Neopixels to circle through its length, one LED at a time, I want it to do it faster as the value received from the sensor increases</p> <pre class="lang-c prettyprint-override"><code>#include &lt;FastLED.h&gt; #define NUM_LEDS 34 #define DATA_PIN 6 #define SENSOR_PIN A0 int airPressure, barometricToRGB, frequency = 0, high = 0, low = 600, interval = 50; long previousMillis = 0; CRGB leds[NUM_LEDS]; void setup() { Serial.begin(115200); pinMode(SENSOR_PIN,INPUT); FastLED.addLeds&lt;NEOPIXEL, DATA_PIN&gt;(leds, NUM_LEDS); } void loop() { airPressure = analogRead(SENSOR_PIN); autoTune(); unsigned long currentMillis = millis(); Serial.print("frequency "); Serial.println(frequency); Serial.print("Time to beat "); Serial.println(frequency*interval); Serial.print("Last Called "); Serial.println(currentMillis - previousMillis); if(currentMillis - previousMillis &gt; (frequency/interval)) { previousMillis = currentMillis; for (int i=0; i&lt;NUM_LEDS; i++) { leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB); FastLED.show(); } } } void autoTune() { if (airPressure &lt; low) { low = airPressure; } if (airPressure &gt; high) { high = airPressure; } barometricToRGB = map(airPressure, low, high, 1, 255); barometricToRGB = constrain(barometricToRGB, 1, 255); frequency = map(airPressure, low, high, 1, 100); frequency = constrain(frequency, 1, 100); } </code></pre> <p>While I had managed to cause the color to change based on the sensor, I can't seem to understand how to control how fast it will go, every how long.</p>
<p>Ok, if I understood what you meant, you want that a single led in the ring is on and the refresh rate is dependent on the pressure, right?</p> <p>If so, you did not write any "select this led" code, so it can't work.</p> <p>I fixed a couple of things in your code. Mainly:</p> <ol> <li>added the circularity to the ring (with variable <code>currentlyOnLed</code>)</li> <li>fixed some types (use the <code>byte</code> unless you need a bigger type)</li> <li>removed some <code>constrain</code>s, which were reduntant</li> <li><code>frequency*interval</code> instead of <code>frequency/interval</code> (I guess it was a typo)</li> <li>I prefer summing the step instead of setting <code>previousMillis</code> to <code>currentMillis</code>, so you will not add error with time passing</li> <li>moved <code>FastLED.show()</code> outside the loop: I'm not sure about this, but I think that you don't need to call it every loop. I can't test it, anyway.</li> </ol> <p>So, here is the fixed code. Let us know if it works for you</p> <pre><code>#include &lt;FastLED.h&gt; #define NUM_LEDS 34 #define DATA_PIN 6 #define SENSOR_PIN A0 int airPressure; int high = 0; int low = 600; byte barometricToRGB; int frequency = 0; byte interval = 50; byte currentlyOnLed; long previousMillis = 0; CRGB leds[NUM_LEDS]; void setup() { Serial.begin(115200); pinMode(SENSOR_PIN,INPUT); FastLED.addLeds&lt;NEOPIXEL, DATA_PIN&gt;(leds, NUM_LEDS); currentlyOnLed = 0; } void loop() { airPressure = analogRead(SENSOR_PIN); autoTune(); unsigned long currentMillis = millis(); Serial.print("frequency "); Serial.println(frequency); Serial.print("Time to beat "); Serial.println(frequency*interval); Serial.print("Last Called "); Serial.println(currentMillis - previousMillis); if(currentMillis - previousMillis &gt; (frequency*interval)) { previousMillis += (frequency*interval); //Set next on led if (currentlyOnLed &gt;= NUM_LEDS - 1) currentlyOnLed = 0; else currentlyOnLed++; for (byte i=0; i&lt;NUM_LEDS; i++) { if (i == currentlyOnLed) leds[i].setRGB( barometricToRGB, 68, 255/barometricToRGB); else leds[i] = CRGB::Black; } FastLED.show(); } } void autoTune() { airPressure = constrain(airPressure, low, high); barometricToRGB = map(airPressure, low, high, 1, 255); frequency = map(airPressure, low, high, 1, 100); } </code></pre>
16469
|button|
1x4 Button membrane help
2015-10-01T23:55:29.407
<p>Im trying out <a href="http://www.adafruit.com/products/1332?gclid=CjwKEAjw7aiwBRCPgdu70arX70wSJADK6iDD89H4xAIdw88_bv9K8EcrhdbdzERDU0gKJgrRwAcO2xoClM_w_wcB" rel="nofollow">this membrane</a> from Adafruit that i bought last week but i have a little issue. ITS SO SENSITIVE! i as so just touch it with my finger and it transmits!. Anyone that has worked with this membrane have the same issue? is there some sort of "fix"?</p> <p><strong>UPDATE</strong></p> <p>Its really simple. But one weird thing, not sure if its supposed to be like that, but by default, the buttons are on <code>HIGH</code>. i used <code>Serial.println(digitalRead(one));</code> to verify that and the output was 1.</p> <pre><code>int two = 8; int one = 9; int four = 10; int three = 11; void setup() { pinMode(one, INPUT); pinMode(two, INPUT); pinMode(three, INPUT); pinMode(four, INPUT); Serial.begin(9600); } void loop() { if(digitalRead(one) == LOW){ Serial.println("One"); }else if(digitalRead(two) == LOW){ Serial.println("Two"); }else if(digitalRead(three) == LOW){ Serial.println("Three"); }else if(digitalRead(four) == LOW){ Serial.println("Four"); } } </code></pre>
<blockquote> <pre><code>pinMode(one, INPUT); </code></pre> </blockquote> <p>You have configured the input with no pullup. Since it is a CMOS input and hence very high impedance, it effectively acts as an antenna picking up random signals including that of your finger becoming capacitively coupled to it. You <em>must</em> enable the pullup on the pins (and connect the common to ground) if you want correct operation.</p> <pre><code> pinMode(one, INPUT_PULLUP); </code></pre>
16476
|sensors|arduino-ide|esp8266|
Can a ESP8266 and a HC-SR04 be friends?
2015-10-02T03:58:26.333
<p>I have some existing code that I've been using with an Uno and a HC-SR04. In order to make my project less expensive, I'm trying to port everything over to a ESP8266-01.</p> <p>The last hang up I've been running into is that it appears that the ESP8266 doesn't support the pulseIn function.</p> <pre><code>duration = pulseIn(echoPin, HIGH); </code></pre> <p>Any idea on how I can change the pulseIn function with interrupts or something else?</p> <p>Lastly I've done a lot of searching for using a HC-SR04 with a ESP8266 and while there are a couple examples out there, I haven't seen anyone do it with Arduino code...</p>
<p>I had trouble with pulseIn() until the proper initializing code was put in setup(). <br> As follows:<br> <br> pinMode(TRIGGER, OUTPUT);<br> digitalWrite(TRIGGER, LOW);<br> delay(2);<br> pinMode(ECHO, INPUT);<br> <br> TRIGGER and ECHO were initially defined at top of code with other variables as follows:<br> #define TRIGGER 13 // Data pin D7<br> #define ECHO 12 // Data pin D6<br> <br> My HC-SR04 board was wired to D7 and D6, but D1 and D2 are often used.<br> <br> Project was a 'Tide' reporting system. A work in progress. Also found HC-SR04 board was unstable if using 3.3vdc as VCC. Works better if the HC-SR04 board VCC is tide to Vin on the ESP8266 board.</p>
16479
|arduino-uno|sensors|
Dust sensor for Arduino in open and windy environment
2015-10-02T07:32:48.730
<p>I intend to create a DIY dust sensor, specifically Particulate Matter up to 10 micrometer in size (PM10) using Arduino UNO for the region surrounding a building which is located next to a factory that produces wood-based products. Is there any specific sensor that should suit my need, that is to collect and measure dust particles in an open environment and possibly a windy condition? Any implementation ideas are also welcome. </p>
<p>A popular option is the Shinyei PPD42 sensor. There are a few well-documented blogs that describe how to connect it to an Arduino. Some of the users determined that the sensors are more accurate when a fan is placed on the unit to blow air through it, but this might not be necessary in an outdoors and windy environment.</p> <p>I have two of these sensors hooked up to an Arduino, one monitoring indoors and one outdoors. I found that the indoors unit needed a fan on it to help it detect particles better (otherwise I was getting too many zeros). But the outdoors unit seems fine without the fan.</p> <p>I mainly followed this blog's instructions for the code: <a href="http://www.howmuchsnow.com/arduino/airquality/grovedust/" rel="nofollow">http://www.howmuchsnow.com/arduino/airquality/grovedust/</a></p> <p>I think I read a few months ago that the next best sensors are in the $200 range.</p> <p>I have a Dylos DC1100 dust monitor (considered very accurate) and it usually correlates with my Shinyei readings. But I'm pretty sure I introduced some "magic numbers" into my code to make the Shinyei readings match more closely with the Dylos. The entire process wasn't easy for me, and it took me weeks to get everything to behave the way I wanted.</p>
16498
|atmega328|adafruit|avrdude|avr-gcc|gcc|
Running Arduino code for Bluefruit LE on bare ATMega328
2015-10-02T18:02:57.563
<p>I need to hook up <a href="https://learn.adafruit.com/downloads/pdf/getting-started-with-the-nrf8001-bluefruit-le-breakout.pdf" rel="nofollow">Bluefruit LE Breakout</a> (nRF8001-based) to ATMega328 chip (to use it as wireless UART), and it seems like the <a href="https://github.com/adafruit/Adafruit_nRF8001/archive/master.zip" rel="nofollow">library provided</a> is for Arduino.</p> <p>What I have is just bare ATMega328 (note the lack of "p"), which I am going to program (using avrispmkii directly). As I already have the MCU assembled, I do not want to change to, say, Arduino Uno to be able to use the library. Most likely, I will "play" with the Bluefruit on Arduino first to get the feel of it, but the code needs to be run on the "bare" ATMega328. The other part of the program (which prepare data to be sent from atmega) is trivial, so I will have no problem to rewrite it from C to Arduino. Porting Adafruit library from C++ to C is probably much more difficult.</p> <p>Thus, one of the possible approaches is to compile the my code + Bluefruit LE code for Arduino, but upload to the ATMega328.</p> <p>And this is where I need help:</p> <p>How to make Arduino (command line tool is ok) to compile to the MCU I have? I guess, the result should be some kind of hex-file for flash (and eeprom?).</p> <p>And, may be useful, which flags to use with avrdude, if there is anything specific for the Arduino-generated code. (I do not need any bootloaders on the chip, just the program, and I do not have UART-USB connected to atmega).</p> <p>Of course, please, mention if there are better ways I overlooked, like some Arduino-compatible gcc toolchain to compile C++/C mix into avr code (avr-g++?). Or maybe there is some C-library for the component atmega needs to talk to.</p> <p>UPDATE: Similar question: <a href="http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal" rel="nofollow">http://www.avrfreaks.net/forum/using-arduino-ide-general-atmel-microcontroller-no-bootloader-no-cristal</a> </p>
<p>The UNO is basically just an ATMega328(P). So you can run the same compiled code for the UNO just fine on a bare ATMega328.</p> <p>You don't have to worry about the P versus non-P version. They are basically the same except for some minor differences concerning low power settings.</p> <p>You can just select the Arduino UNO board as you target. Select the avrispmkii as programmer. Then instead of <code>Upload</code>, choose <code>Upload using Programmer</code> (in the <code>Sketch</code> menu).</p>
16500
|arduino-uno|c++|arduino-ide|
How to find the deferenced value of a transmit Port Register?
2015-10-02T18:06:50.627
<p>So I am working with the SoftwareSerial library. I'm looking at the write function and I see a *reg value being manipulate. I want to find the value of *reg so I traced the value by stepping into each function call.so here we go.</p> <pre><code>*reg = _transmitPortRegister _transmitPortRegister = portOutputRegister(port) //I'm working with pin 1 in register D </code></pre> <p>Continuing...</p> <pre><code>#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) ) const uint16_t PROGMEM port_to_output_PGM[] = { NOT_A_PORT, NOT_A_PORT, (uint16_t) &amp;PORTB, (uint16_t) &amp;PORTC, (uint16_t) &amp;PORTD, }; </code></pre> <p>My first question is what is the point of (uint16_t) &amp;PORTD? I am assuming that's just the value of PORTD's register because it is being anded with an empty 16 bit int. </p> <p>Continuing on, </p> <pre><code>#define PORTB _SFR_IO8(0x05) #define PORTC _SFR_IO8(0x08) #define PORTD _SFR_IO8(0x0B) #define _SFR_IO8(io_addr) _MMIO_BYTE((io_addr) + __SFR_OFFSET) #define __SFR_OFFSET 0x20 #define _MMIO_BYTE(mem_addr) (*(volatile uint8_t *)(mem_addr)) </code></pre> <p>Now, I followed it all the way here. But how do I find out what actually is the deferenced value? Since this is all IDE, i'm not sure how to GDB this either.</p> <p>LASTLY, the write function takes in a parameter b, which is a byte. Now in the write function, this is the code to write.</p> <pre><code>// Write each of the 8 bits for (uint8_t i = 8; i &gt; 0; --i) { if (b &amp; 1) // choose bit *reg |= reg_mask; // send 1 else *reg &amp;= inv_mask; // send 0 tunedDelay(delay); b &gt;&gt;= 1; } </code></pre> <p>In that block of code, I am not quite sure why they are doing b &amp; 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks, they're just oring *reg with reg_mask. How does that translate to sending a one? </p> <p>Sorry for any confusion, i am glad to clarify any confusing parts of this question. Please let me know. </p>
<pre><code>// Write each of the 8 bits for (uint8_t i = 8; i &gt; 0; --i) { if (b &amp; 1) // choose bit *reg |= reg_mask; // send 1 else *reg &amp;= inv_mask; // send 0 tunedDelay(delay); b &gt;&gt;= 1; } </code></pre> <blockquote> <p>In that block of code, I am not quite sure why they are doing b &amp; 1. Are they just anding the whole byte with 1? If so, then why comment it as "choose byte" and inside the if-else blocks,</p> </blockquote> <p>The comment is: choose <strong>bit</strong></p> <p>First, variable <code>b</code> is the <strong>byte</strong> that is being set. Now, since async serial sends the least-significant bit first, at the start of the loop of 8 iterations, it takes the low-order bit to see if it is set or not:</p> <pre><code> if (b &amp; 1) // choose bit </code></pre> <p>If set, it sets the output port to HIGH (by ORing in the appropriate mask to the appropriate register), otherwise it sets the port to LOW (by ANDing in the appropriate inverted mask to the appropriate register). The inverted mask would be set to every bit <strong>but</strong> one.</p> <p>Now look at this:</p> <pre><code> b &gt;&gt;= 1; </code></pre> <p>That shifts the bits right one, throwing away the low-order bit. Now what was previously the second lowest-order bit is now the low-order bit. Then the loop repeats. Now the next bit is sent. And so on for 8 bits.</p> <p>Imagine we were sending 0x39 (0b00111001). For the 8 iterations of the loop we would see:</p> <pre><code>00111001 --&gt; 1 sent, then "b" shifted right one 00011100 --&gt; 0 sent, then "b" shifted right one 00001110 --&gt; 0 sent, then "b" shifted right one 00000111 --&gt; 1 sent, then "b" shifted right one 00000011 --&gt; 1 sent, then "b" shifted right one 00000001 --&gt; 1 sent, then "b" shifted right one 00000000 --&gt; 0 sent, then "b" shifted right one 00000000 --&gt; 0 sent, then "b" shifted right one </code></pre> <p>You can see that the right-most bit is sent (the low-order bit) and then <code>b</code> is shifted right (introducing zeroes at the left), until all 8 bits are sent.</p>
16501
|arduino-uno|shields|
2.8" tft screen arduino all pins used
2015-10-02T18:13:49.920
<p>I'm trying to connect a 2.8" display but it uses all the pins. That similar to this post (here: <a href="https://arduino.stackexchange.com/questions/12076/2-8-tft-touchscreen-prohibits-access-to-unused-pins">2.8&quot; TFT Touchscreen Prohibits Access to Unused Pins</a>)</p> <p>However, they recommend a proto screw shield (show here: <a href="http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&amp;gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&amp;kpid=1480459155" rel="nofollow noreferrer">http://www.mouser.com/ProductDetail/Adafruit/196/?qs=GURawfaeGuDa14An8N8oeg%3D%3D&amp;gclid=CKjBqd2xpMgCFQiVfgodN5wCbA&amp;kpid=1480459155</a>) </p> <p>However, how would that work? I'm a bit of a noob -- does anyone have any diagrams of it being connected, etc?</p> <p>Thanks!</p>
<p>You're confusing the idea of <em>using</em> all the pins to that of <em>plugging into</em> all the pins.</p> <p>Yes, your shield may well have all the pins on it which then fill all the available holes. Only some of them will actually be connected to anything on the circuit board though.</p> <p>The breakout board you link to basically provides a "tee" connection to all the pins, so that you can then get to the pins that, while they may have a lump of metal plugged into them, don't electrically connect to anything at all.</p> <p>You should look at the schematic for your TFT screen to see exactly which pins are in use and which are there but not wired to anything.</p>
16504
|motor|relay|programming|
Programming a motor with an RGB
2015-10-02T18:13:26.433
<p><em>Please see the comments section if confused.</em> I am trying to turn a motor on and off once per second, and when the motor is on, the RGB turns green. When the motor is off, the RGB is red. Everything is connected to an arduino UNO.I have the motor connected to pins 0 and 1, and to the 5V and GND. The RGB is connected to pins 4, 5, and 6, and the 5V. I have two codes; one with a bunch of screwing around with a bunch of different loops and everything else I've tried, and one with the simple motor on/off code.</p> <pre><code>void setup () { pinMode(0,OUTPUT); //IB1 pinMode(1,OUTPUT); //IA1 //// pinMode(2,OUTPUT); //IB2 //// pinMode(3,OUTPUT); //IA2 // pinMode(4,OUTPUT); //RGB // pinMode(5,OUTPUT); //RGB // pinMode(6,OUTPUT); //RGB // pinMode(A0,INPUT); //lMotor //// pinMode(A1,INPUT); //rMotor // Serial.begin(9600); } void loop () { digitalWrite(0,HIGH); delay(1000); digitalWrite(0,LOW); delay(1000); // int lMotor = analogRead(A0); // Serial.write(lMotor); //// int lMotor = analogRead(A1); //// Serial.write(lMotor); // // if (lMotor&gt;10) // { // digitalWrite(4,HIGH); // digitalWrite(5,HIGH); // digitalWrite(6,LOW); // } // else // { // digitalWrite(4,HIGH); // digitalWrite(5,LOW); // digitalWrite(6,HIGH); // } } </code></pre> <p>And here's this:</p> <pre><code>void setup () { pinMode(0,OUTPUT); pinMode(1,OUTPUT); } void loop () { digitalWrite(0,HIGH); delay(1000); digitalWrite(0,LOW); delay(1000); } </code></pre> <p>What do I need to do? Should I use a "while" loop? If so, how? Is my circuit put together properly? I'm using a motor relay switch to turn the motor on/off, but I'm pretty sure it's hooked up right. Any help is appreciated, even if it doesn't answer all of my questions. Thank you.</p>
<p>Try this:</p> <pre><code>void setup () { pinMode(0,OUTPUT); //IB1 pinMode(1,OUTPUT); //IA1 // pinMode(2,OUTPUT); //IB2 // pinMode(3,OUTPUT); //IA2 pinMode(4,OUTPUT); //RGB red pinMode(5,OUTPUT); //RGB green pinMode(6,OUTPUT); //RGB blue boolean motorOn = false; } void loop () { digitalWrite(0,motorOn); if(motorOn) { digitalWrite(4,HIGH); // red on digitalWrite(5,LOW); // green off digitalWrite(6,LOW); // blue off } digitalWrite(4,LOW); // red off digitalWrite(5,HIGH); // green on digitalWrite(6,LOW); // blue off } delay(1000); // wait motorOn = !motorOn; // toggle the status of the motor. } </code></pre> <p>The code above has the disadvantage that the on-time is the same as the off-time. We can make the code more flexible and a little more like your original by doing the LED related code in a subroutine:</p> <pre><code>void setup () { pinMode(0,OUTPUT); //IB1 pinMode(1,OUTPUT); //IA1 // pinMode(2,OUTPUT); //IB2 // pinMode(3,OUTPUT); //IA2 pinMode(4,OUTPUT); //RGB red pinMode(5,OUTPUT); //RGB green pinMode(6,OUTPUT); //RGB blue boolean motorOn = false; } void loop () { motorOn = false; digitalWrite(0,motorOn); updateLEDs(); // update the LED status delay(1000); // wait motorOn = true; // toggle the status of the motor. digitalWrite(0,motorOn); updateLEDs(); // update the LED status delay(750); // wait a different time } void updateLEDs(){ // This routine updates the LEDs based on status of motorOn. if(motorOn) { digitalWrite(4,HIGH); // red on digitalWrite(5,LOW); // green off digitalWrite(6,LOW); // blue off } digitalWrite(4,LOW); // red off digitalWrite(5,HIGH); // green on digitalWrite(6,LOW); // blue off } } </code></pre>
16507
|arduino-mega|uploading|bootloader|ide|ftdi|
Programming an ATMEGA2560 using FTDI
2015-10-02T18:03:48.080
<p>I want to know how exactly do I program (upload arduino sketches) an ATMEGA2560 which is boot loaded with an Arduino Bootloader using a FTDI programmer and an Arduino IDE, is there any capacitors/resistors required? </p>
<p>If you have a bootloader, you just need to connect up four wires from the FTDI cable:</p> <ul> <li>Pin 1 (black) -> Ground</li> <li>Pin 2 (CTS) -> not connected</li> <li>Pin 3 (Vcc) -> 5V</li> <li>Pin 4 (TxD) -> Rx (Mega pin D0)</li> <li>Pin 5 (RxD) -> Tx (Mega pin D1)</li> <li>Pin 6 (green) -> not connected</li> </ul> <p><a href="https://i.stack.imgur.com/GcK9K.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GcK9K.png" alt="FTDI connections"></a></p> <p>This will not auto-reset, so you will have to press (and release) the Reset button on the board at the moment that the sketch starts to upload.</p> <hr> <blockquote> <p>How to make it auto reset?</p> </blockquote> <p>What you <em>should</em> be able to do is connect RTS to Reset on the board, using a 0.1 µF capacitor (in series). I found in practice that this did not bring Reset low enough to trigger it - I'm not sure why, except maybe the board has a stronger pull-up resistor on /RESET than expected. That technique works for me on breadboard Arduinos.</p> <p>Since it didn't work for me, I did not put it in my original answer. You could try that, and if it works, well and good.</p>
16509
|arduino-uno|c++|arduino-ide|
how to create a specific buffer when there is no buffer message in the data packet?
2015-10-02T20:37:37.630
<p>So I'm trying to understand a read method. In this method, </p> <pre><code>// Read data from buffer int SoftwareSerial::read() { if (!isListening()) return -1; // Empty buffer? if (_receive_buffer_head == _receive_buffer_tail) return -1; // Read from "head" uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF; return d; } </code></pre> <p>it looks it receives buffer head. But in the write only a 1 or 0 is being sent as the data packet's header. Nothing else. So how does the arduino know how big of an buffer to create? also, there is no stop bit being transmitted, so how does it look at a buffer tail? Or is this all created regardless of the transmitter? and then, all the values just get read into the buffer, and then read again from there? Also I don't see a delay in this read method. Wouldn't that cause errors in the data flow? How is that being handled? </p>
<p>That read method just retrieves bytes that have already been received from an internal buffer.</p> <p>The buffer is pre-allocated to a specific size (64 bytes) and that is how many bytes can be received before you start to lose data as it gets overwritten. You have to be sure to read your data from the buffer before it overflows.</p> <p>The function that actually receives each UART bit from the IO port, builds them into bytes, and stores them in the internal buffer, is this one:</p> <pre><code>void SoftwareSerial::recv() { #if GCC_VERSION &lt; 40302 // Work-around for avr-gcc 4.3.0 OSX version bug // Preserve the registers that the compiler misses // (courtesy of Arduino forum user *etracer*) asm volatile( "push r18 \n\t" "push r19 \n\t" "push r20 \n\t" "push r21 \n\t" "push r22 \n\t" "push r23 \n\t" "push r26 \n\t" "push r27 \n\t" ::); #endif uint8_t d = 0; // If RX line is high, then we don't see any start bit // so interrupt is probably not for us if (_inverse_logic ? rx_pin_read() : !rx_pin_read()) { // Wait approximately 1/2 of a bit width to "center" the sample tunedDelay(_rx_delay_centering); DebugPulse(_DEBUG_PIN2, 1); // Read each of the 8 bits for (uint8_t i=0x1; i; i &lt;&lt;= 1) { tunedDelay(_rx_delay_intrabit); DebugPulse(_DEBUG_PIN2, 1); uint8_t noti = ~i; if (rx_pin_read()) d |= i; else // else clause added to ensure function timing is ~balanced d &amp;= noti; } // skip the stop bit tunedDelay(_rx_delay_stopbit); DebugPulse(_DEBUG_PIN2, 1); if (_inverse_logic) d = ~d; // if buffer full, set the overflow flag and return if ((_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF != _receive_buffer_head) { // save new data in buffer: tail points to where byte goes _receive_buffer[_receive_buffer_tail] = d; // save new byte _receive_buffer_tail = (_receive_buffer_tail + 1) % _SS_MAX_RX_BUFF; } else { #if _DEBUG // for scope: pulse pin as overflow indictator DebugPulse(_DEBUG_PIN1, 1); #endif _buffer_overflow = true; } } #if GCC_VERSION &lt; 40302 // Work-around for avr-gcc 4.3.0 OSX version bug // Restore the registers that the compiler misses asm volatile( "pop r27 \n\t" "pop r26 \n\t" "pop r23 \n\t" "pop r22 \n\t" "pop r21 \n\t" "pop r20 \n\t" "pop r19 \n\t" "pop r18 \n\t" ::); #endif } </code></pre> <p>To show you how the timing of the routine works, here is a little diagram:</p> <p><a href="https://i.stack.imgur.com/HIwQ3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HIwQ3.png" alt="enter image description here"></a></p>
16512
|arduino-mega|arduino-due|button|
After moving project from Arduino Mega to Due, pushbuttons now erratically toggle multiple buttons
2015-10-02T20:57:58.243
<p>I've had a project running successfully for months on an Arduino Mega, and today I tried to swap the Mega for a Due to increase the speed. After making the change, the entire project is working successfully except for a strange problem with the pushbuttons.</p> <p>I have 5 momentary pushbuttons that toggle different controls (they simply send a wireless signal to toggle different AC outlets). After moving the project to the Due, when 1 button is pressed, it ends up toggling 2 other buttons at the same time.</p> <p>Originally I was using the internal pullups to detect when the buttons were low, but also I've tried connecting them to the Due's 3.3v to detect when they're high, and both times I experienced the exact same behavior.</p> <p>Is there any reason why there would be this difference in pushbutton-reading behavior between the Mega and the Due? Could it be that the Due is more sensitive to noise? How could I fix this?</p> <p>The wires connecting to the pushbuttons run about 8 feet. I never had a problem with this setup while running the sketch on the Mega.</p> <p>Below is the relevant code that detects button presses:</p> <pre><code>#include &lt;Wire.h&gt; #include &lt;SPI.h&gt; #include &lt;Ethernet.h&gt; #include &lt;RCSwitch.h&gt; #include &lt;Servo.h&gt; #include &lt;Event.h&gt; #include &lt;Timer.h&gt; #include &lt;dht.h&gt; #include "RTClib.h" const byte nl1ButtonPin = 40, nl2ButtonPin = 42, nl3ButtonPin = 44, pumpButtonPin = 5, irButtonPin = 27, unsigned long buttonPressTime1, buttonPressTime2, buttonPressTime3, buttonPressTime4, buttonPressTime5; // when the switch last changed state byte oldButtonState1 = HIGH, oldButtonState2 = HIGH, oldButtonState3 = HIGH, oldButtonState4 = HIGH, oldButtonState5 = HIGH; const unsigned long debounceTime = 100; void setup() { pinMode(nl1ButtonPin, INPUT_PULLUP); pinMode(nl2ButtonPin, INPUT_PULLUP); pinMode(nl3ButtonPin, INPUT_PULLUP); pinMode(pumpButtonPin, INPUT_PULLUP); pinMode(irButtonPin, INPUT_PULLUP); } void loop() { byte buttonState1 = digitalRead(nl1ButtonPin); if (buttonState1 != oldButtonState1) { if (millis () - buttonPressTime1 &gt;= debounceTime) { buttonPressTime1 = millis (); // when we closed the switch oldButtonState1 = buttonState1; // remember for next time if (buttonState1 == LOW) { Serial.println("button1 LOW!"); toggleLight1(); } } } byte buttonState2 = digitalRead(nl2ButtonPin); if (buttonState2 != oldButtonState2) { if (millis () - buttonPressTime2 &gt;= debounceTime) { buttonPressTime2 = millis (); // when we closed the switch oldButtonState2 = buttonState2; // remember for next time if (buttonState2 == LOW) { Serial.println("button2 LOW!"); toggleLight2(); } } } byte buttonState3 = digitalRead(nl3ButtonPin); if (buttonState3 != oldButtonState3) { if (millis () - buttonPressTime3 &gt;= debounceTime) { buttonPressTime3 = millis (); // when we closed the switch oldButtonState3 = buttonState3; // remember for next time if (buttonState3 == LOW) { Serial.println("button3 LOW!"); toggleLight3(); } } } byte buttonState4 = digitalRead(pumpButtonPin); if (buttonState4 != oldButtonState4) { if (millis () - buttonPressTime4 &gt;= debounceTime) { buttonPressTime4 = millis (); // when we closed the switch oldButtonState4 = buttonState4; // remember for next time if (buttonState4 == LOW) { Serial.println("button4 LOW!"); togglePump(); } } } byte buttonState5 = digitalRead(irButtonPin); if (buttonState5 != oldButtonState5) { if (millis () - buttonPressTime5 &gt;= debounceTime) { buttonPressTime5 = millis (); // when we closed the switch oldButtonState5 = buttonState5; // remember for next time if (buttonState5 == LOW) { Serial.println("button5 LOW!"); toggleHeater(); } } } } </code></pre> <p>On the serial output, pressing one button shows 2 other buttons as low. So, for example, pressing button2 might show: "Button2 LOW!, Button4 LOW!, Button1 LOW!". There doesn't seem to be any clear patterns with which other 2 buttons get simultaneously pressed. Remember that this exact same code and hardware setup was working perfectly for months on the Mega, which makes me believe maybe it's something related to the Due (maybe 3.3v, maybe stronger PU resistors, etc).</p>
<p>I think I can explain this. You have set up a rather complex (and incorrectly wired) network of resistors. Your switch has pull-up resistors, clearly connected together, and then to the "+" pin. The other side of the switches would go to ground. </p> <blockquote> <p>Note that I don't have anything connected to the VCC of the switch ...</p> </blockquote> <p>Right, so your setup looks like this:</p> <p><a href="https://i.stack.imgur.com/ZDmo9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZDmo9.png" alt="Pull-up resistors"></a></p> <p>Now with no switch pressed they will all read high due to the Due's pull-up (which by the way is around 100 k compared to the Mega's 50 k.)</p> <p>Now you press a switch. The naturally grounds that switch so it reads LOW. However it also pulls down neighbouring switches through the 10 k resistor network. So each switch now is in the middle of a voltage divider. There is 20 k going to ground and a couple of 100 k going to Vcc, like this:</p> <p><a href="https://i.stack.imgur.com/nZNKC.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nZNKC.png" alt="Multiple presses"></a></p> <p>This voltage divider would be enough for that pin to register as LOW, and indeed that would be repeated for each pin.</p> <p>Adding your carefully calculated resistor between the "-" pin and ground is just changing the voltages a bit.</p> <p>The correct solution is to connect the "+" pin to Vcc so that it acts as a proper pull-up. And get rid of that resistor in series with ground.</p> <hr> <p>It probably worked on the Mega because of the different pull-up resistance when you activated the internal pull-up which would have changed the calculations for the voltage divider.</p> <p>I've worked out what I think the voltages will be. Note that the supposedly open switches will actually have 1.1 V on them, which as far as I can tell from the datasheet is in the "undefined" territory between LOW (max 0.99 V) and HIGH (minimum 2.31 V).</p> <p>Reasoning: You can effectively consider that the 4 open switches have 4 x 110 k between them and 3.3 V in parallel. In other words, 27.5 k. With a voltage divider now between that and the 10 k to ground, you have:</p> <pre><code>10 / (10 + 27.5) * 3.3 = 880 mV </code></pre> <p>So, there will be 880 mV on the common point (which is "+" on the board).</p> <p>Now for each switch you have a voltage divider of:</p> <pre><code>10 / 110 * (3.3 - 0.880) = 220 mV </code></pre> <p>Add to that the 880 mV at the common point and we have:</p> <pre><code>0.88 + 0.22 = 1.10 V </code></pre>
16530
|arduino-uno|
Any disadvantages on using Particle Photon over an Arduino?
2015-10-03T20:24:17.803
<p>It seems to me like Photon is 'winning' on the price front and ease of programming and of course the cheap wifi connection.</p> <p>I realize the cloud portion (even the local cloud server) could be considered a disadvantage, but what about things like ability to drive dc/stepper motors or some exotic sensor? Perhaps not enough analog and/or digital pins? etc..</p> <p>One disadvantage I can think of is the lack of resources whereas the Arduino has a ton of references online with working with all kinds of motors and sensors. </p>
<p><strong>Photon advantages:</strong></p> <p>The photon has cloud compatibility and wifi access. The Arduino doesn't without a separate shield.</p> <p>A photon about 1/4 the size of an Arduino UNO</p> <p>Photon is much cheaper than arduinos</p> <p><strong>Arduino UNO advantages:</strong></p> <p>Arduino UNO has 5 volt AND 3.3 volt while Photon has only 3.3 volt</p> <p>Arduino has many resources while Photons don't since Photons are fairly new</p> <p>Arduinos don't need any wifi to work while Photons need to be connected to wifi and the cloud to flash code (Although there is a way to flash over USB cable, it is HIGHLY complicated with need of the terminal and DFU-UTIL installed.)</p> <p>UNO has 5 analog, 13 digital ports while Photon has only 5 analog, 7 digital</p> <p>UNOs have female pins, so no breadboards are necessary for small, simple projects. Photons have male pins, and they need to be plugged into a breadboard or soldered.</p> <p><em>Personally, I have both an UNO and a photon. Photons are useful for small and more compact projects, while Arduinos are for projects on a bigger scale. Unless you specifically need access to the cloud or access to WIFI, I would suggest buying the Arduino. Good luck!</em></p>
16533
|arduino-nano|softwareserial|esp8266|
SoftwareSerial returns garbage when powered externally
2015-10-03T22:27:41.267
<p>I'm currently working on a project with the ESP8266 and Arduino Nano, and when I power the device via USB they talk to each other via SoftwareSerial just fine. I use the Arduino IDE Serial Monitor to monitor this communication. But when I power it with a 15 V wall wart to Vin it returns mostly garbage, again I can tell this with the Arduino IDE Serial Monitor (I know I shouldn't connect two power supplies at a time). When powered over 5 V USB everything is great. Why would I have a problem only when connected to an external power supply?</p>
<p>If you check the specifications they stat 12VDC is the max. Your on board regulator is probably very hot and either shutting down or allowing the voltage to sag. You can get a 9V wall Wart for under $5. the 9V will keep the on-board regulator much cooler and add reliability. </p>
16534
|serial|usb|arduino-nano|current|
how much current does Arduino Nano draw when only using 8 digital pins?
2015-10-03T22:57:37.897
<p>I want to connect an Arduino Nano to an Intel Minnowboard Max (it's like a Raspberry Pi). I know Arduino can draw up to 500 mA current through the USB connection. Since I already need the USB to communicate the Arduino with the Minnowboard, it would be nice to not power the Arduino separately as well. However, I wouldn't want the current the Arduino draws from the Minnowboard to overheat Minnowboard's 2.5A 12V power supply. I only have 8 buttons connected to the digital pins of the Arduino Nano. Nano sends the state of the buttons to the Minnowboard via USB (serial). How much current is Arduino drawing in this case?</p>
<p>I would guess around 50 mA, to power the processor and the USB converter. I notice that <a href="https://electronics.stackexchange.com/questions/68938/power-consumption-of-arduino-nano-current-draw-low-power">this question</a> suggests more like 20 mA.</p> <p>To be certain, you could measure it, but probably 20 to 50 mA would be a ball-park figure.</p>
16538
|arduino-mega|arduino-ide|ftdi|
My mega only works on 1.0.1 IDE
2015-10-04T02:55:04.777
<p>My mega usb/serial adapter died some time ago, so I bought an external FTDI programer wich I got working on 1.0.1 IDE. I can load any program to the mega, even complex led matrix driver I wrote myself so the ATmega works fine and the external FTDI board does too. Strangely enough I if I want to update the IDE (tried once on 1.0.5 and yesterday downloaded 1.6.5) I get an</p> <pre><code> avrdude: stk500v2_getsync(): timeout communicating with programmer </code></pre> <p>When this problem occurs, I see that the programmer board recieves something (it has Rx and Tx LED's) the Mega resets but never sends any data back, which does happen on 1.0.1 IDE. This happens on my pc, and on a laptop son no pc related problems. I'd keep using this version but now I got an OLED display I want to drive (SSD1306 from waveshare) but I can't compile u8glib on 1.0.1 but I can on 1.6.5, however I can't get a simple blink example to upload with this IDE.</p> <p>I suspect the DTR pin (reset pin) is handled differently and that makes the mega stay resetting until it times out. What can be the problem here? How can I get more info from the console to solve this?</p>
<p>You need to add a 100nF (0.1µF) capacitor between DTR and RESET so it generates a pulse instead of a constant LOW all the time the port is open.</p> <p>The older IDE uses an older version of avrdude. The newer version of avrdude with the newer IDE has extra code for manually manipulating DTR to get around some issues with new versions of the FTDI drivers.</p>
16539
|arduino-pro-mini|ftdi|
FTDI breakout connection
2015-10-04T05:13:18.167
<p>I have been successfully programming UNO boards. I wanted to transfer the project to a Pro Mini. I am using a FTDI breakout. It wouldn't show the device port. I found the device driver I was using was supplied by MatterControl. So I updated the driver from FTDI.</p> <p>When I connected it I see the port available, but cannot program it. I get</p> <pre><code>not in sync: resp=0x01 avrdude: stk500_recv(): programmer is not responding </code></pre> <p>I checked in the device manager and see "USB Serial Port (COM5)" and properties shows "This device is working properly." the provider is FTDI. </p>
<p>I made the board using the great tutorial by Nick Gammon for the minimum Arduino board. I got the boot loader to load using Nick's tutorial and then spent a few evenings trying to use FTDI to upload sketches but could not get it to work. In the end, using various bits of inforamtion I found on the web, I made sure the reset signal was coming from the the FTDI (going to low) and then checked the settings of the FTDI and tried to make some changes. I found that the settings in my photos work. Mainly the bit rate 115200 and the latency (m/secs) time to 5 m/secs. The wires from FTDI starting from the top in looking at photo - brown (ground to ground), red (vcc to vcc) orange (tx to rx), Yellow (rx to tx), the other separate orange (was better I used another colour!) is from RTS to reset. I selected Arduino uno as board and (in my case) COM 10. For me it ow works. I don't know if I would make many of these boars though because of the time and effort. However, itwas a good expeiance and I learnt a great deal. Particularly from Nick Gammon. Thanks Nick!</p> <p><a href="https://i.stack.imgur.com/SiaRL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SiaRL.jpg" alt="connections"></a></p> <p><a href="https://i.stack.imgur.com/2KXme.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2KXme.jpg" alt="settings"></a></p>
16542
|motor|
What Driver IC to use for 40v 2amp DC motor?
2015-10-04T10:21:09.460
<p>I am using a 40v 2amp 3300rpm DC motor for my motor control project via arduino. But i don't know what driver ic to use for driving the motor.any help would be appreciated..</p>
<p>I am assuming since you did not state anything differently you simply want to turn it on or off and possibly PWM to control speed of the motor. By far the easiest way is to simply use a N-Channel logic level MOSFET. Connect the Arduino pin of your choice through a 51 (1) ohm resistor to the gate of the MOSFET, also Connect a 10K (2) resistor from the same microprocessor (Arduino) pin to ground. The "Ground" low side of the 40V power supply needs to be connected to the low side of the Arduino. The low side of the 40V power supply must be connected to the source of the MOSFET. </p> <p>Connect the motor from the plus side of the 40V power supply (this will be removed for testing) to the Drain of the N-Channel MOSFET. Last and very important place a diode rated at least 2 amps at 60 volts from the positive side of the poser supply (cathode of the diode, with the band) to the Drain of the MOSFET (anode, no band).</p> <p>Carefully check your wiring; if it is ok you are ready to test it. The safest way is to use a led with a 510 ohm in series with the cathode on the Arduino +5 with the positive side of the 40v power supply disconnected. The anode side connects to the drain of the MOSFET. When the motor is turned on the LED will light, if it does not reverse polarity of the LED. As tempting as it might be do not leave the LED connected to the Arduino when the motor is connected. Up the value of the resistor to about 5.6K and connect it across the motor, it will light when the motor is on.</p> <ol> <li>This helps dampen oscillations</li> <li>Since the Arduino initializes with all pins as inputs this can drift high, this solves that potential problem which would cause the MOSFET to turn on.</li> <li>For the MOSFET you need at least 60V with a 10A rating. This should work with a small heat sink. If you go to a higher amp rating on the MOSFET it will operate cooler.</li> </ol> <p>Output of Arduino goes to 10K to ground and to a 51 ohm resistor (1/8 W or larger) The other side of the resistor goes to the gate of the MOSFET. Ground of the motor power supply, the Arduino and the Source of the MOSFET are connected together. The 2A diode is connected with the cathode (no band) to the drain of the MOSFET, the cathode (band) is connected to the +40V. The motor connects from the +40 to the Drain of the MOSFET, reversing the leads will probably reverse motor direction.</p> <p>Good Luck, Gil</p>
16544
|arduino-uno|
How can I do this sentence show me in arduino
2015-10-04T14:31:47.590
<p>How can I do this sentence show me in arduino."WARNING: Category 'USB' in library Mouse/keyboard is not valid.Setting to 'Uncategorized'</p>
<p>Your question is unclear.</p> <p>Note that <a href="https://www.arduino.cc/en/Reference/MouseKeyboard" rel="nofollow">Mouse and Keyboard libraries</a> are suitable for use with Arduino Due and Zero boards, or with 32u4-based boards like Arduino Leonardo or Micro. They are not relevant when using an Uno.</p>
16548
|bluetooth|atmega328|adafruit|
ATMega328 + Bluefruit LE stops working soon after power on (not consistently)
2015-10-04T16:33:03.197
<p>Now I am <a href="https://arduino.stackexchange.com/questions/16498/running-arduino-code-for-bluefruit-le-on-bare-atmega328">Running Arduino code for Bluefruit LE on bare ATMega328</a> with 8MHz internal clock, with Bluefruit connected, pin 0 and 1 RX/TX unused, and AT42QT1011-based capsense circuits (logical input to pins 1, 2, 3).</p> <p>There appeared one problem: when I try to switch the device ON (with 4.5 V batteries, but the same with 5 V USB power), it happens only after three or more attempts. Each time "loop" stops after a second of what appears to be correct operation. For example, if I touch one of the capsensors on the first second of operation, and LED is on, it stays ON, which means, the "loop" is not run.</p> <p>I have tried to put back the Serial (it was in use in the original echoDemo example), tried to put pollACI after digitalWrite to LED pins. See pin assignments defined in the sketch, those were re-checked with actual circuit.</p> <p>Measured power supply current and voltage - there were no significant changes in it, even if both LEDs were on. BLE module at startup or while transmitting, was not causing any brownouts. In addition, checked input current and voltage with oscilloscope, and there were no anomalies as well.</p> <p>NB, this is atmega328, without "p", so for the record I am using 0x07 efuse, 0xE2 lfuse and 0xD9 hfuse.</p> <p>Also, if the device starts up, it will work fine for at least an hour.</p> <p>What could be other reasons for such random early failure? (in average, about four attempts to switch on, sometimes starts even on first, second time)</p> <p>The sketch in question:</p> <pre><code>/********************************************************************* This is an example for our nRF8001 Bluetooth Low Energy Breakout Pick one up today in the adafruit shop! ------&gt; http://www.adafruit.com/products/1697 Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Kevin Townsend/KTOWN for Adafruit Industries. MIT license, check LICENSE for more information All text above, and the splash screen below must be included in any redistribution *********************************************************************/ //#define F_CPU 8000000 #include &lt;SPI.h&gt; #include "Adafruit_BLE_UART.h" // Connect CLK/MISO/MOSI to hardware SPI // e.g. On UNO &amp; compatible: CLK = 13, MISO = 12, MOSI = 11 #define ADAFRUITBLE_REQ 10 #define ADAFRUITBLE_RDY 2 // This should be an interrupt pin, on Uno thats #2 or #3 #define ADAFRUITBLE_RST 7 #define REDLED 8 #define BLUELED 9 #define LEFTPAD A2 #define RIGHTPAD A3 #define BADPAD A1 Adafruit_BLE_UART BTLEserial = Adafruit_BLE_UART(ADAFRUITBLE_REQ, ADAFRUITBLE_RDY, ADAFRUITBLE_RST); unsigned int leftcnt, rightcnt; void setup(void) { pinMode(REDLED, OUTPUT); pinMode(BLUELED, OUTPUT); pinMode(LEFTPAD, INPUT_PULLUP); pinMode(RIGHTPAD, INPUT_PULLUP); pinMode(BADPAD, INPUT_PULLUP); digitalWrite(BLUELED, LOW); digitalWrite(REDLED, LOW); delay(300); BTLEserial.setDeviceName("MYUART"); /* 7 characters max! */ BTLEserial.begin(); digitalWrite(REDLED, HIGH); delay(300); digitalWrite(BLUELED, HIGH); leftcnt = 0; rightcnt = 0; } aci_evt_opcode_t laststatus = ACI_EVT_DISCONNECTED; void loop() { BTLEserial.pollACI(); if (digitalRead(LEFTPAD)) { leftcnt++; digitalWrite(BLUELED, LOW); } else { leftcnt = 0; digitalWrite(BLUELED, HIGH); } if (digitalRead(RIGHTPAD)) { rightcnt++; digitalWrite(REDLED, LOW); } else { rightcnt = 0; digitalWrite(REDLED, HIGH); } aci_evt_opcode_t status = BTLEserial.getState(); if (status == ACI_EVT_CONNECTED) { boolean inp = false; while (BTLEserial.available()) { char c = BTLEserial.read(); inp = true; } if (inp) { if (leftcnt &gt; 5) { BTLEserial.print("LEFT"); } if (rightcnt &gt; 5) { BTLEserial.print("RIGHT"); } if (digitalRead(BADPAD)) { BTLEserial.print("CENTRAL"); } } } } </code></pre> <p><strong>UPDATE</strong>: MCU's reset pin is pulled-up by a resistor. Bluefruit's RST connected to PD7 on atmega328 (also known as arduino digital pin 7). Also, 3.3 uF capacitor on the power lines near MCU's IC. (there are more near capsense circuits).</p> <p>When I disconnect Bluefruit's power, the rest of the circuit (LEDs showing cap sensors state) works without failures after startup. So it looks like under some circumstances, control never leaves BLE code to return to the loop?</p> <p><strong>UPDATE 2</strong>: Found long list of reset causes (not sure yet whether relevant here): <a href="https://stackoverflow.com/questions/23377948/arduino-avr-atmega-microcontroller-random-resets-jumps-or-variable-data-corrup">Arduino/AVR ATmega microcontroller, random resets, jumps or variable/data corruption ...</a> </p> <p><strong>UPDATE 3</strong>: Added two 100nF bypass capacitors near GND / VCC pins on both sides. The problem is still there.</p> <p><strong>UPDATE 4</strong>: Performed all kinds of experiments, placing BLE module's power lines in different places, with different capacitors. Only in the case of separate power (common ground) the problems were different (but may be due to different times of turning module and MCU on).</p> <p><strong>UPDATE 5</strong>: May be relevant or not, but when I run MCU on 1MHz (8 MHz internal clock, divided by 8 - lfuse 0x62), success rate is better than 70%. The speed seem to be enough for my application, but of course near 100% turn-on success should be achieved.</p> <p><strong>MAY BE IMPORTANT</strong>: I have added watchdog to sketch (thanks to the "Make: Sensors" book by Karvinen &amp; Karvinen, Valtokari):</p> <pre><code> WDTCSR |= (1&lt;&lt;WDCE) | (1&lt;&lt;WDE); WDTCSR = 1&lt;&lt;WDP0 | 1&lt;&lt;WDP3; WDTCSR |= _BV(WDIE); MCUSR &amp;= ~( 1 &lt;&lt; WDRF); </code></pre> <p>And in the respective ISR red led is turned on or off once in about 8 seconds or so. And ISR code works (thus, MCU works all the time too, right?), even though the "loop" runs no longer.</p> <p>Can this still be attributed to trouble with power or is it more likely control flow is stuck somewhere in the BLE library?</p> <p><strong>UPDATE</strong>: Well... As advised here, while trying out Serial (via microbot USB adapter), I understood, that it does not work reliably (if at all, sometimes eats characters, prints garbage, ...). Not sure whether SPI is sensitive to clock accuracy, but if it is, it may be the problem. Also, the circuit turns on always when powered from USB3 port 5V.</p>
<p>The main problem cause was inaccurate internal clock. As soon, as external 8MHz crystal has been attached to XTAL pins (with a pair of 22pF capacitors to GND), problems with turning the board on disappeared.</p> <p>Also, I found</p> <pre><code>while(1); </code></pre> <p>loop in the Adafruit's nRF8001 library, which runs whenever problems with the Bluefruit LE board are encountered. That is possibly why interrupts worked fine, but the whole MCU never returned to the main loop. </p>
16551
|arduino-mega|arduino-ide|pins|interrupt|
Why PJ0 and PJ1 are not reporting as PCINT pins
2015-10-04T21:27:06.873
<p>When the sketch shown at end-of-question is compiled and uploaded to an Arduino board, it is supposed to Serial-print a list of available digital pins, showing for each pin whether it supports PWM or PCINT. (For the latter items, it should indicate whether it has timer-supported PWM, and whether it can cause a hardware-supported pin-change-interrupt.) For example, for an ATmega-2560 board, the program's output includes lines like</p> <pre><code> Pin# Port Mask PWM PCINT 11 PB5 0x20 PWM PCINT5 PCINT0_vect 46 PL3 0x08 PWM 52 PB1 0x02 PCINT1 PCINT0_vect </code></pre> <p>Using arduino 1.6.3 on my Ubuntu 14.04 system with an ATmega-2560 board, the program's output for pins 14 and 15 is:</p> <pre><code> 14 PJ1 0x02 15 PJ0 0x01 </code></pre> <p>As I understand it, those pins should be shown⁽¹⁾ as supporting PCINT9 and PCINT10, with vector PCINT1_vect, but the program doesn't report them as such. What is this problem due to?</p> <p>⁽¹⁾See, for example, table 13.3.9, Alternate Functions of Port J, in doc2549.pdf, the spec sheet for ATmega640/1280/1281/2560/2561. Also see <a href="https://arduino.stackexchange.com/q/9481">Why is my interrupt code not working?</a>.</p> <p>Sketch pinsList.ino:</p> <pre><code>/* pinsList -- JW, 4 October 2015 -- * * Displays a list of Arduino pin numbers for current kind of Arduino * board, along with port codes, pin-change-interrupt numbers, and * pin-change-interrupt vector numbers. * * Here are two examples of output lines for pin 11, the first for an * Uno, the second for a Mega: * * 11 PB3 0x04 PWM PCINT3 PCINT0_vect * 11 PB5 0x20 PWM PCINT5 PCINT0_vect */ //----------------------------------------------------------- // Given a value with 1 bit set, return bit #. Else return 9. byte getBitfromBV (byte m) { byte b=0, v=1; while (v) { if (m==v) return b; ++b; v &lt;&lt;= 1; } return 9; } //----------------------------------------------------------- void processPinNumber(byte pin) { char buffi[128]; // We create text-to-write in buffi byte nbuff=0; // #chars used in buffi byte nPCICR; // 0, 1, or 2 for mask-register # byte bitInByte; // 0 to 7 for bit in I/O mask byte pinPort; // pin's port #, in range 1 to 12 byte PCInum; // PCINT# if pin is a PCI pin char *portLet = "?ABCDEFGHIJKL"; if (pin &gt;= NUM_DIGITAL_PINS) return; pinPort = digitalPinToPort(pin); // Get port #, in range 1 to 12 bitInByte = getBitfromBV(digitalPinToBitMask(pin)); nbuff = snprintf(buffi, sizeof(buffi), " %2d P%c%d 0x%02x", pin, portLet[pinPort], bitInByte, 1&lt;&lt;bitInByte); // Indicate if it's a PWM pin if (digitalPinHasPWM(pin)) { nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PWM"); } else { nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " "); } // If it's a PCINT pin, show its PCINT number and 0, 1, 2 for its vector # if (digitalPinToPCICR(pin)) { // Is it a PCint pin? nPCICR = digitalPinToPCICRbit(pin); // 0, 1, 2 for pin's PCICR bit# PCInum = nPCICR*8 + bitInByte; nbuff += snprintf(buffi+nbuff, sizeof(buffi)-nbuff, " PCINT%d PCINT%d_vect", PCInum, nPCICR); } Serial.println(buffi); } void setup() { delay(50); Serial.begin(115200); delay(50); while (!Serial) ; // wait for serial stream to connect Serial.println("\nPin# Port Mask PWM PCINT"); for (byte p=0; p&lt;NUM_DIGITAL_PINS; ++p) processPinNumber(p); Serial.end(); } void loop() { } </code></pre>
<p>Majenko was <em>very close</em> but seems to have missed the explanatory comment from the source code:</p> <pre><code>// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me) // Pins: 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69 #define digitalPinToPCICR(p) ( (((p) &gt;= 10) &amp;&amp; ((p) &lt;= 13)) || \ (((p) &gt;= 50) &amp;&amp; ((p) &lt;= 53)) || \ (((p) &gt;= 62) &amp;&amp; ((p) &lt;= 69)) ? (&amp;PCICR) : ((uint8_t *)0) ) </code></pre> <p>Which seems like it may apply to the fact that the USART3 pins PJ1 (14) and PJ0 (15) are missing.</p> <p>As for why providing mappings to the hardware USART pins "seems senseless" a little playing with git blame will show that these lines were added to this file <a href="https://github.com/arduino/Arduino/commit/f179794a45c33edcb48c493bc03fb0e39dba11db" rel="nofollow">in commit f179794</a> in response to <a href="http://code.google.com/p/arduino/issues/detail?id=490" rel="nofollow">issue 490</a>:</p> <blockquote> <p>The SoftwareSerial library defines macros that map Arduino pin numbers to the pin changes interrupts on the pins. We should pull this up into the board-specific pin definition header file so that the SoftwareSerial library can work on any AVR for which those macros (and the pin-change interrupts) are defined.</p> </blockquote> <p>Which is to say that David Mellis didn't write those lines for generic interrupt use as part of pins_arduino.h, but rather moved code <strong>originally written as part of the software serial library</strong> to this file to make things more portable (and, though perhaps incidentally, generally usable for other purposes). It's not exactly clear who the original author speaking as "I" in the comment is - the Mega-specific code in question appears to come most immediately from Mikal Hart's extension of Ladyada's Uno-only interrupt soft serial code (which did not have it) but there's also a comment in that seemingly crediting Paul Stoffregen (Teensy boards) for at least some aspect of the macro...</p> <p>It does kind of make sense that someone writing a software serial library could consider using it on hardware serial pins pointless. But counterarguments could also be made - for one example, the 16u2 core either uses or has experimented with software serial at some baud rates, and for another a software serial implementation could be a plausible way of overcoming swapped RX &amp; TX wiring, or a way of implementing inverted signalling logic when using simplified level shifters or talking to something which expects to.</p> <p>Given that in its current location the code is no longer necessarily only for software serial use, it seems plausible that a carefully written and fully validated patch to make it more general might be favorably received.</p>
16553
|arduino-uno|assembly|
Upload Assembly to AVR on a breadboard using Arduino as ISP
2015-10-04T23:38:43.910
<p>I try to learn assembly and use an arduino uno R3 to act as a programmer. i have build a standalone circuit with an atmega328p, can upload usual sketches (written in c) and have also sucessfully burned the bootloader to the external chip with the arduino as an isp but i cant bring my assembly code onto the chip on the breadboard. i tried it with avrdude and the following command</p> <pre><code>avrdude -C avrdude.conf -p atmega328p -c avrisp -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i </code></pre> <p>and also </p> <pre><code>avrdude -C avrdude.conf -p atmega328p -c arduino -P /dev/ttyACM0 -b 115200 -D -U flash:w:test.hex:i </code></pre> <p>but the code is always uploaded to the chip on the arduino - not to the one on the breadboard. can anyone lead me how to upload my assembly programm to the standalone chip on the breadboard using the arduino as isp? is this possible anyway?</p> <p>EDIT This command worked for me</p> <pre><code>avrdude -C avrdude.conf -v -v -v -v -p atmega328p -c stk500v1 -P /dev/ttyACM0 -b19200 -Uflash:w:test.hex:i </code></pre>
<p>Try uploading the blink sketch to the standalone atmega328 first. </p> <p>Once you get that to work you can get the right command form the console (after enabling verbose output, in the settings). </p>
16566
|arduino-uno|servo|
Wrong calculation UNO
2015-10-05T14:51:53.527
<p>I've a joystick and a servo connected to my UNO, but for some reason my calculations keep on being wrong? I'm trying to calculate how the rotation should be of my servo (Tower Pro 9g, max value of 180 I think) with my Joystick (Keyes_SJoys, max value of 1023 on any axis) and example would be:</p> <p>y = 500;<br> servo.write(y * 180 / 1023); // should equal to 87.97, but in reality it's 24?</p> <pre><code>#include &lt;Servo.h&gt; Servo servo; int d2 = 2; int a0 = 0; void setup() { Serial.begin(9600); servo.attach(d2); } void loop() { int y = analogRead(a0); Serial.print("y: "); Serial.println(y); servo.write(y * 180 / 1023); Serial.println(y * 180 / 1023); delay(100); } </code></pre> <p>PS. It's a Robotale UNO; I don't know if that makes any difference or not, but.</p>
<p>The reason you're getting completely the wrong value (not just losing the decimal portion) is because of a problem called <em>integer overflow</em>.</p> <p>Because the Arduino is an 8-bit device the default integer size is double that. That means that an integer value can store 16 bits, and when signed that's -32768 to 32767.</p> <p>Any calculations, unless you specify otherwise, have to fit into that range. If you take your calculation step by step you will see how it works:</p> <pre><code>500 * 180 = 90,000 </code></pre> <p>Represented in Hexadecimal (for ease of demonstration) 90,000 is 0x15F90. That is 17 bits (4 bits per digit, the left hand is just one bit since it's only the value 1), and 17 is more than the maximum 16 allowed. So we have to "overflow" that value and discard the lefthand-most digit to keep it at 16 bits. So we end up with 0x5F90.</p> <p>0x5F90 in decimal is 24464. Now we divide that by 1023 and we get:</p> <pre><code>24464 / 1023 = 23.914 </code></pre> <p>Because it's integers we have no decimal portion of it, so that just ends up as the 23 that you are seeing.</p> <p>Solutions? Change the data type.</p> <p>As @IgorStoppa has pointed out you can use floating point values which gives you big values and the decimal portion. As long as one value in your sum is floating point all the values will be. This is known as <em>promotion</em>. There's numerous ways you can force floating values:</p> <ol> <li>Represent your literals as a floating point value - that means adding a decimal place. You could have (as Igor shows) things like <code>1023.</code>, but I find that a little obscure. It's better to explicitly show a decimal value since it's obvious what it is then, such as <code>y * 180.0 / 1023.0</code>.</li> <li>Use a floating point <em>literal suffix</em>. You can add certain letters after a number to describe what that number is. <code>f</code> is for floating point: <code>y * 180f / 1023f</code>.</li> </ol> <p>Floating point is quite heavy weight though and can cause your program to get bigger than you'd like. If you're not interested in the decimal portion you can instead use <em>long</em> variables. The best way to do that is with the <em>long</em> literal suffix <code>L</code>: <code>y * 180L / 1023L</code></p> <p><em>Promotion</em> means that all the variables are <em>promoted</em> to the size of the biggest variable (not greatest value, the variable with the largest storage space). Long and Float are both 32 bits in size, so using either of those will force the other values to both be <em>promoted</em> to equivalent types.</p>
16567
|arduino-uno|
Beginner here. Which arduino revision should i buy?
2015-10-05T14:57:12.110
<p>I have no idea what difference is there between the revisions and how it affects me. I have a pdf and this pic was in there: <img src="https://i.stack.imgur.com/7ARQA.jpg" alt="arduino pic"></p> <p>My questions</p> <ul> <li>which arduino revision is this?</li> <li>Does it matter which revision i buy?</li> </ul>
<p>That looks like an early-version Uno, rather than an Uno R3 as shown below. (Image is from dxcdn.com and is one of the first few images in a <a href="https://www.google.com/search?hl=en&amp;site=imghp&amp;tbm=isch&amp;source=hp&amp;biw=1002&amp;bih=626&amp;q=UNO+R3&amp;oq=UNO+R3&amp;gs_l=img.12..0l7j0i5i30l3.1757.1757.0.2961.1.1.0.0.0.0.92.92.1.1.0.ecynfh...0...1..64.img..0.1.91.PlZ5WbbvIEA#imgrc=gYQV8pLWKcYuZM%3A" rel="nofollow noreferrer">google images for Uno R3</a> search.)</p> <p><a href="https://i.stack.imgur.com/jhKAV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/jhKAV.jpg" alt="Uno R3"></a></p> <p>For a beginner, replacing a DIP ATMEGA328P may be a chip too far. I suggest that rather than looking for an Uno with a replacable chip, get any Uno you like.</p> <p>Also note that for beginning projects, it makes sense to use the same kind of Arduino – an Uno, a Mega, a Pro Mini, a Nano, etc. – as the guide you are following uses, so that you won't have to adapt any pin numbers and wiring pictures. As you gain experience, it should become easy to adapt designs to different boards.</p>
16573
|analogread|voltage-level|battery|
Wrong analog reading
2015-10-05T18:30:06.770
<p>I am making a simple Li-Ion battery Tester. Basically its two 5R1 resistor in series and a relay (used to cut off the battery when it reaches cutoff voltage). Arduino is connected with ground to the battery and with A3 to the end of the resistors. But when I try to read the analog value, I receive something like 870, which is about 4.24V. BUT the real voltage is about 3.90V (according to my multimeter). How is that possible? Thanks for any suggestions.<a href="https://i.stack.imgur.com/CelLF.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CelLF.png" alt="enter image description here"></a></p>
<p>I have found the answer. I am not an arduino-newbie, but I was thinking that probably I am making a stupid mistake somewhere. But the problem is in <strong>my arduino</strong>. I tried setting pin D13 (and then all other pins) to HIGH, and I only measured <strong>4.60V</strong>! I measured my USB port and it outputs 5.00V exactly, so there must be a problem in the arduino. So the solution - <strong>the ADC takes 4.60V as 1023, and therefore if you calculate it you get that the real voltage is 3.90V</strong>, which is exactly the same as my DMM said. Thanks Majenko, you were pointing the right way :) By the way, I was using a cheap Arduino Nano from China, I bought it only for 2.2 USD from Ebay. When I used original Arduino, the code and circuit perfectly works. Do you think that this can limit the functionality of my board?</p>
16591
|arduino-ide|library|
A question about including libraries
2015-10-06T10:59:21.647
<p>I'm a beginner in creating my own libraries so the following might contain some stupid stuff.</p> <p>Anyways, I'm using NRF24L01+ modules for wireless communication and I've been utilizing the magnificent RF24 library (<a href="https://github.com/TMRh20/RF24" rel="nofollow">https://github.com/TMRh20/RF24</a>) to operate these modules using Arduino. I wanted to clean up my code and decided to write my own library that uses the R24 library. My own library would contain all the subroutines that handle TX and RX functions.</p> <p>Problem is that the RF24 library is initialized using e.g.</p> <pre><code>/* Hardware configuration: Set up nRF24L01 radio on SPI bus plus pins 7 &amp; 8 */ RF24 radio(7,8); </code></pre> <p>To begin using the NRF24L01+ one would the use the RF24 library like for example:</p> <pre><code>byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate. Serial.begin(57600); printf_begin(); radio.begin(); radio.setPALevel(RF24_PA_HIGH); radio.setCRCLength(RF24_CRC_16); radio.setRetries(2,15); radio.setChannel(RFChannel); if(radioNumber){ radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1 }else{ radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1,addresses[1]); } if(radioNumber == 1){ radio.startListening(); // Start listening } radio.printDetails(); </code></pre> <p>Well, now I would like to make a library that would allow me just to call setup to handle all of the above. My library would be called RadioComm so I would call in my main code:</p> <pre><code>RadioComm rComm(); setup() { rComm.setup(); } </code></pre> <p>The problem is that how do I use the RF24 library and all its functions in my library? To initialize the RF24 library in my own library I would have to call somehow this</p> <pre><code>RF24 radio(7,8); </code></pre> <p>and use all the radio. commands. How do I tell my own library that everything starting with "radio." is related to RF24 library because right now I'm getting this:</p> <pre><code>RadioComm.cpp: In member function 'void RadioComm::setup()': RadioComm.cpp:20:18: error: 'radio' was not declared in this scope radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 &amp; 10 </code></pre> <p>Below are my .h .cpp and .ino files </p> <p>Lib_test.ino</p> <pre><code>#include &lt;RadioComm.h&gt; #include &lt;RF24.h&gt; #include &lt;SPI.h&gt; RadioComm rComm; void setup() { rComm.setup(); } void loop() { } </code></pre> <p>RadioComm.h</p> <pre><code>#ifndef RadioComm_h #define RadioComm_h #include "Arduino.h" #include &lt;RF24.h&gt; struct dataStruct{ unsigned long id; float value1; float value2; float value3; float value4; }; class RadioComm { public: RadioComm(); void setup(void); private: int pin1; int pin2; }; #endif </code></pre> <p>RadioComm.cpp</p> <pre><code>#include "Arduino.h" #include "RadioComm.h" #include &lt;RF24.h&gt; #include "printf.h" RadioComm::RadioComm(void) {} void RadioComm::setup() { byte addresses[][6] = {"1Node","2Node"}; // Radio pipe addresses for the 2 nodes to communicate. radio(pin1,pin2); // Set up nRF24L01 radio on SPI bus plus pins 9 &amp; 10 Serial.begin(57600); printf_begin(); radio.begin(); radio.setPALevel(RF24_PA_HIGH); radio.setCRCLength(RF24_CRC_16); radio.setRetries(2,15); radio.setChannel(RFChannel); if(radioNumber){ radio.openWritingPipe(addresses[1]); // Both radios listen on the same pipes by default, but opposite addresses radio.openReadingPipe(1,addresses[0]); // Open a reading pipe on address 0, pipe 1 }else{ radio.openWritingPipe(addresses[0]); radio.openReadingPipe(1,addresses[1]); } if(radioNumber == 1){ radio.startListening(); // Start listening } radio.printDetails(); } </code></pre> <p>Any help is appreciated.</p> <p>Thanks.</p>
<p>Firstly, to address your compilation error:</p> <pre><code>RadioComm rComm(); </code></pre> <p>That is not a constructor, that is a function prototype. When you have no parameters to a constructor you <em>must not</em> include the brackets or it confuses the poor little compiler. </p> <pre><code>RadioComm rComm; </code></pre> <p>Now - to address your main question. Well, there's many ways of doing it, but the way I always tackle this is to have your sketch define the RF24 object and pass it to the library for later use.</p> <p>In the class definition, in the <code>private</code> section, add:</p> <pre><code>RF24 *radio; </code></pre> <p>Then change the constructor to have:</p> <pre><code>RadioComm(RF24 &amp;r); </code></pre> <p>The constructor itself would then read:</p> <pre><code>RadioComm::RadioComm(RF24 &amp;r) { radio = &amp;r; } </code></pre> <p>Now throughout your library, instead of working with <code>radio.whatever</code> you need to work with <code>radio-&gt;whatever</code> since you are now using a pointer to an object not the object itself.</p> <p>Then in your sketch you need to adjust your constructor to be:</p> <pre><code>RF24 myRadio(7, 8); RadioComm rComm(myRadio); </code></pre> <p>The beauty of this is it decouples the configuration of the RF24 class from the RadioComm class, so you can use the same library in a different situation on a different board with different pins without having to change the library - just change the RF24 constructor in your sketch.</p> <p>It also gives you direct access to the RF24 class in your sketch so you can do any advanced manual tweaks outside the library should you wish to.</p>
16595
|arduino-uno|programming|c++|
MPU-9250 : How to convert pitch (+90/-90) to 360 degree?
2015-10-06T13:50:46.487
<p>I'm using Arduino Uno with MPU-9250 to find roll, pitch and yaw. </p> <p>Everything works fine but I want to covert pitch from (+90/-90) to 360 degree.</p> <p>I'm using this code:</p> <pre><code>vec.setX(atan2(2.0 * (m_data[2] * m_data[3] + m_data[0] * m_data[1]), 1 - 2.0 * (m_data[1] * m_data[1] + m_data[2] * m_data[2]))); vec.setY(asin(2.0 * (m_data[0] * m_data[2] - m_data[1] * m_data[3]))); vec.setZ(atan2(2.0 * (m_data[1] * m_data[2] + m_data[0] * m_data[3]), 1 - 2.0 * (m_data[2] * m_data[2] + m_data[3] * m_data[3]))); m_data[0] = scalar; m_data[1] = x; m_data[2] = y; m_data[3] = z; </code></pre> <p>What should I do?</p>
<p>The equations in you example convert a quaternion representation of rotation into euler angles correctly; The "pitch" euler angle only has a valid range of +90/-90 and changing it will make your angular representation invalid.</p> <p>Euler angles specify an arbitrary rotation by 3 consecutive turns. You may want "apparent angle with the horizon", which is not the same thing, and does not define a sequential set of turns to get from rotation A to B.</p> <p>To get pitch and roll with the horizon from a quaternion, I think you want something like:</p> <pre><code>float x = 2*m_data[1]*m_data[3] - 2*m_data[2]*m_data[0]; float y = 2*m_data[1]*m_data[0] + 2*m_data[2]*m_data[3]; float z = 1 - 2*m_data[2]*m_data[2] - 2*m_data[1]*m_data[1]; float pitch = atan2(y,z); float roll = atan2(x,z); </code></pre> <p>I got this by rotating the vector &lt;0,0,1> by the quaternion and then measuring the angles of the result around x and y axis. This kind of freaks out when one of the angles is close to 90 degrees though; there are probably better equations out there.</p> <p>"Yaw vs the horizon" doesn't make any sense, and people usually want the same "style" of yaw you are getting from the euler angle equations, so that shouldn't change.</p>
16599
|arduino-uno|
Help understanding code to build circuit for plant reader
2015-10-06T17:46:48.190
<p>I'm working a design project that measures the tiny changes of conductivity in a plant. (To visualize how a plant reacts to its environment) I'm working with Arduino to realize that. Two wires are hooked up to the plant to measure the changes and are connected to the Arduino. I haven't worked with Arduino before but a friend got me the code from his plant reader (he got help too and doesn't know how to build it anymore). I do understand most of it but I just don't manage to translate the code he gave me into a circuit on the Arduino bread board. I use processing to visualize the measurements afterwards. <a href="https://i.stack.imgur.com/IrmNL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/IrmNL.png" alt="Code plant reader"></a></p> <p>Who can help me building the circuit. I don't get what's happening at pin13. Thank you for helping me :)</p>
<p>Pin13 is attached to the onboard LED.</p> <p>So when you see a reference to it, it means that the program is turning the light ON/OFF. You do not need to do any wiring with it.</p> <p>But the logic seems strange: it turns the LED off only when the analog reading is out of range (and it resets the stress).</p> <p>It seems to imply that once the plant is stressed, it will stay stressed :-)</p> <p>Btw, as side note: posting the code in ASCII form would allow people to quote/comment on it. The screenshot is not very good for that purpose.</p> <p>What cannot be figured out from the code, is how to instrument your plant. If your friend has a working setup, you could try to replicate it. At least post a few pictures.</p>
16602
|arduino-mega|power|hardware|relay|system-design|
Arduino and 127/220 Volts: Relay and Isolation
2015-10-06T18:27:41.587
<p>I am new to Arduino, also, I am not fluent in english.</p> <p>I wish to create a controller for several circuits. All of those circuits are "in parallel" with additional circuits.</p> <p>My question is:</p> <ul> <li>Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?</li> </ul> <p>Suppose the following:</p> <p><a href="https://i.stack.imgur.com/EhmwY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EhmwY.png" alt="Eletric wiring"></a></p> <p>The retangular boxes are "parallel switches" connected to the devices.</p> <pre><code>R = Power Supply Phase S = Another Power Supply Phase N = power Supply Neutral Arduino, C2 and C3 are 127 Volts, (S+N) C0 and C1 are 220 Volts (R+S) </code></pre> <ul> <li><p>Are the Shields safe from oscilations from the eletrical supply?</p></li> <li><p>What / Where / How should I look on what to ground? Local regulations state that I cannot let R and/or S be grounded.</p></li> </ul>
<blockquote> <p>Do a Relay Shield protects the Arduino board from the current and voltage from the power supply?</p> </blockquote> <p>A relay provides <em>galvanic isolation</em> in the circuit. The mains power is electrically isolated from the rest of the circuit since the device that performs the actual switching (the contacts in the relay) have no physical connection to the rest of the circuit - they are merely acted upon by magnetism.</p> <p>That doesn't mean that it's <em>safe</em>, however. There are a number of things you still need to deal with:</p> <ul> <li>The Arduino cannot directly drive a relay - it can't provide enough current. You must use a drive circuit.</li> <li>Back-EMF from the relay coil as the magnetic field collapses can damage sensitive semiconductors - good snubber circuit design is important here.</li> <li>Mains electricity is dangerous and must be treated with respect. Proper circuit design is paramount to ensure that the mains is kept away from the rest of the circuit. Proper connectors must be used and exposed high voltage points must be rendered inaccessible, either by the project housing or by the addition of plastic insulating shielding.</li> <li>Relays as they turn on and off cause sparks. Sparks cause EMI. EMI causes induced currents. Induced currents cause damage to electronics. Minimizing the spark generation not only prolongs the life of your relay but the life of everything else around. Ensure your relays can switch fast enough for the currents you are dealing with, or consider using <em>solid state relays</em> (SSRs) that don't suffer from this issue.</li> </ul>
16606
|arduino-uno|communication|softwareserial|
What is the relationship between the gain on the receiver and the delay time
2015-10-07T00:41:41.917
<p>I was conducting some research on wireless communication between a simple transmitter and receiver module using an Arduino. Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%. I am not quite sure why the data would result in this. I think it possibly has something to do with the gain on the receiver and the delay time. Some sweet spot perhaps? Can anyone offer me some ideas/explanations? Also, sorry for any confusion in this question. I am happy to clarify. </p> <p>Part 2:</p> <p>Hey Everyone, </p> <p>I also had a question regarding what purpose each of the following delay serves in wireless communication. </p> <pre><code>// Write each of the 8 bits for (uint8_t i = 8; i &gt; 0; --i) { if (b &amp; 1) // choose bit *reg |= reg_mask; // send 1 else *reg &amp;= inv_mask; // send 0 tunedDelay(delay);// line in question --------------------- b &gt;&gt;= 1; } </code></pre> <p>and the delay used in the regular blink program. </p> <p><strong>The regular delay used in the blink programs was what set the 2 microsecond delays.</strong></p> <p>Lastly, I am looking at the read and recv methods in the software serial library and i don't see any checks for start bits, so what's the point of writing one in the write method? </p>
<blockquote> <p>Now, I tested the channel accuracy and i received 14% error for a delay of one micro second. For a delay of 2 microseconds, my error was 0%, and for three microseconds, my error rate was 30%.</p> </blockquote> <p>Microsecond resolution delays on an Arduino are tenuous at best. They aren't that accurate. Simply because you're hitting the limit of the speed of the CPU.</p> <p>At 16MHz you have a clock period of 1/16000000 seconds. That's 63ns. That's the <em>granularity</em> of the delays you can achieve - and that can only be achieved by inserting a precise number of <code>NOP</code> assembly instructions.</p> <p>So for the best 1µs delay possible you would need (0.000001 / 0.000000063) 15.87 <code>NOP</code> instructions. Of course, you can't have that many, so you have to round it either up or down. Normal integer truncation would result in 15. So that would actually be a delay of 945ns, which is an error of 5.5%.</p> <p>2µs would be (0.000002 / 0.000000063) 31.74 <code>NOP</code> instructions, which would round to 31, so 1.953µs, or an error of 2.35%. As you can see increasing the length generally reduces the error.</p> <p><em>HOWEVER</em></p> <p>The delay function on the Arduino for microsecond accuracy (<code>delayMicroseconds()</code>) is maybe not as accurate as it could be. Simply because it's impossible to just have an exact number of NOP instructions for a delay since you can't know how long the delay should be until the function is called with a parameter detailing how long the delay should be. So it has to perform a number of calculations and <em>make a number of assumptions</em>. It tries to come close, but it was written for one specific version of the compiler and compilers change. Things may have been changed in how the function gets called, and how long parts of it take (what registers are pushed and popped may change with different compiler versions, for instance). So it's not a perfectly reliable delay.</p> <p>For more detail you can look at the source code of it (it's in <code>wiring.c</code>) and you can see how for small delays it's very hard to get it right. For instance, this couple of lines highlights the problem nicely:</p> <pre><code> // for a one-microsecond delay, simply return. the overhead // of the function call yields a delay of approximately 1 1/8 us. if (--us == 0) return; </code></pre> <p>Note the use of the word <em>approximately</em> there...</p> <p>Also you need to note that the delay functions are just that - a delay <em>at that specific moment in time from the start of the call to its finish</em>. It doesn't take into account anything else that's going on in your code, so a delay of 1µs in a loop of code that does other things will end up in a loop that takes <code>X + 1µs</code> where <code>X</code> is the amount of time that the rest of the code takes to execute.</p> <p>And that's where the <code>tunedDelay()</code> function comes in. It has been specially written to be used in that specific circumstance to provide a delay that <em>takes into account the time the rest of the loop takes to run</em>. That is, the loop's time plus the <code>tunedDelay</code> time equate to the final period you want for the whole loop. For asynchronous serial communications the timing accuracy is important. Since there is no separate (or even embedded) clock to get the timing from both ends have to agree what speed the communication happens at (the baud rate), and any deviation from that can cause communication errors. So the timing has to be as close as possible. A normal <code>delayMicroseconds()</code> function call just wouldn't cut the mustard - they needed it more precise than that. Manually tuned to have specific delay values that are as precise as possible, and that was done for specific baud rates on specific speed chips. Each supported frequency has a table such as this:</p> <pre><code>static const DELAY_TABLE PROGMEM table[] = { // baud rxcenter rxintra rxstop tx { 115200, 1, 17, 17, 12, }, { 57600, 10, 37, 37, 33, }, { 38400, 25, 57, 57, 54, }, { 31250, 31, 70, 70, 68, }, { 28800, 34, 77, 77, 74, }, { 19200, 54, 117, 117, 114, }, { 14400, 74, 156, 156, 153, }, { 9600, 114, 236, 236, 233, }, { 4800, 233, 474, 474, 471, }, { 2400, 471, 950, 950, 947, }, { 1200, 947, 1902, 1902, 1899, }, { 600, 1902, 3804, 3804, 3800, }, { 300, 3804, 7617, 7617, 7614, }, }; </code></pre> <p>That's the value to send to the <code>tunedDelay()</code> function in the four different situations where its used for each of the baud rates at that specific clock frequency (16MHz in that example).</p> <p><code>tunedDelay()</code> itself is written in assembly code and is a very tight loop for the number of iterations specified in the parameter. The shortest possible piece of code with the minimum of overhead to get the maximum accuracy and finest granularity (least number of clock cycles for one iteration) out of it. </p>
16609
|i2c|adafruit|
Connect 2 LSM9DS0 to Flora
2015-10-07T04:26:39.903
<p>So I'd like to connect two of these sensors to an Adafruit Flora (<a href="https://www.adafruit.com/products/2020" rel="nofollow">https://www.adafruit.com/products/2020</a>). In the product page it says you can only connect one but in the forum an admin said that you could do it but it required a bit of hacking. I'm new to arduinos and circuits in general. Can someone tell me how I could do this, or at least point me in the right direction?</p> <p><strong>Edit</strong></p> <p>I decided to use this multiplexer to use LSM9DS0's with the Flora. <a href="https://www.adafruit.com/products/2717" rel="nofollow">https://www.adafruit.com/products/2717</a></p>
<p><a href="https://learn.adafruit.com/adafruit-lsm9ds0-accelerometer-gyro-magnetometer-9-dof-breakouts" rel="nofollow noreferrer">Adafruit's rectangular 9DOF</a> device, unlike <a href="https://www.adafruit.com/products/1059" rel="nofollow noreferrer">their round 9DOF</a>, brings several more signals out to pads. When using I²C with the rectangular 9DOF board, as I understand it signal pin SA0_G can be set low or high to modify the device address:</p> <blockquote> <p>The SDO/SA0 pins (SDO_XM/SA0_XM or SDO_G/SA0_G) can be used to modify the least significant bit of the device address. If the SA0 pin is connected to the voltage supply, LSb is 1 (ex. address 0011101b) else if SA0 pad is connected to ground, the LSb value is 0 (ex. address 0011110b).</p> </blockquote> <p>Controlling that signal should let you put multiple 9DOF's on one system. (See my answer to <a href="https://arduino.stackexchange.com/questions/13830/arduino-due-and-bno055-address-in-i2c-mode/13833#13833">question 13830</a> for some additional comments on setting an I²C address.) Also see tables 15 and 16 on page 33 in the spec sheet (DM00087365.pdf) regarding addresses.</p> <p>If you insist on using round 9DOFs for this application, you would need to find the trace from pin 22<sup>¤</sup> of the LSM9DS0 to Vcc on <em>one</em> of your 9DOF boards; working under a microscope with miniature tools, cut the trace and rewire the pin end of the trace to Ground. This will change that board from using addresses 0x1D and 0x6B to 0x1E and 0x6C, if I correctly understand the spec sheet.</p> <p>It probably would be a good idea to get one of the rectangular 9DOF's so that you could experiment with changing its addresses, before modifying one of the round ones.</p> <p><sup>¤</sup> Looking at the top of the chip, pin 24 is just clockwise from the depressed round dot marking pin 1; pin 22 is 1.75 mm from the corner. See Figure 21, LGA 4x4x1 mm 24-lead outline, in the spec sheet. That figure shows the underside of the chip.</p>
16620
|c++|library|
Error in Arduino Library file
2015-10-07T10:24:07.170
<p>I am working on a project which includes Arduino and a fingerprint scanner. It is completely based on embedded system. But then, I have downloaded a library for the fingerprint scanner. When I run the program I get an error which maps to the cpp file of the library file. See below to see the error and the library file.</p> <p><strong>Error</strong></p> <blockquote> <p>FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function Command_Packet::GetPacketBytes()': C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:17: undefined reference tooperator new[](unsigned int)' FPS_GT511C3\FPS_GT511C3.c.cpp.o: In function FPS_GT511C3::GetResponse()': C:\Users\Dipti\Documents\Arduino\libraries\FPS_GT511C3/FPS_GT511C3.c.cpp:735: undefined reference tooperator new[](unsigned int)' collect2.exe: error: ld returned 1 exit status</p> </blockquote> <p>Library File (CPP)</p> <blockquote> <p>byte* packetbytes= new byte[12];</p> <p>byte* resp = new byte[12];</p> </blockquote>
<p>The core of the problem is that the code is being compiled as C and not C++.</p> <p>The error says 'new[]' is undefined at the link stage. This is because the linker is not pulling in the C++ standard libraries. The built-in function new[] it doesn't exist in C. </p> <p>The filename FPS_GT511C3.c.cpp is the elephant in the room. You could consider renaming it (and others) to FPS_GT511C3.cpp. Although the plain Arduino IDE does not really have a problem with building them.</p> <p>Another option might be to modify the new[] (and delete[]) for C's malloc() and free(). However this is only appropriate for the allocation of simple types (byte, int, etc). If the code also allocates objects, it's not possible to simply swap these functions out since C++ (default) initialisation is be going on.</p>
16625
|arduino-uno|gsm|
Can I use these cheap GSM module with arduino?
2015-10-07T19:02:52.590
<p>I found two cheap GSM module on ebay but didn't know that I can use them with Arduino or not. Will you help me please?</p> <p>Here are the link-</p> <p><a href="http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8" rel="nofollow">http://www.ebay.co.uk/itm/Smallest-SIM800L-GSM-Module-Micro-SIM-Board-Quad-band-Port-Onboard-Antenna-/111789339320?hash=item1a0729f2b8</a></p> <p><a href="http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&amp;_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292" rel="nofollow">http://www.ebay.co.uk/itm/SIM900A-Development-Board-Extension-Module-GSM-GPRS-Antenna-TTL-e/281517486292?_trksid=p2045573.c100033.m2042&amp;_trkparms=aid%3D111001%26algo%3DREC.SEED%26ao%3D1%26asc%3D20131017132637%26meid%3D70128bc79b60410d862b64d36cc479b3%26pid%3D100033%26rk%3D1%26rkt%3D4%26sd%3D281517486292</a></p>
<p>You can actually use the sim900a and 900a mini in the uk but you will have to download firmware and flashing tools that you will find with a web search, not for the beginner though, an 800l is your best bet with a SMA Female JACK Connector to U.FL/IPX Converter Pigtail Cable F1445K so you can attach an sma antenna</p> <p>cheers Stuart</p>
16646
|arduino-uno|button|
How is LED powered when PIN 2 is disconnected?
2015-10-08T15:02:09.557
<p>Using the Arduino tutorial "<a href="https://www.arduino.cc/en/Tutorial/Button" rel="nofollow noreferrer">Button</a>", I have noticed that if I totally disconnect Pin2 from the circuit, the LED comes on dimly.</p> <p>I am trying to understand HOW this happens. Is it simply due to being a floating ground?</p> <p><a href="https://i.stack.imgur.com/St0Tc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/St0Tc.png" alt="enter image description here"></a></p>
<p>The <code>pinMode(buttonPin, INPUT);</code> line tells the board to set the <code>buttonPin</code> in high impedance mode.</p> <p>When you disconnect the wire the state of that pin becomes unknown; usually it oscillates. Since it is oscillating, the LED turns on and off randomly: you see it "dimly light".</p> <p>The usual solution is to use a pull-up or pull-down. I suggest you to wire your buttons towards the ground, declare the pins as <code>pinMode(buttonPin, INPUT_PULLUP);</code> and invert the logic (i.e. <code>buttonState = !digitalRead(buttonPin);</code>). This way it will never oscillate again.</p>
16648
|power|led|arduino-nano|
Using an Arduino Nano, how many LEDs can I safely power?
2015-10-08T17:11:02.023
<p>I am working on building a wordclock using one of the several design ideas that you can find all over the Internet. Something like a mix of this one: <a href="http://www.instructables.com/id/Sleek-word-clock/" rel="nofollow">http://www.instructables.com/id/Sleek-word-clock/</a> and this one: <a href="http://www.instructables.com/id/Personalised-Word-Clock/" rel="nofollow">http://www.instructables.com/id/Personalised-Word-Clock/</a> A lot of the guides suggested building your own Arduino to save money, but I found these Arduino Nano clones for $7/apiece: <a href="http://rads.stackoverflow.com/amzn/click/B00SGMEH7G" rel="nofollow">http://www.amazon.com/gp/product/B00SGMEH7G</a>.</p> <p>I've done a few simple projects before, but nothing with the same kind of power demand. How can I figure out the power requirements? My plan is to use approximately 64 3mm LEDs via shift register, or possibly the equivalent segments of an LED strip.</p> <p>The Nano clone does not have a barrel connector for external power adaptor. Should I directly solder on the power cables from an external adaptor? Use a screw terminal or similar? Is the USB adaptor a good enough source of power for 64 LEDs? Or do I have to do something else to supply external power to that many LEDs?</p> <p>Thanks for any advice! I am experienced in programming but not in electrical engineering so many of the concepts are something I don't have a good handle on yet.</p>
<p>If you are running the LEDs from shift registers then the power rating of the Nano is irrelevant.</p> <p>If you are wanting to use the Nano as the power source (not recommended) then you would need to know both your expected current and what the regulator on the Nano would be able to supply. My immediate guess is "not enough".</p> <p>64 LEDs at full brightness would be expected to use a maximum of say 20mA each, so 1.28A just for the LEDs. That's a huge amount, and way more than any linear regulator can be expected to supply without melting everything around it.</p> <p>So you can reduce your current requirements by not having the LEDs as bright. Half the current does not equate to half the apparent brightness. In fact at half the current you probably won't notice much difference at all. At a tenth of the current you will see them a bit dimmer, but not as much as you would expect.</p> <p>So you can come up with a compromise between the brightness you desire and the current consumed by each LED. </p> <p>Say you end up deciding on (as Gerben has suggested) a current of 5mA per LED. When all LEDs are on that would be (5 × 64) 320mA. That's reasonable for a linear regulator, but still will generate more heat than is really advisable.</p> <p>So you should, for this project (assuming you aren't going to be using multiplexing, which is a whole other ballgame), investigate using a switching (aka "buck") regulator. You can pick these up on eBay for just a couple of dollars and can quite happily supply amps as opposed to milliamps and will allow you to run far more LEDs without going into thermonuclear meltdown.</p> <p>Another important consideration to think about is how much current an individual shift register can provide - both through its output pins and in total for the whole chip. There are special constant current LED driving shift registers that remove the need for individual resistors on each LED and give much better control over the LEDs than traditional logic output shift registers.</p>
16650
|arduino-uno|gps|
Can I use this cheap GPS module with arduino
2015-10-08T19:37:35.773
<p>For my project I need a GPS module, it should be cheap and I should be able to use it with arduino, after some search I got a product on ebay, I'm a 16 year old school boy and I didn't know that it will work with Arduino or not. Help me.</p> <p>Here is the link-- <a href="http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8" rel="nofollow">http://www.ebay.co.uk/itm/DIYMALL-VK16E-Module-Gmouse-GPS-Module-SIRF3-Chip-with-Ceramic-Antenna-TTL-Level-/181594912168?hash=item2a47e675a8</a></p>
<p>After some research it seems you can use that gps module with an Arduino. Here's a link to the data sheet for it: <a href="http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf" rel="nofollow">http://www.hanssummers.com/images/stories/ultimategps/vk16e.pdf</a>. Also it seems like you have to use the TinyGPSPlus library to get it to work. Here's a link to learn more about it: <a href="http://arduiniana.org/libraries/tinygpsplus/" rel="nofollow">http://arduiniana.org/libraries/tinygpsplus/</a>. You may have to use the protocols in this data sheet: <a href="https://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual-Rev2.1-Dec07.pdf" rel="nofollow">https://www.sparkfun.com/datasheets/GPS/NMEA%20Reference%20Manual-Rev2.1-Dec07.pdf</a>. </p> <p>All of this information was taken from this thread: <a href="https://www.linkedin.com/grp/post/4573843-5806249757395406852" rel="nofollow">https://www.linkedin.com/grp/post/4573843-5806249757395406852</a>.</p>
16659
|arduino-uno|c++|
Alternative to delay function
2015-10-09T06:27:50.767
<p>I am trying to make a workaround for the delay function. I am trying to use the function in the Analog Write Mega example, by replacing delay with the function i made. However, whenever i use my function instead of delay i get incorrect led behaviour. </p> <p>Here is the link to the example: </p> <p><a href="https://www.arduino.cc/en/Tutorial/AnalogWriteMega" rel="nofollow">https://www.arduino.cc/en/Tutorial/AnalogWriteMega</a></p> <p>Here is my code:</p> <pre><code>int currmillis = 0; //used in my function to find the current millis() int prevmillis = 0; //used to hold previous value of currmillis int boolval = 0; //used to control whether to write the brightness value to the led or not int time = 0; //used in the delay function, difference between currmillis and prevmillis int timeloop(int); //the function i wrote, it is at the bottom of the code void setup() { Serial.begin(9600); for ( int i = 2; i &lt;= 13; i++) { pinMode(i,OUTPUT); } }//Setting the pins to output and allowing serial communication. void loop (){ for ( int thisPin = 2; thisPin &lt;= 13; thisPin++ ) //to move from one led to the next { for ( int brightness = 0 ; brightness &lt;= 255; brightness++) //change the brightness of the led { boolval = timeloop(2); //the delay function returns the time passed, if the time is greater than or equal to 2, the analogWrite will write the brightness to the led if (boolval &gt;= 2){ analogWrite(thisPin, brightness); }// if 2 ms pass, the led brightness will increase from 0 to 255 and then decrease in the following loop from 255 to 0, Once it reaches 0, the main loop moves to the next led. } for ( int brightness = 255 ; brightness &gt;= 0 ; brightness--) { boolval = timeloop(2); if (boolval &gt;= 2){ analogWrite(thisPin, brightness); } } timeloop(100); // a delay of 100 ms using the function } } int timeloop (int interval){ // the delay function do{ prevmillis = currmillis; //hold previous value currmillis = millis(); //find current value time = (currmillis-prevmillis); }while(time &lt; interval); return time; } </code></pre> <p>Thank you</p>
<p>Depending on what you want the alternative function to do, there are a megaton of timer libraries at the <a href="http://playground.arduino.cc/Main/LibraryList#Timing" rel="nofollow">Arduino playground</a>. One of them is likely to provide what you need.</p>
16662
|arduino-uno|gsm|
Multiple If statements
2015-10-09T11:22:26.837
<p>I am using following code for my arduino project in which i have to control a dc motor using arduino uno via text messages. my question is that i have used multiple number of 'If' statements and only one else statement at the last, i compiled this code and gives no error, is it ok to use multiple If statements one after another without using else after each if?</p> <pre><code>#include &lt;LiquidCrystal595.h&gt; #include &lt;GSM.h&gt; GSM gsmAccess; GSM_SMS sms; char sendernumber[20]; int Enable_m=11; int Control_2=12; int Control_7=10; LiquidCrystal595 lcd(7,8,9); void setup() { Serial.begin(9600); pinMode(Enable_m,OUTPUT); pinMode(Control_2,OUTPUT); pinMode(Control_7,OUTPUT); digitalWrite(Enable_m,LOW); digitalWrite(Control_2,LOW); digitalWrite(Control_7,LOW); lcd.begin(16,2); lcd.clear(); lcd.setCursor(0,0); lcd.print("Hello"); lcd.setCursor(0,1); lcd.print("Everyone"); delay(2000); while (!Serial) Serial.println("SMS Messages Receiver"); boolean notConnected = true; while(notConnected) { if(gsmAccess.begin("0000")==GSM_READY) notConnected = false; else { Serial.println("Not connected"); delay(1000); } } Serial.println("GSM initialized"); Serial.println("Waiting for messages"); } void loop() { // put your main code here, to run repeatedly: char c; int val=0; val=digitalRead(Enable_m); if (val==LOW){ digitalWrite(Enable_m,HIGH); } if (sms.available()) { Serial.println("Message received from:"); sms.remoteNumber(sendernumber, 20); Serial.println(sendernumber); if(sms.peek()=='#') { Serial.println("Discarded SMS"); sms.flush(); } while(c=sms.read()) if(c=='motoroff'){ analogWrite(Enable_m, 0); digitalWrite(Control_2,LOW); digitalWrite(Control_7,LOW); } if(c=='motoronclockwise'){ analogWrite(Enable_m, 255); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } if(c=='motoronanticlockwise'){ analogWrite(Enable_m, 255); digitalWrite(Control_2,HIGH); digitalWrite(Control_7,LOW); } if(c=='speedhalf'){ analogWrite(Enable_m, 128); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } if(c=='speedquarter'){ analogWrite(Enable_m, 65); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } if(c=='speed75'){ analogWrite(Enable_m, 192); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } else{ digitalWrite(Enable_m,HIGH); Serial.print(c); } Serial.println("\nEND OF MESSAGE"); sms.flush(); Serial.println("MESSAGE DELETED"); } } </code></pre>
<pre><code>#include &lt;LiquidCrystal.h&gt; #include &lt;GSM.h&gt; GSM gsmAccess; GSM_SMS sms; char sendernumber[20]; int Enable_m=11; int Control_2=12; int Control_7=10; LiquidCrystal lcd(7,8,9,8,1,2,3,4,5,6); void setup() { Serial.begin(9600); pinMode(Enable_m,OUTPUT); pinMode(Control_2,OUTPUT); pinMode(Control_7,OUTPUT); digitalWrite(Enable_m,LOW); digitalWrite(Control_2,LOW); digitalWrite(Control_7,LOW); lcd.begin(16,2); lcd.clear(); lcd.setCursor(0,0); lcd.print("Hello"); lcd.setCursor(0,1); lcd.print("Everyone"); delay(2000); while (!Serial) Serial.println("SMS Messages Receiver"); boolean notConnected = true; while(notConnected) { if(gsmAccess.begin("0000")==GSM_READY) notConnected = false; else { Serial.println("Not connected"); delay(1000); } } Serial.println("GSM initialized"); Serial.println("Waiting for messages"); } void loop() { // put your main code here, to run repeatedly: // I chose 160 since that is max size for sms char message [160]; // this fills message with null characters memset( message, '\0', sizeof(char)*160 ); int val=0; val=digitalRead(Enable_m); if (val==LOW){ digitalWrite(Enable_m,HIGH); } if (sms.available()) { Serial.println("Message received from:"); sms.remoteNumber(sendernumber, 20); Serial.println(sendernumber); // you used single qoutes properly here // single qoutes denote a char which is a single character if(sms.peek()=='#') { Serial.println("Discarded SMS"); sms.flush(); } // this will add the characters to messages[] for(int i = 0; message[i] = sms.read(); i++){} // I changed this to double qoutes since you need double // qoutes to denote a string literal if(strcmp(message, "motoroff") == 0){ analogWrite(Enable_m, 0); digitalWrite(Control_2,LOW); digitalWrite(Control_7,LOW); } else if(strcmp(message, "motoronclockwise") == 0){ analogWrite(Enable_m, 255); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } else if(strcmp(message, "motoronanticlockwise") == 0){ analogWrite(Enable_m, 255); digitalWrite(Control_2,HIGH); digitalWrite(Control_7,LOW); } else if(strcmp(message, "speedhalf") == 0){ analogWrite(Enable_m, 128); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } else if(strcmp(message, "speedquarter") == 0){ analogWrite(Enable_m, 65); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } else if(strcmp(message, "speed75") == 0){ analogWrite(Enable_m, 192); digitalWrite(Control_2,LOW); digitalWrite(Control_7,HIGH); } // This else will only be executed if the previous if and else if statements are false else{ digitalWrite(Enable_m,HIGH); Serial.print(message); } Serial.println("\nEND OF MESSAGE"); sms.flush(); Serial.println("MESSAGE DELETED"); } } </code></pre> <p>So I've made some edits to your code. For example this code <code>'motoronanticlockwise'</code> isn't correct. Single quotes are used for <code>char</code> data types and double quotes are used for string literals. You should use double quotes since there are multiple characters <code>"motoronanticlockwise"</code>. Also as Majenko said you would have to use <code>strcmp()</code> in order to compare <code>c-strings</code> c-strings are <code>char</code> arrays that have a null terminator <code>'\0'</code>. Also <code>strcmp()</code> returns <code>0</code> if the two strings are equal.</p> <p>Your last <code>else</code> statement will only executed if the previous <code>if</code> statement is <code>false</code>. It seems like you only want it to execute if <strong>all</strong> of the previous <code>if</code> statement are false. To do this you make the first <code>if</code> statement and then make a chain of <code>if else</code> statements followed by a single <code>else</code> statement. You can have a single <code>if</code> statement with no <code>else</code> or <code>if else</code> statements however, if you want <code>else</code> or <code>if else</code> statements then you need to have an <code>if</code> statement. I've made the necessarily edits to your code already.</p> <p>Lastly, this part of the program is the biggest problem <code>while(c=sms.read())</code> This is because <code>sms.read()</code> returns a <code>char</code> so you can only read the sms message one character at a time. To do this properly you should make a character array and store the values returned by <code>sms.read()</code> in it. This can be done like this </p> <pre><code>char message [160]; // I chose 160 since that is max size for sms memset( message, '\0', sizeof(char)*160 ); // this fills message with null characters // this will add the characters to messages[] for(int i = 0; message[i] = sms.read(); i++){} </code></pre> <p>I am using a <code>for</code> loop to iterate through <code>message[]</code>. </p> <p>Try the above and get back to me if there are any problems with it.</p>
16663
|eeprom|
How do you write to a free location on an external EEPROM?
2015-10-09T11:32:43.673
<p>I want to log GPS positions to an external EEPROM over I2C.</p> <p>For example: Latitude: 51.0000 Longitude: 4.0000</p> <p>If I remove the decimal place then each of these addresses would consume up to two bytes each.</p> <p>My question is: <strong><em>How can I log each new set of GPS data to a new memory address on the EEPROM each time?</em></strong> </p> <p>Bearing in mind that the Arduino might be switched off between entries.</p>
<p>The question asks specifically about EEPROM (E2) and many of the answers point out or attempt to address E2's main limitation: limited # of write operations. Not mentioned is E2's slow speed. Its is best suited for storing infrequently modified data such as-built- or setup parameters such device calibration data and features of a device's external operating environment. Its only real advantage over other solutions is that it may already exist on your MCU - Atmega 328, for instance. </p> <p>The new(er) kid on the block for non-volatile data storage is Ferroelectric RAM - FRAM. Write times are on the order of 30 times faster, at 150ns, and endurance is claimed to be 10^12 writes, or 10 million TIMES the endurance of E2. I've built a data logger that uses a ring-buffer in FRAM to store periodic data samples and write them on request.</p> <p>The same techniques proposed in the answers for E2 will work equally well in FRAM with the additional advantage that you can ignore the complications meant to work around E2's limited write-endurance.</p> <p>And by way of disclaimer: I don't sell this this stuff or have any other interest in it. But I do use it and it works like it says on the box.</p> <p><a href="https://www.adafruit.com/product/1897" rel="nofollow noreferrer">Adafruit makes these</a> on a breakout board in a couple of variations - size and serial-bus type - that are sold by them and other retailers. The link is for an 8K-byte, SPI-bus board.</p>
16672
|c++|arduino-ide|
error: expected primary-expression before ',' token
2015-10-09T14:27:18.870
<p>I'm gettng an error "error: expected primary-expression before ',' token" in the following line of code - I have initialized an array with 220 ints. What am I doing wrong here?</p> <pre><code>const PROGMEM int P7Val[] = {1635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,12601635,1635,1635,1635,1635,1630,1630,1630,1630,1630,1625,1625,1625,1625,1620,1620,1620,1620,1615,1615,1615,1610,1610,1610,1605,1605,1605,1600,1600,1600,1595,1595,1595,1590,1590,1590,1585,1585,1580,1580,1580,1575,1575,1570,1570,1570,1565,1565,1560,1560,1555,1555,1555,1550,1550,1545,1545,1540,1540,1535,1535,1535,1530,1530,1525,1525,1520,1520,1515,1515,1510,1510,1505,1505,1500,1500,1495,1495,1490,1490,1490,1485,1485,1480,1480,1475,1475,1470,1470,1465,1465,1460,1460,1455,1455,1450,1450,1445,1445,1440,1440,1435,1435,1430,1430,1425,1425,1420,1420,1415,1415,1410,1410,1405,1405,1400,1400,1395,1395,1390,1390,1385,1385,1380,1380,1380,1375,1375,1370,1370,1365,1365,1360,1360,1355,1355,1350,1350,1345,1345,1345,1340,1340,1335,1335,1330,1330,1325,1325,1320,1320,1320,1315,1315,1310,1310,1305,1305,1305,1300,1300,1295,1295,1290,1290,1290,1285,1285,1280,1280,1275,1275,1275,1270,1270,1265,1265,1265,1260,1260,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180,,1255,1255,1255,1250,1250,1245,1245,1245,1240,1240,1235,1235,1235,1230,1230,1225,1225,1225,1220,1220,1215,1215,1215,1210,1210,1210,1205,1205,1200,1200,1200,1195,1195,1195,1190,1190,1185,1185,1185,1180,1180}; </code></pre>
<p>Two things:</p> <ol> <li>You have a comma missing: <code>1260,12601635,1635,</code></li> <li>You have an extra comma: <code>1180,1180,,1255,1255</code></li> </ol> <p>If you reformat your list into a nice regular table (say 10 entries per line) across multiple lines these things instantly become apparent.</p>
16680
|programming|c|sketch|
How does this code move the bird sprite in this sketch?
2015-10-10T00:07:25.753
<p>I'm teaching this <a href="https://www.dropbox.com/s/1hxxvueidqjoi09/flappyDuino.zip?dl=0" rel="nofollow">sketch</a> in my class. I understand most of the sketch and can see the class that makes the bird move, but I still don't quite understand how the code makes the sprite "move." I can also see what generates the Pipes but I don't how the code creates them or randomizes them. </p> <p>Here is the code for both: </p> <p>Bird</p> <pre><code>class Chym { private: int frameCount; int x; int y; int deltaIde; int delayFrame; int jumpCount; int maxJumpCount; int moveSpeed; bool _isDead; public: void respawn() { x = 24; y = 20; deltaIde = -1; moveSpeed = 1; jumpCount = 0; _isDead = false; } Chym() { frameCount = 0; delayFrame = 0; maxJumpCount = 20; respawn(); } void render() { if (frameCount &lt; ANIM_FRAME / 2) { display.drawBitmap(x, y, flappybird_frame_1, 16, 12, 1); } else { display.drawBitmap(x, y, flappybird_frame_2, 16, 12, 1); } } void update() { delayFrame++; if (delayFrame == DELAY_FRAME) { y += deltaIde * moveSpeed; delayFrame = 0; } if (y &gt; 35) { _isDead = true; } frameCount++; if (frameCount &gt;= ANIM_FRAME) frameCount = 0; } bool isDead() { return _isDead; } void die() { _isDead = true; } void cancelJump() { jumpCount = 0; flyDown(); } void flyUp() { if (jumpCount &lt; maxJumpCount) { deltaIde = -1; moveSpeed = 3; jumpCount++; } else { flyDown(); } } void flyDown() { deltaIde = 1; moveSpeed = 1; } int getX() { return x; } int getY() { return y; } }; </code></pre> <p>Pipe</p> <pre><code>class Bar { private: int x; int y; int delayFrame; int moveSpeed; public: Bar() { delayFrame = 0; x = 0; y = 24; moveSpeed = 2; } void setPos(int sx, int sy) { x = sx; y = sy; } void render() { display.drawBitmap(x, y - 30, bar_top, 8, 20, 1); display.drawBitmap(x, y + 10, bar_bottom, 8, 20, 1); } void update() { delayFrame++; if (delayFrame == DELAY_FRAME) { x -= moveSpeed; if (x &lt; -10) x = 95; delayFrame = 0; } } int hitTest(int tx, int ty) { int hitX = ((tx &gt;= x - 16) &amp;&amp; (tx &lt;= x))?1:0; int hitY = ((ty &lt;= (y - 10)) || (ty + 12 &gt;= y + 10))?1:0; if (hitX != 0) { return hitY; } return 0; } }; </code></pre> <p><a href="https://www.youtube.com/watch?v=04cY78Y2d3g" rel="nofollow">https://www.youtube.com/watch?v=04cY78Y2d3g</a></p>
<p>This part of your code is what changes the sprite's y-value.</p> <pre><code>y += deltaIde * moveSpeed; </code></pre> <p>When you click the "jump" button or when the bird falls the y-value is changed to reflect either an upward movement or a downward movement. When your <code>render()</code> method is called the bird will either be drawn higher up on the y-axis (it's flying) or lower on the y-axis (it's falling).</p> <p>As for the bars, if you watch closely in the video you can see that they aren't actually randomized.</p> <p><strong>Compound Assignment Operators</strong></p> <p><code>+=</code> is the "plus assign" operator. It adds whatever is on the right side to the variable on the left side. Here is a table of other compound assignment operators: <a href="https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators" rel="nofollow">https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Compound_assignment_operators</a></p> <pre><code>int x = 5; x += 2; // equals 7; equivalent to x = x + 2; x = 5; x = x + 2; // also equals 7; equivalent to x += 2; </code></pre>
16688
|arduino-uno|analogread|teensy|
Why does my analogRead work on Teensy but not Arduino Uno?
2015-10-10T07:16:40.450
<p>I have successfully made a voltage measurement circuit on my Teensy 3.1 that reads a voltage coming out of digital pin 0 set high and coming back into an analog pin A0 to read voltage.</p> <p>Basically: </p> <pre class="lang-c prettyprint-override"><code>int timer = 100; int ColA = 0; int Output; // Setting digital pin functions void setup() { Serial.begin(38400); pinMode(0, OUTPUT); } // Program void loop() { digitalWrite(0, HIGH); delay(timer); Output = analogRead(A0); Serial.println(Output); delay(timer); } </code></pre> <p>It works fine with my circuit on a Teensy 3.1 running 3.3v however when i run this code on an Arduino Uno running 5v wired exactly the same way I just get this print out of numbers that cycles back and forth from ~128 down to 0 and back constantly.</p> <p>Any insight on the differences here would be great. I need the 5v micro-controller to run a 4051 multiplexer!</p>
<p>If you're still using D0 as your output on the Uno then yes you are doomed to failure.</p> <p>D0 and D1 are the serial port. You are using that to communicate with the PC. You cannot use them for any other purpose at the same time.</p> <p>Pick a different IO pin to be your voltage source.</p>
16692
|uploading|
Stuck on upload
2015-10-10T08:55:27.703
<p><strong>I just bought the SmartEverything FOX Board which is Arduino compatible</strong> <a href="http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf" rel="nofollow">http://www.smarteverything.it/wp-content/uploads/2015/10/SmartEverything-User-Guide-Ver-1.01.pdf</a> and simply tried to get started with it.</p> <p><strong>My OS is Ubuntu 14.04, my laptop DELL XPS 13 bought in 2014</strong></p> <p><strong>I cannot upload sketches on it, when I try, it gets stuck on uploading</strong>, whether it is a basic script (blinkRBG) or even the default one with empty setup and loop methods, my laptop processor keeps running at 100% and nothing happens. <strong>The board does not do anything, tx/rx leds do not flash.</strong> <strong>I can access to it with a Windows 7 laptop (UPDATE: and another UBUNTU laptop) from a frien</strong>d, I could upload the basic blinkRGB sketch. If I try to upload from my Ubuntu laptop after, it does erase the contents and stop the blinking but nothing follows.</p> <p>When I try to upload, I only get the compiling logs: Quote</p> <pre><code>Sketch uses 13,368 bytes (5%) of program storage space. Maximum is 262,144 bytes. </code></pre> <p><strong>I could still upload sketches to another board from my Ubuntu laptop: to an Arduino micro.</strong></p> <p><strong>I am connecting directly from my board to my laptop through USB 3.0</strong>, I don't have USB2.0 plugs on my laptop, and I currently don't have any programmer device.</p> <p>I tried with different versions of arduino IDE (1.6.4 1.6.5 nightly), same issue every time. The IDE sees that my board is connected on /dev/ttyACM0</p> <p>I tried to run in command line but it gets stuck as well Quote /home/jcharlet/.arduino15/packages/arduino/tools/bossac/1.6-arduino/bossac --port=ttyACM0</p> <p><strong>I've been googling the world but could not find anything, could anyone help me to troubleshoot it please?</strong></p>
<p>Moved to another board more suitable to our needs, but @sm4rteverything (Twitter) gave us the following solution (not tested):</p> <blockquote> <p>This is a known bug of the bootloader.</p> <p>to fix this U need to download the one i attach in this email with the ATMEL-ICE tool. <a href="http://www.atmel.com/tools/atatmel-ice.aspx" rel="nofollow noreferrer">http://www.atmel.com/tools/atatmel-ice.aspx</a></p> <p>Copy the attched file under: \Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme (Linux) C:\Users\\AppData\Roaming\Arduino15\packages\AMEL\hardware\samd\1.0.0\bootloaders\sme (Windows)</p> <p>last follow these three simple step Connect the ATMEL-ICE on the SWD J1 connector (pin 1 on top-rigth , the pin on eon cabel is the red one)</p> </blockquote> <p><a href="https://i.stack.imgur.com/KN53N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KN53N.png" alt="Board picture"></a></p> <blockquote> <p>select on Arduino IDE to connect to ASME via atmel-ice (board menu) tool->burn bootloader</p> </blockquote>
16696
|sensors|adc|algorithm|
Algorithms to reduce measurement error from analogue sensors
2015-10-10T13:06:07.313
<p>When reading analogue sensors - e.g. load cells, accelerometers - via a microcontroller's Analogue to Digital Converter, there are many sources of potential measurement error including:<br> a) Warm-up time for electronics<br> b) Mechanical inertia and resonance<br> c) Spurious random readings (due to e.g. vibration, electrical interference). </p> <p>My current software hack for a) and b) is to simply add a suitable time delay before reading the sensors; however there must be a more robust way of detecting and screening for resonance... </p> <p>My hack for c) is to take the mean of a given number of consecutive readings, but discard any individual readings which exceed a given percentage range from the current mean (pseudocode example below). The trouble with this approach is that it requires an inital `baseline' sensor reading, and if this happens to be spuriously high or low, it can cause subsequent correct readings to be rejected. Another approach might incorporate a weighted moving average, but this would still be skewed by spurious random readings.</p> <p>Are there any robust and elegant approaches / algorithms for the above which are commonly applied in commercial devices (e.g. domestic or laboratory weighing scales) that I could include in my code to improve the accuracy and reliability of measurements?</p> <p>Many thanks in anticipation</p> <pre><code>// Take mean of multiple sensor readings excluding outliers: # define SAMPLES 100 // number of samples to take mean of # define TOLERANCE 0.1 // % range of allowable deviation //between current mean and new values, expressed as decimal n = 1; // loop variable total = analogRead(analogPin); // Running total for calculation of mean &amp; baseline reading mean = total; // mean of all current data while (n &lt; SAMPLES) { new = analogRead(analogPin); if (new &lt; (1 + TOLERANCE) * mean) and (new &gt; (1 - TOLERANCE) * mean){ total += new; // if new reading is within range, calculate new mean n += 1; mean = total / n; } // (else ignore new reading) } Serial.print mean; </code></pre>
<p>... and here's my minimal working example for the Arduino. Feel free to adapt it for your own requirements, and please post any improvements or corrections to my script; or any alternative algorithms for the above. </p> <p>Just noticed that my approach of using the SD to define and exclude outliers is a little more (? unnecessarily) complex than John's algorithm, which defines outliers in terms of the highest and lowest values from the mean; but both methods seem to work nicely. </p> <p>Cheers!</p> <pre><code>#define BUFFER 5 // Buffer size (number of readings to use in rolling Mean) #define SENSORPIN 3 // Analogue input pin from sensor int data[BUFFER]; // Make an array of appropriate size for Buffer void setup() { pinMode(SENSORPIN, INPUT); // Fill buffer with initial data int n = 0; while (n &lt; BUFFER) { data[n] = analogRead(SENSORPIN); n++; } } void loop() { // Calculate Raw Mean &amp; SD float datasum = 0; float diffsum = 0; for (int n = 0; n &lt; BUFFER; n++) { datasum += data[n]; } float mean = float(datasum / BUFFER); for (int n = 0; n &lt; BUFFER; n++) { diffsum += ((data[n] - mean) * (data[n] - mean)); } float sd = sqrt(diffsum / (BUFFER - 1)); // Recalculate Corrected Mean only using data within range +/- 1SD of Raw Mean if (sd != 0) { // Avoid divide by zero error if sd = 0 float newSum = 0; // Sum of readings within acceptable range float newLen = 0; // Number of readings within acceptable range int n = 0; while (n &lt; BUFFER) { if ((data[n] &lt; (mean + sd)) and (data[n] &gt; (mean - sd))) { newSum += data[n]; newLen ++; } n++; } mean = newSum / newLen; // Corrected Mean } // Add your code here to do stuff with variable float 'mean' = the (Corrected) Mean // Read new sensor reading, append to buffer and delete oldest reading for (int n = (BUFFER - 1); n &gt; 0; n--) { data[n] = data[n - 1]; } data[0] = analogRead(SENSORPIN); } </code></pre>
16698
|frequency|oscillator-clock|adc|
Arduino constant clock output
2015-10-10T15:55:44.803
<p>I am controlling an ADC with my Arduino Uno. I would like the clock of the ADC to be the same frequency of the Arduino. Is there any way that I can have a constant clock output from one of the Arduino pin ?</p> <p>Thanks,</p> <p>Liam</p>
<p>This outputs 8 MHz on pin 9:</p> <pre class="lang-C++ prettyprint-override"><code>#ifdef __AVR_ATmega2560__ const byte CLOCKOUT = 11; // Mega 2560 #else const byte CLOCKOUT = 9; // Uno, Duemilanove, etc. #endif void setup () { // set up 8 MHz timer on CLOCKOUT (OC1A) pinMode (CLOCKOUT, OUTPUT); // set up Timer 1 TCCR1A = bit (COM1A0); // toggle OC1A on Compare Match TCCR1B = bit (WGM12) | bit (CS10); // CTC, no prescaling OCR1A = 0; // output every cycle } // end of setup void loop () { // whatever } // end of loop </code></pre> <hr> <blockquote> <p>How can add a prescaler?</p> </blockquote> <p>You change the prescaler bits. You can look at the datasheet or my cheat sheet here:</p> <p><a href="https://i.stack.imgur.com/Ftmib.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ftmib.png" alt="Timer 1 bits"></a></p> <p>You may not need a prescaler, depending on the frequency. Change OCR1A to some number between 0 and 65535 to slow it down.</p> <p>Edit by Edgar: I tested the OCR1A values with an oscilloscope. At the end of this answer are the frequencies.</p> <hr> <blockquote> <p>you use TCR1A, COM1A0 and similar variables. Are these always present and implicitly defined when running code on the ATmega</p> </blockquote> <p>Registers like TCCR1A and so on are defined in files which are automatically included by the Arduino IDE. If you use another toolchain they may be also automatically included. The start point is:</p> <pre class="lang-C++ prettyprint-override"><code>#define &lt;avr/io.h&gt; </code></pre> <p>Inside that file it checks your processor type (from a symbol passed to the compiler) and then includes an appropriate sub-file. Inside those files are defines which relate the register names to their address in the address-space of that particular chip. For example:</p> <pre class="lang-C++ prettyprint-override"><code>#define TCCR1A _SFR_MEM8(0x80) </code></pre> <p>The _SFR_MEM8 basically generates a pointer to a <code>volatile</code> address (because it might change without the compiler knowing it) and then dereferences that variable.</p> <p>Notice that the number 0x80 in that define agrees with the number shown on my chart.</p> <p>Underneath that define in the appropriate file are also the bit positions for the bits in that register, like this:</p> <pre class="lang-C++ prettyprint-override"><code>#define TCCR1A _SFR_MEM8(0x80) #define WGM10 0 #define WGM11 1 #define COM1B0 4 #define COM1B1 5 #define COM1A0 6 #define COM1A1 7 </code></pre> <hr> <blockquote> <p>Secondly, do I correctly understand that the output pin is defined in TCR1A, Output A and Output B, to be on Digital Pin 9 and 10 respectively? </p> </blockquote> <p>Yes, in effect. The datasheet says that if you set the appropriate bits in TCCR1A (note the spelling) then OC1A (board pin 9 on the Uno) or OC1B (board pin 10 on the Uno) will be unchanged/toggled/cleared/set depending on the bits. You can find these names on the datasheet for the Atmega328P (and other devices) and then use the Arduino schematic to find which <em>processor</em> pins are connected to which <em>board</em> pins.</p> <h3>Atmega328P datasheet snippet:</h3> <p><a href="https://i.stack.imgur.com/bHk4y.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bHk4y.png" alt="Atmega328P datasheet"></a></p> <h3>Uno datasheet snippet:</h3> <p><a href="https://i.stack.imgur.com/a0MjE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a0MjE.png" alt="Uno datasheet"></a></p> <hr> <blockquote> <p>Why do you set it to "Toggle" rather than "Set"?</p> </blockquote> <p>Because every time the counter matches I want to flip the pin. That is, on/off/on/off etc.</p> <hr> <blockquote> <p>What does CTC stand for?</p> </blockquote> <p>Clear Timer on Compare. What this means is that (unlike other modes) once the compare match is made, the timer is cleared, thus it starts counting up from zero again.</p> <p>Edit by Edgar: OCR1A values and frequencies</p> <pre class="lang-C++ prettyprint-override"><code>Value, MHz 0 8.00 1 4.00 2 2.67 3 2.00 4 1.60 5 1.33 6 1.14 7 1.00 8 0.889 9 0.800 10 0.727 11 0.667 12 0.615 13 0.571 14 0.533 15 0.500 </code></pre>
16701
|arduino-uno|bluetooth|
Can't figure out how to send Motor Values over Bluetooth, Arduino Bluetooth-controller robot
2015-10-10T16:39:09.193
<p>I was trying to make an Arduino Robot that is Bluetooth controlled but I've some problems!</p> <p>I can't figure out how to parse strings in Arduino like c++/java/python! I tried this, If the first letter is L, set the next value to left motor, same for R</p> <p>but for example "L255" is received as L - 2 - 5 - 5 and it sets L to 2 and ignores 5 - 5.</p> <p>Any ideas on what I should do? </p> <p>EDIT: Thought of something else, Sending L or R will toggle the motors! but that's just terrible, it'll be my last option</p> <p>Update: This is how it works now: L(0-5) means Left motor speed 5 * 51, 6-9 are backwards! its go backwards at (L(6-9) -5 * 51)</p>
<p>A state machine is the right way to go if you are sending multibyte commands.</p> <p>However do you need to send 4 bytes for every turn? Do you need accuracy to one degree? Are you going to make regular turns of greater than 60 degrees? If not I would consider encoding the dAta into a single byte. You will reduce the radio bandwidth by 3/4, it will improve the responsiveness of. Your software and it will remove the need to have a handler for incomplete messages.</p> <p>Of course there are probably other requirements that I don't know that will stop you doing this, but in case you haven't thought of it.</p>
16702
|compile|
Can Arduino libraries be compiled for ARM MCU's?
2015-10-10T16:43:02.597
<p>I am looking for a very low power Micro-controller to interface with the RockBlock Iridium modem. The MCU I am thinking of purchasing is the Gecko Zero by Silicon Labs. </p> <p>I want to know if it is possible to compile the Rockblock-IridiumSBD Arduino library for the Gecko Zero. The Gecko Zero is a 32 bit ARM MCU.</p> <p><a href="https://github.com/mikalhart/IridiumSBD" rel="nofollow">IridiumSBD Library</a></p> <p><a href="http://www.silabs.com/products/mcu/lowpower/Pages/efm32zg-stk3200.aspx" rel="nofollow">Gecko Zero MCU</a></p>
<p>Depending on the rest of your application, you might find the easiest path is to use the Gecko with the mbed.org tools. There already seem to be <a href="https://developer.mbed.org/teams/SiliconLabs/" rel="nofollow">mbed Gecko development boards</a> so the task is, to port the <a href="http://arduiniana.org/libraries/iridiumsbd/" rel="nofollow">Rockblock-IridiumSBD Arduino library</a>. </p> <p>The benefit of using mbed with the Gecko is it looks like mbed have all of the libraries, including low-power control implemented. </p> <p>The <a href="http://arduiniana.org/libraries/iridiumsbd/" rel="nofollow">Rockblock-IridiumSBD Arduino library</a> won't compile 'out of the packet' on mbed.</p> <p>However, the <a href="http://arduiniana.org/libraries/iridiumsbd/" rel="nofollow">Rockblock-IridiumSBD Arduino library</a> appears to be a serial interface over a few wires. They recommend 'soft serial' which uses digitalWrite, under program control, and no deep access to Arduino peripherals. That should be relatively straightforward to port to mbed. Mbed has equivalent library calls for digitalWrite, so a first attempt might be a few global search and replace edits. </p> <p>The alternative would be to use Gecko with an Open Source or commercial development system. However, mbed would provide a faster start, if you have good internet access and are not too paranoid about security, because the tools are 'cloud based', saving you time to set up the tools, and their is an mbed community who might help you over the initial hurdles. </p>
16730
|pins|pwm|
Can I connect an output pin to an input pin to measure it's voltage on a single board?
2015-10-11T12:55:23.063
<p>So just bought an arduino Uno and I've been playing around with it. I want to connect one of the input pins to one of the PWM outputs and measure the output from there by sending it to my computer through <code>Serial</code> and then plot it in python.</p> <p>Sorry if this is a basic question. Thanks</p>
<p>PWM are digital output pins, and it seems that you wish to measure analog equivalent voltage generated by PWM output. If so, you'd need a filter.</p> <p>Construct a unity gain op-amp based RC filter with cut-off frequency significantly smaller than PWM clock frequency. This will generate a analog waveform that can drive analog circuits. You could connect this to ADC input pin.</p> <p>You could Google "Active low pass filter" for a lot of schematics and formula.</p> <p>BUT</p> <p>To be able to faithfully reproduce analog signal captured through ADC on a computer screen graph, your ADC sample rate must be more than ~2.5 times analog signal's bandwidth.</p> <p>If your sample rate is close to Nyquist rates, you'd need to filter (interpolate) your digitized signal in software to generate a smooth graph. This is a bit involved in maths and software. Otherwise you'd only get a "spikey" waveform.</p> <p>Or preferably have a sample rate > 10 times analog bandwidth. This will give large enough sample counts to reliably show analog data without much processing.</p>