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
19420
|arduino-uno|attiny|nrf24l01+|wireless|sleep|
NRF24L01 Connection Not Working
2016-01-10T18:05:14.870
<p>I have an ATTiny85 connected to an NRF24L01+ module using this wiring diagram: <a href="https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2" rel="nofollow">diagram</a>. The ATTiny85 periodically goes in and out of sleep to send some value to a receiver, an Arduino Uno. If the ATTiny is running off the Arduino power supply (3.3v), everything works correctly. When I run the ATTiny off of a separate CR2032 coin cell that delivers around 3v, the Arduino never receives any data. I have a status LED hooked up to the ATTiny to ensure that the ATTiny is waking correctly, which it is. Here's the code for both:</p> <p><strong>EDIT</strong>: Connecting it to an external 3.3v not from the Uno makes everything work - why wouldn't the coin cell's voltage work? I think everything is rated below 2.8v, the CR2032 minimum.</p> <p><strong>ATTiny Code</strong></p> <pre class="lang-c prettyprint-override"><code>#include &lt;avr/sleep.h&gt; #include &lt;avr/interrupt.h&gt; // Routines to set and claer bits (used in the sleep code) #ifndef cbi #define cbi(sfr, bit) (_SFR_BYTE(sfr) &amp;= ~_BV(bit)) #endif #ifndef sbi #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit)) #endif #define CE_PIN 3 #define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN #include "RF24.h" RF24 radio(CE_PIN, CSN_PIN); byte address[11] = "SimpleNode"; unsigned long payload = 0; void setup() { radio.begin(); // Start up the radio radio.setAutoAck(1); // Ensure autoACK is enabled radio.setRetries(15,15); // Max delay between retries &amp; number of retries radio.openWritingPipe(address); // Write to device address 'SimpleNode' pinMode(4, OUTPUT); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); delay(500); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); delay(500); digitalWrite(4, HIGH); delay(500); digitalWrite(4, LOW); delay(1000); setup_watchdog(6); } volatile int watchdog_counter = 0; ISR(WDT_vect) { watchdog_counter++; } void loop() { sleep_mode(); //Go to sleep! if(watchdog_counter &gt;= 5) { digitalWrite(4, HIGH); watchdog_counter = 0; payload = 123456; radio.write( &amp;payload, sizeof(unsigned long) ); //Send data to 'Receiver' ever second delay(1000); digitalWrite(4, LOW); } } //Sleep ATTiny85 void system_sleep() { cbi(ADCSRA,ADEN); // switch Analog to Digitalconverter OFF set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here sleep_enable(); sleep_mode(); // System actually sleeps here sleep_disable(); // System continues execution here when watchdog timed out sbi(ADCSRA,ADEN); // switch Analog to Digitalconverter ON } // 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms // 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec void setup_watchdog(int ii) { byte bb; int ww; if (ii &gt; 9 ) ii=9; bb=ii &amp; 7; if (ii &gt; 7) bb|= (1&lt;&lt;5); bb|= (1&lt;&lt;WDCE); ww=bb; MCUSR &amp;= ~(1&lt;&lt;WDRF); // start timed sequence WDTCR |= (1&lt;&lt;WDCE) | (1&lt;&lt;WDE); // set new watchdog timeout value WDTCR = bb; WDTCR |= _BV(WDIE); } </code></pre> <p><strong>Receiver Code</strong></p> <pre class="lang-c prettyprint-override"><code>#define CE_PIN 7 #define CSN_PIN 8 #include &lt;SPI.h&gt; #include "RF24.h" RF24 radio(CE_PIN, CSN_PIN); byte address[11] = "SimpleNode"; unsigned long payload = 0; void setup() { while (!Serial); Serial.begin(115200); radio.begin(); // Start up the radio radio.setAutoAck(1); // Ensure autoACK is enabled radio.setRetries(15,15); // Max delay between retries &amp; number of retries radio.openReadingPipe(1, address); // Write to device address 'SimpleNode' radio.startListening(); Serial.println("Did Setup"); } void loop(void){ if (radio.available()) { radio.read( &amp;payload, sizeof(unsigned long) ); if(payload != 0){ Serial.print("Got Payload "); Serial.println(payload); } } } </code></pre> <p>Is the problem here that the ATTiny and Uno need to be turned on at the same time to establish a connection, or is it something to do with the battery, or something else entirely? Any help would be appreciated.</p>
<p>I was just researching the exact question and I have some bad news.</p> <p>The ORIGINAL nrf24l01+ alone use around 10-12 ma in transmitting, but unoriginal might even draw more. (<a href="https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf" rel="nofollow">https://www.sparkfun.com/datasheets/Components/SMD/nRF24L01Pluss_Preliminary_Product_Specification_v1_0.pdf</a>)</p> <p>Nevertheless a standard CR2032 battery is simply not made to supply more than a few milliamps at the best, leaving your nrf24L01+ lacking enough current.</p> <p>There is something called shockburst which can lower your consumption considerably at the cost of range - but if it will succeed in transmitting with one CR2032 I'm not sure about. </p> <p>Edit: If you add a capacitor you need to cover at least a 10ma drain for around 15ms (turn on - send - turn of immediately), that will require a minimum of a 200µF capacitor at 3V to be able to deliver the current while keeping above 2.0v.</p>
19422
|usb|arduino-leonardo|
Pinout for Leonardo USB
2016-01-10T19:02:41.657
<p>According to the <a href="https://www.arduino.cc/en/Main/ArduinoBoardLeonardo" rel="nofollow">docs</a>, the Arduino Leonardo uses digital pins 0 and 1 for the <a href="https://en.wikipedia.org/wiki/USB" rel="nofollow">USB D- and D+</a> lines. However, which is which? e.g. is D0=D+ or is D1=D+?</p> <p>To save space in a very tight project, I want to wire USB directly to these pins instead of using the USB plug, however, I can't find any resource that explains which pin goes to which USB line.</p>
<p>As shown in the ATmega32U4 datasheet, D- and D+ connect to pins 3 and 4 respectively <strong><em>of the MCU</em></strong>. But you don't want to wire directly to the chip unless you know what you are doing since the chip does not include the USB termination resistors. Follow the schematics given in the datasheet when connecting to the USB pins of the MCU.</p>
19428
|arduino-uno|
Do I need a lot of Arduinos?
2016-01-10T22:29:53.313
<p>I would like to make a smart home using Arduino. My system must be wireless. I want to control power outlets and lamps and I want to be able to turn off and on power outlets and lamps wirelessly, using my android app, using nRF24L01. </p> <p>Do I need an Arduino for each power outlet and lamp? Do I need to put an Arduino, nRF24L01 and relay inside each power outlet and lamp?</p>
<p>You might also consider using ESP8266 + relay combinations, instead of Pro Mini + nRF24L01 + relay sets. An Arduino IDE setup is available to support C code on ESP8266 systems (<a href="http://l0l.org.uk/2014/12/esp8266-modules-hardware-guide-gotta-catch-em-all/" rel="nofollow">1</a>,<a href="http://makezine.com/2015/04/01/esp8266-5-microcontroller-wi-fi-now-arduino-compatible/" rel="nofollow">2</a>,<a href="http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module" rel="nofollow">3</a>).</p> <p>Note: As a consequence of its higher clock speed and larger RAM size (80 MHz or 160 MHz clock, and 80 KB DRAM, vs Mini's 16 MHz clock and 2 KB SRAM) a typical ESP8266 board uses more power than a Pro Mini + nRF24L01 does. According to <a href="http://nrqm.ca/nrf24l01/hardware/" rel="nofollow">nrqm.ca/nrf24l01</a>, the nRF24L01 draws around 11 or 12 mA when sending or receiving, and 22 μA in low-power standby mode. According to <a href="http://wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module#Electronic_Characteristics" rel="nofollow">wiki.iteadstudio.com/ESP8266_Serial_WIFI_Module</a>, an ESP8266 draws ~ 60 mA receiving and 135–215 mA sending. (That current range covers a power output range of 5.5 dBm. It probably supports a much bigger communication area than nRF24L01 does.) Of course, if all your installations have mains power available, the power requirements might not matter much to you. Note, ESP8266 boards typically run on 3.3 V power instead of 5 V power.</p> <p>As far as cost goes, at the moment Pro Mini clones cost about $2.15 each. nRF24L01's run about $0.90. ESP8266 modules are $2–$3 depending on model and level of module (<a href="https://www.itead.cc/esp8266-serial-wifi-module.html" rel="nofollow">1</a>,<a href="http://www.ebay.com/itm/ESP8266-Remote-Serial-Port-WIFI-Transceiver-Wireless-Module-Esp-07-AP-STA-OT8G-/371241185691?pt=LH_DefaultDomain_0&amp;hash=item566fb2f19b" rel="nofollow">2</a>). You might save a few dollars on your whole system using ESP8266's, but the smaller-sized electronics they provide probably is more important.</p>
19429
|esp8266|
ESP8266 (connected to Arduino) only works when plugged into USB power
2016-01-10T23:27:00.410
<p>The Wi-Fi connects when the Arduino is powered by my computer and a serial console is connected, but not if I plug into an outlet.</p> <p><strong>UPDATE</strong></p> <p>It seems this is a power issue. I am powering the esp8266 from the Redboard 3.3v line that is only rated for 150mA. I will be switching to the 5v line with a 1A regulator.</p> <p>I also switched to 9600 baud for communicating with the esp8266, added retries around all of esp8266 commands, and added reconnect logic in case the esp8266 reboots. With the changes, it works okay even with the underpowered 150mA line.</p> <p>It's still a mystery to me why it works so well when connected to my Macbook.</p>
<p>It sounds like your power supply is inadequate to the task.</p> <p>The ESP8266 is notoriously finicky about having a noise free power supply capable of delivering a lot of instantaneous power. If you are using a wallwart style supply it should promise at least 1A and more is better. Even though the actual use is more like 250 mA.</p>
19446
|arduino-uno|pins|
Can I set an Arduino pin as input and output?
2016-01-11T14:12:49.683
<p>When I used to program PICs, there was a way to set the pins to input and output, at the same time. Can this be done on the Arduino? I see the <a href="https://www.arduino.cc/en/Reference/PinMode" rel="nofollow">pinmode documentation</a>, but nothing about being an IO port. </p>
<p>No there is no function that lets you set all the pins to either input or output at the same time, but it wouldn't take much to write one.</p> <p>No, you can't set an Arduino's pin as bidirectional. If you are running out of pins look at IO expanders or multiple Arduinos.</p> <p>Hope that helps, if not please feel free to clarify what it is you would like to know and we'll try and help.</p>
19447
|arduino-uno|transistor|
Controlling an LED using a transistor (TL188)
2016-01-11T14:35:55.423
<p>I wanted to control an LED using a transistor (my first attempt at using a transistor). I connected a transistor (TL188) to pin 13 of an Arduino Uno accidentally and noticed something.</p> <p><a href="https://i.stack.imgur.com/E2VZV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E2VZV.png" alt="Enter image description here"></a> <em>(The resistor I used was 150&nbsp;ohms, and I forgot to change the resistor value in the diagram.)</em></p> <p>The program on the Arduino Uno was the basic <code>Blink</code> sketch. As per the program, the LED on the Arduino Uno was supposed to turn on for 1000&nbsp;ms and turn off for 1000&nbsp;ms. But when I connected the LED like the diagram below</p> <p><strong>For the first 1000 ms delay:</strong></p> <ul> <li>LED on pin 13 stayed <strong>on</strong></li> <li>LED connected using the transistor stayed <strong>off</strong></li> </ul> <p><strong>For the next 1000 ms delay:</strong></p> <ul> <li>LED on pin 13 stayed <strong>partially on (it was dim)</strong></li> <li>LED with the transistor was <strong>on</strong></li> </ul> <p>I know that the connection that I made is completely wrong. Can someone explain me how and also why the LED on the Arduino Uno was dim?</p>
<p>It really doesn't matter if you use a PNP or NPN transistor, they are just mirrors of one another. If you have some common anode displays then just start directly with the PNP's.</p> <p>The flaw I see in your circuit is that you should always use 2 resistors to drive a LED (See schematic). R2 (as you already have) will limit the current to the LED; 220 Ohm you as illustrated is fine.</p> <p>R1 is needed between the I/O pin and your transistor. This will limit the current through the I/O pin. For what you are attempting a resistor in the range 1K to 2K should do, even if you're switching a few LED's in parallel. If you provide complete details of your setup we can always refine the calculations. One can then take into account the total currents from your displays, the amplification factor of the transistor (hfe) etc. <a href="https://i.stack.imgur.com/dGZvJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dGZvJ.png" alt="enter image description here"></a></p>
19461
|arduino-uno|c|
One time execution of a variable incrementation
2016-01-12T01:48:11.813
<p>As part of a larger script intended for a very simple arduino "synthesizer" I am trying to increment the amount of cycles a melody will be played once a key is pressed (the key in turn passes a value to the variable selectMel). The problem I encounter is that the moment I call my function in the main void loop() function, I cannot control the incrementation of the variable ncycles, which is intended to be only increased once per key press. I tried to solve this by creating a global switchVar variable as an "on/off" switch but that did not do much to solve the issue at hand. </p> <p>Any tips or help will be greatly appreciated!</p> <p>PS: I have of course googled and tried the solutions posted on similar stackExchange posts but to no avail, sadly.</p> <pre><code> void playMan (int ncycles, int mSpeed) { switch (selectMel) { case 1: if (ncycles &gt; 0) { tone(12, NOTE_B7, mSpeed); delay(100); tone(12, NOTE_B5, mSpeed); delay(100); tone(12, NOTE_B3, mSpeed); delay(100); tone(12, NOTE_B1, mSpeed); delay(100); ncycles--; break; case 2: if (millis() % 100 == 0) { if (switchVar == 1) { ncycles += 5; switchVar = 0; } Serial &lt;&lt; ncycles &lt;&lt; endl; } break; default: break; } } } </code></pre>
<p>See <a href="http://www.gammon.com.au/switches" rel="nofollow">http://www.gammon.com.au/switches</a>.</p> <p>Basically you need to detect the transition between the switch not being pressed before, and <strong>now</strong> being pressed. This transition will occur once per press (possibly after you add debouncing). If you just test for the switch pressed naturally you will get multiple increments.</p> <hr> <blockquote> <p>Assuming I add debouncing, how would it help in incrementing the value of ncycles only once ?</p> </blockquote> <p>To clarify, you increment once on a transition, note when you did this (eg, by calling <code>millis()</code> ) and then ignore any further transitions for, say 10 ms.</p>
19466
|bluetooth|arduino-nano|remote-control|
Connect Bluetooth remote control with Arduino
2016-01-12T08:18:33.543
<p>For a project I need to connect a <strong>Bluetooth Remote control</strong> with an <strong>Arduino Nano</strong>.</p> <p>On the Arduino-side I have an <a href="http://www.exp-tech.de/media/archive/gm/service/datasheet/HC-Serial-Bluetooth-Products.pdf" rel="nofollow noreferrer">HC-05-Bluetooth module</a>. With the Android Application "Bluetooth Terminal" I can verify that the connection is ok, because I can send and receive Strings with an Android smartphone.</p> <p>In the minimal example I send values from a sensor which is connected to my Arduino via bluetooth to the smartphone, which is working nice. So I guess the wiring is correct:</p> <pre class="lang-c prettyprint-override"><code>void loop() { sensorValue = analogRead( sensorPin ); cm = 10650.08 * pow( sensorValue, -0.935 ) - 10; Serial.println( cm ); softSerial.println(cm); delay( 500 ); } </code></pre> <p>Instead of sending sensor values, I need to connect said remote with the Arduino. </p> <p><a href="https://i.stack.imgur.com/KUFzI.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KUFzI.jpg" alt="Picture of the remote"></a></p> <p><em>(Picture shows the basic model of said remote control.)</em></p> <p>The remote control has the Bluetooth class <code>20258C</code> which means:</p> <ul> <li>Major Device Class: Peripheral</li> <li>Limited Discoverable Mode</li> <li>Audio</li> <li>Pointing device</li> <li>Remote control</li> </ul> <p><strong>Remote Control Bluetooth Specifications:</strong></p> <ul> <li>BT Device Name: YL-BTM3-xxxxxx</li> <li>Supplier ID and Product ID: 0x0A5C / 0x4503</li> <li>Class of Device: 0x20258C</li> </ul> <p>My Question is: How can I pair those two devices? I can get the remote control into "Pairing mode", by pressing 2 Buttons. But how do I pair the Arduino-Bluetooth-module with this remote-control? Is it possible at all?</p> <p>Best regards</p>
<p>This should be a comment, but..</p> <p>For starters, you'll need to do the pairing from the Arduino with the HC-05 in master mode.</p> <p>Check <a href="https://alselectro.wordpress.com/2014/10/21/bluetooth-hc05-how-to-pair-two-modules/" rel="nofollow">this</a> out.</p>
19467
|arduino-mega|esp8266|
How to integrate ESP8266
2016-01-12T08:46:50.470
<p>Just, to make sure how it works:</p> <ul> <li>I will connect the module to Arduino</li> <li>it will create AP to which I can connect and send commands via HTTP</li> </ul> <p>So I do not need any special equipment on PC side right, I can even connect to the ESP's AP with mobile, right?</p> <p>Is it possible for the ESP to be WIFI client and connect to regular WIFI SSID (the PC will just communicate over regular network)? Is it possible to communicate bidirectional somehow?</p>
<p>Just wanted to second what @larzz11 says in the last para. If you don't need the ADC's, running Arduino code on the device is definitely the simplest/easiest way to use the device. The AT command firmware is challenging to get working in a stable fashion.</p> <p>Also just to re-affirm the power requirements of the ESP8266 is higher than the 3v3 supply on the Arduino—you'll need a step-down converter from a sufficiently powerful 5v supply, or separate power supply, to get it working consistently.</p> <p>Bidirectional comms are definitely doable, but the limited SRAM on Arduino make string parsing a real challenge, and even handling relatively small responses/requests can hit up against the available SRAM.</p> <p>One of the nice things about using Arduino on the ESP8266 is that the ESP8266 has 8 times the amount of SRAM, making that more feasible also.</p>
19474
|gsm|robotics|
Functions of GSM
2016-01-12T12:02:07.797
<p>I am currently working on an arduino project and wanted to use a GSM module. This is my first time working with a GSM module. So I had a few queries.<br> <br> What can a GSM module sim900a do with arduino programming? <br>Also can it do the following:</p> <ol> <li>Send sms when motion is detected by a PIR sensor</li> <li>Send sms to only a particular group of cell phones.</li> <li>Respond to a particular kind of sms</li> </ol>
<blockquote> <ol> <li>Send sms when motion is detected by a PIR sensor</li> </ol> </blockquote> <p><strong>Yes</strong>, write a function that does this. Basic support functions in libraries will help you send the sms and detect the PIR. You need to provide the logic. </p> <blockquote> <ol start="2"> <li>Send sms to only a particular group of cell phones.</li> </ol> </blockquote> <p>If the question is if the GSM module supports group send the answer is <strong>no</strong>. You will have to write a function that sends the SMS to each number in the group.</p> <blockquote> <ol start="3"> <li>Respond to a particular kind of sms</li> </ol> </blockquote> <p><strong>Yes</strong>, again but now you have to write a function that parses incoming messages and does some actions (just as any input parse). </p> <p>The answer to all these questions is <strong>no</strong> if the function is already available in libraries. The answer is <strong>maybe</strong> if someone has already done something similar. </p>
19493
|temperature-sensor|
Sensor for very low temperature (liquid nitrogen)
2016-01-12T20:11:59.493
<p>I'm looking for a way to measure temperatures in range of 40 to -200 °C (100 to −320 °F). The usual solution DS18B20 works only down to -55 °C (-67 °F).</p> <p>Any ideas?</p> <p><em>p.s.</em> Precision of 2 °C would be good enough.</p>
<p>I did a search on "cryogenic temperature sensors" and found these from <a href="http://www.lakeshore.com/products/Cryogenic-Temperature-Sensors/Pages/default.aspx" rel="nofollow">Lake Shore Cyrotronics</a> – the price is shocking. It appears that you can use <a href="http://www.lakeshore.com/products/cryogenic-temperature-sensors/silicon-diodes/dt-670/Pages/Overview.aspx" rel="nofollow">silicon diodes</a> as cryogenic temperature sensors, so you might be able to use less expensive parts if you don't need a ton of accuracy.</p>
19501
|arduino-nano|esp8266|reset|
Watchdog approach
2016-01-12T22:48:42.847
<p>I'm developing up a project that is designed to run 24/7 (an energy monitor) logging via wifi.</p> <p>Due to a variety of considerations I've ended up with a design that links an Arduino Nano with an ESP8266-01.</p> <p>I was considering designing in a watchdog, but had the thought that each of these MCUs could act as the watchdog for the other. My hypothesis is that the likelihood of both going down simultaneously is relatively low, and as both need to communicate with each other regularly, they will know when the other unit has become non-responsive, and they would also be able to initiate a hardware (rather than software) reset on the other device.</p> <p>Is this a valid/workable approach? Or is there something else I need to consider that would warrant an external watchdog(s)?</p> <p>EDIT: as there were a few comments re: low-power etc., just wanted to clarify that this will be powered from the 240v supply it monitors (using a switch-mode supply), so this isn't expected to be an issue.</p>
<p>As a watchdog mechanism to protect against software lockup type issues then using one processor to detect issues and reset the other is an economical idea. However, I would completely agree with Nick that if you want protection from hardware issues like brown outs or slow rise time of the power supply then both micros could share the same vulnerabilities that a dedicated watchdog device would be able to address. How significant this is depends on your power arrangements.</p> <p>The other case to consider is now much does the software of one device interact with and depend on that of the other device such that it is conceivable that one device locking up in some way could impact the other defeating the watchdog functionality.</p> <p>Personally I've seen too many situations where an internal micro watchdog failed to detect and recover an issue so would always go for an external device in any professional product. Even there I would advise the use of a devices which requires the watchdog to be kicked within a time window rather than just within a maximum time period - otherwise if things contrive to go wrong in such a way that the watchdog is permanently getting kicked it will not recover the situation. [I saw the micro pin responsible for kicking a simple external watchdog accidentally reconfigured by runaway code as a timer output once.] </p> <p>I suspect that if you are thinking that your product needs a watchdog then it is worth doing properly with an external one.</p>
19506
|arduino-uno|pins|
Error when trying to write analog and digital signals from different pins (Arduino UNO)
2016-01-13T01:00:08.340
<p>I'm using the Arduino UNO and started noticing some funny behavior when I was trying a few basic projects. Specifically when trying to write an analog signal through one of the PWM pins, then a digital signal through another.</p> <p>Using some LED's connected to a few different permutations of pins 8-13, I found that when I have an analog output set for one of the pins (in this case 9, 10, or 11 as they're the only one's of the set capable of PWM) and then try to output a digital signal from a different pin to another LED the digital signal seems much weaker. That is, the LED shines very very dim.</p> <p>The pins 2-7 work fine. Does the behavior described above indicate anything wrong with the arduino? are those pins potentially damaged, or is there something I'm not understanding here?</p> <p>My code:<br/></p> <pre><code>void setup() {} void loop() { analogWrite(9, 255); delay(1000); analogWrite(9, 0); delay(2000); digitalWrite(8, HIGH); delay(1000); digitalWrite(8, LOW); delay(2000); } </code></pre> <p><a href="https://i.stack.imgur.com/l9DZ6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/l9DZ6.png" alt="Diagram"></a></p>
<p>I tested your code and it does indeed behave the way you said. But that is because you have not declared any pins as output.</p> <p><code>analogWrite</code> does this for you automatically in the library, however <code>digitalWrite</code> does not. This is because sending a digital pin <code>HIGH</code> when it is <code>INPUT</code> turns on the internal pull-up resistors. These are around 50k. Thus you will only see very dim output on the LED. Add this line to <code>setup</code>:</p> <pre class="lang-C++ prettyprint-override"><code> pinMode (8, OUTPUT); </code></pre> <p>(And preferably pin 9 as well, just in case you decide to change to digital writes later).</p>
19509
|usb|arduino-leonardo|
How to diagnose unresponsive Leonardo serial port?
2016-01-13T02:25:42.187
<p>I was using an Arduino Leonardo (in the form of an <a href="https://www.dfrobot.com/wiki/index.php?title=Raspberry_Pi_B%2B_Meet_Arduino_Shield_SKU:DFR0327" rel="nofollow">RPI hat</a>) to control a single DC motor via a <a href="https://www.pololu.com/product/2990" rel="nofollow">motor controller</a>. I have it wired to set Phase and Enable to control motor speed and direction, and I read sensors on the motor's encoder to directly measure motor speed.</p> <p>I triple checked all my wiring, and a test program I wrote to spin the motor at half-speed seemed to work just fine. Then it suddenly stopped working. Now, when I plug the Leonardo into my machine, the ttyACM0 device does not appear, and I seem to have no way to communicate with it anymore.</p> <p>I've noticed that when I press the reset button, the Leonardo's status light flashes for a few seconds and ttyACM0 does momentarily appear. But as soon as the flashing stops, ttyACM0 disappears again. I tried upload a new sketch when the device reappears, but I get a "broken pipe" error.</p> <p>What's going on here? Did I somehow fry my Leonardo, or is it possible I just screwed up the serial port? How do I fix it?</p> <p>Edit: For the host, I've tried Ubuntu 14 running on a Raspberry Pi 2 and a generic 64bit laptop.</p> <p>Edit: My <code>setup()</code> is simply:</p> <pre><code>void count_pan_changes(){ /* CW =&gt; 11,00,11,00,... CCW =&gt; 10,01,10,01,... */ int a = digitalRead(MOTOR_ENCODER_A_PIN); int b = digitalRead(MOTOR_ENCODER_B_PIN); int direction = (a == b) ? +1 : -1; motor_controller.record_direction(direction); } void setup(){ attachInterrupt(digitalPinToInterrupt(MOTOR_ENCODER_A_PIN), count_pan_changes, CHANGE); } </code></pre> <p>Edit: I'm not sure why, but when I disconnected the Leonardo from it's 5V UBEC power supply and powered it directly from my laptop via USB, then ttyACM0 suddenly came back. However, when I reconnect it to its own power supply, I again have problems connecting to it. The first upload and serial terminal seem to work, but as soon as I disconnect, further uploads/serial connections seem to fail with a "broken pipe" error. I'm powering it via a UBEC by connecting the 5V and Gnd lines to one of the Leonardo's GVS headers (i.e. it's not going in through any onboard regulator on the Arduino or RPi). Should this work? The motor is behind a separate UBEC.</p> <p>Edit: Now power cycling isn't even fixing it. I tried erasing the contents using:</p> <pre><code>avrdude -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -e </code></pre> <p>as explained <a href="http://forum.arduino.cc/index.php?topic=261139.0" rel="nofollow">here</a>. This keeps /dev/ttyACM0 from disappearing, but if I try and upload a sketch using <code>ano upload</code>, I still get the error:</p> <pre><code>IOError: [Errno 32] Broken pipe </code></pre>
<p>Since your code does not open the serial port, it is entirely expected that the serial port will appear briefly on reset, and then disappear. Initially it appears as the bootloader looks for a new sketch, and disappears because your code does not open Serial.</p> <p>If you time it correctly you should be able to upload a new sketch after pressing Reset. You need to press Reset fairly precisely after the IDE announces that is uploading. You only have a window of a second or so.</p>
19517
|bluetooth|arduino-nano|remote-control|
HC-05 Bluetooth Module - INQ-Command doesn't work
2016-01-13T13:29:32.877
<p>For a project I need to connect a Bluetooth Remote control with an Arduino Nano.</p> <p><strong>The Problem</strong></p> <p>I am trying to setup a connection to said Bluetooth remote Control. This device is visible! (I have confirmed it with a smartphone)</p> <p>Here are the steps that I am trying to do with the Arduino and HC05 module:</p> <pre><code>AT &lt;-- confirms, that Command Mode is running successfully OK AT+ROLE? &lt;-- 1 For Bluetooth Master Mode +ROLE:1 OK AT+CMODE? &lt;-- 1 allows connecting to any BT address +CMOD:1 OK AT+INQM? &lt;-- Show Inquiry access values +INQM:1,1,48 OK AT+INQ &lt;-- Inquiry Bluetooth Device </code></pre> <p>After ~60 seconds, it just says "OK", but according to <a href="https://alselectro.wordpress.com/2014/10/21/bluetooth-hc05-how-to-pair-two-modules/" rel="nofollow noreferrer">this tutorial</a> or according to <a href="https://youtu.be/Vr4cdpsoVEo?t=6m30s" rel="nofollow noreferrer">this youtube video</a> it should display all Bluetooth-devices, that are ready to connect. The BT device is definately visible. (I tried multiple BT devices like smartphones and peripheral devices).</p> <p><strong>Why is the inquiry not working? What is wrong here?</strong></p> <p><strong>The circuit is exactly like in this picture:</strong></p> <p><a href="https://i.stack.imgur.com/lwMAs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lwMAs.jpg" alt="circuit"></a></p> <p>For setting up the Bluetooth-connection I wire the EN-Pin to +3,3V, which successfully activates <strong>AT-Command-Mode</strong> <a href="http://www.martyncurrey.com/arduino-with-hc-05-bluetooth-module-at-mode/" rel="nofollow noreferrer">According to this site</a>, you can do it like that.</p> <p>Here is my code, that I use, to communicate with the module. - It works good!</p> <pre class="lang-c prettyprint-override"><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(2, 3); // RX | TX // Connect the HC-05 TX to Arduino pin 2 RX. // Connect the HC-05 RX to Arduino pin 3 TX through a voltage divider. // char c = ' '; int buf[64]; //buffer to store AT commands int len = 0; //stores the length of the commands void setup() { Serial.begin(9600); Serial.println("Arduino is ready"); delay(500); mySerial.begin(9600); Serial.println("BlueTooth is ready"); } void loop() { if(Serial.available()) { len = Serial.available(); //store number of bytes to read for(int i = 0; i&lt;len; i++) //store all bytes into the buffer { buf[i] = Serial.read(); } for(int i = 0; i&lt;len; i++) { mySerial.write(buf[i]); Serial.write(buf[i]); } } if(mySerial.available()) { len = mySerial.available(); for(int i = 0; i&lt;len; i++) { buf[i] = mySerial.read(); } for(int i = 0; i&lt;len; i++) { Serial.write(buf[i]); } } } </code></pre> <p><a href="https://electronics.stackexchange.com/questions/180962/hc-05-bluetooth-atinq-command-not-working">Here is a related question but the answer doesn't help.</a></p>
<p>I did a factory reset of the device. That resolved the issue</p> <pre><code>AT+ORGL AT+RESET </code></pre> <p>Another thing that is very important: The KEY-Pin (EV-Pin on some boards) must be HIGH (3Volts), during the INQ-command. If this PIN is not High, the inq-command will not work.</p> <p>If you put 3V to this PIN and release it, you indeed are in AT-Command mode. But not all AT-commands work (e.g. the said at+inq command). If you want to enable all AT-commands the PIN <strong>must remain</strong> high.</p>
19519
|timers|
Replacing delay() with millis()
2016-01-13T14:35:25.873
<p>I'm currently attempting to replace delay() in my project so that i may perform other tasks while waiting on a particular event to fire. </p> <p>The issue I'm having, is every example i've found using millis / elapsedmillis has everything inside the loop, where I'm trying to use it inside void buttons(). needless to say, either it's not going to work outside of loop, or I'm doing something ridiculous, and too tired, or too ignorant to see what i'm doing wrong..</p> <p>The end goal is to have the button draw over the top of the existing one, wait 1000ms then draw the next button. (time interval will be changed later to sync with hardware spin down etc) </p> <p>Here is the complete sketch, perhaps someone can show me a reliable way to replace delay in the buttons funciton:</p> <pre class="lang-c prettyprint-override"><code>#include &lt;Adafruit_GFX.h&gt; #include &lt;TouchScreen.h&gt; #include &lt;stdint.h&gt; #include &lt;SPI.h&gt; #include &lt;SD.h&gt; #include &lt;MCUFRIEND_kbv.h&gt; MCUFRIEND_kbv tft; #include &lt;elapsedMillis.h&gt; elapsedMillis timer0; elapsedMillis sinceTime1; elapsedMillis sinceTime2; elapsedMillis sinceTime3; #define debug = false; //#define debug = true; #if defined(__SAM3X8E__) #undef __FlashStringHelper::F(string_literal) #define F(string_literal) string_literal #endif // most mcufriend shields use these pins and Portrait mode: uint8_t YP = A1; // must be an analog pin, use "An" notation! uint8_t XM = A2; // must be an analog pin, use "An" notation! uint8_t YM = 6; // can be a digital pin uint8_t XP = 7; // can be a digital pin uint8_t Landscape = 0; uint16_t TS_LEFT = 120; uint16_t TS_RT = 940; uint16_t TS_TOP = 940; uint16_t TS_BOT = 180; #define MINPRESSURE 10 #define MAXPRESSURE 1000 // For better pressure precision, we need to know the resistance // between X+ and X- Use any multimeter to read it // For the one we're using, its 250 ohms across the X plate TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); #define LCD_CS A3 #define LCD_CD A2 #define LCD_WR A1 #define LCD_RD A0 // Assign human-readable names to some common 16-bit color values: #define BLACK 0x0000 #define BLUE 0x001F #define RED 0xF800 #define GREEN 0x07E0 #define CYAN 0x07FF #define MAGENTA 0xF81F #define YELLOW 0xFFE0 #define WHITE 0xFFFF int16_t BOXSIZE; int16_t PENRADIUS = 3; uint16_t oldcolor, currentcolor; #define SD_SCK 13 #define SD_MISO 12 #define SD_MOSI 11 #define SD_CS 10 // In the SD card, place 24 bit color BMP files (be sure they are 24-bit!) void setup() { // Init TouchScreen ts = TouchScreen(XP, YP, XM, YM, 300); //call the constructor AGAIN with new values. BOXSIZE = tft.width() / 6; tft.fillScreen(BLACK); // put your setup code here, to run once: Serial.begin(9600); tft.reset(); uint16_t identifier = tft.readID(); if (identifier == 0x7789) { //Serial.println(F("Found ST7789V LCD driver")); TS_LEFT = 120; TS_RT = 940; TS_TOP = 940; TS_BOT = 180; Landscape = 1; } else { //Serial.print(F("Unknown LCD driver chip: ")); //Serial.println(identifier, HEX); return; } //Serial.print(F("Found LCD driver chip ID: ")); //Serial.println(identifier, HEX); tft.begin(identifier); //Serial.print(F("Initializing SD card...")); if (!SD.begin(SD_CS, SD_MOSI, SD_MISO, SD_SCK)) { Serial.println(F("failed!")); return; } //Serial.println(F("OK!")); tft.begin(identifier); tft.setRotation(3); BOXSIZE = tft.width() / 6; tft.fillScreen(BLACK); bmpDraw("splash.bmp", 80, 20); delay(5000); loadhome(); } void loop() { //DO STUFF HERE //Testing Text stuff here tft.setTextColor(BLACK); tft.setTextSize(2); tft.setCursor(15, 33); tft.print("123.456"); tft.setTextColor(BLACK); tft.setCursor(115, 33); tft.print("543.210"); tft.setTextColor(BLACK); tft.setCursor(215, 33); tft.print("789.654"); buttons(); } void loadhome(){ tft.setRotation(3); BOXSIZE = tft.width() / 6; tft.fillScreen(BLACK); bmpDraw("cell.bmp", 10, 25); bmpDraw("cell.bmp", 110, 25); bmpDraw("cell.bmp", 210, 25); bmpDraw("stop.bmp", 15, 175); bmpDraw("locked.bmp", 90, 175); bmpDraw("play.bmp", 165, 175); bmpDraw("home.bmp", 240, 175); bmpDraw("coolstp.bmp", 15, 105); bmpDraw("spinstp.bmp", 240, 105); tft.setTextColor(RED); tft.setTextSize(3); tft.setCursor(50, 3); tft.print("X"); tft.setTextColor(RED); tft.setCursor(150, 3); tft.print("Y"); tft.setTextColor(RED); tft.setCursor(250, 3); tft.print("Z"); } int homer = 0; int play = 1; int lock = 0; int cool = 0; int spin = 0; const int interval = 1000; unsigned long curMillis; //Current millis void buttons(){ //Touchscreen stuff TSPoint p = ts.getPoint(); // if sharing pins, you'll need to fix the directions of the touchscreen pins pinMode(XM, OUTPUT); pinMode(YP, OUTPUT); p.x = map(p.x, TS_LEFT, TS_RT, 0, tft.width()); p.y = map(p.y, TS_TOP, TS_BOT, 0, tft.height()); /* //Use to map buttons //Be sure to mark out button code before use!! if (p.z &gt; MINPRESSURE &amp;&amp; p.z &lt; MAXPRESSURE) { Serial.print(F("p.y =")); Serial.print(p.y); Serial.println(""); Serial.print(F("p.x =")); Serial.print(p.x); Serial.println(""); } */ // Begin Buttons //Coolant Button if (p.y &gt; 110 &amp;&amp; p.y &lt; 170 &amp;&amp; p.x &gt; 250 &amp;&amp; p.x &lt; 300) { // if stop area is pressed if(cool == 0){ bmpDraw("coolen.bmp", 15, 105); //Serial.println(F("Coolant Button Pressed!")); cool = 1; } else { bmpDraw("coolerr.bmp", 15, 105); sinceTime1 = 0; //delay(500); //replacing with millis() if (sinceTime1 &gt;= 1000) { bmpDraw("coolstp.bmp", 15, 105); //Serial.println(F("Coolant Button Pressed!")); cool = 0; } } } //Stop Button if (p.y &gt; 185 &amp;&amp; p.y &lt; 235 &amp;&amp; p.x &gt; 250 &amp;&amp; p.x &lt; 300) { // if stop area is pressed //Serial.println(F("Stop Button Pressed!")); Serial.write(0x18); Serial.print("\n"); } //Lock Button if (p.y &gt; 185 &amp;&amp; p.y &lt; 235 &amp;&amp; p.x &gt; 182 &amp;&amp; p.x &lt; 234) { // if stop area is pressed if(lock == 0){ Serial.print("$X\n"); bmpDraw("unlocked.bmp", 90, 175); //Serial.println(F("Lock/Unlock Button Pressed!")); lock = 1; } else { Serial.print("$X\n"); bmpDraw("locked.bmp", 90, 175); //Serial.println(F("Lock/Unlock Button Pressed!")); lock = 0; } } //Play-Pause Button if (p.y &gt; 185 &amp;&amp; p.y &lt; 235 &amp;&amp; p.x &gt; 110 &amp;&amp; p.x &lt; 160) { // if stop area is pressed if(play == 0){ Serial.print("~\n"); bmpDraw("play.bmp", 165, 175); //Serial.println(F("Play/Pause Button Pressed!")); play = 1; } else { Serial.print("!\n"); bmpDraw("pause.bmp", 165, 175); //Serial.println(F("Play/Pause Button Pressed!")); play = 0; } } //Home Button if (p.y &gt; 185 &amp;&amp; p.y &lt; 235 &amp;&amp; p.x &gt; 35 &amp;&amp; p.x &lt; 90) { // if stop area is pressed if(homer == 0){ bmpDraw("homeg.bmp", 240, 175); //Serial.println(F("Home Button Pressed!")); homer = 1; } else { Serial.print("$H\n"); bmpDraw("homey.bmp", 240, 175); sinceTime2 = 0; //delay(500); //replacing with millis() if (sinceTime2 &gt;= 1000) { bmpDraw("homer.bmp", 240, 175); } //delay(500); //replacing with millis() sinceTime2 = 0; if (sinceTime2 &gt;= 1000) { //delay(750); bmpDraw("homeg.bmp", 240, 175); //Serial.println(F("Home Button Pressed!")); } homer = 1; } } //Spindle Button if (p.y &gt; 110 &amp;&amp; p.y &lt; 170 &amp;&amp; p.x &gt; 35 &amp;&amp; p.x &lt; 90) { // if stop area is pressed if(spin == 0){ bmpDraw("spinen.bmp", 240, 105); //Serial.println(F("Spindle Button Pressed!")); spin = 1; } else { bmpDraw("spinerr.bmp", 240, 105); sinceTime3 = 0; //delay(500); //replacing with millis() if (sinceTime3 &gt;= 1000) { bmpDraw("spinstp.bmp", 240, 105); //Serial.println(F("Spindle Button Pressed!")); } spin = 0; } } } #define BUFFPIXEL 15 void bmpDraw(char *filename, int x, int y) { File bmpFile; int bmpWidth, bmpHeight; // W+H in pixels uint8_t bmpDepth; // Bit depth (currently must be 24) uint32_t bmpImageoffset; // Start of image data in file uint32_t rowSize; // Not always = bmpWidth; may have padding uint8_t sdbuffer[3*BUFFPIXEL]; // pixel in buffer (R+G+B per pixel) uint16_t lcdbuffer[BUFFPIXEL]; // pixel out buffer (16-bit per pixel) uint8_t buffidx = sizeof(sdbuffer); // Current position in sdbuffer boolean goodBmp = false; // Set to true on valid header parse boolean flip = true; // BMP is stored bottom-to-top int w, h, row, col; uint8_t r, g, b; uint32_t pos = 0, startTime = millis(); uint8_t lcdidx = 0; boolean first = true; if((x &gt;= tft.width()) || (y &gt;= tft.height())) return; //Serial.println(); //Serial.print(F("Loading image '")); //Serial.print(filename); //Serial.println('\''); // Open requested file on SD card if ((bmpFile = SD.open(filename)) == NULL) { Serial.println(F("File not found")); return; } // Parse BMP header if(read16(bmpFile) == 0x4D42) { // BMP signature read32(bmpFile); //Serial.println(F("File size: ")); //Serial.println(read32(bmpFile)); (void)read32(bmpFile); // Read &amp; ignore creator bytes bmpImageoffset = read32(bmpFile); // Start of image data //Serial.print(F("Image Offset: ")); Serial.println(bmpImageoffset, DEC); // Read DIB header read32(bmpFile); //Serial.print(F("Header size: ")); //Serial.println(read32(bmpFile)); bmpWidth = read32(bmpFile); bmpHeight = read32(bmpFile); if(read16(bmpFile) == 1) { // # planes -- must be '1' bmpDepth = read16(bmpFile); // bits per pixel //Serial.print(F("Bit Depth: ")); Serial.println(bmpDepth); if((bmpDepth == 24) &amp;&amp; (read32(bmpFile) == 0)) { // 0 = uncompressed goodBmp = true; // Supported BMP format -- proceed! // Serial.print(F("Image size: ")); // Serial.print(bmpWidth); // Serial.print('x'); // Serial.println(bmpHeight); // BMP rows are padded (if needed) to 4-byte boundary rowSize = (bmpWidth * 3 + 3) &amp; ~3; // If bmpHeight is negative, image is in top-down order. // This is not canon but has been observed in the wild. if(bmpHeight &lt; 0) { bmpHeight = -bmpHeight; flip = false; } // Crop area to be loaded w = bmpWidth; h = bmpHeight; if((x+w-1) &gt;= tft.width()) w = tft.width() - x; if((y+h-1) &gt;= tft.height()) h = tft.height() - y; // Set TFT address window to clipped image bounds tft.setAddrWindow(x, y, x+w-1, y+h-1); for (row=0; row&lt;h; row++) { // For each scanline... // Seek to start of scan line. It might seem labor- // intensive to be doing this on every line, but this // method covers a lot of gritty details like cropping // and scanline padding. Also, the seek only takes // place if the file position actually needs to change // (avoids a lot of cluster math in SD library). if(flip) // Bitmap is stored bottom-to-top order (normal BMP) pos = bmpImageoffset + (bmpHeight - 1 - row) * rowSize; else // Bitmap is stored top-to-bottom pos = bmpImageoffset + row * rowSize; if(bmpFile.position() != pos) { // Need seek? bmpFile.seek(pos); buffidx = sizeof(sdbuffer); // Force buffer reload } for (col=0; col&lt;w; col++) { // For each column... // Time to read more pixel data? if (buffidx &gt;= sizeof(sdbuffer)) { // Indeed // Push LCD buffer to the display first if(lcdidx &gt; 0) { tft.pushColors(lcdbuffer, lcdidx, first); lcdidx = 0; first = false; } bmpFile.read(sdbuffer, sizeof(sdbuffer)); buffidx = 0; // Set index to beginning } // Convert pixel from BMP to TFT format b = sdbuffer[buffidx++]; g = sdbuffer[buffidx++]; r = sdbuffer[buffidx++]; lcdbuffer[lcdidx++] = tft.color565(r,g,b); } // end pixel } // end scanline // Write any remaining data to LCD if(lcdidx &gt; 0) { tft.pushColors(lcdbuffer, lcdidx, first); } // Serial.print(F("Loaded in ")); //Serial.print(millis() - startTime); //Serial.println(" ms"); } // end goodBmp } } bmpFile.close(); if(!goodBmp) Serial.println(F("BMP format not recognized.")); } // These read 16- and 32-bit types from the SD card file. // BMP data is stored little-endian, Arduino is little-endian too. // May need to reverse subscript order if porting elsewhere. uint16_t read16(File f) { uint16_t result; ((uint8_t *)&amp;result)[0] = f.read(); // LSB ((uint8_t *)&amp;result)[1] = f.read(); // MSB return result; } uint32_t read32(File f) { uint32_t result; ((uint8_t *)&amp;result)[0] = f.read(); // LSB ((uint8_t *)&amp;result)[1] = f.read(); ((uint8_t *)&amp;result)[2] = f.read(); ((uint8_t *)&amp;result)[3] = f.read(); // MSB return result; } </code></pre>
<p>Taking JRobert's advice, i checked out the simpletimer library.. the final solution was to set up three timers and change the way the buttons functioned. </p> <p>as per documentation of the simpletimer library, added the following global:</p> <pre><code>#include &lt;SimpleTimer.h&gt; SimpleTimer timer; ... </code></pre> <p>Then to setup, i added my three timers</p> <pre><code>timer.setInterval(7000, spindle); //times based on hardware reality timer.setInterval(2000, coolant); timer.setInterval(21500, homer); ... </code></pre> <p>Then started the timers in loop by adding:</p> <pre><code>timer.run(); ... </code></pre> <p>Finally, i edited the buttons and added variables to denote state of button. i.e. </p> <pre><code>/* 0 == on, 1 == transitional1 2 == transitional2 3 == stopped */ int homeb = 0; int cool = 0; int spin = 0; </code></pre> <p>Changed the touch screen code for each button to kick off the timers...</p> <pre><code>//Coolant Button if (p.y &gt; 110 &amp;&amp; p.y &lt; 170 &amp;&amp; p.x &gt; 250 &amp;&amp; p.x &lt; 300) { // if stop area is pressed if(cool == 3){ bmpDraw("coolen.bmp", 15, 105); //PWM the spindle pin on cool = 0; } else { if(cool == 0){ //PWM the spindle pin off cool = 1; //Start the timer sequence for stopping coolant } } } </code></pre> <p>then i added a void for each timer, this is where i redraw the buttons</p> <pre><code>void coolant() { if (cool == 1){ bmpDraw("coolerr.bmp", 15, 105); cool = 2; } else { if (cool = 2){ bmpDraw("coolstp.bmp", 15, 105); cool = 3; } } } </code></pre> <p>Hope this helps someone else in the future, as it was a real pickle for me to figure out at first.. Thanks again, and credit goes to JRobert, his advice pointed me directly to the solution.</p>
19533
|arduino-uno|compile|linux|avr-gcc|
Compilation error using arduino-mk on arch Linux (undefined reference to __dso_handle)
2016-01-13T22:44:54.743
<ol> <li>I'm compiling a simple sketch that reads values from an analog input and activates a buzzer on a digital input.</li> <li>working on an Arduino uno.</li> <li>the sketch compiles and runs fine on windows and arch linux using the Arduino IDE.</li> </ol> <p>I recently tried to start working with Arduino-mk, I tried to compile the said sketch and got the following compiler error (analogVal is the variable holding the analogRead):</p> <p>/usr/bin/avr-gcc -mmcu=atmega328p -Wl,--gc-sections -Os -o /home/niv/Gits/bin/uno/maglove/maglove.elf </p> <pre><code>~/Gits/bin/uno/maglove/maglove.ino.o ~/Gits/bin/uno/maglove/libcore.a -lc -lm /home/niv/Gits/bin/uno/maglove/maglove.ino.o: In function `_GLOBAL__sub_I_nothing': maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xc): undefined reference to `__dso_handle' maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0xe): undefined reference to `__dso_handle' maglove.ino:(.text.startup._GLOBAL__sub_I_nothing+0x18): undefined reference to `__cxa_atexit' /usr/bin/avr-ld: /home/niv/Gits/bin/uno/maglove/maglove.elf: hidden symbol `__dso_handle' isn't defined /usr/bin/avr-ld: final link failed: Bad value collect2: error: ld returned 1 exit status /home/niv/Gits/Arduino-Makefile/Arduino.mk:1416: recipe for target '/home/niv/Gits/bin/uno/maglove/maglove.elf' failed make: *** [/home/niv/Gits/bin/uno/maglove/maglove.elf] Error 1 make: Target 'all' not remade because of errors. </code></pre> <p>I am not very experienced with Arduino yet, and google has failed me in finding this error or any keyword from it in the context of Arduino uno.</p> <p>thanks.</p>
<p>I can't say I fully understand what is going on, but it seems that if you add:</p> <pre><code>void * __dso_handle; </code></pre> <p>You may be able to eliminate one of the problems. You might try the same trick with <code>__cxa_atexit</code> as well.</p> <p>I found the idea by searching on:</p> <blockquote> <p>arduino __dso_handle</p> </blockquote> <p><a href="http://www.esp8266.com/viewtopic.php?f=29&amp;t=2196&amp;p=13039&amp;hilit=dso_handle#p13039" rel="nofollow">This</a> is the webpage that I found that suggested the <code>void *</code> hack.</p>
19534
|arduino-uno|hardware|communication|xbee|
Xbee for Arduino Uno
2016-01-13T22:45:45.090
<p>I'm very new to Arduino, and I was wanting to control my Arduino wirelessly. Some googling shows that there is a shield for Arduino called Xbee that allows wireless communication. Unfortunately, I just purchased the #1 shield without checking specifications, (went back later, couldn't find them :/) and now i have a shield that appears to small for my Uno. <a href="https://www.sparkfun.com/datasheets/Wireless/Zigbee/XBee-Datasheet.pdf" rel="nofollow noreferrer">(XBee Pro 60mW Wire Antenna - Series 1 (802.15.4))</a></p> <p>Some more googling showed results that this was indeed the right shield, but I don't see how since the pin pattern is about half the size as the female ports on the Arduino. Is this the right shield? if so, how do I attach the two pieces of hardware?</p> <p><a href="https://i.stack.imgur.com/Cu8xQ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Cu8xQ.jpg" alt="My arduino"></a> <a href="https://i.stack.imgur.com/RcPsF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RcPsF.jpg" alt="my xbee"></a></p>
<p>What you have there is an XBee <em>module</em>. It is designed to plug into an XBee <em>shield</em> which then plugs into the Arduino.</p> <p>So you need to buy more.</p> <p>That's the bad news. The good news is that you have already bought the most expensive part, and the shield to go with it is pretty cheap.</p> <p>Numerous people make the shields, such as:</p> <ul> <li><a href="https://www.sparkfun.com/products/12847" rel="nofollow">Sparkfun</a></li> <li><a href="http://www.seeedstudio.com/depot/xbee-shield-v20-p-1375.html?cPath=132_134" rel="nofollow">Seeed</a></li> <li><a href="http://www.dfrobot.com/wiki/index.php/Xbee_Shield_For_Arduino_%28no_Xbee%29_%28SKU:DFR0015%29" rel="nofollow">DFRobot</a></li> </ul> <p>Also note that XBees talk to other XBees, so you need at least two of them to get any form of communication going. If you want to talk to your computer there is a device called the <a href="https://www.sparkfun.com/products/11812" rel="nofollow">XBee Explorer</a> which plugs into the PC to allow you to communicate with an XBee module.</p>
19535
|serial|programming|button|debounce|
Why doesn't this debounce function work?
2016-01-13T22:15:23.680
<p><strong>Edit 2</strong> I made a function that works, but I'm still confused about just one thing...</p> <p>I'm very confused about how variables work in C++.</p> <p><strong>In this program...</strong></p> <pre><code> boolean debounce(void) { static boolean buttonState=LOW; static boolean lastButtonState; boolean currentState = digitalRead(4); static unsigned long lastDebounceTime; if (currentState != lastButtonState){ //if the button state has changed lastDebounceTime=millis(); //reset timer } if ((millis()-lastDebounceTime) &gt; 50) //if 50 milliseconds has passed since last bounce { buttonState = currentState; //read value again now that bouncing is over } lastButtonState = currentState; return buttonState; } </code></pre> <p><strong>Why does changing this</strong></p> <pre><code>lastButtonState = currentState; </code></pre> <p><strong>To this</strong></p> <pre><code>lastButtonState = buttonState; </code></pre> <p><strong>Make any difference in the program?</strong></p> <p>When I try the latter line of code, the whole function stops working and I don't understand why.</p>
<p>If you only have one button to debounce, you can store it's state as static variables in the <code>debounce()</code> function itself, like:</p> <pre class="lang-cpp prettyprint-override"><code>bool debounce() { const int pin = 4; static bool last_state; static unsigned long last_change; unsigned long now = millis(); if (now - last_change &gt; 50) { bool state = digitalRead(pin); if (state != last_state) { last_change = now; last_state = state; } } return last_state; } </code></pre> <p>If you may have to debounce more than one button, the cleaner way would be to store the state inside an object, and have the debounce function be one of its methods. That's what the <a href="https://github.com/thomasfredericks/Bounce2" rel="nofollow">Bounce library</a> does.</p>
19545
|shields|
Custom arduino board
2016-01-14T04:35:42.480
<p>Hey There Arduino Coders. I am a relatively seasoned C/C++ programmer. However, I'm still new to the Arduino Game. I'm coming here today to ask you guys a direct question that I couldn't find a direct answer for on google... here it goes:</p> <p>Is it possible,(also practical) to create my own arduino board? after creating a prototype with an arduino uno and various shields?</p> <p>In other words. Is it possible to shrink the arduino(make a custom arduino), and all of its shields on to one board? It seems rather large to have to lug around all of those shields and such. CHEERS!</p>
<p>Yes it is possible. It can be as simple or as complex as you wish :)</p> <p><a href="http://www.instructables.com/id/How-to-make-your-own-Arduino-board/" rel="nofollow">http://www.instructables.com/id/How-to-make-your-own-Arduino-board/</a></p>
19565
|atmel-studio|
How Atmel Studio 7 compile Arduino code?
2016-01-14T17:26:11.600
<p>Atmel stated in their website:</p> <blockquote> <p>Atmel Studio 7 features seamless one-click import of projects created in the Arduino development environment. Your sketch, including any libraries it references, will be imported into Studio 7 as a C++ project. Once imported, you can leverage the full capabilities of Studio 7 to fine-tune and debug your design. Atmel Studio 7 fully supports the powerful embedded debugger on the Arduino Zero board. For other Arduino boards, shield-adapters that expose debug connectors are available, or switch to one of the many available Xplained-Mini/PRO boards to fully leverage the Atmel HW eco-system. Regardless of what you choose, you will surely make something amazing.</p> </blockquote> <p>I wonder how they do it? Is it just a plug-in meaning that we still have to install Arduino software? Or do they have their own compiler and debugger?</p>
<p>Atmel Studio allows for the arduino .ino file to actually be compiled as a c++ project. Doing so allows true debugging, and stepping through all arduino code. It was actually insightful as it walked me through <strong>ARDUINO's main() function</strong>, which is normally tucked away nicely in a library never to be seen.</p> <p>The IDE allows for highly useful features such as refactoring, find and replace, syntax highlighting and much more. I found it very useful, and a pleasant upgrade from the arduino IDE. </p> <p>I often switch back and forth between the Arduino IDE and Atmel Studio, very easy to do.</p> <p>Installing the Arduino software allows Atmel Studio to locate the libraries when it is installed. </p> <p>By installing the Vmicro(visual Micro) toolbar, things really come together, and seem very seamless.</p> <p><a href="https://i.stack.imgur.com/97H9P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/97H9P.png" alt="enter image description here"></a></p>
19566
|arduino-uno|
How to have arduinos work together?
2016-01-14T19:22:54.537
<p>I want to have an Arduino based game you can play on a nokia 5110 screen. The problem is you cant make a medium sized game on an Arduino because the flash size is only 32k. I sit possible to have multiple Arduino's connected to each other, communicating to make it possible to have a bigger game. If it is possible how does it work?</p>
<p>You <strong>can</strong> make quite an impressive game.</p> <p><a href="https://i.stack.imgur.com/1qElu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1qElu.png" alt="Toorum&#39;s Quest"></a></p> <p><strong>Features</strong></p> <ul> <li>Based on ATmega328P running at 16 Mhz (same as Arduino Uno).</li> <li>The game has a display resolution of 104x80 with 256 colors.</li> <li>Video mode is tile based and supports up to 3 sprites per scan line.</li> <li>Sprites are multiplexed so there can be unlimited number of sprites vertically on the screen.</li> <li>4 audio channels with triangle, pulse, sawtooth and noise waveforms.</li> <li>Chiptune music playroutine and sound effects.</li> <li>NES controller support.</li> </ul> <p>Video of it in action:</p> <p><a href="https://www.youtube.com/watch?v=sLvgW_zb6bQ" rel="nofollow noreferrer">https://www.youtube.com/watch?v=sLvgW_zb6bQ</a></p> <p>Original <a href="http://forum.arduino.cc/index.php?topic=197983.0" rel="nofollow noreferrer">post on the Arduino forum</a>. </p> <hr> <p>So, before you start wanting to connect lots of Arduinos together, investigate what can be achieved with just one. :)</p> <p>The first thing to do, as others have mentioned, is to store static information into PROGMEM (see <a href="http://www.gammon.com.au/progmem" rel="nofollow noreferrer">Putting constant data into program memory (PROGMEM)</a> for more details). </p> <p>If Petri Häkkinen can get his title screen, levels, sprites, music, and game logic into an Atmega328P you can too! Have fun!</p>
19574
|usb|button|
Arduino with multiple buttons - will power be an issue?
2016-01-14T21:07:21.777
<p>I have a spare Arduino Uno lying around, which I figured I could attempt to turn into a game controller. First clear issue, that immediately popped up, was that there are not enough digital input pins on the board, but I think I can get around that by using analog pins with appropriate external resistors (is that actually a possibility?). </p> <p>Another one, more severe, is that I'm not sure how I would need to go around wiring microswitch buttons with the board. Assuming they short the circuit when pushed (SPST), I could simply wire one contact to an input pin, set to <code>INPUT_PULLUP</code> mode, and connect the other to ground. However, since I know little about how such circuits work, I'm immediately in doubt about two things. Considering the board would be used as a controller, an external power source is out of question and I'd only want to rely on the USB power. Since I want to use plenty of buttons (up to fifteen), out of caution I'm worried that shorting this many input pins to the ground at once could overload the... regulator I think?</p> <p>So my question is this: is it safe to use multiple, potentially simultaneously pressed, buttons connected to input pins on an Arduino Uno board, powered solely from a USB port? Additionally, just to be clear, is it normal to connect them all to a common ground on the board?</p>
<p>Most of your idea is sensible. Let's go over the sensible part first, and then we'll cover the bits that need work.</p> <p>Using an internal pullup and shorting the input to ground is the correct way to approach this. Note that the pins will read <code>HIGH</code> when off and <code>LOW</code> when triggered this way.</p> <p>Each pullup on an AVR is between 20kohm and 50kohm. This means that the current consumption if all 15 buttons are pressed is at most about \$15 \cdot {5 \text{V} \over 20\text{k}\Omega} = 3.75\text{mA}\$. This isn't enough for the USB connection to care about.</p> <p>As for using the analog connections, A0 through A5 also have digital GPIO capability, which means that you would treat them exactly the same as you would the digital pins (A6 and A7 don't have digital GPIO unless you're running a ATmegaXX8PB with a special core).</p> <p>And now the bad news.</p> <p>The Arduino Uno is based on the ATmega328P, which <em>does not</em> have native USB capability. It communicates with the host through a serial connection via a USB-UART bridge. If you're using a real (or real-enough) Uno then that bridge is a ATmega16U2 which is a MCU that <em>does</em> have native USB capability, so it can be reprogrammed to interpret the serial stream from the '328P and talk USB to the host.</p> <p>But if you aren't then you will either need to run a piece of software on the host that translates the serial stream to HID actions, or you will have to run a software USB stack on the '328P such as V-USB which will allow you to use Low-Speed USB 1.1 directly.</p> <p>My recommendation is to see if you can get an Arduino or other AVR-based board that has an ATmegaXXU4 so that you can use <code>Mouse</code> and <code>Keyboard</code> directly instead of having to faff around with HID profiles and software USB. Unless that's your thing, of course.</p>
19584
|arduino-mega|lcd|esp8266|spi|
3.95 TFT LCD SPI or parallel interface
2016-01-15T05:36:38.503
<p>I would like to get one information about this TFT LCD module . This particular module works with parallel interface with arduino mega and uno.</p> <p>I am trying to get rid of arduino in my project and use esp8266 itself. I have this module <a href="http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html" rel="nofollow">http://www.aliexpress.com/item/3-5-inch-TFT-Touch-LCD-Screen-Display-Module-For-Arduino-UNO-R3-HIGH-QUALITY-Free/1854595985.html</a></p> <p>This has only the parallel interface pins mentioned which requires around more than 10 pins to make it work. Is there any possibility that there is an SPI interface supported for this one by making use of any of the existing pins for the parallel interface. </p> <p>I don't think so but still can someone confirm that. If so I need to get SPI interface ready TFT LCDs. </p> <p>Thanks,</p>
<p>In general, no. The interface used by the chip is normally hard wired either in the connections to the Chip On Glass or in the connections of the shield (most commonly the former) and as such cannot really be changed.</p> <p>You will need to either use a TFT screen that has the interface already set to SPI (and there are many) or use some form of SPI I/O expander to provide enough I/O pins to drive a parallel display.</p> <p>Note that using SPI to communicate with a screen makes the screen updates considerably slower than using a parallel interface. The bigger the screen the slower it gets.</p>
19593
|arduino-uno|communication|nrf24l01+|wireless|linux|
connection between Arduino Uno with nRF24L01 and notebook with wireless card
2016-01-15T09:25:00.623
<p>My project intend to command an Arduino UNO by my notebook without cable. I thought to use a RF Nordic nRF24L01 cabled on an Arduino UNO, and to use the wireless card of my notebook to send command to it. Is it possible? Any solution? Is this hardware solution possible?</p> <p>I need to send to Arduino four analog signals to setup the light of four led.</p>
<p>Absolutely no. Can you connect your bluetooth headset to the wireless router? No because even if they share the same band they "speak" different protocols. So why could you do that with the nRF24L01?</p> <p>If you want to communicate with your PC you have three options:</p> <ol> <li>Choose nRF24L01. In this case, since the PC does not have that device, you will need to make an adapter (the easiest one could be an USB adapter). You can connect a microcontroller to a USB to serial converter and to the nRF24L01 and use it as a bridge.</li> <li>Choose Wifi. Then you'll need a new transceiver for the arduino UNO you are using (maybe the ESP8266, which is around 2$) but can be a bit more complicated for just sharing data (I never used it, though, so I can be wrong).</li> <li>Choose bluetooth. Usually this is my preferred way to communicate with a board. Cheap (the HC-06 module is about 2-3 $) and easy to use (the interface is a plain serial).</li> </ol> <p>Good luck ;)</p>
19600
|adafruit|arduino-micro|
Arduino Micro blue light dimms and turns off when I plug in my circuit
2016-01-15T15:07:06.003
<p>I have a PING Ultrasonic Sensor, Adafruit Absolute Orientation Sensor, and a Continuous rotation servo. All pins are connected to an Arduino Micro. However because the micro only has one 5V output, I used a rail from a breadboard. I connected the + &amp; - leads from all the devices to the rail and then plugged in two leads connecting 5V and GND from the Micro to the rail. My goal was two send power from the Arduino Micro down the rail to all three devices. </p> <p>I plugged in the Micro, and instead of seeing green lights on the sensor (powered on), the blue light on the Micro turned off and the servo twitched. I have no idea why. Do I need external power for the 5V?</p>
<p>This sounds like a lot to have connected to the Micro's 5v pin. Without knowing your exact model of servo, I would still believe you are hitting the current limit. Can you try unplugging the servo and see if the circuit functions without the servo? I would power the servo externally with a 5v supply.</p>
19603
|sd-card|
Corrupted files generated by Arduino with SdFat library. How to avoid that?
2016-01-15T17:20:53.503
<p>I got:</p> <ul> <li><p><a href="https://www.arduino.cc/en/Main/ArduinoBoardDuemilanove" rel="nofollow noreferrer">https://www.arduino.cc/en/Main/ArduinoBoardDuemilanove</a></p></li> <li><p><a href="http://wiki.iteadstudio.com/Stackable_SD_Card_shield_V3.0" rel="nofollow noreferrer">http://wiki.iteadstudio.com/Stackable_SD_Card_shield_V3.0</a> (set to 5V logic)</p></li> </ul> <p>with this <a href="http://pastie.org/10691360" rel="nofollow noreferrer">sketch</a> using SPI/SdFat+OneWire/DallasTemperature+EmonLib and no matter what I try I got corrupted files like <a href="http://pastie.org/10691362" rel="nofollow noreferrer">this</a>.</p> <p>I even haven't attached my sensors yet :( I have tried with 3 SD cards so far, each formatted with <a href="https://www.sdcard.org/downloads/formatter_4/" rel="nofollow noreferrer">SD Memory Card Formatter</a> and each one has this problem.</p> <p>There is a separate question like that (<a href="https://electronics.stackexchange.com/questions/57714/corrupted-files-generated-by-arduino-with-sd-library-how-to-avoid-that">Corrupted files generated by Arduino with SD library. How to avoid that?</a>) but it concerns SPI confict but here SD is my only SPI device on the bus.</p> <p>Any ideas?</p>
<p>This SD shield has CS on D4, not D10</p>
19605
|c++|led|potentiometer|
Running light, without delay, and a potentiometer
2016-01-15T18:10:00.933
<p>I am just getting hands on to my Arduino Uno.</p> <p>I am have finished the blinking light tutorial, managed to read a potentiometer, build a running light with delays and as well a binary counter.</p> <p>Now I build a small project with 5 LEDs and a potentiometer to configure a running light and change the speed of the running light with the potentiometer.</p> <p>The LEDs are connected to the pins 13 to 9 and the potentiometer is connected A0 and 5V.</p> <p>I also managed to program it without a delay function, but I think it is rather ugly.</p> <p>Is there a better way of doing this like I did it?</p> <pre><code>int led1 = 13; int led2 = 12; int led3 = 11; int led4 = 10; int led5 = 9; //the delay int pause = 1500; //count to decide which LEDs are HIGH and which are LOW int count = 0; // will store last time LED was updated unsigned long previousMillis = 0; // the setup routine runs once when you press reset: void setup() { // initialize the digital pin as an output. pinMode(led1, OUTPUT); pinMode(led2, OUTPUT); pinMode(led3, OUTPUT); pinMode(led4, OUTPUT); pinMode(led5, OUTPUT); // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // the loop routine runs over and over again forever: void loop() { unsigned long currentMillis = millis(); // read the input on analog pin 0: pause = analogRead(A0); float voltage = pause * (5.0 / 1023.0); // print out the value and teh corresponding voltage you read: //Serial.println("Value: %d and Voltage: %f", pause, voltage); Serial.print("Value: "); Serial.println(pause); Serial.print("Volts: "); Serial.println(voltage); if (currentMillis - previousMillis &gt;= pause) { // save the last time you blinked the LED previousMillis = currentMillis; if (count == 0) { digitalWrite(led1, HIGH); digitalWrite(led2, LOW); digitalWrite(led3, LOW); digitalWrite(led4, LOW); digitalWrite(led5, LOW); } else if (count == 1){ digitalWrite(led2, HIGH); } else if (count == 2) { digitalWrite(led1, LOW); digitalWrite(led3, HIGH); } else if (count == 3) { digitalWrite(led2, LOW); digitalWrite(led4, HIGH); } else if (count == 4) { digitalWrite(led3, LOW); digitalWrite(led5, HIGH); } else if (count == 5) { digitalWrite(led4, LOW); } else if (count == 6) { digitalWrite(led4, HIGH); } else if (count == 7) { digitalWrite(led5, LOW); digitalWrite(led3, HIGH); } else if (count == 8) { digitalWrite(led4, LOW); digitalWrite(led2, HIGH); } else if (count == 9) { digitalWrite(led3, LOW); digitalWrite(led1, HIGH); } else if (count == 10) { digitalWrite(led2, LOW); digitalWrite(led1, HIGH); count = -1; } count++; } } </code></pre>
<p>Completed now. </p> <p>@all: Thank you very much.</p> <p>@JRobert: Thanks a lot for the very good explanation @jwpat7: Thanks for the code, it helped me a lot.</p> <pre><code>// Sketch re: http://arduino.stackexchange.com/questions/19605/running-light-without-delay-and-a-potentiometer // Set constants for pins with LEDs enum { led1 = 13, led2 = 12, led3 = 11, led4 = 10, led5 = 9}; // Make an array with the LED pin numbers byte ledPins[] = { led1, led2, led3, led4, led5 }; // # of entries in ledPins: enum { numLeds = sizeof(ledPins) / sizeof ledPins[0]}; //count to track which LEDs are HIGH and which are LOW int count = numLeds-1; // Will roll over to 0 // To store last time LED was updated unsigned long previousMillis = 0; //direction forward boolean forward = true; void setup() { // initialize digital pin outputs for (byte i=0; i&lt;numLeds; ++i) pinMode(ledPins[i], OUTPUT); // initialize serial communication at 9600 bits per second: Serial.begin(9600); } // loop() runs over and over again forever: void loop() { unsigned long currentMillis = millis(); // read input on analog pin 0: int deli = analogRead(A0); float voltage = deli * (5.0 / 1023.0); // Print out the value and corresponding voltage you read: // Serial.println("Value: %d and Voltage: %f", pause, voltage); // Serial.print("Value: "); // Serial.println(deli); // Serial.print("Volts: "); // Serial.println(voltage); if (currentMillis - previousMillis &gt;= deli) { // Save the last time we blinked the LED previousMillis = currentMillis; if(forward){ // Turn off current LED, turn on next one digitalWrite(ledPins[count], LOW); count = (count+1) % numLeds; digitalWrite(ledPins[count], HIGH); if(count == numLeds-1 ){ forward = false; count = 0; } } else { digitalWrite(ledPins[count + numLeds-1], LOW); count = (count - 1) % numLeds; digitalWrite(ledPins[count + numLeds-1], HIGH); if(count + numLeds-1 == 0){ forward = true; count = 0; } } } } </code></pre> <p><a href="https://i.stack.imgur.com/DcB7w.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DcB7w.jpg" alt="enter image description here"></a></p>
19609
|build|visualstudio|ino|
Visual Micro without .ino files
2016-01-15T19:24:51.590
<p>I am using the visual micro extension for Visual Studio 2015. I would like to not use any .ino files since I'm trying to setup cppcheck which doesn't recogonize .cpp files, and its just what I'm used to. However when I change my project.ino file to project.cpp the compile option is no longer available (I assume its looking for a .ino file). Is there a project setting I can change to fix this?</p>
<p>As you have found, Visual Micro will not consider the project to be an Arduino project if you do not have a "project_name.ino" included in the project</p> <p>A cheat is to create a "project_name.cpp" and include it in the project. This will cause the .ino to be ignored during compilation. </p> <p>EDIT: The project_name.cpp takes priority during compile, therefore the .ino just becomes a dummy. However the .ino will still be used for intellisense. The cpp should be #included in the .ino along with any libraries you want discovered by intellisense.</p> <p>The Visual Micro release yesterday includes automatic "library in library" discovery which means you would no longer need to put all lib #include's in the project_name.ino. (tip: you can <a href="http://www.visualmicro.com/post/2016/01/14/How-to-improve-compile-times-dramatically.aspx" rel="nofollow noreferrer">switch the "deep search" feature off</a> for each project via the Visual Micro menu. It slows the compile down with large libraries)</p> <p><a href="https://i.stack.imgur.com/kcK3T.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kcK3T.png" alt="enter image description here"></a></p>
19615
|arduino-due|hardware|
Due : DMAC BTSIZE trimmed modulo 8192?
2016-01-15T22:37:24.857
<p>On Arduino Due, I set-up DMA transfers using direct control of memory mapped hardware registers. </p> <p>There is a 16-bit BTSIZE field in CTRLA which indicates the number of (width sized) transfers. If I specify larger than 8191, the value of btcount is trimmed to 13 bits after the DMA channel is enabled. I set chunk size src/dest to 1.</p> <p>The <a href="http://www.atmel.com/Images/Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf" rel="nofollow">ATMEL data sheet for the sam3x</a> (linked from the <a href="https://www.arduino.cc/en/Main/ArduinoBoardDue" rel="nofollow">due page</a>) does not mention this 'limitation' (section 22.7.16), or possibly I'm using it wrong.</p> <p>What reference is canonical and correct for the DMAC (dma controller)?</p> <hr> <p>As noted in the links in the comments, multi-buffer transfer can work around this, but since I don't know why it works or fails, it's hard to decide if that solution will work in all cases.</p>
<p>I'll quote the answer given in <a href="http://community.atmel.com/forum/synchronous-serial-controller-ssc-or-i2s-using-dma-controller-sam3x8e-incomplete-data-transfer" rel="nofollow noreferrer">this link</a> to help make this question more useful for future people who search this problem.</p> <blockquote> <p>The dmac.h file in asf library has a macro named DMA_MAX_LENGTH set to 0xFFF = 4095. We tried changing it to higher values but still Buffer Transfer size (BTSIZE) register was showing only values till 4095. This seemed to us to a hardware limitation of the DMAC in Atmel SAM3x8E (which we did'nt see mentioned in the datasheet). So this closed the option of single buffer transfer for us and we moved to multi-buffer transfer</p> <p>It was a simple way out (even though I took some time to figure it out :P ) - <em>Use multi-buffer transfer with contiguous source address!</em> (see table 22.4 Row 3)</p> </blockquote>
19616
|attiny|nrf24l01+|wireless|
RF24 Stalls Arduino Program with powerDown
2016-01-15T23:31:51.467
<p>I have an ATtiny85 and an Arduino Uno both using NRF24L01 chips to communicate with one another. The ATtiny85 is powered by a CR2032 coin cell. I am using tmrh20's fork of the RF24 library which can be found <a href="http://tmrh20.github.io/RF24/classRF24.html" rel="nofollow">here</a>. Here's the problem I'm encountering:</p> <p>Under the current code posted, the Uno will receive about 80 packets of data (80 packets times 2 seconds per packet is about 160 seconds of time) before the ATtiny will simply stop sending, and the Uno receives no more data. I can tell that it's the ATtiny, because I've got a DMM hooked up to it. Normally, my DMM tells me that the ATtiny is drawing less than 0.005mA of current, but at the instance of the stall the DMM reads approximately 1.4 mA of current draw, which makes sense because under normal conditions with no sleep the ATtiny draws about 1mA, and the radio not in power down mode and not transmitting draws 0.4mA.</p> <p>I've spent quite some time trying everything from setting the clock speed to a different value (it's at 1MHz) to changing the power amplifier value. The only thing I've tried that makes an impact is getting rid of the powerUp and powerDown function calls. Once these are removed everything works perfectly transmission-wise, except the only issue is that the whole system is drawing 0.4mA constantly, which is too much.</p> <p>I don't think the coin cell is a problem considering the system works when the powerUp and powerDown calls are removed. Here's my code:</p> <p>Reciever:</p> <pre><code>#define CE_PIN 7 #define CSN_PIN 8 #include &lt;SPI.h&gt; #include "RF24.h" RF24 radio(CE_PIN, CSN_PIN); byte address[11] = "SimpleNode"; unsigned long payload = 0; void setup() { while (!Serial); Serial.begin(115200); radio.begin(); // Start up the radio radio.setAutoAck(1); // Ensure autoACK is enabled radio.setRetries(15,15); // Max delay between retries &amp; number of retries radio.openReadingPipe(1, address); // Write to device address 'SimpleNode' radio.startListening(); Serial.println("Did Setup"); } long counter = 0; void loop(void){ if (radio.available()) { radio.read( &amp;payload, sizeof(unsigned long) ); if(payload != 0){ Serial.print("Got Payload "); Serial.print(payload); Serial.print(" - "); Serial.println(counter); counter++; } } } </code></pre> <p>Transmitter:</p> <pre><code>//Sleep #include &lt;avr/sleep.h&gt; const int sleepSecs = 2; //Radio #define CE_PIN 3 #define CSN_PIN 3 //Since we are using 3 pin configuration we will use same pin for both CE and CSN #include "RF24.h" RF24 radio(CE_PIN, CSN_PIN); byte address[11] = "SimpleNode"; unsigned long payload = 0; void setup() { //Setup radio radio.begin(); // Start up the radio radio.setAutoAck(1); // Ensure autoACK is enabled radio.setRetries(15,15); // Max delay between retries &amp; number of retries //RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH and RF24_PA_MAX radio.setPALevel(RF24_PA_HIGH); radio.openWritingPipe(address); // Write to device address 'SimpleNode' //Setup sleep setup_watchdog(6); set_sleep_mode(SLEEP_MODE_PWR_DOWN); //Power down everything, wake up from WDT sleep_enable(); } volatile int watchdog_counter = 0; ISR(WDT_vect) { watchdog_counter++; } void loop() { sleep_mode(); //Go to sleep! if(watchdog_counter &gt;= sleepSecs) { ADCSRA |= (1&lt;&lt;ADEN); radio.powerUp(); watchdog_counter = 0; payload = 123456; radio.write(&amp;payload, sizeof(unsigned long) ); //Send data to 'Receiver' every second radio.powerDown(); ADCSRA &amp;= ~(1&lt;&lt;ADEN); //Disable ADC, saves ~230uA } } //Sets the watchdog timer to wake us up, but not reset //0=16ms, 1=32ms, 2=64ms, 3=128ms, 4=250ms, 5=500ms //6=1sec, 7=2sec, 8=4sec, 9=8sec //From: http://interface.khm.de/index.php/lab/experiments/sleep_watchdog_battery/ void setup_watchdog(int timerPrescaler) { if (timerPrescaler &gt; 9 ) timerPrescaler = 9; //Limit incoming amount to legal settings byte bb = timerPrescaler &amp; 7; if (timerPrescaler &gt; 7) bb |= (1&lt;&lt;5); //Set the special 5th bit if necessary //This order of commands is important and cannot be combined MCUSR &amp;= ~(1&lt;&lt;WDRF); //Clear the watch dog reset WDTCR |= (1&lt;&lt;WDCE) | (1&lt;&lt;WDE); //Set WD_change enable, set WD enable WDTCR = bb; //Set new watchdog timeout value WDTCR |= _BV(WDIE); //Set the interrupt enable, this will keep unit from resetting after each int } </code></pre>
<p>A delay after the <code>powerUp()</code> made the program work for longer, but it still stalled. More delays after <code>write()</code> only exacerbated the issue. The only thing that I've done to get this to work is to put the sending code in the watchdog ISR itself. However, this is limited to only around 4 seconds max per sent packet because this is the watchdog's max value, but that's OK for my application.</p> <p>This leads me to believe that somehow the watchdog is interfering with sending, so possibly disabling it and reenabling after sending could have some effect if anyone else is having this problem.</p>
19632
|esp8266|arduino-mini|
Ping IP address using ESP8266 connected to Arduino
2016-01-16T12:06:44.303
<p>I want to make a system using NeoPixels, an Arduino and an ESP8266 module to ping IP addresses on my network to determine if certain people are on our Wi-Fi (I'll be pinging mobile phones).</p> <p>I'm finding it hard to find any help as to how to ping IP addresses from an Arduino using the ESP8266 module. I did find the <a href="http://playground.arduino.cc/Code/ICMPPing" rel="nofollow noreferrer">ICMP Ping library</a>, but it uses the Ethernet shield, and I'm quite new to Arduino so I don't even know if I could modify the library in any way.</p> <p>If anyone could help me on my way, that'd be great!</p>
<p>This answer does not answer your question, but it implements the device you are describing. Unfortunately I don't have enough reputation to comment, so I will post it as an answer.</p> <p>As people said before, ping is not a reliable option to scan the network. On Linux you can use dedicated (software) tools to scan the network, but even they struggle to reliably detect (some) mobile devices. So I wanted my router to do the work for me (at least it should reliably know which devices are logged into the Wi-Fi, right?). </p> <p>Fortunately I have a Fritz!Box that provides an API to communicate with. Based on that API and an ESP8266 I build such a device you described in your question: <a href="http://www.instructables.com/id/Who-Is-Home-Indicator-aka-Weasley-Clock-Based-on-T" rel="nofollow noreferrer">[15min] Weasley Clock / Who is Home Indicator - based on TR-064 (beta)</a>.</p> <p>To do that I wrote a library for Arduino to uses that API: <a href="https://github.com/Aypac/Arduino-TR-064-SOAP-Library" rel="nofollow noreferrer">Aypac/Arduino-TR-064-SOAP-Library</a>.</p>
19635
|arduino-uno|programming|sensors|sketch|robotics|
Details on OV7670
2016-01-16T14:13:55.050
<p>I am thinking of working on a project based on a camera module OV7670. I am making a security system using an arduino where detected motion (I am also using a PIR sensor) will trigger the camera module. I wanted to get all kinds of information needed to work with the camera module in this kind of project. <br><br> I am not expecting a very long answer rearding everything about the module. The most important points and maybe a few references would be enough. It would also be helpful if programming reference for the camera module is also provided.</p>
<p><a href="http://www.arducam.com/camera-modules/0-3mp-ov7670/" rel="nofollow">This post</a> is a link to a blog that describes the pinout and connections, along with some general information. They also have a link to <a href="https://github.com/ArduCAM/Arduino/tree/master/ArduCAM" rel="nofollow">an "ArduCAM" library</a> with <a href="https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/REVC/ArduCAM_OV7670_Camera_Playback/ArduCAM_OV7670_Camera_Playback.ino" rel="nofollow">an example</a> utilizing your camera model. </p>
19636
|ds18b20|
Powering 3.3v sensors from a coin cell
2016-01-16T14:20:43.660
<p>I want to build some small wireless temperature measurement boards, to sprinkle around the house. I'd like to power these from a single coin cell battery (CR2032).</p> <p>For these I'd like to use the DS18B20 sensor. These sensor require a minimal voltage of 3v. A coin cell will however only provide 3v when it's full, and will drop to around 2.6v when 90% discharged.</p> <p>From what I've read the DS18B20 will give <a href="http://openenergymonitor.org/emon/node/2303" rel="nofollow noreferrer">some strange results</a> when the supply voltage is below 3v. Also the <a href="http://openenergymonitor.org/emon/node/2331" rel="nofollow noreferrer">precision can be off</a>, when the supply voltage isn't regulated.</p> <p>(The ATMega328p and NRF24L01, I plan to use, will work just fine at voltages down to 2v, so only the DS18B20 requires 3.3v.)</p> <p>So I've come up with the following solutions:</p> <ol> <li>Use two coin cells, and a (low quiescent current) voltage regulator. (Disadvantage: takes more space, more batteries, slightly more expensive.)</li> <li>Use a boost regulator. (Disadvantage: even more expensive, and a lot more complex (for me at least).)</li> <li>Implement a voltage doubler to power the DS18B20 when needed (every 15 minutes). To regulate the voltage I'd add a 3.3v zener diode to the output. (dirt cheap to implement)</li> </ol> <p>I tend to lean toward option 3, but my question is, could it even work?</p> <p>Is there something to look out for?</p> <p>Or is there an even better solution?</p> <p><strong>edit</strong> I was planning to use the Dickson doubler circuit.</p> <p><a href="https://i.stack.imgur.com/J6gVP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/J6gVP.png" alt="voltage doubler"></a></p>
<p>You're missing out option 4, which is the option I would personally go for:</p> <ul> <li>Use a different temperature sensor.</li> </ul> <p>A quick parametric search on Microchip (my favourite, I'm a Microchip fanboy after all...) I find quite a nice one - the MCP9844.</p> <blockquote> <p>Microchip Technology Inc.’s MCP9844 digital temperature sensor converts temperature from -40°C and +125°C to a digital word. This sensor meets JEDEC Specification JC42.4-TSE2004B1 mobile Platform Memory Module Thermal Sensor Component. It provides an accuracy of ±0.2°C/±1°C (typical/maximum) from +75°C to +95°C. </p> <p>Operating Voltage Range (V): +1.7 to +3.6</p> </blockquote> <p><strong>However</strong> it is only available as a TDFN which makes prototyping difficult, although it is one of my two preferred footprints for real building - the other being variants of QFN.</p> <p>I am sure you can search other makers for similarly specified chips that will do the job without the need for fancy boosters or doublers or the expense of multiple batteries etc.</p> <p>One of the first steps of any design is the component identification. Often the chip or component that many people automatically reach for because it's the first one they used, or it's the one people most often talk about, may not be the right tool for the job. It pays to shop around a bit and look to see if there is something better that will fit the bill and save cost and time in the long run by ending up with a simpler system.</p>
19639
|arduino-uno|
Arduino drawing a bitmap on nokia 5110 lcd
2016-01-16T15:21:27.077
<p>Hello I finally got my nokia 5110 lcd working, I have tested it by displaying bitmap images other people have made. I made my own image and then used lcd assistant to turn it into an array. First look at my code.</p> <pre><code>#include "U8glib.h" </code></pre> <p>U8GLIB_PCD8544 u8g(8, 4, 7, 5, 6); // CLK=8, DIN=4, CE=7, DC=5, RST=6</p> <p>int x = 5; int y = 5;</p> <p>int level = 5;</p> <p>const uint8_t rook_bitmap[] U8G_PROGMEM = { 0x7E, 0x82, 0x04, 0x8E, 0x7A, 0x42, 0xB4, 0x24, 0x08, 0xD8, 0x48, 0x08, 0x08, 0x0C, 0x02, 0x22, 0xD9, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x1E, 0x11, 0x21, 0x22, 0x14, 0x3B, 0xD4, 0x25, 0x29, 0x68, 0xA8, 0xA8, 0x74, 0x0C, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, };</p> <p>void draw(void) { // graphic commands to redraw the complete screen should be placed here<br> u8g.drawBitmapP( 5, 5, 3,18, rook_bitmap);</p> <p>}</p> <p>void setup(void) {</p> <p>}</p> <p>void loop(void) { // picture loop u8g.firstPage();<br> do { draw(); } while( u8g.nextPage() );</p> <p>// y++; // rebuild the picture after some delay delay(1000); }</p> <p>The part that goes wrong is at u8g.drawBitmapP(5,5,21,18, rook_bitmap); I know it is to do with the 21 and 18 being wrong because I don't know where to get those numbers. Is it the width and height of the image when it is in paint.net or what is it?</p>
<p>The 21 and 18 are the dimensions of the image. It's not just pixels though.</p> <p>The first number (21) is the number of <em>bytes</em> in a row of the image - that is one eighth of the width in pixels. The width <em>must</em> be a multiple of 8.</p> <p>The second number is the number of rows in the image - basically the height in pixels.</p> <p>The two numbers, when multiplied together, must equal the number of bytes in your array.</p> <p>From <a href="https://code.google.com/p/u8glib/wiki/userreference#drawBitmap" rel="nofollow">the documentation:</a></p> <blockquote> <p><strong>Description</strong></p> <p>Draw a bitmap at the specified x/y position (upper left corner of the bitmap). Parts of the bitmap may be outside the display boundaries. The bitmap is specified by the array bitmap. A cleared bit means: Do not draw a pixel. A set bit inside the array means: Write pixel with the current color index. For a monochrome display, the color index 0 will usually clear a pixel and the color index 1 will set a pixel. </p> <p><strong>Arguments:</strong></p> <ul> <li>u8g : Pointer to the u8g structure (C interface only).</li> <li>x: X-position (left position of the bitmap).</li> <li>y: Y-position (upper position of the bitmap).</li> <li>cnt: Number of bytes of the bitmap in horizontal direction. The width of the bitmap is cnt*8.</li> <li>h: Height of the bitmap. </li> </ul> </blockquote> <hr> <p>It would appear your image data is complete gibberish. This is what I decode it to be:</p> <pre><code> ###### # # # ### # # #### # # # ## # # # # ## ## # # # # ## # # # # ## ##### # #### # # # # # # # # ## ### # # ## # # # # # # # ## # # # # # # # ### ## ## </code></pre>
19642
|serial|arduino-mega|c++|rs485|rs232|
Long Distance Communication with Arduino
2016-01-16T16:52:56.753
<p>I am reading the value of six potentiometers with a TX Arduino and receiving that data and applying those numbers to a motor using serial. It is working fine through TTL but I am going to need to do this over a 60 ft tether.</p> <p>I have done a little research and see that I could use RS 232 but that the maximum you should go with that is 50 ft, which will not work if I'm not mistaken. I have also seen RS 485 which will give us 4000 ft, which is overkill but will work. However, that only offers one-way communication, if I'm not mistaken. What I'm wondering is which protocol should I convert it to, and how I would have to adjust my RX and TX code.</p> <p>TX code:</p> <pre><code>/* Transmitting Code Reads potentiometers and sends them through serial */ int data [10]; // to send bytes int start [2]; int pot0Pin = A0; // analog pin used to connect the potentiometer int pot0; // variable to read the pot0ue from the analog pin int pot1Pin = A1; int pot1; int pot2Pin = A2; int pot2; unsigned char checksum0; unsigned char checksum1; unsigned char checksum2; void setup() { Serial.begin(9600); Serial1.begin(9600); pinMode(19, INPUT); pinMode(18, OUTPUT); } void loop() { // READ THE POTENTIOMETERS: pot0 = analogRead(pot0Pin); // reads the value of the potentiometer (pot0ue between 0 and 1023) data[0] = pot0 &amp; 0xFF; //least significant 8 bit byte data[1] = (pot0 &gt;&gt; 8); //most significant 2 bits pot1 = analogRead(pot1Pin); data[2] = pot1 &amp; 0xFF; data[3] = (pot1 &gt;&gt; 8); pot2 = analogRead(pot2Pin); data[4] = pot2 &amp; 0xFF; data[5] = (pot2 &gt;&gt; 8); // CREATE CHECKSUMS: checksum0 = ~(data[0]+data[1]) + 1; checksum1 = ~(data[2]+data[3]) + 1; checksum2 = ~(data[2]+data[3]) + 1; // WRITE VALUES AND CHECKSUMS TO SERIAL: Serial1.write(data[0]); Serial1.write(data[1]); Serial1.write(data[2]); Serial1.write(data[3]); //bytes sent Serial1.write(data[4]); Serial1.write(data[5]); Serial1.write(checksum0); Serial1.write(checksum1); Serial1.write(checksum2); // send the checksum delay(10); // delay in between reads for stability } </code></pre> <p>RX code:</p> <pre><code>/* Receving Code Reads bytes from Transmitting Code and put thems back together Applies the read bytes to our motor control board */ unsigned char val[10]; // variable to read the value from the analog pin int motorVal; int coolVal; // 0-1024 received from serial int coolVal1; int coolVal2; unsigned char checksum1; unsigned char checksum2; unsigned char checksum3; unsigned char checkit1; unsigned char checkit2; unsigned char checkit3; int directionPin = 8; int PWM_out_pin = 9; // works on pins 2 - 13 and 44 - 46 void setup() { Serial.begin(9600); Serial1.begin(9600); // Serial1.begin(9600); pinMode(10, INPUT); pinMode(18, OUTPUT); pinMode(8, OUTPUT); pinMode(9, OUTPUT); } void loop() { if (Serial1.available()&gt;5) { val[0]=Serial1.read(); // least significant 8 bits val[1]=Serial1.read(); // most significant 2 bits val[2]=Serial1.read(); val[3]=Serial1.read(); val[4]=Serial1.read(); val[5]=Serial1.read(); checksum1=Serial1.read(); checksum2=Serial1.read(); checksum3=Serial1.read();// get the checksum last checkit1 = val[0]+val[1]+checksum1; checkit2 = val[2]+val[3]+checksum2; checkit3 = val[4]+val[5]+checksum3; if (checkit1==0); { coolVal = val[1]&lt;&lt;8 | val[0]; } if (checkit2==0); { coolVal1 = val[3]&lt;&lt;8 | val[2];} if (checkit3==0); { coolVal2 = val[5]&lt;&lt;8 | val[4]; } Serial.print(coolVal); Serial.print(" "); Serial.print(coolVal1); Serial.print(" "); Serial.println(coolVal2); delay(10); } // FOR MOTOR 1 (more will be added once we achieve successful serial): if (coolVal &gt; 550) { digitalWrite (directionPin, HIGH); motorVal = map(coolVal, 550, 1023, 0, 1023); analogWrite (PWM_out_pin, motorVal / 4); } if ((coolVal &lt; 550) &amp;&amp; (coolVal &gt; 500)) { digitalWrite (directionPin, HIGH); analogWrite (PWM_out_pin, 0); } if (coolVal &lt; 500) { digitalWrite (directionPin, LOW); motorVal = map(coolVal, 0, 500, 1023, 0); analogWrite (PWM_out_pin, motorVal / 4); } } </code></pre>
<p>You can do two-way communication with RS485. I have a <a href="http://www.gammon.com.au/forum/?id=11428" rel="nofollow noreferrer">page about RS485</a> with schematics and code, including calculating checksums.</p> <p>You don't have to use twisted cable, that would just add to the reliability. You would need 4 cores (power, ground, A and /B) however if the other end was self-powered (ie. a battery) then you could skip that. There has been a bit of debate about whether the ground wire is needed (assuming you don't send power) but it is probably sensible to include it.</p> <p>The page I linked above also describes a rolling master system, where each node has a chance to "talk" to other nodes. This demonstrates that you can send and receive on the same pair of wires.</p> <p>In my test of the rolling master (using UTP cable) I had it working over 40 meters (ignore the figure on the schematic). So your 50 feet range should be easily achievable.</p> <p><a href="https://i.stack.imgur.com/I5ZZa.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I5ZZa.png" alt="RS485 connection"></a></p>
19648
|arduino-uno|serial|arduino-ide|usb|communication|
Difference between /dev/ttyACM0 and /dev/ttyS0 (Arduino IDE ports under Linux)
2016-01-16T21:30:13.823
<p>I use the Arduino IDE to upload sketches to my Arduino Uno. My OS is Linux Ubuntu 14.04 LTS. The Arduino IDE has two ports by default for communication with the Arduino Uno: </p> <pre><code>/dev/ttyACM0 /dev/ttyS0 </code></pre> <ol> <li>What is the difference between these two ports ? </li> <li>What does "ACM0" and "S0" mean ?</li> <li>Are there configuration files somewhere in the OS folder structure that describe the parameters of these ports ?</li> </ol> <p>I know that when I select <code>/dev/ttyACM0</code>, I am able to send data to my Arduino Uno. However it does not work when I select <code>/dev/ttyS0</code>. </p> <p>I just want to better understand what these ports are exactly.</p>
<p>Some high-level languages (e.g. matlab) treat all serial ports as the /dev/ttyS# selecter. To interface with an Arduino with MATLAB you have to rename /dev/ttyACM0 as /dev/ttyS#.</p> <p>This may also be an option in the Arduino IDE, and that is why those options exist.</p>
19654
|arduino-uno|serial|xbee|
Communication between Arduino and XBee
2016-01-16T23:38:06.697
<p>I have two XBee Pro S2Bs: one is plugged in to a USB explorer, and; the other is plugged into an Arduino Wireless Protoshield, which is connected to an Arduino Uno.</p> <p>My XBee connected to the explorer is configured as the <em>coordinator</em> in AT mode, and the XBee connected to the Arduino is configured as a <em>router</em> in AT mode. As a side note, I tested the network with a second USB explorer, and I was able to communicate between both XBees.</p> <p>I uploaded the following code to the Arduino (which is just a sample I pulled off the internet somewhere):</p> <pre class="lang-c prettyprint-override"><code>char rx_byte; void setup() { Serial.begin(9600); } void loop() { if (Serial.available() &gt; 0) { rx_byte = Serial.read(); Serial.print("You Typed: "); Serial.println(rx_byte); } } </code></pre> <p>Once I upload the code and turn on the serial monitor for the Arduino (using either the Arduino IDE or Visual Micro, with the Arduino plugged in via USB), and turn on the serial monitor on for the XBee connected to the USB explorer (using the serial monitor in XCTU), I get the following results:</p> <ul> <li><p>If the wireless proto shield has its switch set to USB mode, then I can send data from the Arduino serial monitor to the serial monitor in XCTU, but the Arduino serial monitor doesn't receive data that is typed into the XCTU serial monitor.</p></li> <li><p>If the wireless proto shield has its switch set to Micro mode, then I get mostly the opposite result. I can send data from XCTU serial monitor to the Arduino serial monitor, which the result is returned to the XCTU serial monitor, e.g., if I type "X" in XCTU serial monitor, both serial monitors say "You Typed: X". However, if I try to send data through the Arduino's serial monitor, neither serial monitor displays anything.</p></li> </ul> <p>What I would like to do is be able to type in either serial monitor and have the data displayed in both serial monitors, like you would expect in a simple chat program.</p> <p>Can someone see where I have gone wrong and/or how to get to the correct result?</p>
<p>Check out <a href="https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test" rel="nofollow">https://learn.sparkfun.com/tutorials/xbee-shield-hookup-guide/example-communication-test</a> Essentially you need to set up Software Serial for your xbee to communicate on a couple of digital pins, instead of using hardware serial. When using hardware serial (the RX and TX pins) only one device works on it at a time, hence why you can't use the xbee and the serial monitor at the same time. </p>
19672
|arduino-uno|rtc|oscillator-clock|
Do I have to use an RTC to build a clock?
2016-01-17T18:42:07.357
<p>While I was researching ideas for an Arduino clock, I found several clocks that incorporated an RTC (Real Time Clock) module.</p> <p>I don't know why it is used in some clocks.</p> <p>So, here are my questions:</p> <ul> <li>How does an RTC module work?</li> <li>Do I have to use it "like a rule" (is an RTC necessary or unnecessary) in my clock?</li> </ul>
<p>I built a clock designed a while ago by Geoff Graham, who <a href="http://geoffg.net/GPS_Synchronised_Clock.html" rel="nofollow noreferrer">synchronized to a GPS</a> around every 24 hours, and used the internal clock in-between. The GPS corrected for drift in the internal clock (and, of course, gave you the time accurately in the process).</p> <p>This is more expensive than a RTC, but more accurate. If you also had an RTC it would drift less during the day. Or, you could read from the GPS all the time and not have an RTC.</p> <p>I made a <a href="http://www.gammon.com.au/forum/?id=11991" rel="nofollow noreferrer">GPS clock</a> myself which does that - just shows the GPS time.</p> <p><a href="https://i.stack.imgur.com/aWQyV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/aWQyV.jpg" alt="GPS clock"></a></p> <p>Higher-contrast image:</p> <p><a href="https://i.stack.imgur.com/NhA5R.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NhA5R.jpg" alt="GPS clock face"></a></p> <p>Internals:</p> <p><a href="https://i.stack.imgur.com/r9MOy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r9MOy.jpg" alt="Inside GPS clock"></a></p> <hr> <p>This is <a href="http://www.gammon.com.au/forum/?id=12106" rel="nofollow noreferrer">another project</a> that uses an RTC clock chip (indicated on photo):</p> <p><a href="https://i.stack.imgur.com/2EZ5o.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2EZ5o.png" alt="Temperature sensor"></a></p> <p>However if you go for just an RTC chip you can expect it to drift over time. They are more accurate than counting processor ticks (and survive a power outage because of the backup battery) but are not as accurate as the GPS.</p> <p>Those clock chips are pretty cheap. I got 30 of them for $10 from eBay.</p>
19673
|input|arduino-uno|electronics|
İs there any way different way than GND's Arduino
2016-01-16T21:40:55.640
<p>İ'm making a project on my arduino uno when i figured out i had no more GND left to finish the circuit. İs there any other way to optimize, use pins as input maybe. İ tried whit other websites, however, they weren't much of a use. Can you show an example also. <br> Thank you sooo much in advance, <br> Dario</p>
<p>Dario,</p> <p>There are only 3 ground pins on the Arduino Uno, but don't be afraid to "breakout" these pins with wire. It doesn't matter if you connect multiple component grounds together, as long as they are connected to ground with no resistance between them, the circuit will close. </p> <p>Strip board and pin headers will help you here, try this: <a href="http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/" rel="nofollow">http://www.instructables.com/id/Home-Made-Arduino-Prototype-Shield/</a></p>
19679
|power|
Connecting Arduino To mains
2016-01-17T21:12:25.733
<p>How would iconnect my Arduino Mega to house Mains, without buying a transformer, and having to make a whole setup for that. Can i just use a regular phone adapter? Or is 1 Amp too large (or 2 Amps).</p>
<p>Amps tell you how much current you can draw from the power supply, or "how much it can do".</p> <p>You can hook up 3Amps power supply to a device that draws 1Amp and it will work ok, still having 2 amps of reserve.</p> <p>You must pay attention to power supply <strong>voltage</strong> and keep it in specified range.</p> <p>Arduino Mega has recommended input voltage of 7-12V, so you must deliver at least 7V. There are plenty of cheap wall power supplies with voltage regulation from 1.5V to 12V.</p> <p>How much current it will draw depends on your application, but I doubt that you can suck more than 0,5-1A in a typical application.</p>
19689
|arduino-uno|
Reverse the order of a hex string
2016-01-17T23:46:11.303
<p>I'm printing an "unsigned long" value to HEX via:</p> <pre><code>println(cardCode, HEX); </code></pre> <p>The value that I'm getting is: 69fb879d</p> <p>I need it to be reversed as: 9d87fb69</p> <p>I populate cardCode via the code:</p> <pre><code>for (i=1;i&lt;bitCount;i++) { cardCode &lt;&lt;=1; cardCode |= databits[i]; } </code></pre> <p>going into this my bitCount value is 32, so basically I'm populating cardCode based on 32 bits from the variable databits which is of type unsigned char.</p> <p>I am absolutely crap at bitwise conversions (bit-shifting, etc.), is there a simple way to do this reversal? Is this even enough information to go on?</p>
<p>The title of this question is "Reverse the order of a hex string" but it was actually about reversing byte order in an unsigned long int.</p> <p>Here is an answer for reverse the order of a string (null terminated vector of char).</p> <p>There is a <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__string.html#gacfdb3ab0c1f988f86d04d706d8e0ce3f" rel="nofollow">standard function</a> for that in the C string function library.</p> <pre><code>char* strrev(char* s); </code></pre> <p>Cheers!</p>
19700
|arduino-uno|led|pwm|attiny|
Arduino non-blocking software PWM LED fader not working
2016-01-18T06:13:27.410
<p>I am trying to write a simple software PWM to fade some LEDs because I don't have enough PWM I/O Ports.</p> <p>The code evaluates how long you want the LED to fade, and breaks it down into a number of steps. During each step, it will evaluate the period the LED should be on.</p> <p>I have the following code:</p> <pre><code>class Led{ public: Led(int pin); void setup(); // void updateFadeDirection(); void updateBrightness(); private: int _pin; unsigned long _currentTime; unsigned long _startTime; // Very beginning of fade period unsigned long _fadePeriod; // How long to fade on and off int _fadeStep; // current fade step i.e. 1/255 int _fadeSteps; // How many steps to take until full brightness int _fadeDirection; // low to high or high to low? float _T_on; // Amount of time to turn LED on float _T_fadeStep; // Amount of time per step increment of brightness unsigned long _stepTime; // Start of current step period bool _evaluated; }; Led::Led(int pin){ _pin = pin; } void Led::setup(){ pinMode(_pin, OUTPUT); _startTime = micros(); _fadePeriod = 2*1000000; //microseconds(us) _fadeStep = 50; // start at 0 brightness here _fadeSteps = 100; _fadeDirection = 1; _T_fadeStep = _fadePeriod/_fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on _stepTime = micros(); delayMicroseconds(200); } void Led::updateBrightness(){ _currentTime = micros(); if(_currentTime - _startTime &lt; _fadePeriod){ if (_currentTime - _stepTime &gt; _T_on){ digitalWrite(_pin, LOW); } else { digitalWrite(_pin, HIGH); } if(_currentTime - _stepTime &gt;= _T_fadeStep){ // _fadeStep++; _stepTime = _currentTime; _T_on = (_fadeStep/_fadeSteps) * _T_fadeStep; } } else{ digitalWrite(_pin, HIGH); } } Led LED0(0); void setup() { LED0.setup(); } void loop() { LED0.updateBrightness(); } </code></pre> <p>The current behaviour when powered on is the single LED will be turned off, then will turn on after 2 seconds.</p> <p>In particular, it never seems to enter the <code>else</code> part</p> <pre><code> if (_currentTime - _stepTime &gt; _T_on){ digitalWrite(_pin, LOW); } else { digitalWrite(_pin, HIGH); } </code></pre> <p>The problem is that the LED will never hit <code>HIGH</code> until the outer <code>else</code> is triggered.</p> <p>I believe it has to do with <code>_T_on</code> being an <code>int</code> and the timestamps being <code>unsigned long</code> and me not casting it.</p> <p>The expected behaviour is 2 seconds of dimmed (50%) light, and then a full 100% when it hits the outer <code>else</code>.</p>
<p>As @ott-- has mentioned, because of the <code>int</code> datatype, <code>_fadeStep</code>/<code>_fadeSteps</code> will always evaluate to 0.</p> <p>Here's the updated code along with some timing tweaks:</p> <pre><code>float fadeSteps = 150; // How many steps to take until full brightness class Led{ public: Led(int pin, float fadeStep=0); void setup(); // void updateFadeDirection(); void updateBrightness(); private: int _pin; unsigned long _currentTime; unsigned long _startTime; // Very beginning of fade period unsigned long _fadePeriod; // How long to fade on and off float _fadeStep; // current fade step i.e. 1/255 int _fadeDirection; // low to high or high to low? unsigned long _T_on; // Amount of time to turn LED on unsigned long _T_fadeStep; // Amount of time per step increment of brightness unsigned long _stepTime; // Start of current step period bool _evaluated; }; Led::Led(int pin, float fadeStep){ _pin = pin; _fadeStep = fadeStep; } void Led::setup(){ pinMode(_pin, OUTPUT); _startTime = micros(); _fadePeriod = 2000000; //microseconds(us) _fadeDirection = 1; _T_fadeStep = _fadePeriod/2/fadeSteps; // i.e. 2000000us/100steps = 20000us/step of brightness _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; // i.e. 20/100 * 20000us = 4000us on _stepTime = micros(); } void Led::updateBrightness(){ _currentTime = micros(); if (_currentTime - _stepTime &gt; _T_on){ digitalWrite(_pin, LOW); } else { digitalWrite(_pin, HIGH); } if(_currentTime - _stepTime &gt;= _T_fadeStep){ _fadeStep += _fadeDirection; _stepTime = _currentTime; _T_on = (_fadeStep/fadeSteps) * _T_fadeStep; } if(_fadeStep &gt;= fadeSteps-1) { _fadeDirection = -1; } else if(_fadeStep &lt;= 1) { _fadeDirection = 1; } } Led LED0(0); Led LED1(1,fadeSteps/5); Led LED2(2,2*fadeSteps/5); Led LED3(3,3*fadeSteps/5); Led LED4(4,4*fadeSteps/5); void setup() { LED0.setup(); LED1.setup(); LED2.setup(); LED3.setup(); LED4.setup(); } void loop() { LED0.updateBrightness(); LED1.updateBrightness(); LED2.updateBrightness(); LED3.updateBrightness(); LED4.updateBrightness(); } </code></pre> <p>Some refactoring is needed to be more modular, but will fade (using software PWM) LEDs asynchronously on every digital OUT port on an attiny85. Can also set the starting brightness so that you can make an LED fading chaser.</p>
19705
|arduino-uno|timers|rtc|millis|
Managing timer intervals using millis at random intervals
2016-01-18T12:47:28.617
<p>I am doing a project which needs to meet the following specifications.</p> <blockquote> <p>On receiving an SMS arduino will start switching 1st relay on after some time duration(say 30 Seconds) relay 1 will be turned off and it will now turn on 2nd relay for (say 20seconds) so on 1>2>3>4.</p> </blockquote> <p>The problem im facing is managing the time intervals between the switching process,i did think of using millis() i.e <strong>(currentMillis-previousMillisx>Intervalx)</strong> as in blinkWithoutDelay ,how ever this will work only once as i dont not know when will the next SMS come to the system ,if the user decides to send the message after 1hour currentMillis-previousMillisx will always return true so i cannot keep the motor on for (Say 30 seconds) and same will happen with all 4 cases.</p> <p>If there is any alternative logic for this problem please suggest me or can i just add RTC for my project to manage time easily</p> <p>Thank You</p>
<p>I do not really understand your problem. More specifically, “currentMillis-previousMillisx will always return true” does not make sense, as it is not a boolean expression (it's <code>unsigned long</code>).</p> <p>Anyway, the technique shown in blinkWithoutDelay is the way to go. Here is my (untested) version:</p> <pre class="lang-c++ prettyprint-override"><code>const int relay_count = 4; // we have 4 relays const int relay_pins[relay_count] = {2, 3, 4, 5}; const unsigned long durations[relay_count] = {30000, 20000, 15000, 10000}; bool sms_received(); // you implement this one void loop() { static int current_relay = -1; // meaning: no active relay static unsigned long last_switch; unsigned long now = millis(); // If no relay is active, wait for an SMS. if (current_relay == -1) { if (sms_received()) { // Switch on first relay. current_relay = 0; digitalWrite(relay_pins[current_relay], HIGH); last_switch = now; } } // Otherwise, switch relays when it is time to do so. else if (now - last_switch &gt;= durations[current_relay]) { digitalWrite(relay_pins[current_relay], LOW); if (++current_relay == relay_count) { current_relay = -1; // no active relay } else { digitalWrite(relay_pins[current_relay], HIGH); last_switch = now; } } } </code></pre> <p>BTW, you did not specify what should happen if you receive an SMS while one of the relays is active. I assume the SMS are only acknowledged when no relay is active. Otherwise you would have to change the code.</p>
19714
|bluetooth|
Arduino Uno, HM-10 Bluetooth Module, Not Discoverable
2016-01-18T19:23:35.533
<p>In short, I've hooked up an HM-10 to digital pins 10 and 11 on my Uno (required because TX/RX (0/1) can't be used whilst a serial connection is present). The Bluetooth module is a <a href="http://www.sunfounder.com/index.php?c=show&amp;id=38&amp;model=HM-10" rel="nofollow">Sunfounder HM-10</a> which comes with a <a href="http://www.sunfounder.com/js/edit/attached/file/Bluetooth4_en.zip" rel="nofollow">data sheet</a>. I'm successfully communicating with the HM-10 and I've written a modified version of serial comms tutorial code provided so it stores the reads up in a buffer before outputting them which works fine, I can set all properties on the HM-10 using this method.</p> <p>The delays were necessary as it seems the clock cycle can't 'keep up' - bytes go missing when reading/writing, so if I attempt to write by just using <code>Serial.read()</code> in <code>loop()</code> alone then not all of it is read/written.</p> <p>Here's the code.</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(10, 11); // RX, TX void setup() { // Open serial communications and wait for port to open: Serial.begin(57600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } Serial.println("Goodnight moon!"); delay(500); // set the data rate for the SoftwareSerial port mySerial.begin(9600); mySerial.print("Wake up wake up wake up wake up wake up! Wake up wake up wake up wake up wake up!"); } void loop() // run over and over { if (mySerial.available()) { String s = ""; char c; while((c = mySerial.read()) != -1) { s += c; delay(10); } Serial.println("Received: " + s); } if (Serial.available()) { String s = ""; char c; while((c = Serial.read()) != -1) { s += c; delay(10); } delay(10); Serial.println("Sent: " + s); mySerial.print(s); } } </code></pre> <p>This allows me to show input and output as follows:</p> <pre><code>Sent: AT+ADDR? Received: OK+ADDR:F4B85EB42D64 Sent: AT+ADVI? Received: OK+Get:0 Sent: AT+ALLO? Received: OK+Get:0 Sent: AT+BATT? Received: OK+Get:077 </code></pre> <p>So good so far. Here's what I can't figure out from the data sheet. How do I make the bluetooth module discoverable on, say, my Mac or from my iPhone? I've tested setting <code>AT+ROLE0</code> or <code>AT+ROLE1</code> followed by <code>AT+RESET</code> and also set <code>AT+NAME</code> so I know what to expect, yet I can't discover the module.</p> <p>Also to note, the status LED is flashing as per the specification as an unconnected status (500ms high, 500ms low) which indicates <code>AT+PIO10</code> is setup. <code>AT+ADTY?</code> is set to 0 which allows it to be advertising, responds to scanning and connectable.</p> <p>I'm likely missing something quite obvious. Any ideas?</p>
<p>Thanks for your answer! In another thread, I found a free iOS bluetooth scanning app called LightBlue Explorer (<a href="https://itunes.apple.com/au/app/lightblue-explorer-bluetooth/id557428110?mt=8" rel="nofollow noreferrer">https://itunes.apple.com/au/app/lightblue-explorer-bluetooth/id557428110?mt=8</a>) which also lets you read/write to the device. Super handy. Adding that here for the next person who encounters this thread and wants a rec for a scanning app.</p>
19717
|arduino-uno|bluetooth|softwareserial|hc-05|
Connection bluetooth master and slave with Android
2016-01-18T20:51:47.527
<p>I send a date from my android to arduino without problem, but also i want send date from arduino to android later of received the date from android.</p> <p>I have time trying it, but i can not yet, help me. My codec of arduino</p> <pre><code>char enter; #include &lt;SoftwareSerial.h&gt; SoftwareSerial conect(10,11); void setup() { pinMode(8,OUTPUT); conect.begin(9600); digitalWrite(8,LOW); } void loop() { if(conect.available()&gt;0) { enter=conect.read(); if(entrada=='1') { digitalWrite(8,HIGH); conect.print("1"); } } } </code></pre> <p>And in the side from android this is my handler for drive the the date that arrive.</p> <pre><code> Handler mhandler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case CONECTADO: //ManejarDatos msjre = new ManejarDatos((BluetoothSocket)msg.obj); msjre = new ManejarDatos((BluetoothSocket)msg.obj); break; case MENSAJELEYENDO: byte[] readBuf = (byte[])msg.obj; String string = new String(readBuf,0,msg.arg1); Toast.makeText(getApplicationContext(), string, Toast.LENGTH_LONG).show(); break; } } }; </code></pre> <p>And on my class for read and write i have this</p> <pre><code>private class ManejarDatos extends Thread { private final OutputStream salidadatos; private final BluetoothSocket sockk; private final InputStream entradadatos; public ManejarDatos(BluetoothSocket socke1) { sockk=socke1; OutputStream temporalsalida=null; InputStream temporalentrada=null; try { temporalentrada=socke1.getInputStream(); temporalsalida=socke1.getOutputStream(); }catch (IOException e){} salidadatos=temporalsalida; entradadatos=temporalentrada; } public void run() { byte[] espera; int esperaalmacen; while (true) { try { espera=new byte [1024]; esperaalmacen=entradadatos.read(espera); mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera) .sendToTarget(); }catch (IOException e){break;} } } public void escribe(byte[] bytes) { try { salidadatos.write(bytes); //handler.obtainMessage(MENSAJE_SALIDA,-1,-1,bytes).sendToTarget(); }catch (IOException e){ //Log.e(TAG, "....Error al enviar dato" + e.getMessage() + "..."); } } public void cancel() { try{ sockk.close(); }catch (IOException e){} } } </code></pre> <p>When i push button, send a date to arduino, here my codec of button(i send 1 for bluetooth)</p> <pre><code> Enviar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String salida="1"; msjre.escribe(salida.getBytes()); } }); </code></pre>
<p>What is <code>entrada</code>? Replace <code>entrada</code> with <code>enter</code> in your arduino code and try again. Also try this <code>run()</code> code instead:</p> <pre><code>public void run() { byte[] espera = new byte[1024]; int esperaalmacen; while (true) { try { esperaalmacen=entradadatos.read(espera); mhandler.obtainMessage(MENSAJELEYENDO,esperaalmacen,-1,espera) .sendToTarget(); }catch (IOException e){break;} } } </code></pre>
19730
|programming|arduino-ide|
expected ';' before '{' token error
2016-01-19T00:54:15.450
<p>I am trying to figure out what I did wrong in my sketch. In my void loop(), at the very bottom of the sketch, my if/else statement keeps compiling with the above error. Originally, it was an if/else if/else statement. I had the current else's an else if and the Update in my else. Someone had corrected me on it and i removed the code and made the proper changes and the error started. Now, just for the sake of my sanity I went ahead and put the ';' at the end of my else, which I know is wrong, just to see if it compiled, which it did. I ran the sketch and sure enough it broke the operation. I cannot figure out what it is looking for. Any help would be appreciated.</p> <pre><code> //ASHPD Barrel Version 4.0.2 (adding pulse) Created By Gixxerfool 01.11.2016 #include &lt;Adafruit_NeoPixel.h&gt; #ifdef __AVR__ #include &lt;avr/power.h&gt; #endif // Pattern types supported: enum pattern {NONE, CHASE, PULSE}; #define orange 255,128,0 #define blue 0,0,255 char targetColor = '0,0,255'; // NeoPattern Class class NeoPatterns : public Adafruit_NeoPixel { public: // Member Variables: pattern ActivePattern; // which pattern is running unsigned long Interval; // milliseconds between updates unsigned long lastUpdate; // last update of position uint32_t Color1; // What color is used uint16_t TotalSteps; // total number of steps in the pattern uint16_t Index; // current step within the pattern // Constructor NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type) :Adafruit_NeoPixel(pixels, pin, type) { } // Update the pattern void Update() { if ((millis() - lastUpdate) &gt; Interval) // time to update { lastUpdate = millis(); switch (ActivePattern) { case CHASE: ChaseUpdate(); break; // case PULSE: //PulseUpdate(); //break; default: break; } } } // Increment the Index and reset at the end void Increment() { Index++; if (Index &gt;= TotalSteps) { Index = 0; } } // Calculate 50% dimmed version of a color (used by ChaseUpdate) uint32_t DimColor(uint32_t color) { // Shift R, G and B components one bit to the right uint32_t dimColor = Color(Red(color) &gt;&gt; 1, Green(color) &gt;&gt; 1, Blue(color) &gt;&gt; 1); return dimColor; } // Returns the Red component of a 32-bit color uint8_t Red(uint32_t color) { return (color &gt;&gt; 16) &amp; 0xFF; } // Returns the Green component of a 32-bit color uint8_t Green(uint32_t color) { return (color &gt;&gt; 8) &amp; 0xFF; } // Returns the Blue component of a 32-bit color uint8_t Blue(uint32_t color) { return color &amp; 0xFF; } // Initialize for a CHASE void Chase(uint32_t color1, uint8_t interval) { ActivePattern = CHASE; Interval = interval; TotalSteps = (numPixels()); Color1 = color1; Index = 0; } // Update the Chase Pattern void ChaseUpdate() { for (int i = 0; i &lt; numPixels() + 1; i++) { if (i == Index) // Scan Pixel { setPixelColor(i, Color1); } else // Fading tail { setPixelColor(i, DimColor(getPixelColor(i))); } } show(); Increment(); } //Initialize for a pulse void Pulse(uint32_t color1, uint8_t interval) { ActivePattern = PULSE; Interval = interval; TotalSteps = 256; Color1 = color1; Index = 0; } //Update the Pulse void PulseUpdate() { for (int h = 0; h &lt; 256; h++) { for (int i = 0; i &lt; 126; i++) { for (int j = 0; j &gt; -1; j--) { if (h == Index) { setPixelColor(i, Color1); } else { setPixelColor(j, Color1); } } show(); Increment(); } } } }; // Define some NeoPatterns NeoPatterns Ring3(16, 4, NEO_GRB + NEO_KHZ800); NeoPatterns Ring2(12, 1, NEO_GRB + NEO_KHZ800); NeoPatterns Ring1(7, 0, NEO_GRB + NEO_KHZ800); // Initialize everything and prepare to start void setup() { // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket #if defined (__AVR_ATtiny85__) if (F_CPU == 16000000) clock_prescale_set(clock_div_1); #endif // End of trinket special code pinMode(2, INPUT); //Sets pin 2 as an input // Initialize all the pixels Ring1.begin(); Ring2.begin(); Ring3.begin(); //Set all pixels to off Ring1.show(); Ring2.show(); Ring3.show(); ring3Wipe(Ring3.Color(blue), 50); // Wipe ring 3 in blue once ring2Wipe(Ring2.Color(blue), 50); // wipe ring 2 in Blue once ring1FadeUpBlue(Ring1.Color(blue)); //Fade in ring1 once //Start the idle pattern //Name.PatternName(Name.Color(targetColor), Interval) Changing Interval will adjust the speed of the pattern Ring1.Pulse(Ring1.Color(blue), 500); Ring2.Chase(Ring2.Color(blue), 55);//keep the interval 15ms above ring3 for synchronicity Ring3.Chase(Ring3.Color(blue), 40);//keep the interval 15ms below ring2 for synchronicity } void ring1FadeUpBlue(uint8_t wait) { for(int j = 0; j &lt; 255; j++) { uint32_t color = Ring1.Color(0, 0, j ); // ramp up the blue only for(uint16_t i=0; i &lt; Ring1.numPixels(); i++) { Ring1.setPixelColor(i, color); } delay(7); Ring1.show(); } } //wipes the ring2 once in blue void ring2Wipe(uint32_t c, uint8_t wait) { for(uint16_t i=0; i &lt; Ring2.numPixels(); i++) //This for loop runs reverse to ring3 loop { Ring2.setPixelColor(i, c); Ring2.show(); delay(wait); } } //wipes the ring3 once for the color blue void ring3Wipe(uint32_t c, uint8_t wait) { //uint32_t and uint8_t are the colorWipe parameters c=color wait=#of ms between pixels. larger # slows the action for(uint16_t i=0; i &lt; Ring3.numPixels(); i++) { Ring3.setPixelColor(i, c); Ring3.show(); delay(wait); } } // Main loop void loop() { // Update the rings. Ring1.Update(); Ring2.Update(); Ring3.Update(); // check for button press: if (digitalRead(2) == LOW) // Button is pressed { Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange Ring2.Color1 = Ring2.Color(orange); Ring1.Color1 = Ring1.Color(orange); } else (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go { Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue Ring2.Color1 = Ring2.Color(blue); Ring1.Color1 = Ring1.Color(blue); } } </code></pre>
<p>The if-else construct is incorrect.</p> <p>It needs to be like this:</p> <pre><code>if (condition) { //actions } else { //other actions } </code></pre> <p>Which reads: if the conditions are true, then do actions, otherwise do other actions.</p> <p>OR it can be like like this</p> <pre><code>if (condition) { //actions } else { if (other condition){ //other actions } } </code></pre> <p>Which reads: if conditions are true, then do actions, otherwise, if other conditions are true, then do other actions. Note that in this structure, if neither conditions or "other conditions" are true, then we do nothing.</p> <p>So if DigitalRead can <strong>only</strong> be HIGH or LOW, then you don't need condition that in the "else" statement. Your code can look like this:</p> <pre><code> // check for button press: if (digitalRead(2) == LOW) // Button is pressed { Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange Ring2.Color1 = Ring2.Color(orange); Ring1.Color1 = Ring1.Color(orange); } else { // digitalRead(2) must be HIGH if it's not LOW //Kicks the color back to blue after the button is let go Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue Ring2.Color1 = Ring2.Color(blue); Ring1.Color1 = Ring1.Color(blue); } </code></pre> <p>Only if digitalRead could return another value (e.g. 3, 100, 75 etc) then you would need the other conditions in your else clause, but the code would need to look like this:</p> <pre><code> // check for button press: if (digitalRead(2) == LOW) // Button is pressed { Ring3.Color1 = Ring3.Color(orange);//Change the target color to orange Ring2.Color1 = Ring2.Color(orange); Ring1.Color1 = Ring1.Color(orange); } else { if (digitalRead(2) == HIGH)//Kicks the color back to blue after the button is let go { Ring3.Color1 = Ring3.Color(blue);//Change the target color back to blue Ring2.Color1 = Ring2.Color(blue); Ring1.Color1 = Ring1.Color(blue); } } </code></pre> <p>Note: you don't actually need the braces around the second "if" statement there, but it makes the structure more clear.</p>
19755
|bluetooth|attiny|spi|adafruit|
BLE SPI Module with ATtiny85
2016-01-19T23:31:42.980
<p>Adafruit carries a number of Bluetooth LE 4.0 modules in their store, notably the SPI (<a href="https://www.adafruit.com/products/2633" rel="nofollow">https://www.adafruit.com/products/2633</a>) and UART (<a href="https://www.adafruit.com/product/2479" rel="nofollow">https://www.adafruit.com/product/2479</a>) version. I have used the NRF24L01 module with ATtiny85 via SPI to transmit data in the past, and this uses 3 pins. I used the following setup to do so: <a href="https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2" rel="nofollow">https://www.hackster.io/arjun/nrf24l01-with-attiny85-3-pins-74a1f2</a>. </p> <p>My previous system consisted of ATtiny85s communicating with a receiver (Bluefruit Feather) via NRF24L01 radios. As the receiver got data, it sent it to an iPhone app that I wrote. Now, I would like to cut out this receiver and BLE straight to the iPhone, which supports multiple peripheral connections.</p> <p>However, unlike the RF24 library, the Adafruit BLE SPI library needs the actual SPI library to compile correctly, which for some reason the RF24 library (this version: <a href="http://tmrh20.github.io/RF24/" rel="nofollow">http://tmrh20.github.io/RF24/</a>) doesn't. I don't quite get how the RF24 library can compile fine without the SPI library when targeting the ATtiny85 - Is there some way to get this to work similar to the RF24 library?</p> <p>Alternatively, I think there is a way to do software UART on ATtiny85, which I know nothing about, so if there truly is no way to do SPI is UART possible?</p> <p>I realize that this is a question best asked to Adafruit, which I have done, but I thought I'd post it here and see if anyone can help.</p> <p>Thanks, Alex</p>
<p>I find the ATTiny85 working well with software serial port. Serial UART (or in fact any of the protocols like I2C or SPI) are just bit banging - and you can do that pretty well in software. Of course, having a hardware support makes things easier and faster, but there is nothing badly wrong with a software uart either. Except that you have to continuously check if there is some data arrives. </p> <p>I was using software serial on Adafruit Trinket (ATTiny85) in various projects to talk to a Bluetooth 2.1 module, and it worked pretty well.</p> <p>Here <a href="http://arduining.com/category/trinket-projects/" rel="nofollow">http://arduining.com/category/trinket-projects/</a> they use the same approach to talk to an ESP8266.</p> <p>You may wish to look for the SoftwareSerial lib for Trinket, or in certain cases you may want to go for the SendOnlySoftwareSerial lib (send only, but smaller code footprint).</p> <p>Also a hardware based serial lib is available: <a href="https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/" rel="nofollow">https://blog.adafruit.com/2013/09/30/hardware-serial-library-for-the-trinket/</a></p>
19756
|serial|c++|hardware|softwareserial|
How does serial communications work on the Arduino?
2016-01-20T02:45:05.987
<p>With reference to the Arduino Uno, Mega2560, Leonardo and similar boards:</p> <ul> <li>How does serial communications work?</li> <li>How fast is serial?</li> <li>How do I connect between a sender and receiver?</li> </ul> <p><em>Please note: This is intended as a reference question.</em></p>
<p>Asynchronous serial (usually referred to as serial) communications is used to send bytes from one device to another. A device could be one or more of the following:</p> <ul> <li>Arduino</li> <li>PC</li> <li>GPS</li> <li>RFID card reader</li> <li>LCD display</li> <li>Modem</li> <li>Other</li> </ul> <hr> <h2>Clock rate and sampling of data</h2> <p>Unlike SPI / USB / I2C serial communications does not have a clock signal. The sampling clock is an agreed-upon sample rate (known as the baud rate). Both sender and receiver must be configured to be using the same rate or the receiver will receive meaningless data (due to the bits not being sampled at the same rate that they were sent).</p> <p>The transmission is <a href="https://en.wikipedia.org/wiki/Asynchronous_communication" rel="noreferrer">asynchronous</a> which basically means that bytes can be sent at any time, with varying gaps between them. This graphic illustrates a single byte being sent:</p> <p><a href="https://i.stack.imgur.com/LcurN.png" rel="noreferrer"><img src="https://i.stack.imgur.com/LcurN.png" alt="Serial comms - sending one byte"></a></p> <p>The graphic above shows the letter 'F' being transmitted. In ASCII this is 0x46 (in hex) or 0b01000110 (in binary). The <em>least</em> significant (low-order) bit is transmitted first, thus in the above graphic you see the bits arriving in the order: <code>01100010</code>.</p> <p>The "idle" time between bytes is transmitted as continuous "1" bits (effectively, the transmit line is held high continuously).</p> <p>To indicate the start of a byte, the <em>Start Bit</em> is always indicated by pulling the line low as shown on the graphic. Once the receiver sees the start bit, it waits for 1.5 times the sample time, and then samples the data bits. It waits 1.5 times so that it:</p> <ul> <li>Skips the start bit</li> <li>Samples half-way through the next bit</li> </ul> <p>If the baud rate is 9600 baud, for example, then the sample rate will be <code>1/9600 = 0.00010416</code> seconds (104.16 µs).</p> <p>Thus, at 9600 baud, after receiving a start bit the receiver waits for 156.25 µs, and then samples every 104.16 µs.</p> <p><a href="https://i.stack.imgur.com/SoFKx.png" rel="noreferrer"><img src="https://i.stack.imgur.com/SoFKx.png" alt="Start bit timing"></a></p> <p>The purpose of the <em>Stop Bit</em> is to ensure that there definitely is a 1-bit between each byte. Without the stop bit, if a byte ended in a zero, then it would be impossible for the hardware to tell the difference between that and the start bit of the next byte.</p> <p>To produce the above output on an Uno you could write this code:</p> <pre class="lang-C++ prettyprint-override"><code>void setup() { Serial.begin(9600); Serial.print("F"); } void loop () { } </code></pre> <hr> <h2>Number of data bits</h2> <p>In order to save transmission time (in the olden days, heh) you were allowed to specify different numbers of data bits. The AtMega hardware supports data bits numbering from 5 to 9. Clearly the less data bits the less information you can send, but the faster it will be.</p> <hr> <h2>Parity bits</h2> <p>You can optionally have a parity bit. This is calculated, if required, by counting the number of 1's in the character, and then making sure that this number is odd or even by setting the parity bit to 0 or 1 as required.</p> <p>For example, for the letter "F" (or 0x46 or 0b01000110) you can see that there are 3 ones there (in 01000110). Thus we already have odd parity. So, the parity bit would be as follows:</p> <ul> <li>No parity: omitted</li> <li>Even parity: a 1 (3 + 1 is even)</li> <li>Odd parity: a 0 (3 + 0 is odd)</li> </ul> <p>The parity bit, if present, appears after the last data bit but before the stop bit.</p> <p>If the receiver does not get the correct parity bit, that is called a "parity error". It indicates that there is some problem. Possibly the sender and receiver are configured to use different baud (bit) rates, or there was noise on the line which turned a zero to a one or vice-versa.</p> <p>Some early systems also used "mark" parity (where the parity bit was always 1 regardless of the data), or "space" parity (where the parity bit was always 0 regardless of the data).</p> <hr> <h2>9-bit transmission</h2> <p>Some communication equipment uses 9-bit data, so in these cases the parity bit is turned into the 9th bit. There are special techniques for sending this 9th bit (the registers are 8-bit registers so the 9th bit has to be put somewhere else).</p> <hr> <h2>Number of stop bits</h2> <p>Early equipment tended to be somewhat slower electronically, so to give the receiver time to process the incoming byte, it was sometimes specified that the sender would send two stop bits. This basically adds more time where the data line is held high (one more bit time) before the next start bit can appear. This extra bit time gives the receiver time to process the last incoming byte.</p> <p>If the receiver does not get a logical 1 when the stop bit is supposed to be, that is called a "framing error". It indicates that there is some problem. Quite possibly the sender and receiver are configured to use different baud (bit) rates.</p> <hr> <h2>Notation</h2> <p>Commonly, serial communication is indicated by telling you the speed, number of data bits, type of parity, and number of stop bits, like this:</p> <pre class="lang-C++ prettyprint-override"><code>9600/8-N-1 </code></pre> <p>This is telling us:</p> <ul> <li>9600 bits per second</li> <li>8 data bits</li> <li>No parity (you might see instead: E=even, O=odd)</li> <li>1 stop bit</li> </ul> <p>It is important that the sender and receiver agree on the above, otherwise communication is unlikely to be successful.</p> <hr> <h2>Pin-outs</h2> <p>The Arduino Uno has digital pins 0 and 1 available for hardware serial:</p> <p><a href="https://i.stack.imgur.com/eFevW.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eFevW.png" alt="Arduino Uno serial pins"></a></p> <p>To connect two Arduinos you <em>swap</em> Tx and Rx like this:</p> <p><a href="https://i.stack.imgur.com/QJO4F.png" rel="noreferrer"><img src="https://i.stack.imgur.com/QJO4F.png" alt="Connecting two Arduinos together"></a></p> <hr> <h2>Speed</h2> <p>A wide range of speeds is supported (see graphic below). "Standard" speeds are usually a multiple of 300 baud (eg. 300/600/1200/2400 etc.).</p> <p>Other "non-standard" speeds can be handled by setting the appropriate registers. The HardwareSerial class does this for you. eg.</p> <pre class="lang-C++ prettyprint-override"><code>Serial.begin (115200); // set speed to 115200 baud </code></pre> <p>As a rule-of-thumb, assuming you are using 8-bit data, then you can estimate the number of bytes you can transmit per second by dividing the baud rate by 10 (because of the start bit and stop bit).</p> <p>Thus, at 9600 baud you can transmit 960 bytes (<code>9600 / 10 = 960</code>) per second.</p> <hr> <h2>Baud rate errors</h2> <p>The baud rate on the Atmega is generated by dividing down the system clock, and then counting up to a pre-set number. This table from the datasheet shows the register values, and error percentages, for a 16 MHz clock (such as the one on the Arduino Uno).</p> <p><a href="https://i.stack.imgur.com/Dlzee.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Dlzee.png" alt="Baud rate errors"></a></p> <p>The U2Xn bit affects the clock rate divisor (0 = divide by 16, 1 = divide by 8). The UBRRn register contains the number the processor counts up to.</p> <p>So from the table above, we see that we get 9600 baud from a 16 MHz clock as follows:</p> <pre class="lang-C++ prettyprint-override"><code>16000000 / 16 / 104 = 9615 </code></pre> <p>We divide by 104 and not 103 because the counter is zero-relative. Thus the error here is <code>15 / 9600 = 0.0016</code> which is close to what the table above says (0.02%).</p> <p>You will notice that some baud rates have a higher error amount than others.</p> <p>According to the datasheet the maximum error percentage for 8 data bits is in the range of 1.5% to 2.0% (see the datasheet for more details).</p> <hr> <h2>Arduino Leonardo</h2> <p>The Arduino Leonardo and Micro have a different approach to serial communications, as they connect directly via USB to the host computer, not via the serial port.</p> <p>Because of this, you must wait for Serial to become "ready" (as the software establishes an USB connection), with an extra couple of lines, like this:</p> <pre class="lang-C++ prettyprint-override"><code>void setup() { Serial.begin(115200); while (!Serial) {} // wait for Serial comms to become ready Serial.print("Fab"); } void loop () { } </code></pre> <p>However, if you want to actually communicate via pins D0 and D1, (rather than by the USB cable) then you need to use Serial1 rather than Serial. You do so like this:</p> <pre class="lang-C++ prettyprint-override"><code>void setup() { Serial1.begin(115200); Serial1.print("Fab"); } void loop () { } </code></pre> <hr> <h2>Voltage levels</h2> <p>Note that the Arduino uses TTL levels for serial communications. This means that it expects:</p> <ul> <li>A "zero" bit is 0V</li> <li>A "one" bit is +5V</li> </ul> <p>Older serial equipment designed to plug into a PC's serial port probably uses RS232 voltage levels, namely:</p> <ul> <li>A "zero" bit is +3 to +15 volts</li> <li>A "one" bit is −3 to −15 volts</li> </ul> <p>Not only is this "inverted" with respect to TTL levels (a "one" is more negative than a "zero"), the Arduino cannot handle negative voltages on its input pins (nor positive ones greater than 5V).</p> <p>Thus you need an interface circuit for communicating with such devices. For input (to the Arduino) only, a simple transistor, diode, and a couple of resistors will do it:</p> <p><a href="https://i.stack.imgur.com/8WUMU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/8WUMU.png" alt="Inverting buffer"></a></p> <p>For two-way communication you need to be able to generate negative voltages, so a more complex circuit is required. For example the MAX232 chip will do that, in conjunction with four 1 µF capacitors to act as charge-pump circuits.</p> <hr> <h2>Software Serial</h2> <p>There is a library called SoftwareSerial that lets you do serial communications (up to a point) in software rather than hardware. This has the advantage that you can use different pin configurations for serial communications. The disadvantage is that doing serial in software is more processor-intensive and more prone to error. See <a href="https://www.arduino.cc/en/Reference/SoftwareSerial" rel="noreferrer">Software Serial</a> for more details.</p> <hr> <h2>Mega2560</h2> <p>The Arduino "Mega" has 3 additional hardware serial ports. They are marked on the board as Tx1/Rx1, Tx2/Rx2, Tx3/Rx3. They should be used in preference to SoftwareSerial if possible. To open those other ports you use the names Serial1, Serial2, Serial3, like this:</p> <pre class="lang-C++ prettyprint-override"><code>Serial1.begin (115200); // start hardware serial port Tx1/Rx1 Serial2.begin (115200); // start hardware serial port Tx2/Rx2 Serial3.begin (115200); // start hardware serial port Tx3/Rx3 </code></pre> <hr> <h2>Interrupts</h2> <p>Both sending and receiving, using the HardwareSerial library, use interrupts.</p> <h3>Sending</h3> <p>When you do a <code>Serial.print</code>, the data you are trying to print is placed in an internal "transmit" buffer. If you have 1024 bytes or more of RAM (such as on the Uno) you get a 64-byte buffer, otherwise you get a 16-byte buffer. If the buffer has room, then the <code>Serial.print</code> returns immediately, thus not delaying your code. If there is no room, then it "blocks" waiting for the buffer to be emptied enough for there to be room.</p> <p>Then, as each byte is transmitted by the hardware an interrupt is called (the "USART, Data Register Empty" interrupt) and the interrupt routine sends the next byte from the buffer out of the serial port.</p> <h3>Receiving</h3> <p>As incoming data is received an interrupt routine is called (the "USART Rx Complete" interrupt) and the incoming byte is placed into a "receive" buffer (the same size as the transmit buffer mentioned above).</p> <p>When you call <code>Serial.available</code> you find out how many bytes are available in that "receive" buffer. When you call <code>Serial.read</code> a byte is removed from the receive buffer and returned to your code.</p> <p>On Arduinos with 1000 bytes or more of RAM, there is no rush to remove data from the receive buffer, provided you don't let it fill up. If it fills up then any further incoming data is discarded.</p> <p>Note that because of the size of this buffer there is no point in waiting for a very large number of bytes to arrive, for example:</p> <pre class="lang-C++ prettyprint-override"><code>while (Serial.available () &lt; 200) { } // wait for 200 bytes to arrive </code></pre> <p>This will never work because the buffer cannot hold that much.</p> <hr> <h2>Tips</h2> <ul> <li><p>Before reading, always make sure data is available. For example, this is wrong:</p> <pre class="lang-C++ prettyprint-override"><code>if (Serial.available ()) { char a = Serial.read (); char b = Serial.read (); // may not be available } </code></pre> <p>The <code>Serial.available</code> test only ensures you have <em>one</em> byte available, however the code tries to read two. It may work, if there are two bytes in the buffer, if not you will get -1 returned which will look like 'ÿ' if printed.</p></li> <li><p>Be aware of how long it takes to send data. As mentioned above, at 9600 baud you an only transmit 960 bytes per second, so trying to send 1000 readings from an analog port, at 9600 baud, won't be very successful.</p></li> </ul> <hr> <h2>References</h2> <ul> <li><a href="http://www.gammon.com.au/forum/?id=10894" rel="noreferrer">Async (Serial) peripheral interface - for Arduino</a></li> <li><a href="http://www.gammon.com.au/serial" rel="noreferrer">How to process incoming serial data without blocking</a></li> <li><a href="http://en.wikipedia.org/wiki/RS-232" rel="noreferrer">RS-232 - Wikipedia</a></li> <li><a href="http://arduino.cc/en/Reference/Serial" rel="noreferrer">Arduino Reference - Serial</a></li> </ul>
19762
|programming|sketch|teensy|software|
Take an Arduino or Teensy prototype to Mass production - Loading software onto microcontroller
2016-01-20T09:40:28.407
<p>I am developing an educational product that I would like to mass produce. I am not sure of the quantity yet, but I imagine we will make a few hundred PCBs at least to begin</p> <p>I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor. (He used the term "fuse", although I don't see this elsewhere in the forum. is this the right term?)</p> <p>He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.</p> <p>Can someone shed some light on this for me? How can I take Arduino prototyping code and use it in mass production?</p>
<blockquote> <p>I spoke with an electrical engineering about how to take an Arduino prototype to mass production, and he warned me that the code written in the Arduino IDE cannot be fused onto the processor.</p> </blockquote> <p>That's nonsense. The output from the IDE compiler is a .hex file which is then sent via <code>avrdude</code> to program the board. If the output cannot be "fused" onto the processor how does he imagine we ever get anything done?</p> <p>Possibly he is referring to changing the fuses to make it impossible to read the code back from the chip. This can be easily accomplished.</p> <hr> <blockquote> <p>He said that I would probably have to take each product, and load the Arduino code on manually, plugging in each one to a computer and upload like one would when prototyping. </p> </blockquote> <p>You have obviously spoken to someone with no experience in Arduinos, possibly one of those engineers with an active dislike of it.</p> <p>I have written code to run on an Arduino to upload sketches to another board.</p> <p>You can read about it at <a href="http://www.gammon.com.au/uploader" rel="nofollow noreferrer">Atmega chip stand-alone programmer to upload .hex files</a>. The idea is you take your .hex file, put it onto an SD card and then program your target board in a few seconds.</p> <p>User "Crossroads" from the Arduino forum has taken that idea and made a <a href="http://crossroadsfencing.com/BobuinoRev17/index.html" rel="nofollow noreferrer">stand-alone board</a>, looking like this:</p> <p><a href="https://i.stack.imgur.com/OQAQM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OQAQM.jpg" alt="Hex programmer"></a></p> <p>You put up to 255 hex files onto the SD card. You dial-up which one you want with the rotary dial. You plug in the ICSP cable into your target board, and hit the "program" button. The whole thing takes a few seconds.</p> <p>It is designed to be used "in the field". All you have to do is plug in a power-pack to supply power to it.</p> <p>If you needed to protect the target boards with a fuse setting after uploading, you would modify the code in the programmer slightly to do that for you.</p> <p>It would be helpful to have an ICSP header on your target boards, both for programming before deployment, and in case you find a bug and have to change it.</p> <p>Failing that you might put the chips into a suitable board first (eg. with a ZIF socket), program them off-board, and then solder them on. There are lots of options for you.</p> <hr> <blockquote> <p>Also, he said the other option would be to recode my Arduino sketch from scratch using an AVR code.</p> </blockquote> <p>I don't see why that would be necessary, in any way.</p>
19767
|sensors|sketch|
What if Ultrasonic sensor doesn't detect object?
2016-01-20T11:05:06.480
<p>I am trying to write a sketch where a function will only be triggered when the ultrasound doesn't return back. Thus when the echo pin is checked after 1 second after the trigger pin was written high, it must be low. Will it be a digitalRead function?</p>
<p>What type of Ultrasonic sensor do you have?</p> <p>I'll go with HC-SR04, since I've got one of those laying around here. The other ultrasonic sensors should be working in the same way.</p> <p><strong>Before you start!</strong></p> <p>Read the datasheet. A fast search on google with: "[manufacturer][device id][device description] datasheet .pdf" will do good.</p> <p>Example: <a href="http://www.micropik.com/PDF/HCSR04.pdf" rel="nofollow">http://www.micropik.com/PDF/HCSR04.pdf</a></p> <p>The datasheet will tell you important things/values and sometimes even interfacing examples or code. Like:</p> <ul> <li>Max input voltage</li> <li>Max current</li> <li>Pin-out diagrams</li> <li>How to interface with the device</li> <li>Min/max operating temperature</li> </ul> <p><strong>Wiring up</strong></p> <p>The datasheet will tell you what to connect, to which pins.</p> <p>We've got 5V, Trigger (input), Echo (output), 0V (ground).</p> <p>(As per datasheet)</p> <p>It's best to do the wiring before you put power on it, because you can accidently short it when moving wires around.</p> <p><strong>Interfacing</strong></p> <p>I would recommend checking some code examples before you attempt to roll your own. Or just start from an example and edit it to your specifications.</p> <p>The timing diagram shows us it needs a 10uS pulse on the trigger input. And the duration of the echo will show the distance (58 uS per cm or 148 uS per inch).</p> <p>The datasheet also suggest to use over 60ms measurement cycles.</p> <p><strong>Code</strong></p> <p>Taking all that into account:</p> <pre><code>#define trigPin 13 #define echoPin 12 #define led 11 #define led2 10 const unsigned long timeout = 400*58; //Max of 400CM, adjust this to your own max. void setup() { Serial.begin(115200);//Stop using 9600 as default, it's not fast. pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(led, OUTPUT); pinMode(led2, OUTPUT); } void loop() { unsigned long distance;//unsigned, since we don't get negative distances. digitalWrite(trigPin, HIGH); delayMicroseconds(10); //10 uS pulse. digitalWrite(trigPin, LOW); distance = round(pulseIn(echoPin, HIGH,timeout) /58);//Distance in CM's, use /148 for inches. if (distance == 0){//Reached timeout Serial.println("Out of range"); } else { Serial.print(distance); Serial.println(" cm"); } delay(60);//Wait 60 ms for next cycle. } </code></pre> <p>To be honest, I'm not even slightly sure if this code is working. I modified this code: <a href="http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/" rel="nofollow">http://www.instructables.com/id/Simple-Arduino-and-HC-SR04-Example/</a></p> <p>So that you're actually using the timeout right, and do the timing according to the datasheet.</p>
19768
|programming|communication|
Can RX and TX be temporarily transposed on demand?
2016-01-20T11:28:38.887
<p>Only 2 arduinos can normally be linked via serial port because TX and RX need to be cross-linked, and connecting multiple TXs together would cause conflict.</p> <p>RS485 allows multiple nodes connected in parallel on a 2 wire differential 'bus', using a TX ENABLE pin to allow one master to transmit while all other slaves listen. </p> <p>I suspect it should be possible to similarly connect multiple serial RXs together to give a common listening bus, and be able to use TX ENABLE on any one node at a time to transpose its RX and TX to allow its TX to transmit to the other RXs. This might be physically done using a changeover relay swapping RX with TX, but is it possible to somehow temporarily switch the TX and RX assignments on demand by software?</p> <p>I doubt the actual pin assignments can be changed in-situ, but perhaps the same results are achievable with some programming wizards sleight-of-hand trickery?</p>
<p>On an AVR-based Arduino, you can selectively enable the transmitter and receiver side of the UART (c.f. the datasheet of your MCU). Thus, you could in principle just connect all the TX and RX together, and make sure only one transmitter is enabled at a time, while all the others are in high impedance. If you do this, I would strongly recommend you put a current-limiting resistor in series with each TX, just in case.</p> <p>For example, on an Arduino Uno (<a href="http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf" rel="nofollow">Atmega328P</a>), you can use the following functions:</p> <pre class="lang-cpp prettyprint-override"><code>static inline void enable_tx() { UCSR0B |= _BV(TXEN0); } static inline void disable_tx() { UCSR0B &amp;= ~_BV(TXEN0); } static inline void enable_rx() { UCSR0B |= _BV(RXEN0); } static inline void disable_rx() { UCSR0B &amp;= ~_BV(RXEN0); } </code></pre> <p><strong>Edit</strong>: Beware that <code>Serial.begin()</code> enables both the transmitter and the receiver.</p>
19771
|c|
"EVERY_N_MILLISECONDS"
2016-01-20T11:49:53.587
<p>One of the FastLED examples that I've seen was using code that looks like this:</p> <blockquote> <p>EVERY_N_MILLISECONDS( 300 ) { transition_step(); }</p> </blockquote> <p>I've copied it and successfully used it in the same context - but I have no idea what it is or how it works.</p> <p>A Google search finds no reference anywhere at all. </p> <p>I'm still a beginner with C but this looks like a Define to me - all being in uppercase - is it defined somewhere in the FastLED library?</p>
<p>Its a macro that wraps the code you put inside of it to only be run based on the time interval you pass to it. The purpose of it is to allow for timer based code to be ran without having to block the main <code>loop()</code>. When the code is compiled it gets wrapped by other code that governs how the code inside it should run.</p> <p>Lets say you want to run a method every 100ms. A simple approach would be the following:</p> <pre class="lang-c prettyprint-override"><code>// loop() runs the code within it over and over at a rate based on the // how fast the microprocessor runs - specifically how long it takes // for the processor to get through the code inside of it. void loop(){ doMethod(); delay(100); checkForButtonInput(); } </code></pre> <p>The issue here is that during the <code>delay()</code>, the <code>delay()</code> function, by its design, hogs all the processor time for 100ms, and so the <code>checkForButtonInput()</code> is not able to check for input, as the program is currently stuck looping inside of <code>delay()</code> until 100ms has passed.</p> <p><code>EVERY_N_MILLISECONDS( &lt;mseconds&gt; ){}</code> is the answer here, and you can think of it working to add code to you code like this (although this isn't exactly accurate):</p> <pre class="lang-c prettyprint-override"><code>void loop() { EVERY_N_MILLISECONDS( 100 ){ //pseudocode //if ( it has been 100ms since last time we did doMethod() ) { doMethod(); // reset time since we did doMethod() to 0 //} //else { // continue... //} } checkForButtonInput(); } </code></pre> <p>so if it hasn't been 100ms since the last time we were in the <code>EVERY_N_MILLISECONDS</code> wrapped code then we just move on, and so the <code>checkForButtonInput()</code> is called as much as possible and inputs wont be missed.</p>
19778
|motor|sketch|robotics|
How to make two wheels turn only for a particular amount of time?
2016-01-20T14:13:13.223
<p>I am trying to make a robot turn (dc motors are being used) back 180 degrees. So I used an l289n for it and made one wheel turn clockwise and vice-versa. <br><br>But as I wan't it to make only a 180 degrees turn, I wanted to set an amount of time for it to turn. Is there any other way to do the same thing, if yes, please tell, if no, help me...</p>
<p>Use the <a href="https://www.arduino.cc/en/Reference/Delay" rel="nofollow">delay()</a> function.</p> <p>Pseudo code as follows:</p> <pre><code>1) Turn clockwise motor on; 2) Turn counterclockwise motor on; 3) delay(&lt;time&gt;); 4) Turn CW motor off; 5) Turn CCW motor off. </code></pre>
19782
|arduino-mega|spi|digital-analog-conversion|
Arduino to DAC to ADC back to Arduino?
2016-01-20T18:21:08.453
<p>My question is simple. Is the following possible?</p> <p>I am using one Arduino Mega 2560 board and its SPI functionality to adjust voltages (0-4.096V) through a 12-bit DAC (MCP4822). </p> <p>I would like to measure the output voltages from the DAC by feeding them through a 12-bit ADC and back to the Arduino. The DAC's output voltages that will be directly measured by the ADC will be displayed on an LCD and on LabVIEW.</p> <p>Is this possible, given that both the DAC and the ADC have to be connected to the same SDI and SCK pins on the Arduino for SPI to work?</p>
<p>Yes, perfectly possible. Just provide two separate CS pins to select between the two devices.</p>
19787
|arduino-ide|wifi|esp8266|
ESP8266 Analog read interferes with wifi?
2016-01-20T23:13:21.130
<p>Short version: I have a program that connects my ESP8266 to WIFI so I can control a relay connected to it over the internet or a button. I also have a sensor for my door. This software works perfectly, if I add a light dependent resistor to it (which is connected correctly since I do get readings from it) and start reading data I lose my WIFI connection. Has anyone got any idea why this is happening?</p> <p>Long version: </p> <p>So I have this program running on my Esp8266 </p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;ESP8266WiFi.h&gt; IPAddress ip(192, 168, 0, 150); IPAddress gateway(192, 168, 0, 1); IPAddress subnet(255, 255, 255, 0); const char* ssid = "mySSID"; const char* password = "myPSW"; const char* host = "192.168.0.228"; const int buttonPin = 0; const int relayPin = 4; const int doorPin = 5; const int ldrPin = A0; //int ldrState; //int serialCount = 0; //int ldrMin = 0; //int ldrMax = 1024; int buttonState = 0; int doorState = 0; byte Main_Light_State_Begin; bool Main_Light_State; bool doorNotified = false; bool button_action_taken = false; bool Main_Light_DBR = true; String HTTP_Get_Response; WiFiServer server(80); //Functions String HTTP_Get(char* Adress, String URL, bool Last_Line_Bool) { WiFiClient client; const int httpPort = 80; if (!client.connect(Adress, httpPort)) { Serial.println("connection failed"); return "Failed"; } Serial.print("Requesting URL: "); Serial.println(URL); Serial.println("at adress"); Serial.println(Adress); client.print(String("GET ") + URL + " HTTP/1.1\r\n" + "Host: " + Adress + "\r\n" + "Connection: close\r\n\r\n"); delay(10); String Response; String Last_Line; while (client.available()) { String line = client.readStringUntil('\r'); Serial.print(line); Response = Response + line; } return Response; Serial.println(); Serial.println("closing connection"); } void setup() { Serial.begin(115200); delay(1000); Serial.println(); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); WiFi.config(ip, gateway, subnet); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi connected"); server.begin(); - Serial.println("Server started"); Serial.println(WiFi.localIP()); pinMode(relayPin, OUTPUT); pinMode(buttonPin, INPUT); pinMode(doorPin, INPUT); // pinMode(ldrPin, INPUT); } void loop() { if (WiFi.status() != WL_CONNECTED) { Serial.println("Wifi NOT Connected"); } //Sensors buttonState = digitalRead(buttonPin); doorState = digitalRead(doorPin); //ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100); //Serial.println(analogRead(ldrPin)); // if (serialCount == 1000) { // Serial.println(ldrState); // serialCount = 0; // } else { // serialCount ++; // } //Doorsensor if (doorState == HIGH) { if (doorNotified == false) { Serial.println("DOOR"); HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?door_opened=true", false); doorNotified = true; } } else if (doorState == LOW) { if (doorNotified == true) { doorNotified = false; delay(500); } else { doorNotified = false; } } //Button if (buttonState == LOW) { if (button_action_taken == false) { if (Main_Light_State == true) { Serial.println("SWITCH"); Main_Light_State = false; digitalWrite(relayPin, HIGH); delay(500); Main_Light_DBR = false; } else if (Main_Light_State == false) { Serial.println("SWITCH"); Main_Light_State = true; digitalWrite(relayPin, LOW); delay(500); Main_Light_DBR = false; } button_action_taken = true; } } else if (buttonState == HIGH) { if (button_action_taken == true) { button_action_taken = false; delay(500); } else { button_action_taken = false; } } //Main_Light_State if (Main_Light_State == true) { digitalWrite(relayPin, LOW); if (Main_Light_DBR == false) { HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_on_dbr=true", false); Main_Light_DBR = true; } } else if (Main_Light_State == false) { digitalWrite(relayPin, HIGH); if (Main_Light_DBR == false) { HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_off_dbr=true", false); Main_Light_DBR = true; } } WiFiClient client = server.available(); if (!client) { return; } Serial.println("new client"); while (!client.available()) { delay(1); } String req = client.readStringUntil('\r'); Serial.println(req); client.flush(); if (req.indexOf("/main_light/on") != -1) { Main_Light_State = true; Main_Light_DBR = false; } else if (req.indexOf("/main_light/off") != -1) { Main_Light_State = false; Main_Light_DBR = false; } else if (req.indexOf("/main_light/switch") != -1) { Serial.println("SWITCH"); if (Main_Light_State == true) { Main_Light_State = false; } else if (Main_Light_State == false) { Main_Light_State = true; } Main_Light_DBR = false; } else if (req.indexOf("/main_light/state") != -1) { } else { Serial.println("invalid request"); client.stop(); return; } client.flush(); String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n"; s += (Main_Light_State) ? "1" : "0"; client.print(s); delay(1); Serial.println("Client disonnected"); } </code></pre> <p>With the lines I commented like above everything works fine. I have a light dependant resistor connected (correctly, I get correct measurements from it) to A0. From the moment on I uncomment the lines involving this LDR and thus start reading data from it I lose my wifi connection. Has anyone got any idea why this is? Thank you!</p>
<p>Here is what I usually do to give repetition at fixed intervals: </p> <pre><code>void readAnalogSensor(){ if (millis()&lt;taskTime) return; // time is not expired yet taskTime += 50; // set time for the following execution // .... more code for the task that is done every 50 ms } </code></pre> <p>This requires an <code>unsigned long variable taskTime</code>. You may also use a constant instead of the 50.<br> <code>taskTime</code> should be set to some value close to <code>millis()</code> at the end of <code>setup()</code>, otherwise there will be a rapid sequence of executions while <code>taskTime</code> catches up with <code>millis()</code>. </p>
19792
|led|button|rgb-led|
Changing how a longpress is executed
2016-01-21T05:07:02.713
<p>I have an RGB LED common Anode attached to my Uno and this code detects a long press to turn the LED on and off. Short presses cycle through colors, then off.</p> <p>The problem is that a longpress is 2+sec, but it doesn't register until I release the button. How would I set this up to execute the code at 2sec regardless of whether the button is released?</p> <p>It's probably not worth my time if it requres too much modification. I have a working item, it's just not... ideal.</p> <pre class="lang-c prettyprint-override"><code>Xhunsigned long keyPrevMillis = 0; const unsigned long keySampleIntervalMs = 25; int redPin = 11; int greenPin = 10; int bluePin = 9; int LEDcolor=0; // 0=White, 1=Red, 2=Green, 3-Blue, 4=Yellow, 5=Purple, 6=Pink, 7=Orange, 8=Off int LEDstatus =0; //0=Off, 1=On int changed =0; //has the LEDstatus just changed? byte longKeyPressCountMax = 80; // 80 * 25 = 2000 ms byte longKeyPressCount = 0; byte prevKeyState = HIGH; // button is active low const byte keyPin = 2; // button is connected to pin 2 and GND // called when button is kept pressed for less than 2 seconds void shortKeyPress() { Serial.println("short"); if (LEDstatus==1) { LEDcolor = LEDcolor +1; if (LEDcolor==0) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 0);Serial.println("White");} if (LEDcolor==1) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Red");} if (LEDcolor==2) {analogWrite(redPin, 255);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Green");} if (LEDcolor==3) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 0);Serial.println("Blue");} if (LEDcolor==4) {analogWrite(redPin, 0);analogWrite(greenPin, 0);analogWrite(bluePin, 255);Serial.println("Yellow");} if (LEDcolor==5) {analogWrite(redPin, 175);analogWrite(greenPin, 255);analogWrite(bluePin, 175);Serial.println("Purple");} if (LEDcolor==6) {analogWrite(redPin, 0);analogWrite(greenPin, 255);analogWrite(bluePin, 155);Serial.println("Pink");} if (LEDcolor==7) {analogWrite(redPin, 5);analogWrite(greenPin, 215);analogWrite(bluePin, 255);Serial.println("Orange");} if (LEDcolor==8) {analogWrite(redPin, 255);analogWrite(greenPin, 255);analogWrite(bluePin, 255);Serial.println("Off");LEDstatus=0;} } } // called when button is kept pressed for more than 2 seconds void longKeyPress() { Serial.println("long"); if (LEDstatus==0 &amp;&amp; changed==0) { analogWrite(redPin, 0); analogWrite(greenPin, 0); analogWrite(bluePin, 0); LEDcolor=0; changed=1; LEDstatus=1;Serial.println("On"); } if (LEDstatus==1 &amp;&amp; changed==0) { analogWrite(redPin, 255); analogWrite(greenPin, 255); analogWrite(bluePin, 255); LEDcolor=0; changed=1; LEDstatus=0;Serial.println("Off"); } changed=0; } // called when key goes from not pressed to pressed void keyPress() { Serial.println("key press"); longKeyPressCount = 0; } // called when key goes from pressed to not pressed void keyRelease() { Serial.println("key release"); if (longKeyPressCount &gt;= longKeyPressCountMax) { longKeyPress(); } else { shortKeyPress(); } } void setup() { Serial.begin(9600); pinMode(keyPin, INPUT); digitalWrite(keyPin, HIGH); pinMode(redPin, OUTPUT); pinMode(greenPin, OUTPUT); pinMode(bluePin, OUTPUT); analogWrite(redPin, 255); analogWrite(greenPin, 255); analogWrite(bluePin, 255); } void loop() { // key management section if (millis() - keyPrevMillis &gt;= keySampleIntervalMs) { keyPrevMillis = millis(); byte currKeyState = digitalRead(keyPin); if ((prevKeyState == HIGH) &amp;&amp; (currKeyState == LOW)) { keyPress(); } else if ((prevKeyState == LOW) &amp;&amp; (currKeyState == HIGH)) { keyRelease(); } else if (currKeyState == LOW) { longKeyPressCount++; } prevKeyState = currKeyState; } } </code></pre>
<p>I've rewritten the code entirely. Not that yours was terrible, it was just easier for me to start from scratch. You are left with a very empty <code>loop()</code>, which I always prefer.</p> <p>The code contains three 'colours' and an OFF state. You can add as many other colours as you wish: add an enumeration to <code>_LED_STATE</code> and then add a corresponding <code>case(&lt;NEW_COLOUR&gt;)</code> statement in <code>LEDcontrol()</code>. I haven't included any <code>analogWrite()</code> functions - or in fact any declarations for the LED pins at all - because I'm a little too lazy but it should be obvious where to put them within the case statement.</p> <p>Note that in the final <code>case()</code> statement, the LED state is changed from green to off. This means that a short press will turn the LED off after it has cycled through all the other colours, but will stay off until a long press. If you only want long pressed to switch off/on, change line 103 to <code>eLED_STATE = _LED_STATE_RED;</code>, or whichever the first colour is.</p> <pre class="lang-c prettyprint-override"><code>#define btn 3 // button pin #define SHORT_PRESS 100 // useful for debouncing, can be changed #define LONG_PRESS 2000 // defines how long a 'long press' is #define CYCLE false #define SHOW true //--// You can add new colours in this enum block enum _LED_STATE { _LED_STATE_OFF, _LED_STATE_RED, _LED_STATE_BLUE, _LED_STATE_GREEN }; _LED_STATE eLED_STATE = _LED_STATE_OFF; void setup() { pinMode(btn, OUTPUT); LEDcontrol(SHOW); } void loop() { if (digitalRead(btn)) btnPressed(); } void btnPressed() { unsigned long tStart = millis(); //--// Loop continuously while button is pressed while (digitalRead(btn)) { //--// If LONG_PRESS is exceeded... if (millis() &gt; tStart + LONG_PRESS) { //--// If LED is off, turn it on if (eLED_STATE == _LED_STATE_OFF) eLED_STATE = _LED_STATE_RED; // Choose 'starting' colour //--// If LED is on, turn if off else eLED_STATE = _LED_STATE_OFF; //--// Update LED to display new eLED_STATE LEDcontrol(SHOW); //--// Now loop here until button is released while (digitalRead(btn)); } } //--// If button is released in between the two press times if ((millis() &gt; tStart + SHORT_PRESS) &amp;&amp; (millis() &lt; tStart + LONG_PRESS)) { //--// Ignore if LED is off ////// REMOVE //////////////////// if (eLED_STATE == _LED_STATE_OFF) ////////// IF //////////////////// return; ///////////// NECESSARY ////////// //--// Change the LED colour LEDcontrol(CYCLE); //--// Update LED to display new eLED_STATE LEDcontrol(SHOW); } //--// This helps to debounce; experiment with it delay(10); } void LEDcontrol(bool SHOW_OR_CYCLE) { switch (eLED_STATE) { case(_LED_STATE_RED) : { if (SHOW_OR_CYCLE) { // paint it red return; } eLED_STATE = _LED_STATE_GREEN; return; } case(_LED_STATE_GREEN) : { if (SHOW_OR_CYCLE) { // paint it green return; } eLED_STATE = _LED_STATE_BLUE; return; } case(_LED_STATE_BLUE) : { if (SHOW_OR_CYCLE) { // paint it blue return; } //--// What happens after last colour? Next colour or OFF? eLED_STATE = _LED_STATE_OFF; return; } case(_LED_STATE_OFF) : { if (SHOW_OR_CYCLE) { // paint it black return; } eLED_STATE = _LED_STATE_RED; return; } } } </code></pre>
19818
|serial|sensors|
Processing Serial data
2016-01-21T21:32:26.760
<p>I have a PM10 sensor that I'd like to get the values from.</p> <p>Here's the official documentation from the sensor: <a href="https://i.stack.imgur.com/kyNv5.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/kyNv5.png" alt=" Sensor documentation "></a></p> <p>I've looked as serial communication, but how do i process byte by byte of information if it's coming in byte at a time?</p> <p>I'm looking at this example:</p> <pre><code>void setup() { Serial.begin(9600); Serial.println("&lt;Arduino is ready&gt;"); } void loop() { recvOneChar(); showNewData(); } void recvOneChar() { if (Serial.available() &gt; 0) { receivedChar = Serial.read(); newData = true; } } void showNewData() { if (newData == true) { Serial.print("This just in ... "); Serial.println(receivedChar); newData = false; } } </code></pre> <p>Ideally, i'd like to get the PM2 and PM10 values and print them out. </p>
<p>The proper method of receiving this kind of data is to use a <em>sliding window</em>. That is you visualise the stream of bytes as just that - a stream of bytes (think letters on paper tape). You then have a conceptual "window" on that data which is the width of the packet (10 bytes in this case). As the data passes behind the window you see just 10 bytes of it. When that 10 bytes is in the "right" format (that is, it starts with 0xAA, ends with 0xAB and the checksum is valid) then you have a valid packet and can read the values from it.</p> <p>The simplest method of implementing that is with a 10-byte array. As a byte arrives on the serial port you shuffle all the bytes down the array to make room for the new byte at the top of the array. Once 10 bytes have arrived that first byte should now have made its way to the bottom of the array.</p> <p>For instance:</p> <pre><code>uint8_t window[10]; void setup() { Serial.begin(9600); } void loop() { if (Serial.available()) { // Slide the window for (uint8_t i = 0; i &lt; 9; i++) { window[i] = window[i + 1]; } // Add the new character window[9] = Serial.read(); // Output the current window data for debugging dumpWin(); // Check the framing characters if ((window[0] == 0xAA) &amp;&amp; (window[9] == 0xAC)) { // Calculate the checksum uint8_t cs = 0; for (uint8_t i = 2; i &lt; 8; i++) { cs += window[i]; } // If the checksum matches... if (cs == window[8]) { // ...we have a valid packet! } } } } void dumpWin() { for (int i = 0; i &lt; 10; i++) { Serial.print(window[i], HEX); Serial.print(" "); } Serial.println(); } </code></pre> <p>Getting the data out of the valid packet is now a case of combining bytes into 16-bit integers then dividing them into floats. For instance the PM2.5 would be:</p> <pre><code>uint16_t pm25i = (window[3] &lt;&lt; 8) | window[2]; float pm25 = (float)pm25i / 10.0; </code></pre> <p>The PM10 would be the same but with window[5] and window[4] of course.</p> <hr> <p>Since you can't really use the hardware UART for both communication with your sensor and communication with the PC you may want to investigate the use of <a href="https://www.arduino.cc/en/Reference/SoftwareSerial" rel="nofollow">SoftwareSerial</a> instead of the hardware UART pins for communicating with the sensor.</p>
19832
|serial|esp8266|arduino-pro-mini|
What is the best serial protocol for bidirectional communication with NodeMCU?
2016-01-22T09:10:20.177
<p>Except hardware UART. Main requirements are reliability and simplicity of use. Speed isn't as important.</p> <p>Details:</p> <p>I have an Arduino Pro Mini (ATmega328P 5V) controlled via UART.<br> I wish to connect an ESP8266 with stripped-down NodeMCU to offer a web interface for the same functionalities, sending &lt;=122 character strings to Arduino and possibly getting a short response.<br> I do not want to use Arduino for processing the interface (too little memory) or use the ESP only (need a stable clock and multiple analog inputs).<br></p> <p>My research shows that:</p> <ul> <li>ESP8266 has obvious timing issues, having been designed for a different purpose.</li> <li><a href="https://github.com/IRNAS/SimpleArduinoESP-Lua" rel="nofollow noreferrer">Controlling the ESP8266 from Arduino via hardware serial</a> works fine, but I need it the other way around, too. Also, NodeMCU is rather chatty and I don't know how to suppress it, and I'd rather keep the hardware serial ports for programming.</li> <li>The same via <a href="https://arduino.stackexchange.com/q/17184">SoftwareSerial</a> is <a href="https://primalcortex.wordpress.com/2014/12/30/esp8266-nodemcu-and-lua-language-and-some-arduino-issues/" rel="nofollow noreferrer">unreliable</a></li> <li>Personal experience shows OneWire works poorly on ESP8266 (though it may have been fixed)</li> </ul> <p>I have no experience with I2C and SPI beyond polling a slave, and don't know about reliability on ESP8266.<br> The Arduino already works as an I2C master.<br> I'm assuming I2C is the way to go, but wanted to ask for opinions first.</p> <p><strong>[EDIT]</strong> Seems I have once again neglected to set up the proper context. The reason I'm asking is that ESP8266 <em>can't do very precise timing</em>, leading to communication problems. Hardware UART to hardware UART is shown to be reliable. For most other protocols, at least one side does bit-banging. I have not done or found extensive reliability tests for those options, and hope instead that the community can offer some insights. Can you?</p>
<p>So you are asking how to use an Arduino Pro Mini as a smart peripheral connected to a NodeMCU master, without making use of the hardware serial port on the latter.</p> <p>In general, this is either going to operate slowly enough that you can guarantee reception, or you will need to use some kind of flow control or acknowledgement.</p> <p>One question is whether the APM can always receive at any time, or whether it has to do things which would cause it to not respond for some while and possibly lose data.</p> <p>Hardware I2c or SPI, with a software flow control protocol using additional pins, are probably your best bets if you cannot use async serial. For example the APM sets OK2SEND high when it's ready to receive (this is an APM output pin connected to a NodeMCU input pin). When NodeMCU detects this high, it writes to I2C and then sets HAVESENT high. When the APM detects &amp; processes incoming data as I2C slave, it sets OK2SEND low. NodeMCU sees OK2SEND low (ack'ing the byte) and sets HAVESENT low. APM detects HAVESENT low which completes the handshake. When APM is ready for another byte, it sets OK2SEND high again. etc. Variants could send more than one byte per handshake, if performance needs that; APM asserting OK2SEND would be contracting to handle that number of bytes.</p> <p>If you can guarantee that the APM will respond quickly enough to interrupts, you could use an interrupt driven I2C slave system on it, and simplify the above. The APM could be like a dedicated I2C peripheral, albeit a slow one.</p>
19834
|arduino-uno|motor|
Share battery pack with Arduino and DC motors
2016-01-22T13:18:52.050
<p>I used 6 rechargable AA batteries (total 7.2V) to power my Arduino (UNO R3) Car's two DC Motors (using L293D IC as motor driver). I used separate 9V battery to power arduino itself. But I want to share same 6 battery pack to power my arduino via barrel jack. Please suggest me how can I do this? What precautions Should I take? Like decoupling capacitors or any other?</p>
<p>You may have read that the UNO can accept 7-12 volts as input power. Your AA battery pack (7.2 volts) is very near the low limit of 7 volts. After just a little discharge of the battery (and also voltage drop from motors running), your batteries are likely to deliver less than 7 volts. </p> <p>As your AA battery goes below 7 volts, then the 5 volts (regulated) will also begin to go lower. A reasonable scenario would be if AA battery was 6.5 volts (1/2 volt low), then the 5 volts regulated would be about 4.5 volts. The UNO is likely to operate ok at this voltage, but as voltage goes lower operation could become a problem depending upon your program used. </p> <p>Since you are experimenting with a toy car, I would say to go ahead and run both the motors and UNO from the same battery pack. Not a lot to lose on trying. </p> <p>The UNO already has decoupling capacitors in it's 5 volt regulator circuit. </p> <p>Just for fun, you could use an Analog input to measure your 5 volts and if the voltage drops to 4.5 volts, you could dis-allow motor operation and flash an LED (or other action). Just a low battery indicator. </p> <p>If you decide to measure the 5 volts with an analog input, read up on using resistor dividers and the Analog reference (A-ref). Because 5 volts dropping to 4.5 volts could effect your analog reading, depending upon what you use for Analog reference.</p>
19835
|arduino-mega|sensors|current|digital-in|pull-up|
ArduinoMEGA: 64 digital inputs cause random digitalRead values
2016-01-22T13:21:26.850
<p>I have 64 hall effect sensors (magnetic field sensors) (<a href="http://nl.farnell.com/webapp/wcs/stores/servlet/ProductDisplay?partNumber=2455494" rel="nofollow noreferrer">DRV5023AJQLPG</a>) connected to an Arduino MEGA 2560. For that, I use 48 digital pins and 16 analog pins as digital input pins. The program in the Arduino continuously reads out those 64 digital input pins (in a for-loop) and sends out a serial byte, to a laptop via a usb cable, whenever one of those input pins changes between LOW and HIGH. I also use the ATmega2560’s internal pullup resistors to prevent irregular readouts of the input pins when the sensor is not giving a 0v output (i.e. when it isn’t measuring a strong enough magnetic field).</p> <p>Everything is working fine when I only physically connect up to 16 of the sensors. The laptop then only receives bytes that correctly tell when a sensor measures a state-change.</p> <p>However, when I start connecting more of those 64 sensors, then the laptop starts receiving irregular streams of bytes, erroneously suggesting that all the connected sensors measure changing magnetic fields (HIGH and LOW readouts).</p> <p>I can think of two reasons why these irregular readouts occur: 1. Either, the ATmeag2560’s internal pullup resistors arent working as I think they should. 2. Or, the arduino board and >16 hall effect sensors combined are pulling to much current.</p> <ol> <li><p><strong>Pullup resistors not working?</strong> When testing with only 16 sensors connected, it is a stable, properly working setup. When I explicitly <em>don’t</em> use the pullup resistors in the program then the setup <em>does</em> start behaving irregular, also with just 16 sensors. So the internal pullup resistors seem to be properly activated by the program. </p></li> <li><p><strong>Arduino + 64 sensors draw to much current?</strong> Besides powering the Arduino board and sensors via the usb cable (providing 500mA), I’ve also tried external power sources that provide 1 or 2A. I’ve also powered the Arduino board via an external 5v, +1A voltage regulator, bypassing the Arduino’s onboard voltage regulator. This all doesn’t seem to make a difference in the system’s irregular behaviour. When measuring those setup’s current usage (with amperage meter) it didn’t go above <strong>250mA</strong>.</p></li> </ol> <p>Calculating the combined current usage (using datasheet info), I came to this:</p> <pre><code>- sensor operating current: 2,7 mA - sensor output current when in ‘active’ state: 0,25 mA - TOTAL current of 64 sensors (3mA*64=) 192 mA - Arduino MEGA current (approx) 150 mA - TOTAL current of 64 sensors + Arduino MEGA: **342 mA** </code></pre> <p>So, both the calculated and measured current usage seem within the range of what can be handled by mentioned power sources.</p> <p>I’m kinda stuck now. Can anyone suggest anything that might cause this problem? Or point to incorrect thinking of me? Thanks for any responses.</p> <hr> <p>'Schematic' (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line):</p> <p><a href="https://i.stack.imgur.com/E57Se.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E57Se.jpg" alt="&#39;schematic&#39; (only showing first 8 sensors connected. The ArduinoMEGA is connected to a computer via a usb cable with disabled power line)"></a></p> <p>Top-side: the hall effect sensors and Vcc an GND rails: <a href="https://i.stack.imgur.com/cuwYF.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cuwYF.jpg" alt="Top: the hall effect sensors and Vcc an GND rails"></a></p> <p>Bottom-side: ArduinoMEGA + the 64 red sensor output lines to the input pins: <a href="https://i.stack.imgur.com/0eqiP.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0eqiP.jpg" alt="Bottom: ArduinoMEGA + the 64 red sensor output lines to the input pins"></a></p> <p>Below is the Arduino code:</p> <pre class="lang-c prettyprint-override"><code>/* Arduino to Pd protocol Placing or removing a chess piece sends only one byte. There’s no other serial data being communicated. event: byte value: placing a chess piece on a square: 0-63 removing a chess piece from a square: 64-127 ArduinoMEGA pin to byte value mapping: byte pin 0 6 1 7 2 8 3 9 … 46 52 47 53 48 A0 (analog 0) 49 A1 50 A2 … 62 A14 63 A15 */ byte prevSquares[64]; // array that holds previous readouts byte i; // variable used in for-loops byte sensorValue; // variable temp storing of digitalread void setup() { Serial.begin(9600); for (i = 0; i &lt; 64 ; i++) { pinMode(i+6, INPUT_PULLUP); // activate pullup resistor } for (i = 0; i &lt; 64 ; i++) { prevSquares[i] = digitalRead(i+6); } } void loop() { for (i = 0; i &lt; 64 ; i++) { sensorValue = digitalRead(i+6); if (sensorValue != prevSquares[i]) { // chess piece was placed or removed from square if (sensorValue == 0) { // chess piece was placed // send serial byte (0-63): Serial.write(i); } else { // chess piece was removed // send serial byte (64-127): Serial.write(i + 64); } //update prevSquares array: prevSquares[i] = sensorValue; } } } </code></pre>
<p>After seeing your schematic, I think the general problem here is that you need to more closely read and follow the datasheet for this part. A lot of times, when you are hobbling a project together at a small scale there are a lot of things you can ignore and get away with, but as you scale up, all the rounded corners start to add up. In this case, you can get away with 16, but once you start adding too more, it becomes too much. Let's go over a few:</p> <p><strong>Pull up resistors</strong></p> <p>Like I mentioned in the comments, relying on the internal pull ups is probably not a good idea. In my personal experience, they are only really good for adding a quick button input for debugging purposes. I'm not sure specifically what would cause issues only after 16 sensors. It could be that collectively internal pullups are subject to a different and lower current limit, but I'm not familiar enough with the internal architecture of the ATMega2560 to do more than just speculate.</p> <p>Whatever the case, the best practice here would be to use separate external pull up resistors, within the specifications of the datasheet. (See equation 1 on page 13 of the datasheet.)</p> <p><strong>Decoupling Capacitor</strong></p> <p>Per the datasheet, page 17:</p> <blockquote> <p>A 0.01-µF (minimum) ceramic capacitor rated for VCC must be placed as close to the DRV5023 device as possible.</p> </blockquote> <p>This capacitor is referred to as C1 in the datasheet figures and is required. This type of capacitor is called a decoupling capacitor, and one of the things it does is provide a local energy storage, so that when the sensor starts pulling a little extra current, it doesn't have to wait for the regulator to respond, it has some local energy already.</p> <p>Your schematic indicates a single 1uF capacitor on the output of the voltage regulator, however, there are no capacitors for the sensors. The one capacitor is only for output filtering for the regulator, and will not satisfy any decoupling needs of the sensor.</p> <p><strong>Filtering Capacitor</strong></p> <p>Referred to as C2 in the datasheet, this an optional capacitor to filter out high frequency noise. This isn't needed in most cases, in fact, per the datasheet, page 13:</p> <blockquote> <p>Most applications do no require this C2 filtering capacitor.</p> </blockquote> <p>However, your project might not fall into "most applications" and there are a few things specifically that worry me.</p> <ol> <li>You have long wires that are basically acting as antennas that will capture any nearby noise.</li> <li>You have long power lines running parallel to your signal lines which can cause stray inductance which leads to other interesting things. (With the thickness of the plywood separating them, this might not be an issue, but it is something to be aware of).</li> </ol> <p>I would definitely try the first two ideas above to begin with, and only pursue this as a last resort. The only way to know for sure if this is something you need is to stick an oscilloscope on the line and see how noisy it is, but that is not something you probably have handy.</p> <p><strong>Other Concerns</strong></p> <p>I'm just a little bit worried about voltage drop. Depending on the gauge of wire used, with all the sensors connected, at the end of a strand you might have a non-negligible voltage drop.</p> <p>With that many wires running together into the Mega, there might be cross talk problems.</p> <p>Another common problem with scaling up is that there is a higher probability of having faulty components. This is especially with this part which per the datasheet indicates that is particularly sensitive to ESD. It could be that there is a dead sensor that has failed in such a way that it is causing problems for the other sensors. Maybe go through and test all 64 sensors, 8~16 at a time to make sure that separately they all work, and that the issue only occurs when all of them are connected.</p> <p><strong>Other Ideas</strong></p> <p>Many other comments on the question have suggested a multiplexer and/or multiplexing and I will just briefly echo that here. Multiplexers are typically used in situations where you don't have enough pins and you want to split a single pin to multiple other pins. While that isn't an issue here with the Mega (it appears you have enough pins to do what you are wanting to do), there are other benefits that can be derived from multiplexing this.</p> <p>For example, one thing you could do is split up the board into 8 - 2 x 4 chunks and then have a multiplexer (such as a 4051 or a 74151) local to each chunk. Then you would have just 8 short wires going into the multiplexer, as opposed to having long antenna-like wires heading to the Mega. This could improve overall signal integrity.</p>
19844
|arduino-ide|uploading|bootloader|teensy|
Use command line to upload program through hex file to Teensy-LC
2016-01-22T18:00:41.877
<p>I want to make a standalone programmer for Teensy-LC in <strong>windows 8.1</strong>.</p> <p>So basically I have provided the board to a client of mine and now I want to change the program loaded into the Teensy-LC board.</p> <p>But the solution available right now is to send the <a href="https://www.pjrc.com/teensy/loader.html" rel="nofollow noreferrer">Teensy Loader</a> and send the hex file. But the teensy LC board is packed inside a device. So reset button cannot be pressed.</p> <p>Also it would be better if this code can be burned in an installer format instead of the <a href="https://www.pjrc.com/teensy/loader.html" rel="nofollow noreferrer">Teensy Loader</a>.</p> <p>Is there any way to make this work?</p> <p><strong>EDIT</strong></p> <p>My Teensy.exe does not have the option for program or reboot The icons are not accessible</p> <p><a href="https://i.stack.imgur.com/ZYGzx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZYGzx.png" alt="Teensy.exe"></a></p> <p>Does that mean my interrupts are disabled or there might be something else I am doing wrong? My program loads on pressing the reset button but I cannot press the program button inside Teensy.exe</p> <p>If I turn off the Auto Mode, all icons go grey.</p> <p><a href="https://i.stack.imgur.com/d6vri.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d6vri.png" alt="AutoMode turned off"></a></p>
<p>Sadly the accepted answer is incomplete and requires manual steps.</p> <p>The reason why your "Auto" button is greyed out is that you did not execute the second executable that is required for that: "Teensy_Reboot.exe". You find it on your disk if you have installed TeensyDuino.</p> <p>First kill Teensy.exe if it is running (Important)</p> <p>Then you write path and file of your Hex file into the registry: </p> <pre><code>HKEY_CURRENT_USER\Software\PJRC\teensy\dir HKEY_CURRENT_USER\Software\PJRC\teensy\file </code></pre> <p>Then you start Teensy.exe</p> <p>Then you start Teensy_Reboot.exe as a hidden process.</p> <p>That is the solution of your problem!</p> <p>It is a shame that Paul does not document his stuff.</p> <p>NOTE: If you have previously loaded a sketch into the Teensy that was compiled with "USB Type: No USB" the reboot will not work and the button on the board must be pressed manually, but Teensy_Reboot.exe is still usefull because it enables the green "Auto" button in Teensy.exe.</p> <p>NOTE: Teensy_Reboot.exe has a severe bug: If the Teensy.exe is not successfull because another program still had the Teensy CDC COM port open while you started Teensy.exe, the Teensy_Reboot.exe may run eternally consuming 100% CPU under some circumstances. I reported that bug in the forum of Paul but he never answered to my posting.</p> <hr> <p><strong>PLAN B:</strong></p> <p>The disadvantage of using teensy_reboot.exe is that you don't know if the programming was successful or not because sadly teensy_reboot does not return any usefull exit code.</p> <p>So the better option (which requires more code) is to instruct Teensy.exe directly from your program. Therefore you need a TCP connection to localhost.</p> <p>You find more details in this thread: <a href="https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443" rel="nofollow">https://forum.pjrc.com/threads/38684-How-does-Teensy-Reboot-exe-communicate?p=120443</a> where Paul (once again) did not answer my question.</p> <hr> <p><strong>PLAN C:</strong></p> <p>You can even replace Teensy.exe with your own code. Have a look at this project: <a href="https://github.com/Koromix/ty" rel="nofollow">https://github.com/Koromix/ty</a> Sadly this code depends on the huge QT library. Apart from that it may not work with future versions of Teensies.</p>
19847
|c|
Check the value of character variable
2016-01-21T07:10:54.580
<p>I'm writing some code for Arduino and I'm not sure if I'm checking the value of this character variable correctly. Can you please tell me if this is correct:</p> <pre><code>const char* front = "front"; const char* back = "back"; eyeballs(front); eyeballs(back); void eyeballs(const char* frontOrBack){ if (frontOrBack == "front") { digitalWrite(frontEyes, LOW);}//end if else if (frontOrBack == "back") { digitalWrite(backEyes, LOW);}//end else*/ } </code></pre>
<p>Another option would be an enum.</p> <pre><code>enum { FRONT, BACK } . . . if (frontOrBack == FRONT) { // Stuff } else if (frontOrBack == BACK) { // Some other stuff } </code></pre>
19851
|c++|h-bridge|
How to properly reverse DC motor direction with 2 limit switchws
2016-01-22T19:56:09.203
<p>Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.</p> <pre><code>const int sw2 = 2; //Up Limit switch const int sw3 = 3; //Down Limit switch const int ic1_2 = 8; //TA8409S IN2 const int ic1_1 = 9; //TA8409S IN1 const int enable = 10; //TA8409S Enable (motor) int sw2State = 0; int sw3State = 0; void setup() { pinMode(sw2, INPUT_PULLUP); pinMode(sw3, INPUT_PULLUP); pinMode(ic1_1, OUTPUT); pinMode(ic1_2, OUTPUT); pinMode(enable, OUTPUT); digitalWrite(enable, 1); Serial.begin(9600); } void loop() { tilt_up(); } void tilt_up() { Serial.print("up Started\n"); digitalWrite(ic1_1, LOW); digitalWrite(ic1_2, HIGH); sw2State = digitalRead(sw2); if (digitalRead(sw2State == LOW)) { tilt_down(); Serial.print("sw2 pressde\n"); } } void tilt_down() { Serial.print("down Started\n"); digitalWrite(ic1_1, HIGH); digitalWrite(ic1_2, LOW); sw3State = digitalRead(sw3); if (digitalRead(sw3State == LOW)) { tilt_up(); Serial.print("sw3 Pressed\n"); } } </code></pre>
<p>I got it to work!!! do not know if it is the right way ... but it works. thank you all for your input/advice. here is the new working code:</p> <pre><code>/* */ // set pin numbers: const int sw2 = 2; // Down limit const int sw3 = 3; // Up Limit const int ledPin = 13; // Pwr L.E.D const int ic1_2 = 8; // TA8409S IN2 const int ic1_1 = 9; // TA8409S IN1 const int enable = 10; // TA8409S Enable (motor) int sw2State = 0; // Down Limit State int sw3State = 0; // Up Limit State void setup() { // Setting L.E.D and Motor In, Enable pins as an output: pinMode(ic1_1, OUTPUT); pinMode(ic1_2, OUTPUT); pinMode(enable, OUTPUT); pinMode(ledPin, OUTPUT); // Setting limit switches pins as inputs pinMode(sw2, INPUT_PULLUP); pinMode(sw3, INPUT_PULLUP); // Enables motor digitalWrite(enable, 1); //Starts program down down(); } void loop() { // reads the state of the limit switches sw2State = digitalRead(sw2); sw3State = digitalRead(sw3); if (sw3State == LOW) { down(); } if (sw2State == LOW) { up(); } } void up() { digitalWrite(ic1_1, LOW); digitalWrite(ic1_2, HIGH); } void down() { digitalWrite(ic1_1, HIGH); digitalWrite(ic1_2, LOW); } void err() { digitalWrite(enable, LOW); digitalWrite(ic1_1, LOW); digitalWrite(ic1_2, LOW); } </code></pre>
19852
|c++|button|
How to change Void with button press
2016-01-22T20:18:37.990
<p>I have 2 buttons and 2 voids (blink_slow) (blink_fast). i need to be able to press button 1 and blink-slow void will run, then press button 2 and blink fast will run. none of my code works, any idea how i can do this?</p> <pre><code>const int btn1 1; const int btn2 2; const int led 13; void setup(){ pinMode(btn1,INPUT_PULLUP); pinMode(btn2,INPUT_PULLUP); pinMode(led,OUTPUT); digitalWrite(led,HIGH); } void loop(){ if(digitalRead(btn2 =LOW)){ blink_slow(); } if(digitalRead(btn3 =LOW)){ blink_fast(); } void blink_slow(){ digitalWrite(led,LOW); delay(1000) digitalWrite(led,HIGH); delay(1000) } void blink_fast(){ digitalWrite(led,LOW); delay(500) digitalWrite(led,HIGH); delay(500) } </code></pre>
<p>Start by correcting the obvious:</p> <pre><code>const int btn1 = 2; const int btn2 = 3; const int led = 13; void setup() { pinMode(btn1, INPUT_PULLUP); pinMode(btn2, INPUT_PULLUP); pinMode(led, OUTPUT); digitalWrite(led, HIGH); } void loop() { if (digitalRead(btn2) == LOW) { blink_slow(); } else if (digitalRead(btn3) == LOW) { blink_fast(); } void blink_slow() { digitalWrite(led, LOW); delay(1000) digitalWrite(led, HIGH); delay(1000) } void blink_fast() { digitalWrite(led, LOW); delay(500) digitalWrite(led, HIGH); delay(500) } </code></pre> <p>The mistakes where 1) const variable assignment, 2) using pin 1 (TX) is a potential risk if you later what to use Serial for debugging, etc, 3) condition expression, and a lot of formatting. Open your C/C++ book and check the syntax. </p> <p>Now your turn to improve this!</p>
19879
|arduino-nano|esp8266|temperature-sensor|
ESP8266 cannot read DHT22
2016-01-23T12:12:27.110
<p>I am trying to build a WiFi humidity and temperature sensor. My board is a nodeMCU using the ESP8266 connected via USB. The board is working fine with various WiFi examples and various serial examples. Hence I guest my environment is OK.</p> <p>Now I am trying to connect a DHT22 to read temperature and humidity. To reduce the error sources I boiled down my code to the standard DHT example:</p> <pre><code>// Example testing sketch for various DHT humidity/temperature sensors // Written by ladyada, public domain #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT22 // DHT 22 (AM2302) DHT dht(DHTPIN, DHTTYPE); void setup() { Serial.begin(9600); Serial.println("DHTxx test!"); dht.begin(); } void loop() { delay(2000); float h = dht.readHumidity(); float t = dht.readTemperature(); float f = dht.readTemperature(true); if (isnan(h) || isnan(t) || isnan(f)) { Serial.println("Failed to read from DHT sensor!"); return; } Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.println(" *C "); } </code></pre> <p>Nevertheless I always get the message "Failed to read from DHT sensor!".</p> <p>Regarding the hardware I tried connecting the sensor with or without the 10k resistor, tried different DHTs and different pins. To rule out the DHTs I connected them with an Arduino Nano where these are working fine (both with and without resistor and using the same code). The only difference I see is that the Arduino is using 5V while the ESP8266 is using 3.3V - which is nonetheless inside the rating of the DHT.</p> <p>Any ideas?</p>
<p>I had been racking my brain for over 16 hours trying to figure out why this library would not work. I tested the DHT on an Arduino and it worked fine but whenever I tried on the nodeMCU it failed to read or gave spurious data. That is untill I saw the above answer that is not mentioned anywhere. The pins for the nodeMCU are not the same as the Arduino. (I thought that by defining the pin it would be using the pin stated) This is false as the library is mapped the Arduino pins so this is something to look out for, for any nodeMCU/ESP8266 beginners.</p>
19892
|ide|c-preprocessor|
List of Arduino board preprocessor #defines
2016-01-23T17:03:42.180
<p>When one selects a board within Arduino IDE, a preprocessor definition is added to one of the behind-the-scenes files.</p> <p>After a lot of hunting and some good fortune I found that the format of this definition is:</p> <pre><code>#define ARDUINO_&lt;PROCESSOR-DESCRIPTOR&gt;_&lt;BOARDNAME&gt; </code></pre> <p>Some are easy to guess (<code>ARDUINO_AVR_UNO</code>, for example), but others are less so. The Pro Micro has '16' or '8' appended to the definition depending on the speed. I do not know if the definition is different for 5V or 3.3V. I haven't managed to guess the definition for the Mega2560, but it isn't anything obvious.</p> <p><strong>Question 1</strong>: Is there a list in existence of the possible definitions?</p> <p><strong>Question 2</strong>: Is there any distinction, as far as compilation and preprocessor involvement is concerned, between <em>BoardX</em>-5V and <em>BoardX</em>-3.3V, and how is this distinction defined?</p>
<p>Mikael has the right answer, but there are multiple boards.txt files depending on the installed boards with board manager, modifying the command to:</p> <pre><code>grep board= `find . -name boards.txt` | cut -f2 -d= | sort -u </code></pre> <p>and running it from your base Arduino directory collects the whole set.</p>
19901
|arduino-uno|communication|
Arduino radio communications
2016-01-23T22:45:04.570
<p>I have an Arduino and I am building a space satellite, just for fun. I'm not going to launch it obviously. </p> <p>I have built all the sensors and everything works. I was looking into communication because if a satellite is in space it needs to send down the data. </p> <p>Is it possible to have radio communication between two Arduino or an Arduino and something else that are 100km apart, it doesn't need to particle, I'm just wondering if it is possible and how it works. Is it possible without going out to buy shields?</p>
<p>Majenko covered several aspects of radio communications between a satellite and a ground station. An additional factor to consider is that the <a href="https://en.wikipedia.org/wiki/Horizontal_coordinate_system" rel="nofollow">azimuth or altitude</a> of a low-altitude satellite changes rapidly as it passes over a ground station. For example, a satellite 100 km up takes about 86 minutes per orbit and travels at about 7.84 Km/s, and probably would be in view for less than a minute per pass. [See eg <em><a href="http://keisan.casio.com/exec/system/1224665242" rel="nofollow">Orbit of a satellite Calculator</a></em> at casio.com.] Unless a phased array is used, and assuming communication is highly directional, the big dish on the ground will need to swing at up to 4.5° per second (about 270° per minute) as it tracks the satellite passing over. The much smaller antenna on the spacecraft should rotate at the same rate, the opposite direction.</p> <p>Note, an alternative to radio communications is a tight-beam laser system. Rather than using big, bulky microwave or UHF antennas to achieve directionality, you would use a small telescope (a few cm of aperture) on the satellite and a larger telescope (as much aperture as you can afford) at the ground station. Infrared or visible light lasers at each end of the link would be modulated to transmit at a high data rate. Accurate tracking and aiming might end up being important research projects for this approach.</p>
19910
|arduino-uno|rfid|processing-lang|
Read RFID Card Number in Processing over Serial
2016-01-24T12:47:43.007
<p>I have successfully setup up a RFID reader with Arduino Uno and EM-18 Card Reader Module.</p> <p>Its program for Arduino is below:</p> <pre><code>int count = 0; // count = 0 char input[12]; // character array of size 12 boolean flag = 0; // flag =0 void setup() { Serial.begin(9600); // begin serial port with baud rate 9600bps } void loop() { if(Serial.available()) { count = 0; while(Serial.available() &amp;&amp; count &lt; 12) // Read 12 characters and store them in input array { input[count] = Serial.read(); count++; delay(5); } //Serial.print("Card ID - "); Serial.print(input); // Print RFID tag number } } </code></pre> <p>But when try to read the code over serial in the program for locking/unlocking mouse in Processing the values of strings don't match. Hence the mouse doesn't get unlocked.</p> <p>The program for processing is as below:</p> <pre><code>import processing.serial.*; import java.awt.AWTException; import java.awt.Robot; Robot robot; boolean locked = false; Serial port; void setup() { println(Serial.list()); //Prints available ports port = new Serial(this, Serial.list()[36], 9600); //Chooses the first available port try { robot = new Robot(); //Creates robot } catch (AWTException e) { e.printStackTrace(); } } void draw() { if (locked == true) robot.mouseMove(0, 0); //If locked, moves mouse to top left corner while (port.available() &gt; 0) { String input = port.readString(); //println(input); if (input.equals("11006F26DC84") == true) locked = false; //If it read my card it will unloack. } } void keyPressed () { if (key == 'l') { locked = true; //Locks it } if (key == 'u') { locked = false; //Unlocks it } if (key == ESC) { key = 0; //Disables escape as quit } } </code></pre> <p>Please point the incorrect syntax and suggest correct one.</p>
<p><code>input</code> has to be 13 characters in size; you forgot to include a byte for the null-terminator. Then right before <code>Serial.print(input)</code>, you write <code>input[12] = 0</code>. Also the argument to <code>string.equals()</code> should be a String as well; you must write the statement like this: <code>input.equals(String("11006F26DC84"));</code></p>
19911
|hardware|
How to latch a 200mS LOW pulse?
2016-01-24T13:35:43.143
<p>Trying to latch a 200 mS, LOW event to log the event. LOW only occurs when external Watchdog timer sends reset pulse to the Arduino.</p> <p>Is a D Latch suitable for this application? It has been years since my digital class; help most appreciated.</p> <p>How would you proceed?</p>
<p>I understand your question to be : you want to latch (and indicate) whenever an external watchdog timer has reset your Arduino. </p> <p>D type flip flop (latch) can be used. You would use the clock input as the trigger. However, most D types clock on a rising edge. You could use an inverter on the input to the clock to get the D type to clock on a falling edge. You would also connect the D (Data) input high (logic 1). Then when your input (event) goes low, the Q output will latch high. The 200 mS is irrelevant because the latch ocurrs at the change from high to low (low to high on clock input). </p> <p>You would also need a means of resetting the latch, which many D types have a reset input or a clear input. </p> <p><a href="https://i.stack.imgur.com/iLDH3.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iLDH3.jpg" alt="enter image description here"></a> </p> <p>You could also use a more simple SR latch (set reset latch) using 2 Nand gates. SR latch changes state when the “set” input goes low (providing that R input was high). Make the R input go low to reset the latch. </p> <p><a href="https://i.stack.imgur.com/nAjFT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nAjFT.jpg" alt="enter image description here"></a> </p> <p>POSSIBLE ALTERNATIVE : If you have some means of operator intervention (or even a switch). You could have your program light an LED at startup. Operator (person) could reset LED. Then afterwards, any reset (restart of program) would light the LED.</p>
19912
|sensors|sketch|project|
Detecting Motion behind a robot
2016-01-24T13:46:42.653
<p>I am building a motion following robot. It has two PIR sensors on the left and right. It has an ultrasonic sensor in the front. When either of the PIR sensors detect motion then it turns to that side. <br><br>When both the PIR sensors sense motion then I calculate the distance first( with the ultrasonic sensor, if distance &lt;= 50 cm and > 5 cm then the robot moves forward. But it could mean that the motion is either in the front or in the back. Thus, my robot moves forward even the motion is behind it. <br><br> I need some help devising a method so that when motion is detected behind then the robot will turn back. I tried making the robot turn right when both the sensors detect motion, then it will turn towards the left(i.e. front) or right(i.e. back). But in reality this method is not so practical as it would to a lot of confusion when the intruder we are trying to detect is still in motion. Plz help. A sample sketch would help.</p>
<p>This is a basic problem of only having two sensors. There is no way that two sensors of this simple type (some motion yes/no) can be used to work out where the motion comes from except when there is a difference between the two sensors. Anything else is, and always will be, ambiguous.</p> <p>If you think of it as a circle divided in two, you have only three possible conditions:</p> <p><a href="https://i.stack.imgur.com/d2Xeo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/d2Xeo.png" alt="enter image description here" /></a></p> <p>That is, <em>left</em>, <em>right</em> or <em>somewhere</em>. Not ideal.</p> <p>So you need more data to be able to make a decision. That means more sensors. The ideal scenario is four sensors - left, right, front and rear. That gives you many possible scenarios, including:</p> <p><a href="https://i.stack.imgur.com/WPggl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WPggl.png" alt="enter image description here" /></a></p> <p>As you can see from that you have a full 360° idea of where the motion is. You can even know how far to the left it is by if the front or rear is also on. For instance, using sailing terminology, those 8 circles would mean (in order):</p> <ol> <li>Motion on the left beam</li> <li>Motion on the port bow</li> <li>Motion dead ahead</li> <li>Motion on the starboard bow</li> <li>Motion on the starboard beam</li> <li>Motion on the starboard quarter</li> <li>Motion dead astern</li> <li>Motion on the port quarter</li> </ol> <p>Also the dead-ahead and dead-astern could be indicated by just the forward or rear sensor on and the left/right sensors both off. You could even use that fact to give some indication of the distance of the motion depending on the angular coverage of the different sensors.</p>
19913
|arduino-uno|arduino-nano|analogread|voltage-level|
Precision voltmeter using Arduino
2016-01-24T14:01:14.857
<p>I am newbie, I need to measure precise voltage in range 0.00-0.80V, two digits precision. </p> <p>The voltage will not be greater than 1V-1.2V. </p> <p>I wonder if I need divider or not, I am sure that voltage won't rise above 1.2V.</p> <p>Can I connect the point to measure directly to analog input, or I still need to use divider? Please explain why. </p>
<p>A divider is used to (as the name suggests) reduce a higher voltage to a lower voltage. Using a divider on a small voltage will only make it smaller and harder to measure.</p> <p>To get the most out of your measuring you need to have the <em>reference</em> voltage as close to the highest voltage you want to measure as possible. The highest voltage that can be applied is not dependent on the reference voltage, but the supply voltage, and as 1.2V is way less than 5V (or 3.3V on a 3.3V board) you have no worries there.</p> <p>So you need to change the reference voltage - the voltage that the ADC uses as its upper <em>measurement</em> voltage. That's simple enough, since many of the Arduino boards include an internal 1.1V analog reference voltage generator that you can switch to (see: <a href="https://www.arduino.cc/en/Reference/AnalogReference">analogReference()</a>)</p> <p>So when you have switched to the 1.1V analog reference the ADC is capable of measuring 0-1.1V in 1024 steps. That's 1.1/1023=0.00107V per bit of precision.</p> <p>The formula is:</p> <pre><code>V = ADC / 1023 * Vref </code></pre> <p>So a reading of 1 would give you 0.00107V - a reading of 2 would be 0.00215V, etc. That's plenty of resolution to meet your 2 decimal places requirement.</p> <p><strong><em>One thing to note</em></strong> though is that the internal 1.1V reference isn't that stable or accurate (or not even there on some chips). If you need better stability and accuracy then it could pay to use an external voltage reference chip. These are like a linear voltage regulator but are far more accurate and stable (and can't provide lots of current). Pick one that is greater than your upper measurement voltage but as close to it as you can get (so just above 0.8V) and feed the output into the external <em>ARef</em> pin and switch the analog reference to the <code>EXTERNAL</code> mode.</p> <p>You <em>could</em> use a voltage divider on the external ARef pin to provide a low reference voltage, but the stability and accuracy will be no better (and probably worse) than the internal 1.1V voltage reference, so there really is no point.</p>
19918
|serial|arduino-mega|
Atlas Scientific pH project - serialEvent3 problems
2016-01-24T16:06:43.857
<p>I am trying to get this pH project working and I've noticed that the serialEvent3 never sets the boolean value sensor_string_complete to true. I am not sure if it is actually capturing the values from the probe. What I want is for every loop through it should grab a pH value and that is not happening right now. Most times through the loop the serial3 port is not providing any values. Here is my code:</p> <pre><code>String sensorstring = ""; boolean sensor_string_complete = false; float pH; void setup() { Serial.begin(38400); Serial3.begin(38400); // pH stamp } void serialEvent3() { //if the hardware serial port_3 receives a char sensorstring = Serial3.readStringUntil(13); //read the string until we see a &lt;CR&gt; sensor_string_complete = true; //set the flag used to tell if we have received a completed string from the PC } void loop() { getPh(); if (sensor_string_complete == true) readph(); } void getPh() { Serial.println("we are here"); Serial3.print("r"); Serial3.print(13); } void readph(){ Serial.println("read ph here"); if (isdigit(sensorstring[0])) { pH = sensorstring.toFloat(); Serial.println(pH); } else{ Serial.println(sensorstring); } sensorstring = ""; sensor_string_complete = false; } </code></pre> <p>This returns values such as we are here we are here we are here read ph here 7.0 we are here read ph here 7.0 we are here we are here we are here read ph here 7.0</p> <p>I want this to return these values every loop. I expect to see: We are here read ph here 7.0 We are here read ph here 7.0</p> <p>Any help on this would be great. Thanks so much!</p>
<p>On a typical Arduino, the delay between <code>loop()</code> ending and <code>loop()</code> running again is a few microseconds. <code>Serial.println()</code> in <code>getPh()</code> is interrupt-driven so that call too takes only a few microseconds. Writing two bytes with <code>Serial3.print()</code> at 38400 bps will take about half a millisecond. In short, there is plenty of time for <code>loop()</code> to run several times before <code>serialEvent3()</code> sets <code>sensor_string_complete</code>.</p> <p>To call <code>getPh()</code> once and <code>readph()</code> once per <code>loop()</code>, instead of </p> <pre><code>if (sensor_string_complete == true) readph(); </code></pre> <p>say</p> <pre><code>while (!sensor_string_complete) {} readph(); </code></pre> <p>This will stall the loop while the pH sensor takes and reports a reading.</p> <p>Note, in <code>getPh()</code> instead of using two separate <code>Serial3.print()</code> statements, you can just say <code>Serial3.print("r\r")</code>.</p>
19924
|arduino-due|interrupt|adc|analog-sampling|
Arduino Due: Interrupt-based ADC hangs processing
2016-01-24T17:58:46.453
<p>I am trying to build an oscilloscope using an Arduino Due and an LCD. I have the LCD running perfectly and started working on using the ADC peripheral to sample signals. Here's what I have so far:</p> <pre><code>#define SAMPLE_BUFFER_SIZE 800 volatile int sample_buffer[SAMPLE_BUFFER_SIZE]; volatile bool sample_buffer_full = 0; volatile int sample_buffer_idx = 0; void adcm_init() { pmc_enable_periph_clk(ID_ADC); // To use peripheral, we must enable clock distributon to it adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST); // initialize, set maximum posibble speed adc_disable_interrupt(ADC, 0xFFFFFFFF); adc_set_resolution(ADC, ADC_12_BITS); adc_configure_power_save(ADC, 0, 0); // Disable sleep adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1); // Set timings - standard values adc_set_bias_current(ADC, 1); // Bias current - maximum performance over current consumption adc_stop_sequencer(ADC); // not using it adc_disable_tag(ADC); // it has to do with sequencer, not using it adc_disable_ts(ADC); // deisable temperature sensor adc_disable_channel_differential_input(ADC, ADC_CHANNEL_7); adc_configure_trigger(ADC, ADC_TRIG_SW, 1); // triggering from software, freerunning mode adc_disable_all_channel(ADC); adc_enable_channel(ADC, ADC_CHANNEL_7); // just one channel enabled adc_enable_interrupt(ADC, ADC_IER_DRDY); // Data Ready Interrupt Enable NVIC_EnableIRQ(ADC_IRQn); adc_start(ADC); } void ADC_Handler(void) { if (!sample_buffer_full) { if ((adc_get_status(ADC) &amp; ADC_ISR_DRDY) == ADC_ISR_DRDY) { sample_buffer[sample_buffer_idx] = adc_get_latest_value(ADC); sample_buffer_idx++; if (sample_buffer_idx == SAMPLE_BUFFER_SIZE) { sample_buffer_full = 1; sample_buffer_idx = 0; } } } } void setup() { adcm_init(); Serial.begin(115200); } void loop() { Serial.print("Loop\n"); if (sample_buffer_full) { for (int i = 0; i &lt; SAMPLE_BUFFER_SIZE; i++) { Serial.print(sample_buffer[i]); Serial.print(" "); } Serial.print("\n"); sample_buffer_full = 0; } } </code></pre> <p>This was copied and slightly modified from somewhere on the internet (can't remember where, though). I have also studied the docs and this code seems to make perfect sense and it should work.</p> <p>The idea is for the sampling to be interrupt-based. However, if I set the ADC to freerunning mode and enable interrupts, it just gives up and stops working.</p> <p>What I mean by that is: on my serial monitor, after pressing reset, all I see are 2 lines saying "Loop" and it just stops there. Normally it should print "Loop" indefinitely, and also print ADC values from time to time.</p> <p>If I disable interrupts, "Loop" is printed indefinitely, but of course no values are shown. If I disable free-running mode, "Loop" is printed and no values are shown unless the buffer size is 1, in which case the same value is printed over and over (as expected, in that case the interrupt runs only once, right at the beginning).</p> <p>The CPU clock freq. is 84Mhz, I'm going for the fastest I can get out of the ADC, so a sample is taken (and an interrupt is fired) every 1Mhz. That means 84 clock cycles per interrupt. Don't know for sure if that is enough for the rest of the program to work, but my gut tells me that's not a problem. Besides, I tried with a lower ADC clock value and it still didn't work.</p> <p>Any ideas? I'm really at a loss here...</p>
<p>In your interrupt handler, <code>ADC_Handler()</code>, you set <code>sample_buffer_full</code> when the buffer is full. <s>I don't see anywhere in the code where <code>sample_buffer_full</code> ever gets reset (cleared) once it's been set.</s></p> <p>While <code>sample_buffer_full</code> is set, it disables the body of the interrupt handler – ie, the handler's structure is</p> <pre><code>if (!sample_buffer_full) { ...body of handler... } </code></pre> <p>– and in particular, prevents <code>adc_get_latest_value(ADC);</code> from occurring. The <a href="https://android.googlesource.com/platform/external/arduino-ide/+/f876b2abdebd02acfa4ba21e607327be4f9668d4/hardware/arduino/sam/system/libsam/source/adc.c?autodive=0%2F%2F%2F" rel="nofollow">source code</a> of <code>adc_get_latest_value();</code> is like</p> <pre><code>uint32_t adc_get_latest_value(const Adc *p_adc) { return p_adc-&gt;ADC_LCDR; } </code></pre> <p>which accesses the ADC data register. According to section 43.6.4 <em>Conversion Results</em> on page 1322 of the data sheet, Atmel-11057-32-bit-Cortex-M3-Microcontroller-SAM3X-SAM3A_Datasheet.pdf, </p> <blockquote> <p>The channel EOC bit in the Status Register (ADC_SR) is set and the DRDY is set. In the case of a connected PDC channel, DRDY rising triggers a data transfer request. In any case, either EOC and DRDY can trigger an interrupt.</p> <p>Reading one of the ADC_CDR registers clears the corresponding EOC bit. Reading ADC_LCDR clears the DRDY bit and EOC bit corresponding to the last converted channel.</p> </blockquote> <p>It appears to me that your code enables interrupts, fills a buffer, sets <code>sample_buffer_full</code>, then spins in <code>ADC_Handler()</code>. That is, repeatedly executes <code>ADC_Handler()</code> without clearing the EOC bit.</p> <p>Note, for oscilloscope applications with a Due, I suggest using DMA buffers instead of one interrupt per conversion. See <a href="http://forum.arduino.cc/index.php?topic=137635.5" rel="nofollow">thread #137635</a>, <em>speed of analogRead</em>, in forum.arduino.cc for DMA code to read one or two analog channels on a Due at one sample per microsecond. Also see <a href="http://www.edaboard.com/thread283843.html" rel="nofollow">edaboard.com/thread283843</a> and <a href="http://forum.arduino.cc/index.php?topic=186169.0" rel="nofollow">forum.arduino.cc #186169</a></p> <p><em>Edit note:</em> Although <code>sample_buffer_full</code> does get reset, that reset happens after a time-consuming for-loop. Whether it takes some hundreds of microseconds or a few milliseconds, the for-loop is enough of a delay that at least one more conversion and interrupt will occur before <code>sample_buffer_full</code> gets cleared. One unhandled conversion is enough to lock up the interrupt handler. Here are some alternative approaches to consider:</p> <p>• Use a circular buffer, and never stop filling it. This is ok if you are only interested in the most recent data, rather than a complete waveform record.</p> <p>• Set or reset <code>sample_buffer_full</code> as now; and remove the initial if test from the handler. Instead, put an <code>if</code> before <code>sample_buffer_idx++;</code>, to not increment if the buffer is full.</p> <p>• Turn off ADC's freerun mode. This is a reasonable thing to do when not taking data.</p> <p>• Turn off ADC's interrupt when not taking data. Also reasonable.</p> <p>• Use multiple buffers. Reasonable, but by itself doesn't avoid the problem.</p> <p>• Read the latest value every time the handler executes [for example, say <code>int datum = adc_get_latest_value(ADC);</code> as the first statement in the handler] and then only store that value in certain cases. An easy and effective way to avoid problem.</p>
19926
|motor|
Transistor slows motor instead of turning it off
2016-01-24T21:03:40.513
<p>I'm new to electrical engineering and I am currently trying to make a motor turn on for one second, turn off for one second, and repeat.</p> <p>I'm using an Arduino Uno's <code>digitalWrite()</code> feature to activate a transistor, allowing the external 9V battery to turn on the motor.</p> <p>Although everything is responding, instead of the motor turning on and off like I want it to, it spins fast for a second, then spins slower for a second. I would like the motor to stop completely, but cannot figure out how to do that.</p> <p>Here's the schematic of my circuit:</p> <p><img src="https://i.stack.imgur.com/EoTLx.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fEoTLx.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p><strong>Code:</strong></p> <pre><code>void setup(){ pinMode(9, OUTPUT); } void loop(){ digitalWrite(9, HIGH); delay(1000); digitalWrite(9, LOW); delay(1000); } </code></pre> <p>Why isn't the motor completely turning off?</p>
<p>I can't make much sense of your diagram- but this is the correct way to do it: </p> <p><img src="https://i.stack.imgur.com/cGWWK.png" alt="schematic"></p> <p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fcGWWK.png">simulate this circuit</a> &ndash; Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p> <p>R1 is low enough that the base gets 10-15mA of drive, sufficient for a few hundred mA of motor current. D1 protects the transistor Q1 when it turns off (from the motor inductance). The emitter of the NPN transistor should be grounded and then the collector will either be near ground or at the 9V level depending on whether it is off or on. </p> <p>You may have damaged the transistor you are using (due to breaking it down in reverse across the E-B junction) so I would suggest proceeding with a new one. You didn't mention it, but it probably got quite warm. </p>
19935
|arduino-mega|accelerometer|gyroscope|magnetometer|
How to use Multiple MPU9250 to Arduino Lilypad
2016-01-25T01:28:45.797
<p>Is it possible to connect more than one or to be specific 5 MPU9250 into 1 Arduino lilypad? How will I set the addresses, and where should I put the pins for SDA and SCL? I hope someone out there could help me on this project.</p> <p>Cheers! </p> <p>What if I have this working codes, how will I edit this to connect more than two MPU9250? Please guide me. Thanks.</p> <pre><code> #include &lt;Wire.h&gt; #include &lt;TimerOne.h&gt; #define MPU9250_ADDRESS 0x68 #define MAG_ADDRESS 0x0C #define GYRO_FULL_SCALE_250_DPS 0x00 #define GYRO_FULL_SCALE_500_DPS 0x08 #define GYRO_FULL_SCALE_1000_DPS 0x10 #define GYRO_FULL_SCALE_2000_DPS 0x18 #define ACC_FULL_SCALE_2_G 0x00 #define ACC_FULL_SCALE_4_G 0x08 #define ACC_FULL_SCALE_8_G 0x10 #define ACC_FULL_SCALE_16_G 0x18 // This function read Nbytes bytes from I2C device at address Address. // Put read bytes starting at register Register in the Data array. void I2Cread(uint8_t Address, uint8_t Register, uint8_t Nbytes, uint8_t* Data) { // Set register address Wire.beginTransmission(Address); Wire.write(Register); Wire.endTransmission(); // Read Nbytes Wire.requestFrom(Address, Nbytes); uint8_t index=0; while (Wire.available()) Data[index++]=Wire.read(); } // Write a byte (Data) in device (Address) at register (Register) void I2CwriteByte(uint8_t Address, uint8_t Register, uint8_t Data) { // Set register address Wire.beginTransmission(Address); Wire.write(Register); Wire.write(Data); Wire.endTransmission(); } // Initial time long int ti; volatile bool intFlag=false; // Initializations void setup() { // Arduino initializations Wire.begin(); Serial.begin(115200); // Set accelerometers low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS,29,0x06); // Set gyroscope low pass filter at 5Hz I2CwriteByte(MPU9250_ADDRESS,26,0x06); // Configure gyroscope range I2CwriteByte(MPU9250_ADDRESS,27,GYRO_FULL_SCALE_1000_DPS); // Configure accelerometers range I2CwriteByte(MPU9250_ADDRESS,28,ACC_FULL_SCALE_4_G); // Set by pass mode for the magnetometers I2CwriteByte(MPU9250_ADDRESS,0x37,0x02); // Request continuous magnetometer measurements in 16 bits I2CwriteByte(MAG_ADDRESS,0x0A,0x16); pinMode(13, OUTPUT); Timer1.initialize(10000); // initialize timer1, and set a 1/2 second period Timer1.attachInterrupt(callback); // attaches callback() as a timer overflow interrupt // Store initial time ti=millis(); } // Counter long int cpt=0; void callback() { intFlag=true; digitalWrite(13, digitalRead(13) ^ 1); } // Main loop, read and display data void loop() { while (!intFlag); intFlag=false; // Display time Serial.print (millis()-ti,DEC); Serial.print ("\t"); // _______________ // ::: Counter ::: // Display data counter // Serial.print (cpt++,DEC); // Serial.print ("\t"); // ____________________________________ // ::: accelerometer and gyroscope ::: // Read accelerometer and gyroscope uint8_t Buf[14]; I2Cread(MPU9250_ADDRESS,0x3B,14,Buf); // Create 16 bits values from 8 bits data // Accelerometer int16_t ax=-(Buf[0]&lt;&lt;8 | Buf[1]); int16_t ay=-(Buf[2]&lt;&lt;8 | Buf[3]); int16_t az=Buf[4]&lt;&lt;8 | Buf[5]; // Gyroscope int16_t gx=-(Buf[8]&lt;&lt;8 | Buf[9]); int16_t gy=-(Buf[10]&lt;&lt;8 | Buf[11]); int16_t gz=Buf[12]&lt;&lt;8 | Buf[13]; // Display values // Accelerometer Serial.print (ax,DEC); Serial.print ("\t"); Serial.print (ay,DEC); Serial.print ("\t"); Serial.print (az,DEC); Serial.print ("\t"); // Gyroscope Serial.print (gx,DEC); Serial.print ("\t"); Serial.print (gy,DEC); Serial.print ("\t"); Serial.print (gz,DEC); Serial.print ("\t"); // _____________________ // ::: Magnetometer ::: // Read register Status 1 and wait for the DRDY: Data Ready uint8_t ST1; do { I2Cread(MAG_ADDRESS,0x02,1,&amp;ST1); } while (!(ST1&amp;0x01)); // Read magnetometer data uint8_t Mag[7]; I2Cread(MAG_ADDRESS,0x03,7,Mag); // Create 16 bits values from 8 bits data // Magnetometer int16_t mx=-(Mag[3]&lt;&lt;8 | Mag[2]); int16_t my=-(Mag[1]&lt;&lt;8 | Mag[0]); int16_t mz=-(Mag[5]&lt;&lt;8 | Mag[4]); // Magnetometer Serial.print (mx+200,DEC); Serial.print ("\t"); Serial.print (my-70,DEC); Serial.print ("\t"); Serial.print (mz-700,DEC); Serial.print ("\t"); // End of line Serial.println(""); // delay(100); } </code></pre>
<p>If you use I2C, you can use an I2C multiplex chip to handle the arbitration to handle lots of MPU-9250s. I had a setup with 6x of them going. I did find however, that the amount of CPU time that it takes for I2C communication is high, so once you get in to that many 9250s, you don't have much CPU time left over for other things. Using SPI is a bit trickier to get going, but it is wicked fast and also lets you take advantage of the FIFO buffer on the 9250s. </p> <p>Majenko mentioned using the I2C master functionality on the 9250 to daisy chain - I had also tried that approach before I tried the I2C multiplexer. I have to say it was a horrible experience. When you use that I2C master function, you are actually programming the advanced functionality of the 9250 instead of using the Arduino coding in C. Once it all starts working (if it does), it acts quite flaky. That functionality on the chip was really designed to enable using an external magnetometer on the 6250 to get 9dof. Any more complex use than that gets hairy with the interchip timing, and initializing on startup is also rough.</p> <p>Final answer - put in the time to learn how to use the SPI bus as mentioned in some of the other answers. Once you get through the learning curve, it can run at up to 20khz communication speed. SPI is designed for high speed communication. I2C is designed to be easier to use but for things with lower update rates.</p>
19946
|robotics|
PID tuning help
2016-01-25T12:06:57.283
<p>I'm currently working on a self-balancing robot with an Arduino Uno and a 10DOF ADXL345 sensor. Everything is going fine until I got to this PID tuning part. I've read about it several times but I'm unable to get the desired results. Can somebody give a detailed guide on PID tuning? Thank you.</p>
<p>In real life there is no set equation to find the PID values. At best you'll get close with equations and then need to tune the parameters.</p> <p>For anyone into PID loops have a read of <a href="http://controlguru.com/table-of-contents/" rel="nofollow">this</a>. I've found it to be excellent.</p> <p>My advice is to:</p> <ul> <li>only use P</li> <li>set I &amp; D to 0</li> <li>get it and good as you can by trial and error</li> <li>add I and trial it too</li> </ul> <p>D is for experts really and may cause weird/undesirable jitter.</p>
19951
|arduino-uno|c++|arduino-ide|class|ino|
Arduino declaring class in h and cpp file Undefined Reference
2016-01-25T16:33:14.147
<p>I am trying to compile my project, but unfortunately get errors. </p> <p>I created class and separated implementation and declaration (cpp file and h file)</p> <p>Here they are </p> <p><strong>sensor.h</strong></p> <pre><code>#ifndef SENSOR_H #define SENSOR_H #include &lt;stdint.h&gt; #include "Arduino.h" // Sensor types enum SensorType { ANY_SENSOR, UNKNOWN_SENSOR, WATER_SENSOR, TEMPERATURE_SENSOR, VIBRATION_SENSOR, INTERCOM_SENSOR, HUMIDITY_SENSOR, PIR_SENSOR, SOUND_SENSOR, LIGHT_SENSOR }; class Sensor { public: // Variables declaration uint32_t sensorId; SensorType sensorType; float currentValue; bool isEnabled; float criticalLowerLevel; float criticalUpperLevel; // Methods declaration Sensor(); Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper); String toString(); bool isCriticalLevelRised() { return (this-&gt;currentValue &gt;= this-&gt;criticalUpperLevel || this-&gt;currentValue &lt;= this-&gt;criticalLowerLevel); }; void enable(bool enable); void toggle(); static String convertSensorTypeToString(SensorType sensorType); }; #endif </code></pre> <p>And cpp file </p> <pre><code>#include "sensor.h" Sensor::Sensor() { this-&gt;sensorId = 0; this-&gt;sensorType = UNKNOWN_SENSOR; this-&gt;currentValue = 0; this-&gt;isEnabled = false; this-&gt;criticalLowerLevel = 0; this-&gt;criticalUpperLevel = 0; } Sensor::Sensor(uint32_t id,SensorType type,long currentValue,bool isEnabled,long lower,long upper) { this-&gt;sensorId = id; this-&gt;sensorType = type; this-&gt;currentValue = currentValue; this-&gt;isEnabled = isEnabled; this-&gt;criticalLowerLevel = lower; this-&gt;criticalUpperLevel = upper; } void Sensor::enable(bool enable) { this-&gt;isEnabled = enable; } void Sensor::toggle() { this-&gt;enable(!this-&gt;isEnabled); } String Sensor::toString() { String response = ""; response += F("Sensor id is "); response += this-&gt;sensorId; response += '\n'; response += F("Sensor type is "); response += convertSensorTypeToString(this-&gt;sensorType); response += '\n'; response += F("Sensor current value is "); response += this-&gt;currentValue; response += '\n'; response += F("Sensor isEnabled is "); response += this-&gt;isEnabled; response += '\n'; response += F("Sensor criticalLowerLevel is "); response += this-&gt;criticalLowerLevel; response += '\n'; response += F("Sensor criticalLowerLevel is "); response += this-&gt;criticalUpperLevel; response += '\n'; return response; } String Sensor::convertSensorTypeToString(SensorType sensorType) { switch (sensorType) { case UNKNOWN_SENSOR: return F("UNKNOWN SENSOR"); case ANY_SENSOR: return F("ANY_SENSOR"); case WATER_SENSOR: return F("WATER_SENSOR"); case TEMPERATURE_SENSOR: return F("TEMPERATURE_SENSOR"); case VIBRATION_SENSOR: return F("VIBRATION_SENSOR"); case HUMIDITY_SENSOR: return F("HUMIDITY_SENSOR"); case PIR_SENSOR: return F("PIR_SENSOR"); case SOUND_SENSOR: return F("SOUND_SENSOR"); case LIGHT_SENSOR: return F("LIGHT_SENSOR"); default: return F("UNKNOWN TYPE"); } } </code></pre> <p>And I got following errors </p> <pre><code>ketch/NodeIntercom.ino.cpp.o: In function `sendSensorMessageToMaster(RF24Mesh*, SensorDataMessage*, char, unsigned int, bool)': /home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h:48: undefined reference to `Sensor::toString()' sketch/NodeIntercom.ino.cpp.o: In function `handleSetSensorDataRequest(RF24NetworkHeader*)': /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:97: undefined reference to `Sensor::toggle()' /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:89: undefined reference to `Sensor::enable(bool)' sketch/NodeIntercom.ino.cpp.o: In function `SensorDataMessage': /home/iron/Arduino/What'sHappening/NetworkMaster/common.h:40: undefined reference to `Sensor::Sensor()' sketch/NodeIntercom.ino.cpp.o: In function `__static_initialization_and_destruction_0': /home/iron/Arduino/What'sHappening/NodeIntercom/NodeIntercom.ino:35: undefined reference to `Sensor::Sensor(unsigned long, SensorType, long, bool, long, long)' collect2: error: ld returned 1 exit status </code></pre> <p>What I am doing wrong ? Please help.</p> <p><strong>EDIT</strong></p> <p>Yes main sketch compiles perfectly where this files are located.</p> <p>But I don't want to duplicate common files in my all my arduino sketches withing the project, they are the same for whole project. Here my files location </p> <pre><code>--ArduinoProjects ---NodeIntercom ----NodeIntercom.ino ---MasterNode ----MasterNode.ino ----sensor.h ----sensor.cpp ----common.h </code></pre> <p>So this files are only located in MasterNode directory </p> <p>And I tried to include them like this </p> <pre><code>#include "/home/iron/Arduino/What'sHappening/NetworkMaster/common.h" #include "/home/iron/Arduino/What'sHappening/NetworkMaster/additional_functions.h" </code></pre> <p>And in common.h I include sensor.h Also tried to include directly, but still the same</p> <p>But headers files included as above works perfectly. </p> <p>What is the right way to solve this problem, I don't want to duplicate this class in each folder whenever I change it. </p> <p>If there is no way, maybe create symbolic link (I am using linux) ?</p> <p><strong>PARTIAL SOLUTION</strong></p> <p>Just use symbolic links in the sketch directory and this works perfectly</p>
<p>The Arduino build preprocessing cannot locate the sensor source and header files if they are located in another sketch directory. The files needs to be moved to separate directory if shared (as a library).</p> <pre><code>--Sketchbook ---NodeIntercom ----NodeIntercom.ino ---MasterNode ----MasterNode.ino ---libraries ----Sensor -----Sensor.h -----Sensor.cpp </code></pre> <p>The Sensor header is included with</p> <pre><code>#include &lt;Sensor.h&gt; </code></pre> <p>in the sketches that needs to use it. </p>
19955
|data-type|mathematics|
Trouble with large numbers
2016-01-25T17:28:56.043
<p>Probably something stupid, but I can't figure out how to work with these large numbers, then cast the result (which will be small) to an integer. I keep getting negative numbers, which I think means I'm overflowing somewhere.</p> <pre><code>int freq = 440; int len = 256; long timer = 2000000.0 / (freq * len); int roundedTimer = int(timer); </code></pre> <p>I should get 18, but I'm getting -108...</p>
<p><code>freq * long</code>, since they are both integers, are calculated as integers.</p> <p><code>440*256=112640</code> - in binary that is <code>1 1011 1000 0000 0000</code> and trimmed to 16 bits becomes <code>1011 1000 0000 0000</code> which is <code>-18432</code> and that is where the heart of your problem is. Unless you explicitly say otherwise the Arduino's compiler does all calculations (except floating point) as 16-bit signed integers.</p> <p>By casting the values to <code>long</code> it forces the compiler to 'overflow' the 16-bit limit and use a 32-bit limit instead:</p> <pre><code>long timer = 2000000 / ((long)freq * (long)len); </code></pre> <p>Another alternative is to define <code>freq</code> and <code>len</code> to be <code>long</code> from the outset instead of <code>int</code>.</p>
19958
|audio|
Calculate OCR2A from audio frequency
2016-01-25T15:57:01.863
<p>I'm working on a Arduino-based synthesizer using <a href="http://makezine.com/projects/make-35/advanced-arduino-sound-synthesis/" rel="nofollow">this tutorial</a>, specifically using a wavetable and 1-bit DAC. I understand that the value for OCR2A register sets the frequency, but how do I calculate the value?</p> <p>I've seen <a href="http://cdn.makezine.com/make/35/OCR2A-frequency-table.pdf" rel="nofollow">this list of notes</a> which is great, but I want arbitrary frequencies in Hz...</p> <p>Here's the code I'm working from:</p> <pre><code>#include &lt;avr/interrupt.h&gt; // sinewave parameters #define FREQ 18 #define PI2 6.283185 // 2*PI saves calculation later #define AMP 127 // scaling factor for sine wave #define OFFSET 128 // offset shifts wave to all &gt;0 values #define LENGTH 256 // length of the wave lookup table byte wave[LENGTH]; // wavetable void setup() { // populate wavetable for (int i = 0; i &lt; LENGTH; i++) { float v = (AMP * sin((PI2 / LENGTH) * i)); wave[i] = int(v + OFFSET); } // set timer1 for 8-bit fast PWM output pinMode(9, OUTPUT); // make timer’s PWM pin an output TCCR1B = (1 &lt;&lt; CS10); // set prescaler to full 16MHz TCCR1A |= (1 &lt;&lt; COM1A1); // pin low when TCNT1=OCR1A TCCR1A |= (1 &lt;&lt; WGM10); // use 8-bit fast PWM mode TCCR1B |= (1 &lt;&lt; WGM12); // set up timer2 to call ISR TCCR2A = 0; // no options in control register A TCCR2B = (1 &lt;&lt; CS21); // set prescaler to divide by 8 TIMSK2 = (1 &lt;&lt; OCIE2A); // call ISR when TCNT2 = OCRA2 OCR2A = FREQ; // set frequency of generated wave sei(); // enable interrupts to generate waveform! } void loop() { // nothing to do here! } // called every time TCNT2 = OCR2A ISR (TIMER2_COMPA_vect) { // called when TCNT2 == OCR2A static byte index = 0; // points to each table entry OCR1AL = wave[index++]; // update the PWM output asm("NOP; NOP"); // fine tuning TCNT2 = 6; // timing to compensate for ISR run time } </code></pre>
<p>The equation to calculate it is given in the first article you linked:</p> <p><a href="https://i.stack.imgur.com/1NREx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1NREx.jpg" alt="From linked Makezine article &quot;Advanced Arduino Sound Synthesis&quot;"></a></p> <p>The 2MHz value comes from the factor of 8 prescale on the 16MHz clock and 256 is the size of the lookup table specified by your <code>LENGTH</code> define. If you start from a frequency you want to synthesize, just use the above equation to solve for the necessary value of OCR2A. Note that since you have to input integer values to OCR2A, you can't really achieve <em>arbitrary</em> frequencies, but you're certainly not locked in to the values given in the supplemental musical note PDF you reference.</p> <p>So, to solve for OCR2A: </p> <pre><code>OCR2A = TCNT2_rate / (desiredFreq * wavetableLength); </code></pre>
19961
|arduino-uno|frequency|
Maximum frequency of digital signal in Arduino Uno?
2016-01-25T20:22:07.387
<p>As Arduino Uno has a 16 MHz oscillator but while running program it has less frequency because some of the processing power is used for running the program. I have used the <code>delay(1)</code> but it is giving me around 500 Hz. </p> <p><strong>My questions:</strong></p> <ol> <li>Is there any way to achieve more than 500 Hz?</li> <li>What would be the maximum frequency of digital signal for below program?</li> </ol> <pre class="lang-cpp prettyprint-override"><code>void setup() { pinMode(13, OUTPUT); } void loop() { digitalWrite(13, HIGH); digitalWrite(13, LOW); } </code></pre>
<p><strong>Nick Gammon's</strong> code worked fine for me. Here is an <strong>oscilloscope picture</strong> of the waveform I've got from <strong>his code</strong>:</p> <p><a href="https://i.stack.imgur.com/8NWfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8NWfq.png" alt="Output of Arduino UNO pin 9, approximately 1 V peak-to-peak Amplitude with spikes"></a></p> <p>His code above (<em>from Nick Gammon, on Jan 25 '16 at 20:33</em>) worked excellent for me. I used his code on Arduino UNO and got about <strong>7.9 MHz</strong> of output frequency on an approximately <strong>1 V amplitude</strong> (peak-to-peak, with spikes making it go to about <strong>2 V peak-to-peak amplitude</strong>).</p> <p>The image above was obtained with my 40 MHz Oscilloscope from <em>ICEL Manaus</em> (manufacturer) at pin 9 (I used the Arduino UNO), with a LED and a resistor as a load at pin 9: </p> <ul> <li>a green LED of about 1.79 V voltage drop</li> <li>and a 4.7 Ohms resistor with 5% tolerance</li> </ul> <p>The oscilloscope probe (<em>Channel 2, with fall slope trigger detect</em>) is on the 4.7 Ohms resistor. It follows the connection order out of the pin 9 from Arduino UNO: <em>PIN 9</em> > <em>green LED</em> > <em>4.7 Ohms resistor</em> > <em>GROUND</em>.</p> <p>The green LED keeps blinking at a normal luminescence, as compared when used at other output frequencies.</p> <p>I used a external 5 V DC power supply, along with the USB connection on my PC.</p> <p>If you have any questions just put them here. Thanks and thanks <a href="https://arduino.stackexchange.com/users/10794/nick-gammon">Nick Gammon</a></p>
19963
|arduino-uno|
Recommendations for limit switches for Arduino
2016-01-25T20:55:55.863
<p>I'm looking for a limit switch to use with the Arduino. In my project I want to count how many times my <a href="http://cdn.shopify.com/s/files/1/0220/4654/products/slider1_large.jpeg?v=1420208854" rel="nofollow noreferrer">turntable</a> makes a full 360° rotation. An object (wheel, pipe, whatever) will be sticking out the side of the turntable and when it comes in contact with the limit switch that will be right next to the turntable, it should notify the Arduino.</p> <p>Any suggestions on which limit switch I should get?</p> <p>Thanks so much in advance!</p>
<p>Instead of a limit switch a hall effect sensor with a moving magnet is an optimal soltuntion since it is contact less there will be no frictional side effects on your application.</p> <p>But there is one more better way to it, try to use an rotary encoder, something like a 400/600 ppr should also be fine for this, doing this way you have more positional data of the turntable, </p> <p>You can calculate no of turn, arcs etc.</p> <p>For eg: </p> <ol> <li>A 400ppr would give you a resolution of 0.9 degree per pulse, and </li> <li>600ppr would give you 0.6degree per pulse of accuracy.</li> </ol> <p>Although you can go for even higher ppr encoders but you can get these at very low cost. </p> <p>Pic from: <a href="https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1" rel="nofollow noreferrer">https://m.ebay.co.uk/itm/400BM-Rotary-Encoder-Module-LPD3806-360-6mm-Shaft-Arduino-Pi-Flux-Workshop-/112607725039?_mwBanner=1</a> </p> <p>Note: Just an example, price may be different at other webites, haven't checked the price while writing this solution. <a href="https://i.stack.imgur.com/7BnyH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7BnyH.jpg" alt="A 400ppr rotary encoder"></a></p>
19964
|potentiometer|
Problem with a digital potentiometer application
2016-01-25T21:10:49.953
<p>I am a beginner when it comes to electronics, coding and things like that (this is practically the first time I have done anything like this), so when building an application that is supposed to vibrate a vibration motor with a strength based on the distance measurement made by the ultrasonic rangefinder, I bumped up with a problem.</p> <p>The MCP 41010 digital potentiometer seems to let electricity through only when it is given a SPI.transfer(128). Any other number stops the flow of electricity completely.</p> <p>I have tried some addresses such as 00, 0x00, 0x01 and 0x04 to replace the 0 and the result was the same. With addresses 0x11 and 0x08 the digital potentiometer didn't react at all.</p> <p>In addition to the code I have here I have tried just copy-pasting some of the tutorials I found from the internet, for example this one <a href="https://arduino.stackexchange.com/questions/4952/digital-potentiometer-not-fading-led">Digital Potentiometer not fading LED</a> without really understanding the commands formats thing all that well. With that code I got a vibration that didn't seem to fade in or fade out at all, so the problem remains (I lack a way to properly test that though).</p> <p>So... what am I doing wrong and how to fix it?</p> <p>Thank you!</p> <p><a href="https://i.stack.imgur.com/klwYJ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/klwYJ.png" alt="enter image description here"></a></p> <p>Many tutorials were used when making the code.</p> <pre> &#35;&#105;&#110;&#99;&#108;&#117;&#100;&#101;&#32;&#60;&#83;&#80;&#73;&#46;&#104;&#62;&#13;&#10;&#13;&#10;&#105;&#110;&#116;&#32;&#118;&#99;&#99;&#32;&#61;&#32;&#50;&#59;&#32;&#47;&#47;&#32;&#97;&#116;&#116;&#97;&#99;&#104;&#32;&#112;&#105;&#110;&#32;&#50;&#32;&#116;&#111;&#32;&#118;&#99;&#99;&#13;&#10;&#105;&#110;&#116;&#32;&#116;&#114;&#105;&#103;&#32;&#61;&#32;&#51;&#59;&#32;&#47;&#47;&#32;&#97;&#116;&#116;&#97;&#99;&#104;&#32;&#112;&#105;&#110;&#32;&#51;&#32;&#116;&#111;&#32;&#84;&#114;&#105;&#103;&#13;&#10;&#105;&#110;&#116;&#32;&#101;&#99;&#104;&#111;&#32;&#61;&#32;&#52;&#59;&#32;&#47;&#47;&#32;&#97;&#116;&#116;&#97;&#99;&#104;&#32;&#112;&#105;&#110;&#32;&#52;&#32;&#116;&#111;&#32;&#69;&#99;&#104;&#111;&#13;&#10;&#105;&#110;&#116;&#32;&#103;&#110;&#100;&#32;&#61;&#32;&#53;&#59;&#32;&#47;&#47;&#32;&#97;&#116;&#116;&#97;&#99;&#104;&#32;&#112;&#105;&#110;&#32;&#53;&#32;&#116;&#111;&#32;&#71;&#78;&#68;&#13;&#10;&#13;&#10;&#105;&#110;&#116;&#32;&#115;&#104;&#111;&#114;&#116;&#101;&#115;&#116;&#32;&#61;&#32;&#50;&#53;&#48;&#59;&#13;&#10;&#105;&#110;&#116;&#32;&#108;&#111;&#110;&#103;&#101;&#115;&#116;&#32;&#61;&#32;&#49;&#50;&#48;&#48;&#48;&#59;&#13;&#10;&#13;&#10;&#105;&#110;&#116;&#32;&#67;&#83;&#32;&#61;&#32;&#49;&#48;&#59;&#32;&#47;&#47;&#32;&#102;&#111;&#114;&#32;&#100;&#105;&#103;&#105;&#32;&#112;&#111;&#116;&#13;&#10;&#13;&#10;&#13;&#10;&#118;&#111;&#105;&#100;&#32;&#115;&#101;&#116;&#117;&#112;&#40;&#41;&#32;&#123;&#13;&#10;&#13;&#10;&#32;&#32;&#83;&#80;&#73;&#46;&#98;&#101;&#103;&#105;&#110;&#32;&#40;&#41;&#59;&#13;&#10;&#32;&#32;&#112;&#105;&#110;&#77;&#111;&#100;&#101;&#32;&#40;&#118;&#99;&#99;&#44;&#79;&#85;&#84;&#80;&#85;&#84;&#41;&#59;&#13;&#10;&#32;&#32;&#112;&#105;&#110;&#77;&#111;&#100;&#101;&#32;&#40;&#103;&#110;&#100;&#44;&#79;&#85;&#84;&#80;&#85;&#84;&#41;&#59;&#13;&#10;&#32;&#32;&#112;&#105;&#110;&#77;&#111;&#100;&#101;&#32;&#40;&#67;&#83;&#44;&#32;&#79;&#85;&#84;&#80;&#85;&#84;&#41;&#59;&#32;&#47;&#47;&#32;&#102;&#111;&#114;&#32;&#100;&#105;&#103;&#105;&#32;&#112;&#111;&#116;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#105;&#110;&#105;&#116;&#105;&#97;&#108;&#105;&#122;&#101;&#32;&#115;&#101;&#114;&#105;&#97;&#108;&#32;&#99;&#111;&#109;&#109;&#117;&#110;&#105;&#99;&#97;&#116;&#105;&#111;&#110;&#58;&#13;&#10;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#98;&#101;&#103;&#105;&#110;&#40;&#57;&#54;&#48;&#48;&#41;&#59;&#13;&#10;&#13;&#10;&#125;&#13;&#10;&#13;&#10;&#118;&#111;&#105;&#100;&#32;&#108;&#111;&#111;&#112;&#40;&#41;&#13;&#10;&#123;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#118;&#99;&#99;&#44;&#32;&#72;&#73;&#71;&#72;&#41;&#59;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#101;&#115;&#116;&#97;&#98;&#108;&#105;&#115;&#104;&#32;&#118;&#97;&#114;&#105;&#97;&#98;&#108;&#101;&#115;&#32;&#102;&#111;&#114;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#111;&#102;&#32;&#116;&#104;&#101;&#32;&#112;&#105;&#110;&#103;&#44;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#97;&#110;&#100;&#32;&#116;&#104;&#101;&#32;&#100;&#105;&#115;&#116;&#97;&#110;&#99;&#101;&#32;&#114;&#101;&#115;&#117;&#108;&#116;&#32;&#105;&#110;&#32;&#105;&#110;&#99;&#104;&#101;&#115;&#32;&#97;&#110;&#100;&#32;&#99;&#101;&#110;&#116;&#105;&#109;&#101;&#116;&#101;&#114;&#115;&#58;&#13;&#10;&#32;&#32;&#108;&#111;&#110;&#103;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#59;&#13;&#10;&#32;&#32;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#84;&#104;&#101;&#32;&#80;&#73;&#78;&#71;&#41;&#41;&#41;&#32;&#105;&#115;&#32;&#116;&#114;&#105;&#103;&#103;&#101;&#114;&#101;&#100;&#32;&#98;&#121;&#32;&#97;&#32;&#72;&#73;&#71;&#72;&#32;&#112;&#117;&#108;&#115;&#101;&#32;&#111;&#102;&#32;&#50;&#32;&#111;&#114;&#32;&#109;&#111;&#114;&#101;&#32;&#109;&#105;&#99;&#114;&#111;&#115;&#101;&#99;&#111;&#110;&#100;&#115;&#46;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#71;&#105;&#118;&#101;&#32;&#97;&#32;&#115;&#104;&#111;&#114;&#116;&#32;&#76;&#79;&#87;&#32;&#112;&#117;&#108;&#115;&#101;&#32;&#98;&#101;&#102;&#111;&#114;&#101;&#104;&#97;&#110;&#100;&#32;&#116;&#111;&#32;&#101;&#110;&#115;&#117;&#114;&#101;&#32;&#97;&#32;&#99;&#108;&#101;&#97;&#110;&#32;&#72;&#73;&#71;&#72;&#32;&#112;&#117;&#108;&#115;&#101;&#58;&#13;&#10;&#32;&#32;&#112;&#105;&#110;&#77;&#111;&#100;&#101;&#40;&#116;&#114;&#105;&#103;&#44;&#32;&#79;&#85;&#84;&#80;&#85;&#84;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#116;&#114;&#105;&#103;&#44;&#32;&#76;&#79;&#87;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#101;&#108;&#97;&#121;&#77;&#105;&#99;&#114;&#111;&#115;&#101;&#99;&#111;&#110;&#100;&#115;&#40;&#50;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#116;&#114;&#105;&#103;&#44;&#32;&#72;&#73;&#71;&#72;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#101;&#108;&#97;&#121;&#77;&#105;&#99;&#114;&#111;&#115;&#101;&#99;&#111;&#110;&#100;&#115;&#40;&#53;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#116;&#114;&#105;&#103;&#44;&#32;&#76;&#79;&#87;&#41;&#59;&#13;&#10;&#32;&#32;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#84;&#104;&#101;&#32;&#115;&#97;&#109;&#101;&#32;&#112;&#105;&#110;&#32;&#105;&#115;&#32;&#117;&#115;&#101;&#100;&#32;&#116;&#111;&#32;&#114;&#101;&#97;&#100;&#32;&#116;&#104;&#101;&#32;&#115;&#105;&#103;&#110;&#97;&#108;&#32;&#102;&#114;&#111;&#109;&#32;&#116;&#104;&#101;&#32;&#80;&#73;&#78;&#71;&#41;&#41;&#41;&#58;&#32;&#97;&#32;&#72;&#73;&#71;&#72;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#112;&#117;&#108;&#115;&#101;&#32;&#119;&#104;&#111;&#115;&#101;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#105;&#115;&#32;&#116;&#104;&#101;&#32;&#116;&#105;&#109;&#101;&#32;&#40;&#105;&#110;&#32;&#109;&#105;&#99;&#114;&#111;&#115;&#101;&#99;&#111;&#110;&#100;&#115;&#41;&#32;&#102;&#114;&#111;&#109;&#32;&#116;&#104;&#101;&#32;&#115;&#101;&#110;&#100;&#105;&#110;&#103;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#111;&#102;&#32;&#116;&#104;&#101;&#32;&#112;&#105;&#110;&#103;&#32;&#116;&#111;&#32;&#116;&#104;&#101;&#32;&#114;&#101;&#99;&#101;&#112;&#116;&#105;&#111;&#110;&#32;&#111;&#102;&#32;&#105;&#116;&#115;&#32;&#101;&#99;&#104;&#111;&#32;&#111;&#102;&#102;&#32;&#111;&#102;&#32;&#97;&#110;&#32;&#111;&#98;&#106;&#101;&#99;&#116;&#46;&#13;&#10;&#32;&#32;&#112;&#105;&#110;&#77;&#111;&#100;&#101;&#40;&#101;&#99;&#104;&#111;&#44;&#73;&#78;&#80;&#85;&#84;&#41;&#59;&#13;&#10;&#32;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#61;&#32;&#112;&#117;&#108;&#115;&#101;&#73;&#110;&#40;&#101;&#99;&#104;&#111;&#44;&#32;&#72;&#73;&#71;&#72;&#41;&#59;&#13;&#10;&#13;&#10;&#32;&#32;&#105;&#102;&#32;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#62;&#32;&#50;&#48;&#48;&#32;&#38;&#38;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#60;&#32;&#50;&#50;&#48;&#41;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#76;&#105;&#109;&#105;&#116;&#105;&#110;&#103;&#32;&#111;&#117;&#116;&#32;&#97;&#110;&#32;&#117;&#110;&#119;&#97;&#110;&#116;&#101;&#100;&#44;&#32;&#114;&#97;&#110;&#100;&#111;&#109;&#108;&#121;&#32;&#97;&#112;&#112;&#101;&#97;&#114;&#105;&#110;&#103;&#32;&#100;&#105;&#115;&#116;&#97;&#110;&#99;&#101;&#32;&#109;&#101;&#97;&#115;&#117;&#114;&#101;&#109;&#101;&#110;&#116;&#13;&#10;&#32;&#32;&#47;&#47;&#32;&#109;&#97;&#100;&#101;&#32;&#117;&#115;&#101;&#108;&#101;&#115;&#115;&#32;&#98;&#121;&#32;&#108;&#97;&#116;&#101;&#114;&#32;&#99;&#111;&#100;&#101;&#32;&#116;&#104;&#111;&#117;&#103;&#104;&#13;&#10;&#32;&#32;&#32;&#32;&#123;&#13;&#10;&#32;&#32;&#32;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#112;&#114;&#105;&#110;&#116;&#40;&#34;&#69;&#114;&#114;&#111;&#114;&#32;&#34;&#41;&#59;&#13;&#10;&#32;&#32;&#32;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#112;&#114;&#105;&#110;&#116;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#41;&#59;&#13;&#10;&#32;&#32;&#32;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#112;&#114;&#105;&#110;&#116;&#40;&#34;&#92;&#110;&#34;&#41;&#59;&#13;&#10;&#32;&#32;&#32;&#32;&#13;&#10;&#32;&#32;&#32;&#32;&#32;&#114;&#101;&#116;&#117;&#114;&#110;&#59;&#13;&#10;&#32;&#32;&#32;&#32;&#125;&#13;&#10;&#13;&#10;&#32;&#32;&#32;&#47;&#47;&#32;&#67;&#111;&#109;&#112;&#114;&#101;&#115;&#115;&#105;&#110;&#103;&#32;&#116;&#104;&#101;&#32;&#114;&#101;&#115;&#117;&#108;&#116;&#32;&#111;&#102;&#32;&#116;&#104;&#101;&#32;&#100;&#105;&#115;&#116;&#97;&#110;&#99;&#101;&#32;&#109;&#101;&#97;&#115;&#117;&#114;&#101;&#109;&#101;&#110;&#116;&#32;&#105;&#110;&#116;&#111;&#32;&#116;&#104;&#101;&#32;&#115;&#99;&#97;&#108;&#101;&#32;&#111;&#102;&#32;&#48;&#32;&#45;&#32;&#49;&#50;&#56;&#13;&#10;&#32;&#32;&#105;&#102;&#32;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#60;&#32;&#115;&#104;&#111;&#114;&#116;&#101;&#115;&#116;&#41;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#61;&#32;&#115;&#104;&#111;&#114;&#116;&#101;&#115;&#116;&#59;&#13;&#10;&#32;&#32;&#105;&#102;&#32;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#62;&#32;&#108;&#111;&#110;&#103;&#101;&#115;&#116;&#41;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#61;&#32;&#108;&#111;&#110;&#103;&#101;&#115;&#116;&#59;&#13;&#10;&#32;&#32;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#61;&#32;&#40;&#49;&#46;&#48;&#102;&#45;&#40;&#40;&#102;&#108;&#111;&#97;&#116;&#41;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#32;&#45;&#32;&#115;&#104;&#111;&#114;&#116;&#101;&#115;&#116;&#41;&#32;&#47;&#32;&#40;&#102;&#108;&#111;&#97;&#116;&#41;&#40;&#108;&#111;&#110;&#103;&#101;&#115;&#116;&#32;&#45;&#32;&#115;&#104;&#111;&#114;&#116;&#101;&#115;&#116;&#41;&#41;&#41;&#32;&#42;&#32;&#49;&#50;&#56;&#59;&#13;&#10;&#32;&#32;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#67;&#83;&#44;&#32;&#76;&#79;&#87;&#41;&#59;&#13;&#10;&#32;&#32;&#83;&#80;&#73;&#46;&#116;&#114;&#97;&#110;&#115;&#102;&#101;&#114;&#40;&#48;&#41;&#59;&#32;&#47;&#47;&#32;&#48;&#120;&#48;&#49;&#32;&#97;&#110;&#100;&#32;&#48;&#120;&#48;&#52;&#32;&#115;&#101;&#101;&#109;&#32;&#116;&#111;&#32;&#34;&#119;&#111;&#114;&#107;&#34;&#32;&#116;&#111;&#111;&#46;&#32;&#87;&#105;&#116;&#104;&#32;&#48;&#120;&#49;&#49;&#32;&#97;&#110;&#100;&#32;&#48;&#120;&#48;&#56;&#32;&#110;&#111;&#32;&#118;&#111;&#108;&#116;&#97;&#103;&#101;&#32;&#103;&#111;&#101;&#115;&#32;&#116;&#104;&#114;&#111;&#117;&#103;&#104;&#13;&#10;&#32;&#32;&#83;&#80;&#73;&#46;&#116;&#114;&#97;&#110;&#115;&#102;&#101;&#114;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#41;&#59;&#32;&#47;&#47;&#32;&#115;&#101;&#110;&#100;&#105;&#110;&#103;&#32;&#97;&#32;&#110;&#117;&#109;&#98;&#101;&#114;&#32;&#102;&#114;&#111;&#109;&#32;&#48;&#32;&#116;&#111;&#32;&#49;&#50;&#56;&#32;&#116;&#111;&#32;&#116;&#104;&#101;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#32;&#112;&#111;&#116;&#101;&#110;&#116;&#105;&#111;&#109;&#101;&#116;&#101;&#114;&#13;&#10;&#32;&#32;&#100;&#105;&#103;&#105;&#116;&#97;&#108;&#87;&#114;&#105;&#116;&#101;&#40;&#67;&#83;&#44;&#32;&#72;&#73;&#71;&#72;&#41;&#59;&#13;&#10;&#32;&#32;&#13;&#10;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#112;&#114;&#105;&#110;&#116;&#40;&#100;&#117;&#114;&#97;&#116;&#105;&#111;&#110;&#41;&#59;&#32;&#47;&#47;&#32;&#112;&#114;&#105;&#110;&#116;&#105;&#110;&#103;&#32;&#116;&#104;&#101;&#32;&#114;&#101;&#115;&#117;&#108;&#116;&#32;&#111;&#102;&#32;&#116;&#104;&#101;&#32;&#109;&#101;&#97;&#115;&#117;&#114;&#101;&#109;&#101;&#110;&#116;&#32;&#97;&#110;&#100;&#32;&#99;&#97;&#108;&#99;&#117;&#108;&#97;&#116;&#105;&#111;&#110;&#115;&#13;&#10;&#32;&#32;&#83;&#101;&#114;&#105;&#97;&#108;&#46;&#112;&#114;&#105;&#110;&#116;&#40;&#34;&#92;&#110;&#34;&#41;&#59;&#13;&#10;&#13;&#10;&#32;&#32;&#100;&#101;&#108;&#97;&#121;&#40;&#49;&#48;&#48;&#41;&#59;&#13;&#10;&#125; </pre>
<p>Digital potentiometers are not a good choice for controlling the speed of a motor. They are designed only for very low current applications - things like setting offset points for op-amps and things like that - things where you would use a small trimmer pot rather than a large power <em>rheostat</em>.</p> <p>Instead you should be controlling the motor using PWM and a transistor (<a href="http://www.circuitstoday.com/pwm-generation-and-control-using-arduino" rel="nofollow noreferrer">here is a good tutorial</a>).</p> <p>But to help you understand the digital potentiometer and so you can work with it better:</p> <p>Step one is always to read <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/11195c.pdf" rel="nofollow noreferrer">the datasheet</a>. That details the SPI communication protocol for you so you can know what numbers mean what.</p> <p>In this case the protocol is made up of two bytes - a command byte and a data byte.</p> <p>The command byte is made up like this:</p> <p><a href="https://i.stack.imgur.com/2gUGj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2gUGj.png" alt="enter image description here"></a></p> <p>As you can see it's in two parts - a command and a potentiometer selector. So to set the resistance of potentiometer 0 you would need to craft a command byte that had the write command and the code for potentiometer 0. That would be <code>0b00010001</code> or 0x11 in hex. So your transaction would look like:</p> <pre><code>digitalWrite(CS, LOW); SPI.transfer(0x11); SPI.transfer(duration); digitalWrite(CS, HIGH); </code></pre> <p>Another important part of the datasheet is the electrical characteristics. That is a table that tells you the minimum, typical and/or maximum values for different parameters. One important one here is the <em>wiper current</em> which it states as being allowed between -1mA and +1mA. That is the maximum current you are allowed to draw through the digital potentiometer before you risk damaging it. That is why it's not good for powering things like motors, no matter how small.</p>
19966
|c++|arduino-nano|spi|shift-register|icsp|
Arduino Nano, ICSP header and 595 Shift register
2016-01-25T22:12:08.497
<p>I'm trying to control a 4-digit 7 segment display with an Arduino Nano, but I'm getting something wrong. I'm using the ICSP header to interface with a 74HC595 Shift Register which is then connected to the display. I've tested and retested the connections and everything seems to be alright, however the shift register doesn't have the desired output, and I notice it only shifs one single bit when I press the reset button on the arduino board.</p> <pre><code>74HC595 | A. Nano DS &lt;-----&gt; MOSI (ICSP) SH_CP &lt;-----&gt; SCK (ICSP) ST_CP &lt;-----&gt; D6 MR &lt;-----&gt; 5V (ICSP) OE &lt;-----&gt; GND (ICSP) VDD &lt;-----&gt; 5V (ICSP) GND &lt;-----&gt; GND (ICSP) </code></pre> <p>My code:</p> <pre><code>//pin connected to STCP const int latchPin = 6; //pin connected to SHCP const int clockPin = 17; //pin connected to DS (MOSI) const int dataPin = 11; byte val=0; void setup() { // put your setup code here, to run once: //SPI pins are output pinMode(latchPin,OUTPUT); pinMode(clockPin,OUTPUT); pinMode(dataPin,OUTPUT); pinMode(3,OUTPUT); updateRegister(0); } void loop() { // put your main code here, to run repeatedly: digitalWrite(3,HIGH); for (int i=0; i&lt;8; i++) { updateRegister(); delay(500); } } void updateRegister() { //pull latch low to write new bits to the register digitalWrite(latchPin,LOW); //shift out the data shiftOut(dataPin,clockPin,LSBFIRST,val); //pull latch pin high so that the leds light up digitalWrite(latchPin,HIGH); } </code></pre>
<p><code>const int clockPin = 17;</code></p> <p>I'm pretty sure that should be 13, not 17.</p>
19967
|analogread|
Analog Pins are sensing Values
2016-01-25T22:23:00.170
<p>I used the example code AnalogReadSerial and tried it on all analog pins from A0 to A7. None of the analog pins were connected to anything so I expectedy to get 0 in the serial monitor. But as it turns out, I was wrong. Only pin A7 shows 0 to 19 values on the serial monitor. The rest have values ranging from 100 to 300 for pins A2, A3, A4, A5 and A6. The worst performers are A1 and A0 with values from 921 to 1023 showing on the serial monitor. What is the cause of this and how will I fix it?</p>
<p>The ADC is multiplexed across the pins, and will carry a small charge from pin to pin. If you want them to be zero, tie them to ground. </p> <p>This answer, <a href="https://arduino.stackexchange.com/a/575/6628">https://arduino.stackexchange.com/a/575/6628</a> , suggests pulling them to ground for higher accuracy.</p>
19971
|serial|baud-rate|
Converting data between baud rates
2016-01-25T23:44:47.663
<p>This isn't strictly limited to Arduino but I spend a lot of time with serial devices on my Arduino and I'm sure that others do as well: </p> <p>Here goes..</p> <p>Let's say a device sends three characters [ABC] via serial at 9600 8N1.</p> <p>And let's also say the device receiving the data only knows that it's serial stream and 8N1 but does not know the baud.</p> <p>The receiving device would need to take a guess at the baud and so probably get it wrong. It would therefore receive weird characters.</p> <p>Is there anyway/anything around that a user could paste the strange characters into that would reverse engineer (from the bit stream) to give the correct baud and hence correct ascii characters [ABC]?</p>
<p>In the days of dumb terminals and time sharing systems, setting the baud rate was accomplished by the terminal sending a pre-determined series of characters with gaps between them and the host changing its baud rate and looking for the expected data. It is best to start at a high baud rate and drop the rate between tries.</p> <p>For example the terminal user would hit Enter repeadedly and the host would try decreasing baud rates until it saw the Carriage Return character. When it saw the CR, it would respond with "Login Please" and you would know you were good to go.</p>
19985
|arduino-ide|esp8266|nodemcu|
ESP8266, Arduino IDE vs Lua?
2016-01-26T16:03:28.863
<p>I'm planning to buy an ESP8266. Do I really need to learn Lua to play with it? I have seen some people using it with the standard Arduino IDE.</p> <p>Do you need a custom firmware to use the Arduino IDE instead of Lua?</p> <p>The Arduino IDE seems better for me because I already know the syntax. Is there any downside to using the Arduino IDE instead of NodeMCU with Lua?</p>
<p>Sorry for bumping, but this thread helped me to decide for Arduino IDE.</p> <p>I started with Arduino IDE but couldn't get it to work with ESP-07. Moved on to NodeMCU and Lua with Esplorer. Took me a while to get it working there also due to the odd bootloader baud rate. First it seemed so easy to set up a WEB-server, but problem was that all the examples found were based on an ancient FW 0.96, and trying with the latest 2.1 didn't work at all. So realising that people hadn't done much with newer FW gave me second thoughts.</p> <p>Now with Arduino IDE things start to work the way they should! :)</p>
19988
|arduino-uno|esp8266|
Both red and blue led of ESP8266 stays on
2016-01-26T18:31:39.540
<p>I've connected ESP8266 to Arduino UNO. After a getting a huge trouble I successfully managed to run some AT commands. I have also tested AP mode.</p> <p>Then I got some trouble with software serial communication with Arduino and decided to change baud-rate to 9600 (previously it was 115200).</p> <p>I used <code>AT+IPR=9600</code> command to change it.</p> <p>After that blue led of esp stays on and not taking AT commands any more, but output some gibberish to serial monitor with few ascii text like below:</p> <pre><code>ets Jan 8 2013,rst cause:4, boot mode:(3,6) wdt reset 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 : DIO SPI Flash Size &amp; Map: 8Mbit(512KB+512KB) jump to run user1 @ 1000 </code></pre> <p>Note: I know it consumes a lot power tried external 3.3V power supply and voltage divider for rx pin.</p> <p>Any help would be appreciated. </p>
<p>If you have too, you can find the firmware for the ESP8266 <a href="https://github.com/espressif/esp8266_at/tree/master/bin" rel="nofollow">here</a> and re-flash it.</p> <p>There's some good info <a href="http://bbs.espressif.com/download/file.php?id=84" rel="nofollow">here</a> about the instruction set.</p> <p>With respect to your issue of the blue (traffic) light staying on, I can't imagine that the baud command would have caused an issue. Perhaps you need to double check your circuit and make sure that the Rx pin of the ESP8266 is not being held high.</p> <p>What happens with only 3.3V and GND connected to the ESP8266?</p> <p>Also the output you're getting is similar to the output from “AT+GMR”. Are you sending it that in a loop by chance?</p>
19996
|oscillator-clock|
What is the relation between Arduino's clock and possible VGA resolution?
2016-01-27T01:10:45.653
<p>I have seen it said over and over (in different places) that in order to achieve 640x480 resolution out to a DB15 VGA connection, the arduino would need to be clocked at 25Mhz or that at half resolution it would need to be clocked at 12.5Mhz. </p> <p>What is the relation between resolution and internal clock? I would expect that so long we can feed the signal fast enough that would be enough.</p>
<p>I doubt if that would be fast enough. See <a href="http://www.gammon.com.au/forum/?id=11608" rel="nofollow noreferrer">my thread about connecting to a VGA monitor</a>.</p> <p>Borrowing from that page, so as to not make a link-only answer ...</p> <hr> <p>For 640x480 pixels of active video you have something like this:</p> <p><a href="https://i.stack.imgur.com/tGTx3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tGTx3.png" alt="Video timing diagram"></a></p> <hr> <h2>Vertical Sync</h2> <p>Let's start with the vertical sync pulses. In fact, we'll show how all the timing data can be derived from three figures:</p> <ul> <li>The screen refresh rate (eg. 60 Hz)</li> <li>The screen resolution (eg. 640 x 480)</li> </ul> <p>So what is the refresh rate? It's the rate at which the entire screen is redrawn. If you ever looked at Windows screen resolution you probably saw something like this:</p> <p><a href="https://i.stack.imgur.com/cxDIR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cxDIR.png" alt="Refresh rate"></a></p> <p>That's the refresh rate: 60 Hz (60 times a second). This figure was probably originally chosen because it is the mains frequency in the USA, so that would minimize the artifact of mains hum bars appearing on the screen, in the days of CRT monitors.</p> <p>The other figure of interest is the screen resolution.</p> <p>In our case we are going for the minimum we can (640 x 480) and seeing where those figures lead us.</p> <p>Starting with the refresh rate, a 60 Hz refresh rate will require a "vertical sync" pulse 60 times a second, or a period of 1/60 (16.66 ms).</p> <hr> <h2>Generating vertical sync pulses</h2> <p>This code in my VGA output sketch generates the vertical sync pulses:</p> <pre class="lang-C++ prettyprint-override"><code> // Timer 1 - vertical sync pulses pinMode (vSyncPin, OUTPUT); Timer1::setMode (15, Timer1::PRESCALE_1024, Timer1::CLEAR_B_ON_COMPARE); OCR1A = 259; // 16666 / 64 uS = 260 (less one) OCR1B = 0; // 64 / 64 uS = 1 (less one) </code></pre> <p>The clock period is 62.5 ns (1/16000000). By applying a prescaler of 1024 the timer counts up once every 64 µs. So to get a period of 1/60 of a second (16666 µs) we need to count up to 260 (16666 / 64 = 260). Since the timer counts are zero-relative we set OCR1A to count up to 259. This sets the frequency of Timer 1.</p> <p>Then we need to set the pulse width by putting the correct value in OCR1B. We want a pulse width of two lines. One line is 1 / 60 / 525, namely 31.7 µs. So two lines would be 63.4 µs. This is close enough to exactly one timer count (64 µs). So OCR1B is set to zero (being zero-relative, making it zero gives a count of 1).</p> <p>Timer 1 is configured to "clear B on compare" which effectively means that it toggles the output pin (D10 on the Uno) so it is high for the duty cycle width (64 µs) and low the rest of the time. If you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.</p> <p>The timer is also set up to generate an interrupt, which is used to tell the code that we are starting another vertical cycle, by setting the line count to zero:</p> <pre class="lang-C++ prettyprint-override"><code>ISR (TIMER1_OVF_vect) { vLine = 0; messageLine = 0; backPorchLinesToGo = verticalBackPorchLines; } // end of TIMER1_OVF_vect </code></pre> <hr> <h2>Horizontal sync</h2> <p>Horizontal sync pulses tell the monitor when to start drawing each line.</p> <p>To calculate the horizontal sync frequency we need to divide the overall frame rate (60 Hz) by the number of total lines (525 if you count the sync pulse itself, and the front and back porches).</p> <p>In other words:</p> <pre class="lang-C++ prettyprint-override"><code> (1/60) / 525 * 1e6 = 31.74 µs </code></pre> <p>We also need to know the sync pulse width. That is documented to be 96 pixels, so we need to know the width of one pixel. That would be the figure above, divided by 800 (being the total screen width including the sync pulse, and front and back porches).</p> <p>Thus that is:</p> <pre class="lang-C++ prettyprint-override"><code>((1/60) / 525 * 1e9) / 800 = 39.68 ns 1 / (((1/60) / 525 * 1e6) / 800) = 25.2 MHz </code></pre> <p>So our pixel width is 39.68 ns and the pixel clock is 25.2 mHz.</p> <p>The horizontal sync pulse width is 96 pixels, so we want a pulse of:</p> <pre class="lang-C++ prettyprint-override"><code>96 * 39.68 ns = 3.8 µs </code></pre> <hr> <h2>Generating horizontal sync pulses</h2> <p>Now we are ready to set up the timer for the horizontal sync pulses:</p> <pre class="lang-C++ prettyprint-override"><code> // Timer 2 - horizontal sync pulses pinMode (hSyncPin, OUTPUT); Timer2::setMode (7, Timer2::PRESCALE_8, Timer2::CLEAR_B_ON_COMPARE); OCR2A = 63; // 32 / 0.5 µs = 64 (less one) OCR2B = 7; // 4 / 0.5 µs = 8 (less one) </code></pre> <p>The clock period is 62.5 ns (1/16000000). By applying a prescaler of 8 the timer counts up once every 0.5 µs. So to get a period of 32 µs we need to count up to 64 (32 / 0.5 = 64). Since the timer counts are zero-relative we set OCR2A to count up to 63. This sets the frequency of Timer 2.</p> <p>Then we need to set the pulse width by putting the correct value in OCR2B. We want a pulse width of 96 pixels (3.8 µs). So OCR2B is set to 7 (being zero-relative, making it 7 gives a count of 8, which is 4 / 0.5).</p> <p>Again, if you wanted the opposite sync pulse polarity, change CLEAR_B_ON_COMPARE to SET_B_ON_COMPARE.</p> <p>The timer is also set up to generate an interrupt, which has the sole purpose of waking the processor up from sleep, so it can draw each line with exactly the same delay after the pulse. If it wasn't asleep, there would be a variation of two to three clock cycles (since an interrupt cannot occur during a single instruction) and this gives very bad-looking "jitter" on the screen.</p> <pre class="lang-C++ prettyprint-override"><code>ISR (TIMER2_OVF_vect) { } // end of TIMER2_OVF_vect </code></pre> <hr> <h2>Pixel data</h2> <p>Now things get tricky ...</p> <p>Let's see how long we have to draw 640 pixels:</p> <pre class="lang-C++ prettyprint-override"><code>((1/60) / 525 * 1e9) / 800 * 640 = 25396.82 ns (25.39 µs) </code></pre> <p>It just can't be done on this processor. The clock period itself is only 62.5 ns, so there is no way we can output a pixel every 39.68 ns (that is: 25396.82 / 640 = 39.68).</p> <p>The fastest way we can get bits "out the door" is using the SPI hardware. That can run at a maximum clock rate of twice the system clock, that is, one pixel every 125 ns. So we will have to settle for having the pixels 4 times as wide. A horizontal resolution therefore of 160 pixels. Since we will display 8-pixel characters, that gives us 20 characters per line.</p> <hr> <h2>Summary</h2> <p>Even at 25 MHz processor speed (which exceeds its spec) you won't be able to clock out pixels fast enough for 640 pixel width (since the fastest SPI speed is half the processor clock speed).</p> <hr> <blockquote> <p>I would expect that so long we can feed the signal fast enough that would be enough.</p> </blockquote> <p>That's the tricky bit. To output data you have to do more than merely send it. You have to read it from memory, so it would take a least a couple of clock cycles to do that.</p> <hr> <h2>Example of working at that resolution</h2> <p>A screen shot of my sketch in action (160 characters wide - 640 pixels and 30 characters high - 480 pixels, which is 16 pixels each as they were "doubled" in height to make them look in proportion). The font data was 8x8 pixels, and thus they appear as 16x16 on the screen.</p> <p><a href="https://i.stack.imgur.com/SC5PU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SC5PU.jpg" alt="Example VGA output"></a></p> <hr> <blockquote> <p>So does that mean that there really isn't a direct relation between clock speed and resolution? Other than, the clock must be faster than this</p> </blockquote> <p>To work even at that speed the processor speed needs to be a multiple of the VGA clock, or close enough for the monitor to accept. (Looking at my figures the pixel rate is not in fact a multiple of 39.68 ns, so I am guessing that my monitor was able to adjust).</p> <p>You could get better results by having a system clock which was an exact multiple of 39.68 ns (around 25 MHz - precisely 25.201613 MHz) - which is what you suggested in the question. However that just gives more accurate timing, you would still get similar resolution to what I show here.</p> <p>So yes, to work on more monitors you should have a direct relation between clock speed and resolution.</p> <p>I seem to have a 25.175 MHz crystal in my parts drawer, so perhaps I experimented with this a while back. Of course, you have to recalculate the other timings if you use that, and the processor is running out of spec.</p>
20000
|arduino-uno|motor|adafruit|arduino-motor-shield|
Why is my Adafruit motor shield not spinning my motors?
2016-01-27T04:00:20.803
<p>I'm using the Adafruit Motor Shield v2.3. I'm powering the Arduino with a USB cable and I'm powering the motor shield with a 9 volt battery.</p> <p>I removed the vin pin, and I'm using <a href="https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/install-software" rel="noreferrer">this</a> tutorial/code to make the DC motor spin.</p> <p>I've tried 3 different kinds of DC motors, but none of them will do anything. The Arduino works for normal sketches, like lighting up LEDs, but I can't get the motors to work.</p> <p>Any ideas?</p> <p>Edit: I'm using Adafruit's "Motor Test" code from the Motor Shield v2 library, as shown below. The motor is on port 1.</p> <pre><code>// Adafruit Motor shield library // copyright Adafruit Industries LLC, 2009 // this code is public domain, enjoy! #include &lt;AFMotor.h&gt; AF_DCMotor motor(4); void setup() { Serial.begin(9600); // set up Serial library at 9600 bps Serial.println("Motor test!"); // turn on motor motor.setSpeed(200); motor.run(RELEASE); } void loop() { uint8_t i; Serial.print("tick"); motor.run(FORWARD); for (i=0; i&lt;255; i++) { motor.setSpeed(i); delay(10); } for (i=255; i!=0; i--) { motor.setSpeed(i); delay(10); } Serial.print("tock"); motor.run(BACKWARD); for (i=0; i&lt;255; i++) { motor.setSpeed(i); delay(10); } for (i=255; i!=0; i--) { motor.setSpeed(i); delay(10); } Serial.print("tech"); motor.run(RELEASE); delay(1000); } </code></pre> <p><a href="https://i.stack.imgur.com/NqNqb.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/NqNqb.jpg" alt="enter image description here"></a></p>
<p>I see that this is still not working even with a proper battery. My next best guess is you need to update your library:</p> <blockquote> <pre><code>// Adafruit Motor shield library // copyright Adafruit Industries LLC, 2009 // this code is public domain, enjoy! #include &lt;AFMotor.h&gt; </code></pre> </blockquote> <p>Judging by <code>2009</code> and <code>AFMotor.h</code> you have a copy of an old version of the library. I recommend getting the <a href="https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library" rel="nofollow">latest version</a> and following the <a href="https://learn.adafruit.com/adafruit-motor-shield-v2-for-arduino/using-dc-motors" rel="nofollow">official tutorial</a>.</p>
20003
|threads|
mthread and multiple header files
2016-01-27T07:16:09.950
<p>I'm using mthreads (<a href="https://github.com/jlamothe/mthread" rel="nofollow">https://github.com/jlamothe/mthread</a>) for my arduino. But now as the project is getting bigger, it would make sense to break it up in several files.</p> <p>I successfully outsourced already a part which is not threaded. But somehow I cannot make up my mind how to use mthread in conjunction with several header files. </p> <p>here is what I got: </p> <p>main: call header:</p> <pre><code>#include "tcan.h" </code></pre> <p>tcan.h:</p> <pre><code>#ifndef tcan_h #define tcan_h #include "Arduino.h" class tcan : public Thread { public: tcan(); protected: bool loop(); private: }; #endif </code></pre> <p>tcan.cpp</p> <pre><code>#include "Arduino.h" #include "tcan.h" #include &lt;mcp_can.h&gt; bool tcan::loop() { // lala return true; } </code></pre> <p>but I get an error when compiling:</p> <blockquote> <p>tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {</p> </blockquote> <p>Thanks in advance</p>
<p>The compiler error is due to that the compiler does not know what Thread is.</p> <blockquote> <p>tcan.h:6:28: error: expected class-name before '{' token class tcan : public Thread {</p> </blockquote> <p>The issue is that the header file is not complete. <strong>A good practice is to include all header files that are needed to read the header file.</strong> As <em>Thread</em> is defined in <em>mthread.h</em> the <em>tcan.h</em> file should be: </p> <pre><code>#ifndef tcan_h #define tcan_h #include &lt;mthread.h&gt; class tcan : public Thread { public: tcan(); protected: bool loop(); private: }; #endif </code></pre> <p>Cheers!</p>
20006
|arduino-nano|remote-control|android|
Can Android phone can be used instead of( or with) Arduino as controller?
2016-01-27T08:23:13.790
<p>I am Android application developer and I want to modify regular toy RC car which can be controlled by Android phone. I want to use 2 Android phones: 1 as remote controller, 1 as controller in RC car. I want to use sensors like GPS, Mobile network, Wifi in RC car in RC car side. I want to know: can I use Android phone as controller in RC car. I am thinking about 2 options:</p> <ol> <li>phone as controller (without arduino) - this option would be the best </li> <li>if phone cannot give commands maybe with arduino, while using phone's sensors like gps, mobile network, wifi, bluetooth</li> </ol> <p>Is this possible? If yes, what tools I should use to connect?</p>
<p>You cannot directly control your RC car using and Android phone if you are talking about a normal RC car. If you have an RC car that can be already connected via bluetooth this is another story.</p> <p>So for normal RC car you would need to have:</p> <p>AndroidPhone -> Network -> AndroidPhone -> SerialInterface -> Arduino -> RC</p>
20015
|arduino-uno|relay|
How to switch on 32A/240VAC with Arduino?
2016-01-27T14:08:58.223
<p>I have an air conditioner switch rated at 32A/240V AC - how do I turn this on using Arduino and Relay.</p> <p>I'm based in India and I am unable to find a relay switch rated higher than <a href="http://www.amazon.in/Channel-Module-Shield-Arduino-Electronic/dp/B00C59NOHK/ref=pd_sim_sbs_147_6?ie=UTF8&amp;dpID=51amkYDfw4L&amp;dpSrc=sims&amp;preST=_AC_UL160_SR160%2C160_&amp;refRID=1DYV10685X37A49WG5NV" rel="nofollow">this</a>.</p> <p>I don't want to try anything that results in a fire hazard. My aim is to switch on the AC with my mobile phone. I'm using Arduino Uno with a 2.4GHz transceiver for communication.</p>
<p>Just go with a solid state relay: you can search on ebay for SSR-40DA (240V, 40A, from China around 4$) or, better, SSR-100DA (240V, 100A, from China around 6$). For 32A you should definitely mount it on an heatsink (they sell quite a lot of them on ebay).</p> <p>The main advantage of that kind of SSR is that you can command them directly from the arduino. No transistors, no limiting resistors, just connect the ground and the pin and you are done.</p> <p>With a relay my arduino halted often (probably because of the 5V-12V boost, but it was necessary to drive the 12V relay). In the end I switched to an SSR and... Works like a charm. And since it is quite cheap I suggest you to use it.</p>
20018
|rfid|
How to emulate an RFID tag with the RC522
2016-01-27T15:48:03.587
<p>Is it possible to emulate an RFID tag with the <a href="http://playground.arduino.cc/Learning/MFRC522" rel="nofollow">RC522</a>? (Spec sheet: <a href="http://www.nxp.com/documents/data_sheet/MFRC522.pdf" rel="nofollow">nxp MFRC522.pdf</a>)<br> I want the RC522 to act like a NTAG213 nxp.com/documents/data_sheet/NTAG213_215_216.pdf and to be read/write by other readers/writers.<br> Are there libraries for that purpose?</p>
<p>No. Looking at the datasheet, card emulation is not a feature provided by the RC522.</p> <p>Another popular chip, the <a href="https://www.adafruit.com/datasheets/pn532ds.pdf" rel="nofollow">PN532</a>, does seem to indicate support for that feature, however, looking at the most popular <a href="https://github.com/adafruit/Adafruit-PN532" rel="nofollow">library for this chip</a> from Adafruit, it does not implement this feature. Another <a href="https://github.com/Seeed-Studio/PN532" rel="nofollow">library</a> from Seeed, does seem to implement it, but it looks rather limited as to which cards can be emulated, and the library itself hasn't been updated in a while.</p>
20025
|programming|
How can Arduino know that the number in a variable is a pin number and not something else?
2016-01-27T20:09:07.147
<p>I have a question with the topic <em>variables</em>.</p> <p>So, a variable is a place where you can store data. </p> <p>And when you make a variable with datatype int (<code>int ledpin=13;</code>) then you store a value 10 in a variable named <code>ledpin</code>.</p> <p>BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?</p>
<blockquote> <p>BUT how can the Arduino know it's a pin number 13 from Arduino or a random number 13 that we are storing there?</p> </blockquote> <p>The Arduino does not "know" the intention of a variable. The variable "becomes" a pin number when passed as an argument to pinMode() or digitalRead(). </p> <p>The use of a variable to "name" a pin is part of a programming style. There are a lot of examples sketches that try to convey programming style. One of these is to reduce the amount of ripple effects of change; reduce the number of line to change for a logical change. </p> <p>Continuing the LED pin number example above. The "baseline" code is:</p> <pre><code>void setup() { pinMode(13, OUTPUT); ... } void loop() { digitalWrite(13, HIGH); ... digitalWrite(13, LOW); ... } </code></pre> <p>This works just fine BUT what is the ripple effect if we change the pin "13". The example uses symbols OUTPUT, HIGH and LOW which are also just numbers.</p> <p>Typically in C the tradition is to use the preprocessor and define a macro.</p> <pre><code> #define LED 13 </code></pre> <p>The preprocessor will replace LED in the source code with 13 and the compiler sees the same code as above.</p> <p>An alternative is using a variable.</p> <pre><code> int LED = 13; </code></pre> <p>The drawback is that memory is allocated and it is possible to change the value at run-time which is often a very bad idea especially for a pin. The definition should actually be:</p> <pre><code> const int LED = 13; </code></pre> <p>The drawback with the macro is that it is just a value. In C++ it is best to use a constant variable. This tells the compiler both what data type and value it is. A constant variable cannot be assigned (again). </p> <p>The next level to strength code quality and reduce ripple effects is to use lexical scope. A lexical scope such as a function body, class or namespace defines "when" a symbol is available. </p> <p>An example; first global scope where definitions are available across the source code (just as for a macro): </p> <pre><code>const size_t BUF_MAX = 32; static char buf[BUF_MAX]; const char* read() { ... for (int i = 0; i &lt; BUF_MAX; i++) buf[i] = ... ... } </code></pre> <p>Local lexical scope; definitions within a function:</p> <pre><code>const char* read() { const size_t BUF_MAX = 32; static char buf[BUF_MAX]; ... for (int i = 0; i &lt; BUF_MAX; i++) m_buf[i] = ... } </code></pre> <p>The symbols buffer <em>buf</em> and the buffer size <em>BUF_MAX</em> are only available in the function.</p> <pre><code>class Reader { public: void read() { ... for (int i = 0; i &lt; BUF_MAX; i++) m_buf[i] = ... } protected: const size_t BUF_MAX = 32; char m_buf[BUF_MAX]; ... }; </code></pre> <p>Again the symbols are only available within the class and member function. Here is also another example of programming style. The prefix <em>m_</em> is used to show that it is member data. </p> <p>Last, the same example using a namespace:</p> <pre><code>namespace Reader { const size_t BUF_MAX = 32; char buf[BUF_MAX]; ... void read() { ... for (int i = 0; i &lt; BUF_MAX; i++) buf[i] = ... } }; ... for (int i = 0; i &lt; Reader::BUF_MAX; i++) Reader::buf[i] = ...; </code></pre> <p>All symbols must have the prefix Reader when used outside the namespace. </p> <p>These techniques have been developed to allow writing larger programs with reuse. It is important to use them when writing a library for Arduino and especially when sharing. Ripple effects and symbol redefinition/collisions are reduced. </p>
20026
|power|motor|digital|
Powering Motor doesnt work from Digital Pin, but works on 5V power
2016-01-27T20:13:31.950
<p>I am building a little car project, and I have come across an issue that has made me go mental. I have a single motor (3V-5V), that on direct 3.3V &amp; 5V output works fine. However, when I connect this to a digital port, it for some reason doesn't power. Of course, I first thought it was not supplying correct power, so I got myself a voltage meter and tried that. 3.3V outputs, well 3.3V, all fine. The digital port outputs 4-5V (when it is coded to). So here is my question: Why aren't my motors powering/turning? </p>
<p>Power is made up of two values, not one. Besides the voltage there is the current (P=VI), and it's the current you are lacking.</p> <p>A motor needs a large amount of current to start turning (called the <em>stall current</em>) and a digital I/O pin can only supply a relatively small amount (absolute maximum 40mA, recommended maximum 25mA). The power pins though can supply many hundreds of mA.</p> <p>You should never try and power a motor directly from an I/O pin since you risk damaging the I/O pin. Instead you should use the I/O pin to control an NPN transistor or N-channel FET, which is then used to switch the power (actually the ground connection) to the motor from one of the power pins.</p> <p>Here is a good tutorial: <a href="http://www.circuitstoday.com/pwm-generation-and-control-using-arduino" rel="nofollow">http://www.circuitstoday.com/pwm-generation-and-control-using-arduino</a></p>
20053
|led|pwm|
Why does an RGB LED between VCC and PWM work?
2016-01-28T11:05:47.090
<p>I'm an Arduino beginner and I recently bought a cheap starter kit on eBay. One of the lessons in the starter kit is an <a href="http://wiki.epalsite.com/index.php?title=Starter_Kit_for_Arduino#Lesson_6_RGB_LED_various_color_display" rel="nofollow noreferrer">RGB LED controlled by 3 PWM output pins</a>. However, the arrangement of the connections seems a bit funny to me: <a href="https://i.stack.imgur.com/Qupku.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Qupku.jpg" alt="Strange LED PWM setup"></a></p> <p>To my surprise, it worked. I could see the three LEDs inside the plastic change colors. Why does this work? Do the PWM pins accept current whilst low? Is this a common arrangement? See the above link for the code provided in the lesson.</p>
<blockquote> <p>Do the PWM pins accept current whilst low?</p> </blockquote> <p>The pins <strong>sink</strong> current when low. And yes, that is commonly done. The pins are <strong>not</strong> "do nothing" at LOW, and "put 5V there" at HIGH. They are specifically designed to try to source (drive high) current when HIGH and sink (drive low) current when LOW.</p> <p>To have pins (more or less) do nothing, you have to set them to INPUT mode. Then they try to neither source nor sink. </p> <p><em>Caveat:</em> if you enable the internal pull-ups they will try to weakly source current.</p> <hr> <blockquote> <p>Is this a common arrangement?</p> </blockquote> <p>It is quite common, depending on whether the device you are controlling is active high, or active low.</p>
20059
|arduino-uno|c++|
What's the difference between setting a variable outside a function and setting a variable inside a function?
2016-01-28T16:24:11.790
<p>I'm programming C++ for arduino and today I have seen an example like this</p> <pre><code>void loop() { byte variable = 0; // &lt;&lt; This variable is the question. //more stuff here } </code></pre> <p>Is the same as this?:</p> <pre><code>byte variable = 0; void loop() { //stuff here } </code></pre> <p>If the answer is "no", my question is "why?".</p> <p>Thanks for your time!</p>
<p>The difference is not only about where you set the variable, but about where you defined it as well. </p> <p>Defined outside the function, it will have global scope and lifetime, meaning it is visible everywhere and it exists for the entire duration of the program. If you then place an initializer inside the function, whatever value it had just before function-entry will be replaced by the initializer value.</p> <p>If you define it inside the function (and without a "static" specifier) it only exists while that function is executing, and is only visible to code inside the function. Because it only comes into existence when the function is entered, you must initialize it within the function, somehow.</p> <p>If you define it inside the function, but <em>with</em> a static specifier,</p> <pre><code>static byte variable = 0; </code></pre> <p>then it will exist for the entire execution of the program but will only be visible to code within the function. In addition, an initializer on its definition (as opposed to other assignments to the variable) will only be executed once, just before the program begins executing, and <em>will not</em> be executed within function. </p> <p>Using local and static (as opposed to global) variables is considered good program-variable hygiene because it hides those variables (to a greater or lesser degree) from code that needn't and shouldn't be able see or alter them.</p>
20062
|pwm|c|atmega328|
Atmega328 PWM frequency setting not working
2016-01-28T16:48:35.920
<p>I have an Arduino UNO with Atmega 328 SMD, and I am trying to use PWM, but by setting registers, not using analogWrite(). My code is:</p> <pre><code>DDRD |= (1 &lt;&lt; PORTD6); //Setting pin D6 as output OCR0A = 128; //50% duty cycle TCCR0A |= (1 &lt;&lt; COM0A1)|(1 &lt;&lt; WGM01)|(1 &lt;&lt; WGM00); //setting mode and fast pwm TCCR0B |= (1 &lt;&lt; CS01); //setting the prescaler to 8, which should yield PWM with frequency of 8 kHz </code></pre> <p>The problem is with the last line. No matter what I do, it results in PWM with frequency of 1 kHz. Setting different prescaler bits just yield 1 kHz PWM again. I was thinking that maybe its because I am programming this in Arduino IDE, and I kHz is Arduinos default frequency? Or where am I making the mistake? Thanks for any answers.</p>
<p>Your code assumes that TCCR0n are zero. But what if they are not. What if there is some hidden <a href="https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/wiring.c#L263">initialization</a>?</p> <p>Timer0 is used by the Arduino micro/millis counter and the prescale (TCCR0B) is initiated by setting bits CS00 and CS01 in init() before setup() is called.</p> <p>If you really want to use Timer0 you will need to set/clear all the prescale bits. Alternatively clear the register before setting any bit. </p>
20065
|arduino-uno|
Where to start?
2016-01-28T17:35:54.327
<p>I am totally new to Arduino and I'm a real beginner with electronics and robotics. I would like to know where to start, knowing that my ultimate goal is to build an autonomous robot (I know that I will not be able to do this project before learning a lot of things). I am a developer so I have no problem with C and C++, actually I am using C++ at work.</p> <p>Thanks</p>
<p>It's sounds silly, but just get an UNO, a breadboard, wires, 1 resistor (220 ohm) and an LED.</p> <p>Wire up a LED circuit, and program the Arduino to flash the LED. (There's a million examples of this all over the internet).</p> <p>Without getting into any sort of heavy circuits or complex programming, you'll have a quick stress-free introduction to Arduino. </p> <p>This will teach you:</p> <ul> <li>using a breadboard</li> <li>wiring digital ports on the Arduino</li> <li>polarity of components (LED yes, Resistor no)</li> <li>using the Arduino IDE</li> <li>uploading to the board</li> </ul> <p>This is a great jumping-in point because it's reasonably fool-proof. </p> <p>Sure you can eventually be PID-controlling the balance of a 2-wheel robot. But build yourself a working foundation of good knowledge first.</p>