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
13964
|wifi|arduino-yun|wireless|
Recover from wrong Wi-Fi password on Arduino Yún
2015-08-05T08:04:26.250
<p>I'm trying to customize my Arduino Yún to work as an access-point (or hotspot) for providing services to clients directly connected and, alternatively, to work as a client on a wireless network for downloading resources from the Internet.</p> <p>The access to such a wireless network is gained after the user submits a network SSID and password in the web control panel provided by Yún.</p> <p>How can I recover from a user submitting a wrong password? At the moment the Yún stays stuck without any connection, and thus is unreachable via SSH to attempt any recover.</p>
<p>At the end I came out with a button connected to one of the digital input pins and a sketch that, using the bridge to communicate with the "Linux part" of Yún, restores original values in the configuration files and reboots the whole controller.</p> <p>After the reboot completes the Arduino Yún is accessible again through the Wi-Fi network "Arduino Yun xxxxxxxxxx".</p>
13975
|lcd|
Porting SH1106 Oled Driver - 128 x 64 / 128 x 32 Screen is garbled but partially responsive
2015-08-05T18:09:26.327
<p>I'm porting the <a href="http://www.waveshare.com/w/upload/5/5e/SH1106.pdf" rel="nofollow noreferrer">SH1106</a> driver to netmf and have found several libraries that more or less accomplish the same thing. A few were much easier to understand and had less abstraction so I followed those. </p> <p>I've tried the U8glib with my arduino and it works just fine. The ported display driver yields these results:</p> <p><a href="https://i.stack.imgur.com/vwQEM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vwQEM.jpg" alt="enter image description here"></a> inverted: <a href="https://i.stack.imgur.com/tkkMc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tkkMc.jpg" alt="enter image description here"></a></p> <p>What you're looking at is the screen right after the initialization and attempting to draw a filled circle. You can see the bottom of the circle at the top of the screen. Somehow the origin or page is shifted, but I don't fully understand what's going on. I can send the invert display command and that works as well and turn the display on and off. My initialization code is this:</p> <pre class="lang-c prettyprint-override"><code>public void init() { resetPin.Write(true); Thread.Sleep(1); // VDD (3.3V) goes high at start, resetPin.Write(false); // bring reset low Thread.Sleep(10); // wait 10ms resetPin.Write(true); // bring out of reset dcPin.Write(DisplayCommand); SendCommandB(0xAE); /*display off*/ SendCommandB(0x02); /*set lower column address*/ SendCommandB(0x10); /*set higher column address*/ SendCommandB(0x41);//0x40); /*set display start line*/ SendCommandB(0xB0); /*set page address*/ SendCommandB(0x81); /*contract control*/ SendCommandB(0x80);//contrast); /*128*/ SendCommandB(0xA1); /*set segment remap*/ SendCommandB(0xA6);//invertSetting); /*normal / reverse*/ SendCommandB(0xA8); /*multiplex ratio*/ SendCommandB(0x3F); /*duty = 1/32*/ SendCommandB(0xAD); /*set charge pump enable*/ SendCommandB(0x8B); /*external VCC */ SendCommandB(0x30); // | Vpp); /*0X30---0X33 set VPP 9V liangdu!!!!*/ SendCommandB(0xC8); /*Com scan direction*/ SendCommandB(0xD3); /*set display offset*/ SendCommandB(0x00); /* 0x20 */ SendCommandB(0xD5); /*set osc division*/ SendCommandB(0x80); SendCommandB(0xD9); /*set pre-charge period*/ SendCommandB(0x1F); /*0x22*/ SendCommandB(0xDA); /*set COM pins*/ SendCommandB(0x12); SendCommandB(0xDB); /*set vcomh*/ SendCommandB(0x40); SendCommandB(0xAF); /*display ON*/ // Switch to 'data' mode dcPin.Write(Data); this.ClearScreen(); this.Refresh(); } </code></pre> <p>I have two methods to "refreshing"</p> <pre class="lang-c prettyprint-override"><code>public virtual void Refresh() { Spi.Write(displayBuffer); } /// &lt;summary&gt; /// Send buffer to display /// &lt;/summary&gt; public void Display() { //set column address dcPin.Write(DisplayCommand); SendCommandB(0x21); SendCommandB(0); SendCommandB((byte)(Width - 1)); //set page address SendCommandB(0x22); SendCommandB(0); SendCommandB((byte)(_pages - 1)); dcPin.Write(Data); //Spi.Write(displayBuffer); for (ushort i = 0; i &lt; displayBuffer.Length; i = (ushort)(i + 16)) { //Spi.Write(displayBuffer); SendArray(displayBuffer, i, (ushort)(i + 16)); } } </code></pre> <p>At this point I'm a little lost. My hunch is something to do with paging and or display RAM. I'm looking for some insight here on how to fix this as I know there's a lot of experience here with these displays. Thanks!</p>
<p>While your initialization routine looks fine to me (comparing to the datasheet and as evidenced by the fact the display turns on), what doesn't look right is your drawing routine:</p> <pre><code>//set column address dcPin.Write(DisplayCommand); SendCommandB(0x21); SendCommandB(0); SendCommandB((byte)(Width - 1)); //set page address SendCommandB(0x22); SendCommandB(0); SendCommandB((byte)(_pages - 1)); </code></pre> <p>The commands 0x21 and 0x22 don't correspond to any commands I can see in the datasheet. They look more like commands more commonly seen with ILIxxxx or SSDxxxx screens to create an "addressable window" from 0,0 to Width-1, _pages-1.</p> <p>Instead you should be using the same commands you used in the setup routine to set the current col / page coordinate in RAM to write to.</p> <p>Commands <code>(0x00 | (col &amp; 0x0F))</code> and <code>(0x10 | (col &gt;&gt; 4))</code> set the column position, and <code>(0xB0 | (page &amp; 0x0F))</code> set the page number.</p> <p>You then write all 128 bytes for the current page before moving on to the next page. This means you will have to do it a page at a time, something like:</p> <pre><code>for (ushort page = 0; page &lt; 4; page++) { // Set the current RAM pointer to the start of the currently // selected page. dcPin.Write(DisplayCommand); sendCommandB(0x00); // Set column number 0 (low nibble) sendCommandB(0x10); // Set column number 0 (high nibble) sendCommandB(0xB0 | (page &amp; 0x0F)); // Set page number // Send a single page (128 bytes) of data. // Without knowing the rest of your program I don't know the right // data sending routines to use, so I made them up. Change it to // do it how your program expects. Maybe with your SendArray // function. dcPin.Write(DisplayData); for (ushort col = 0; col &lt; 128; col++) { sendDataB(displayBuffer[page * 128 + col]); } } </code></pre> <p>Note that this method is very similar to how the KS0108 GLCD drivers work. Each byte of the page represents 8 pixels on the screen so the screen, at 32 pixels high, is split into 4 pages, where each page is 8 pixels, or one byte, high.</p> <p>The effect you are currently seeing is because you are never changing the current page number (0) so you are always writing your data to the first page. This loops around multiple times, so you end up writing all 4 pages to the same strip of the display ending up with the last page being displayed, which is the last 8 lines of your display data. The rest of the display is never being touched and just contains whatever random data was in the RAM at power-on.</p>
13983
|power|attiny|
ATtiny85: Power consumption vs clock speed
2015-08-05T21:39:22.100
<p>Short and simple: What is the power consumption for an ATtiny85 running at 1 MHz and 8 MHz using the internal clock? Not using any sleep modes.</p> <p>I have googled a lot and can't find any info on this. I ask because I want to know if it is worth using 1 MHz to increase battery life.</p>
<p>The datasheet shows that current decreases at lower frequencies. Around <strong>1 mA</strong> at 1 MHz running at 5 V. More like 5 mA at 8 MHz running at 5 V.</p> <p><a href="https://i.stack.imgur.com/sJkkV.png" rel="noreferrer"><img src="https://i.stack.imgur.com/sJkkV.png" alt="Supply current vs frequency"></a></p> <p>You can save quite a bit by using lower voltages as well, as you can see. For really big savings use a sleep mode. Read about <a href="http://www.gammon.com.au/power" rel="noreferrer">Power saving techniques for microprocessors</a>.</p> <hr> <p><em>(Edited to add)</em></p> <p>To amplify on my remarks, you should be able to get <strong>200 nA</strong> consumption at 3.5 V in sleep mode with no watchdog timer. That will still respond to interrupts, such as closing a switch. </p> <p><a href="https://i.stack.imgur.com/oagxo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/oagxo.png" alt="Supply current with watchdog disabled"></a></p> <hr> <p>If you need to do things periodically you can enable the watchdog, and then get around <strong>5 µA</strong> consumption at 3.5 V.</p> <p><a href="https://i.stack.imgur.com/ZPVOo.png" rel="noreferrer"><img src="https://i.stack.imgur.com/ZPVOo.png" alt="Supply current with watchdog enabled"></a></p> <hr> <p>This is so much less current than the 1 mA mentioned above, that it is well worth exploring running in power-down mode, where possible.</p>
13984
|web-server|
Is there any way to separate this short code into its own function? (webserver, trying to use client.print outside of main loop)
2015-08-05T21:39:41.390
<p>I have an arduino webserver that uses the following code:</p> <pre><code>client.println(F("HTTP/1.1 200 OK")); client.println(F("Content-Type: text/html")); client.println(); client.println(F("&lt;HTML&gt;&lt;HEAD&gt;")); ... if (fan1Toggle == 0) client.print(F("Fan1&lt;font color=\"red\"&gt;&amp;#8226;&lt;/font&gt;&lt;a href=\"/?fan1on\"&gt;On&lt;/a&gt;&lt;br&gt;")); else client.print(F("Fan1&lt;font color=\"green\"&gt;&amp;#8226;&lt;/font&gt;&lt;a href=\"/?fan1off\"&gt;Off&lt;/a&gt;&lt;br&gt;")); if (fan2Toggle == 0) client.print(F("Fan2&lt;font color=\"red\"&gt;&amp;#8226;&lt;/font&gt;&lt;a href=\"/?fan2on\"&gt;On&lt;/a&gt;&lt;br&gt;")); else client.print(F("Fan2&lt;font color=\"green\"&gt;&amp;#8226;&lt;/font&gt;&lt;a href=\"/?fan2off\"&gt;Off&lt;/a&gt;&lt;br&gt;")); ... </code></pre> <p>The page is pretty long, allowing the user to toggle over a dozen different switches. Some of the code checks to see the state of a certain switch, and then displays a green or red bullet ("&amp;#8226", like &#8226;) on the page if the switch is on or off.</p> <p>Since the code for the colored bullet is repeating, I wanted to make a function for it. Then I would just call (for example) "<code>displayBullet(fan1Toggle);</code>", and it would determine if fan1 was on or off, and display the correct color depending on the state.</p> <p>I tried to create the following function:</p> <pre><code>void displayBullet(int toggle) { if (toggle == 0) //switch is off, so display red bullet client.print(F("&lt;font color=\"red\"&gt;&amp;#8226;&lt;/font&gt;")); else //switch is on, so display green bullet client.print(F("&lt;font color=\"green\"&gt;&amp;#8226;&lt;/font&gt;")); } </code></pre> <p>But then I got an error saying that "'client' is not declared in this scope".</p> <p>Is there any way to work around that error, so that I can get the displayBullet() function I want? Or is this something that can't be shortened like this, because the "client" function has to be inside the main loop?</p> <p>Thanks!</p>
<p>You can pass client to the function by reference, like this:</p> <pre class="lang-C++ prettyprint-override"><code>void displayBullet(EthernetClient &amp; client, int toggle) { if (toggle == 0) //switch is off, so display red bullet client.print(F("&lt;font color=\"red\"&gt;&amp;#8226;&lt;/font&gt;")); else //switch is on, so display green bullet client.print(F("&lt;font color=\"green\"&gt;&amp;#8226;&lt;/font&gt;")); } </code></pre> <p>Now it knows about <code>client</code>. Make sure you pass client when you call it:</p> <pre class="lang-C++ prettyprint-override"><code>displayBullet(client, 1); </code></pre>
13991
|arduino-due|library|compile|adafruit|
Adafruit DHT22 Library + Arduino Due not compiling?
2015-08-06T11:51:46.593
<p>i recently purchased a DHT22's and tried to get it to work using <a href="https://github.com/adafruit/DHT-sensor-library" rel="nofollow">Adafruit's DHT library</a> on Github. When i compile it with a Arduino DUE, it gives me the following error:</p> <pre><code>C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp: In constructor 'DHT::DHT(uint8_t, uint8_t, uint8_t)': C:\Users\Moz\Documents\Arduino\libraries\DHT-sensor-library-master\DHT.cpp:14:9: error: invalid conversion from 'Pio*' to 'uint8_t {aka unsigned char}' [-fpermissive] _port = digitalPinToPort(pin); ^ Error compiling. </code></pre> <p>It compiles on a Arduino Uno but not on the DUE. </p> <p>What is the reason for this? </p> <p>Edit: Below is the example code i use</p> <pre><code>#include "DHT.h" #define DHTPIN 2 // what pin we're connected to #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; } // Compute heat index in Fahrenheit (the default) float hif = dht.computeHeatIndex(f, h); // Compute heat index in Celsius (isFahreheit = false) float hic = dht.computeHeatIndex(t, h, false); Serial.print("Humidity: "); Serial.print(h); Serial.print(" %\t"); Serial.print("Temperature: "); Serial.print(t); Serial.print(" *C "); Serial.print(f); Serial.print(" *F\t"); Serial.print("Heat index: "); Serial.print(hic); Serial.print(" *C "); Serial.print(hif); Serial.println(" *F"); } </code></pre>
<p>There are several Arduino libraries for reading DHT22 and related DHT sensors. The Adafruit DHT library does not compile for the Due since it uses AVR specific functions not available on ARM (Due).</p> <p>For the Arduino Due use Rob Tillaart's DHTstable library available from his <a href="https://github.com/RobTillaart/Arduino" rel="nofollow">github page</a> where you can download a zip file. Note that his project also has a "DHTlib" library which does not support the Due. There exists yet more DHT libraries which Rob has listed on the <a href="http://playground.arduino.cc/Main/DHTLib" rel="nofollow">DHTLib page on arduino.cc</a>.</p>
13996
|sd-card|
How to pass a filename to a function? What type of variable is the filename?
2015-08-06T16:34:34.633
<p>In the example below, I have two functions that write numbers to two different files on an SD card. I'm using the <a href="https://github.com/greiman/SdFat" rel="nofollow">SdFat library</a>. </p> <p>Is there any way I can combine the two functions into one, so that I can call (for example): <code>writeToFile(int t, FileName "filename1.txt");</code>?</p> <p>In the example below, to write a value to the "temperature.txt" file, I would like to be able to call: <code>writeToFile(7, "temperature.txt");</code> In my sketch I have about a dozen functions that are writing to a dozen different files, so it would be very handy to be able to combine them into one function.</p> <p>I think the main part I'm stuck on is I have no idea what the filename variable would be, or how to pass the filename to the function.</p> <pre><code>#include &lt;SdFat.h&gt; SdFat sd; void setup() { if (!sd.begin(chipSelect, SPI_HALF_SPEED)) { sd.initErrorHalt(); } setTemperature(7); setFanSpeed(4); } void setTemperature(int t) { SdFile rdfile("temperature.txt", O_WRITE); rdfile.rewind(); rdfile.println(t); rdfile.close(); } void setFanSpeed(int t) { SdFile rdfile("fanspeed.txt", O_WRITE); rdfile.rewind(); rdfile.println(t); rdfile.close(); } </code></pre>
<p>String literals are of type <code>const char *</code>. Ordinary <code>char *</code>s can be passed to it though; the <code>const</code> means that the compiler will make sure that the function doesn't attempt to change the contents.</p> <pre><code>void setFileParameter(const char *filename, int value) { ... } </code></pre>
13998
|arduino-nano|
Arduino Nano with CH340 reboots on OS X El Capitan
2015-08-06T17:29:20.230
<p>I installed OS X El Capitan beta on my Macbook. Now my Nano-sized Chinese Arduino operating on CH340 chip reboots the laptop when USB is unplugged. While plugged, it works fine, I can upload sketches and send/receive data via Serial. </p> <p>I've tried reinstalling the CH340 driver and running the following command as per <a href="https://www.reddit.com/r/arduino/comments/3dfr2e/ch340g_arduinos_with_osx_el_capitan/" rel="nofollow">this solution</a> and it didn't help:</p> <pre><code>sudo nvram boot-args="kext-dev-mode=1 rootless=0" </code></pre> <p>I appreciate any ideas...</p>
<p>If you have macOS High Sierra like mine 10.13.4 This is work for me <a href="https://github.com/awangga/NFCReader" rel="nofollow noreferrer">https://github.com/awangga/NFCReader</a></p>
14002
|arduino-mega|c++|firmware|
Uploading Marlin Firmware To Melzi-ATmega1284p
2015-08-07T05:06:24.320
<p>I'm trying to flash the Marlin Firmware to my Prusa i3 3D Printer, which uses Melzi 2.0 board. Melzi is a variation of Sanguino, and Sanguino is a variation of the Arduino.</p> <p>The problem is that the version I'm using of Marlin (<a href="https://github.com/MarlinFirmware/Marlin" rel="nofollow">this one</a>, development branch) only works with Arduino Mega. I saw that the file <code>pins_RAMPS_13.h</code> says the following (line 15-17):</p> <pre><code>#if !defined(__AVR_ATmega1280__) &amp;&amp; !defined(__AVR_ATmega2560__) #error Oops! Make sure you have 'Arduino Mega' selected from the 'Tools -&gt; Boards' menu. #endif </code></pre> <p>So I tried to make this part to look like this:</p> <pre><code>#if !defined(__AVR_ATmega1280__) &amp;&amp; !defined(__AVR_ATmega2560__) &amp;&amp; !defined(__AVR_Melzi_ATmega1284p16mhz__) #error Oops! Make sure you have 'Arduino Mega' selected from the 'Tools -&gt; Boards' menu. #endif </code></pre> <p>Does anybody know if there's another repository made for the Melzi board?<br> Or if I should use another firmware, like Repetier (I tried, fail)?<br> Thanks for any help.</p>
<p>It looks like the Marlin firmware supports two versions of the Melzi board, although it isn't clear if it specifically includes the 2.0 version. The best thing to do is just try it. In the <code>Configuration.h</code> file find the section where it says:</p> <pre><code>#ifndef MOTHERBOARD   #define MOTHERBOARD BOARD_ULTIMAKER #endif </code></pre> <p>Now replace <code>BOARD_ULTIMAKER</code> with <code>BOARD_MELZI_1284</code> and try that. If that doesn't work you can try just <code>BOARD_MELZI</code>. If neither of those work, you are out of luck, unless you are willing to dig in and do the pin mappings yourself.</p>
14010
|arduino-mega|pwm|arduino-nano|wireless|
how to build rc transmitter and receiver with an old rc transmitter
2015-08-07T09:07:10.773
<p>I've got an Arduino Mega, an Arduino Nano, two NRF24L01 wireless modules and a old Multiplex Transmitter system.</p> <p>I want to get the PWM signal and send it to the other arduino which should control the servos and the motor controller.</p> <p>Is there a good instruction or know somebody how to do that easily?</p> <p>I need it for a rc plane and the range should be 1km.</p>
<p>If you are controlling an RC plane, you should probably just buy a transmitter and receiver specifically designed for that. They are cheap and reliable and will generate PWM signals on their own.</p> <p>If you must use an Arduino for some reason, NRF24L01 are not going to cut it as they are not powerful enough to reach 1 km. You should probably look into something like an XBee Series 1. With about 60 mW transmit power, its range is up to 1.6 km.</p>
14014
|arduino-uno|accelerometer|gyroscope|magnetometer|
Will it work ? MPU6050 Gyro etc. etc. module
2015-08-07T11:56:07.437
<p>Will this code read the values properly ? Using <a href="https://github.com/sparkfun/MPU-9150_Breakout/blob/master/firmware/MPU6050/MPU6050.h" rel="nofollow">MPU6050.h</a>.</p> <pre><code>#include &lt;MPU6050.h&gt; #include &lt;Wire.h&gt; void setup() { Serial.begin(115200); Wire.begin(); MPU6050.initialize(); } void loop() { MPU6050.getWaitForExternalSensorEnabled(); float X = getRotationX(); float Y = getRotationY(); float Z = getRotationZ(); Serial.print("X:"); Serial.println(X); Serial.print("Y:"); Serial.println(Y); Serial.print("Z:"); Serial.println(Z); } </code></pre> <p>Please be patient. I know nothing about gyroscope's working. I'm stupid.</p>
<p>Code would normally look like this</p> <pre><code>#include &lt;MPU6050.h&gt; #include &lt;Wire.h&gt; MPU6050 mpu; void setup() { Serial.begin(115200); Wire.begin(); mpu.initialize(); } void loop() { //what is this doing for you? mpu.getWaitForExternalSensorEnabled(); if(mpu.getIntDataReadyStatus() == 1) { float X = mpu.getRotationX(); float Y = mpu.getRotationY(); float Z = mpu.getRotationZ(); Serial.print("X:"); Serial.println(X); Serial.print("Y:"); Serial.println(Y); Serial.print("Z:"); Serial.println(Z); } else { Serial.println("MPU not ready"); } } </code></pre>
14020
|serial|arduino-yun|
How to empty the buffer for Serial port?
2015-08-07T21:50:39.657
<p>I have a Yun that accepts commands via the bridge (note the below code is part of a very simple virtual keyboard that accepts commands then runs <code>Keyboard.println</code> on them:</p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;stdlib.h&gt; #include &lt;string.h&gt; HardwareSerial *port; void setup() { port = &amp;Serial1; port-&gt;begin(9600); } void loop() { if (port-&gt;available()) { String cmd = port-&gt;readString(); if(cmd.length() &gt; 1){ String instruction = cmd; int arg_comma_index = 0; arg_comma_index = instruction.indexOf(","); String func = instruction.substring(0, arg_comma_index); String args = instruction.substring(arg_comma_index + 1, instruction.length() + 1 ); Keyboard.begin(); Keyboard.println(args); Keyboard.end(); } port-&gt;read(); // Try to throw away whatever's left to prevent looping (which is still happening). } } </code></pre> <p>If I send it a short string: </p> <ul> <li>The first time, immediately after starting the sketch, it works.</li> <li>The second time, it works but loops anywhere from 1-5 times.</li> <li>The third time, it loops more times still.</li> <li>If I leave the device running (even if not operating it), the number of times it loops goes up <em>when</em> I finally do send it an instruction. I'm seeing 20-75 loops after less than 15 minutes of uptime.</li> </ul> <p>Clearly the loops where no instruction is being received are still building up something here. I've tried:</p> <ul> <li>Restarting the port each <code>void loop()</code>.</li> <li>Flushing the port at the top and/or bottom of each <code>void loop()</code>.</li> <li>Setting <code>cmd = ""</code> at the end of each <code>void loop()</code>.</li> <li>Checking <code>peek()</code>, <code>available()</code>, and <code>readString()</code> - after I send it one instruction, they return the same values every single time they loop.</li> </ul>
<p>I wouldn't be using readString myself. In fact I wouldn't be using the String class at all. <code>readString</code> keeps reading until it times out (by default after one second), so it may read more - or less even - than you want. It will also introduce a one-second delay while it sits around waiting for that second to elapse.</p> <p>You are much better off doing a non-blocking loop, and then processing data when you get a known delimiter, like a newline or comma, or whatever you designate as "ending the stream". Example code that uses a newline delimiter:</p> <pre class="lang-C++ prettyprint-override"><code>// how much serial data we expect before a newline const unsigned int MAX_INPUT = 50; void setup () { Serial.begin (115200); } // end of setup // here to process incoming serial data after a terminator received void process_data (const char * data) { // for now just display it // (but you could compare it to some value, convert to an integer, etc.) Serial.println (data); } // end of process_data void processIncomingByte (const byte inByte) { static char input_line [MAX_INPUT]; static unsigned int input_pos = 0; switch (inByte) { case '\n': // end of text input_line [input_pos] = 0; // terminating null byte // terminator reached! process input_line here ... process_data (input_line); // reset buffer for next time input_pos = 0; break; case '\r': // discard carriage return break; default: // keep adding if not full ... allow for terminating null byte if (input_pos &lt; (MAX_INPUT - 1)) input_line [input_pos++] = inByte; break; } // end of switch } // end of processIncomingByte void loop() { // if serial data available, process it while (Serial.available () &gt; 0) processIncomingByte (Serial.read ()); // do other stuff here like testing digital input (button presses) ... } // end of loop </code></pre> <p>In my example code you would do whatever-it-is you want in <code>process_data</code> which is called once an entire line arrives. Then you don't need to discard incoming data (empty the serial buffer), which seems to me to be a bad idea anyway.</p>
14028
|arduino-mega|i2c|
unresolved overloaded function type for Wire.onReceive
2015-08-08T08:08:29.177
<p>I am attempting to make an I2C slave out of my Arduino and I can't get past the Wire.onReceive function. Here is my code. The documentation says to just add a function that has the style of void myHandler(int bytes) but I can't figure out why my readPI function does not meet these requirements.</p> <pre class="lang-C++ prettyprint-override"><code> #include "piCom.h" #include "WireAddresses.h" #include &lt;Wire.h&gt; pi::pi(){ Wire.begin(NB_INFO); // is 0x04 Wire.onReceive( readPI ); //Wire.onRequest(sendPI); } void pi::readPI(int byteCount){ while( Wire.available() ){ ref_IMU = Wire.read(); }//end while }//end readPI void pi::sendPI(){ Wire.write(1); //use to send pressure info to pi }//end sendPI //double pi::getref_IMU(){return ref_IMU;} </code></pre> <p>then here is the error</p> <pre class="lang-C++ prettyprint-override"><code>piCom.cpp: In constructor 'pi::pi()': piCom.cpp:7: error: no matching function for call to'TwoWire::onReceive(&lt;unresolved overloaded function type&gt;)' Wire.onReceive( readPI ); ^ no matching function for call to 'TwoWire::onReceive(&lt;unresolved overloaded function type&gt;)' </code></pre> <p>Any help is greatly appreciated.</p>
<pre><code> void pi::sendPI(){ </code></pre> <p>That is a class function (method) which has an implicit <strong>this</strong> pointer. You can't use it as a static ISR.</p> <p>In general, classes cannot implement ISRs for this reason. There are a few workarounds, one being to make it a <strong>static</strong> class function. However then it will affect the entire class, not just one instance.</p>
14030
|servo|rf|virtualwire|
Receiving partial messages when using VirtualWire and ServoTimer2
2015-08-08T11:40:06.327
<p>I'm writing a project where an Arduino board that is connected to a servo engine receives commands from another Arduino. The possible commands are:</p> <ol> <li>Move 10 degrees</li> <li>Reset position</li> <li>Sweep until you're told to stop</li> </ol> <p>My problem is with the sweep-mode, when I get the sweep command, I get into a while loop, that first checks for a sweep-terminator and then sweeps.</p> <pre><code>} else if (message == sweep) { Serial.println("sweep"); while (msg1 != sweep_term) { // set the direction for the servo to move if (val == 750){ val = 2250; } else { val = 750; } // move the servo myservo.write(val); // wait for the servo to move delay(15); // wait for a message if (vw_get_message(buf1, &amp;buflen1)) { buf1[buflen1] = '\0'; msg1 = (char*)buf1; memset(buf1,'0',VW_MAX_MESSAGE_LEN); Serial.print(buflen1); Serial.print(" [sweep] Got: "); Serial.println(msg1); } } } </code></pre> <p>For some reason, when I'm in this loop I don't get the sweep terminator message, or I get a part of it. I suspect that the servo is responsible for this, since when I run the same program without <code>myservo.write()</code>s I <em>do</em> receive those terminators.</p>
<p>I simply connected the servo to an external power 5V power source, and everything works perfectly fine. It seems like the servo's resistance was too much for the RF receiver to be able to work as well.</p>
14031
|serial|interrupt|
MPU9150 (JEFF LIB) + FIFO_OVERFLOW INTERRUPT + SERIAL PRINT
2015-08-08T16:56:08.523
<p>Overflow enthusiasts!</p> <p>I am trying to log accelerometer and gyro data using Serial.print. I have enabled the FIFO_Overflow interrupt. Whenever I log data, the serial port freezes. I am suspecting an interrupt issue while I am using Serial.print. Is there any way to get continuous data for debugging purposes? I know that the Serial library can affect interrupts and wonder whether you guys could help me a little bit ?</p> <pre class="lang-c prettyprint-override"><code>#include "Wire.h" #include "I2Cdev.h" #include "MPU9150.h" #include "helper_3dmath.h" // class default I2C address is 0x68 // specific I2C addresses may be passed as a parameter here // AD0 low = 0x68 (default for InvenSense evaluation board) // AD0 high = 0x69 MPU9150 accelGyroMag; #define LED_PIN 13 volatile boolean state_fifo_int = false; uint16_t fifo_count; uint8_t fifo_buffer[8]; int16_t acc_temp[3]; int16_t gyro_x; void setup(){ // join I2C bus (I2Cdev library doesn't do this automatically) Wire.begin(); // initialize serial communication // (38400 chosen because it works as well at 8MHz as it does at 16MHz, but // it's really up to you depending on your project) Serial.begin(115200); // initialize device Serial.println("Initializing I2C devices..."); accelGyroMag.initialize(); // verify connection Serial.println("Testing device connections..."); Serial.println(accelGyroMag.testConnection() ? "MPU9150 connection successful" : "MPU9150 connection failed"); // configure Arduino LED for pinMode(LED_PIN, OUTPUT); attachInterrupt(0,fifo_int,CHANGE); } void fifo_int() { state_fifo_int = true; } void loop(){ while(!state_fifo_int) { accelGyroMag.setIntFIFOBufferOverflowEnabled(true); // enable fifo_interrupt accelGyroMag.setFIFOEnabled(true); accelGyroMag.setAccelFIFOEnabled(true); accelGyroMag.getXGyroFIFOEnabled(); accelGyroMag.getAccelFIFOEnabled(); fifo_count = accelGyroMag.getFIFOCount(); accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes acc_temp[0] = (((int16_t)fifo_buffer[0]) &lt;&lt; 8) | fifo_buffer[1]; acc_temp[1] = (((int16_t)fifo_buffer[2]) &lt;&lt; 8) | fifo_buffer[3]; acc_temp[2] = (((int16_t)fifo_buffer[4]) &lt;&lt; 8) | fifo_buffer[5]; gyro_x = (((int16_t)fifo_buffer[6]) &lt;&lt; 8) | fifo_buffer[7]; Serial.print((float)acc_temp[0]/16384); Serial.print(" "); Serial.print((float)acc_temp[1]/16384); Serial.print(" "); Serial.print((float)acc_temp[2]/16384); Serial.print(" "); Serial.println(gyro_x); } accelGyroMag.setIntFIFOBufferOverflowEnabled(false); // disable fifo_interrupt accelGyroMag.resetFIFO(); state_fifo_int = false; } </code></pre> <p>The library for the MPU9150 is by Jeff Rowberg.</p>
<p>After reading the datasheet on the PS manual, I found out that the INT1 pulse had a width of 50uS.</p> <p>So what I simply did was to declare a global integer and check it at the end of the loop.</p> <p>Whenever I checked the incremented variable at the end, it was 48!.I personally suspected that my loop speed was to slow. Additionally the timeout value 14 ms per loop arbitrary. Clearly a disparity exists in the interrupt routine for the sensor and the microcontroller.</p> <p>So what I simply did was to reconfigure the sensor output to a latched signal which clearly solved the problem. I am now getting synchronized interrupt with convincing results.</p> <p>Here is the code:</p> <pre><code>#include "Wire.h" #include "I2Cdev.h" #include "MPU9150.h" #include "helper_3dmath.h" #define LED_BUILTIN 13 MPU9150 accelGyroMag; volatile boolean state_fifo_int = false; int x = 0; void blink(uint16_t offTime, uint16_t onTime){ digitalWrite(LED_BUILTIN,HIGH); if(onTime) delay(onTime); digitalWrite(LED_BUILTIN,LOW); if(offTime) delay(offTime); } void resetSensor(){ accelGyroMag.reset(); delay(50); accelGyroMag.initialize(); //Serial.println("Initialize if connection test failed"); if(accelGyroMag.testConnection()){ //disable interrupts accelGyroMag.setIntFIFOBufferOverflowEnabled(false); // disable fifo_interrupt accelGyroMag.resetFIFO(); // verify connection //Serial.println("Connection tested successfully, Disabling interrupts"); } if(!accelGyroMag.testConnection()){ // try to recover sensor accelGyroMag.initialize(); //Serial.println("Initialize if connection test failed"); } if(accelGyroMag.testConnection()){ // reconfigure sensor for Fifo and interrupts accelGyroMag.setFIFOEnabled(true); accelGyroMag.setXGyroFIFOEnabled(true); accelGyroMag.setAccelFIFOEnabled(true); accelGyroMag.setInterruptMode(false);// Set interrupt logic level mode 0 = active-high accelGyroMag.setInterruptLatch(true); //set interrupt 1=latch-until-int-cleared ( latch after INT_STATUS READ) accelGyroMag.setIntFIFOBufferOverflowEnabled(true); } else { // Serial.println("MPU9150 connection failed"); //Serial.println("locking UP"); while(true){ for(uint8_t i=0;i&lt;3;i++){blink(50,100);} // S delay(250); for(uint8_t i=0;i&lt;3;i++){blink(50,300);} // O delay(250); for(uint8_t i=0;i&lt;3;i++){blink(50,100);} // S delay(500); } } } void setup(){ Wire.begin(); Serial.begin(115200); pinMode(LED_BUILTIN, OUTPUT); // other stuff attachInterrupt(0,fifo_int,RISING); resetSensor(); } void fifo_int() { x++; state_fifo_int = true; } static unsigned long timeout = 0; // used to detect dead sensor/connection uint16_t fifo_count; uint8_t fifo_buffer[8]; int16_t acc_temp[3]; int16_t gyro_x; void loop(){ if(state_fifo_int){ // interrupt has triggered blink(0,1); // really quick blink // really quick blink //Serial.println(x); state_fifo_int = false; accelGyroMag.resetFIFO(); accelGyroMag.getFIFOBytes(fifo_buffer,8); // fill in fifo bytes accelGyroMag.getIntFIFOBufferOverflowStatus(); // read the INT_STATUS reg in order to clear the Latch. acc_temp[0] = (((int16_t)fifo_buffer[0]) &lt;&lt; 8) | fifo_buffer[1]; acc_temp[1] = (((int16_t)fifo_buffer[2]) &lt;&lt; 8) | fifo_buffer[3]; acc_temp[2] = (((int16_t)fifo_buffer[4]) &lt;&lt; 8) | fifo_buffer[5]; gyro_x = (((int16_t)fifo_buffer[7]) &lt;&lt; 8) | fifo_buffer[8]; timeout = millis(); } if((millis()-timeout)&gt;1000){ //last interrupt was over 1 second ago! better reset Sensor! blink(100,500); blink(100,500); resetSensor(); } } </code></pre>
14045
|arduino-mega|
Reading a part of bitmap image on Arduino
2015-08-09T14:11:48.620
<p>I'm pretty much a beginner when it comes to programming and have only recently started learning C++. Right now I'm stuck trying to covert a bitmap into a binary array. This is for a Robotics competition I've entered. The bitmap is a 54*96 pixel monochromatic 1 bpp image. I'm confused with the offset positions while trying to read the header. This is the code I've written so far and would greatly appreciate any help. I think the error lies in increment of the <code>lineNo</code> variable which needs to be in hex, but how to increment such values? </p> <p>What I want to ultimately achieve is to read only some parts of the bitmap particularly the boxes with cross on them (see image below). How do I find out the pixel locations? </p> <pre class="lang-cpp prettyprint-override"><code>#include &lt;SD.h&gt; #include &lt;SPI.h&gt; File bMap; File Text; void setup() { Serial.begin(9600); while (!Serial) { ; } Serial.print("Initializing SD card..."); pinMode(10, OUTPUT); if (!SD.begin(4)) { Serial.println("initialization failed!"); return; } Serial.println("initialization done."); int height = 0; int width = 0; int bitmapOffset = 0xa; bMap = SD.open("map.bmp", FILE_READ); Text = SD.open("test.txt", FILE_WRITE); \\bMap.seek(0xa); \\bitmapOffset = bMap.read(); \\Serial.println(bitmapOffset, BIN); \\Serial.println(bMap, HEX); bMap.seek(0x16); for (int i = 0; i &lt; 4; i++) { height += (bMap.read() &lt;&lt; (8 * i)); Serial.println(height); int lineNo; int fileposition = 0; for (lineNo = 0; lineNo &lt; height; lineNo++) fileposition = bitmapOffset + (lineNo); bMap.seek(fileposition); //Serial.print(lineNo); Serial.print(fileposition); //Serial.print(bitmapOffset); } bMap.seek(0x12); for (int i = 0; i &lt; 4; i++) { width += (bMap.read() &lt;&lt; (8 * i)); Serial.println(width); if (Text) { Text.println(height, width); Text.close(); } } } void loop() {} </code></pre> <p><a href="https://i.stack.imgur.com/hSEHx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/hSEHx.png" alt="Maze"></a> </p>
<p>Any coordinate in a bitmap (note: the term bitmap here [all lower case] refers to the concept of a grid of pixels, not the Windows BMP file format which I will always refer to as BMP all in capitals) can easily be calculated as long as you know the width. The height is only needed to stop you going too far.</p> <p>Any pixel offset in a buffer of pixels is calculated as <code>y * width + x</code> assuming a <em>left-right / top-down</em> pixel arrangement in the buffer.</p> <p>The information you are really interested in with your bitmap is actually considerably less than is in the BMP that you show. Your BMP is 56x96 pixels, but the information you actually care about is actually only in a resolution of 7x12 blocks.</p> <p>It would be far simpler if you could pre-process the provided BMP on a PC to create an array of 84 entries each with a different tag or value to represent what it is. Your image there could then be represented as the array:</p> <pre><code>{ 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 0, 0, 1, 3, 3, 0, 0, 0, 0, 1, 3, 0, 0, 1, 1, 0, 0, 3, 3, 2, 1, 0, 0, 0, 3, 3, 1, 0, 0, 1, 0, 3, 3, 0, 1, 0, 0, 0, 3, 3, 0, 0, 0, 2, 0, 3, 3, 0, 0, 1, 0, 0, 3, 3, 1, 1, 0, 1, 0, 3, 3, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 3, 3, 3 }; </code></pre> <p>Where 0 is an open white space, 1 is a closed black space, 2 is a black space with a cross and 3 is a border space.</p> <p>The two crosses would then be calculated as <code>(1,4) = 4 * 7 + 1 = 29</code> and <code>(4,7) = 7 * 7 + 4 = 53</code>.</p> <p>Working with BMP files is somewhat more tricky. They come in multiple depths and multiple bit arrangements, as well as different versions with different header sizes. They also have different padding requirements for different line lengths and bit depths, and are generally a rather nasty file format all round.</p> <p>And on top of that they are upside down. BMP is the only file format I know of where 0,0 is at the bottom left instead of the top left. Consequently you have to invert all your Y coordinates to make sense of it, and parsing a BMP file from the top down is really slow because you have to keep jumping backwards in the file.</p> <p>So it would be much better if you could write a program on a PC using software which already understands the BMP format and can render it into a buffer for your program to then parse each block to work out what it is and build up a small 84 byte file of the actual information you need for your robot.</p> <p>If you must read the BMP file directly on the Arduino then I have code you use to help you. It's not designed for the Arduino but for the chipKIT boards (though it's very similar) and is designed as part of my DisplayCore framework for chipKIT (and other more powerful) boards, but you are welcome to take whatever bits you like, or just use bits to give you more insight into how BMP files work. You can get the code from Github here: <a href="https://github.com/MajenkoLibraries/DisplayCore/tree/master/ImageReaders/BMPFile" rel="nofollow">https://github.com/MajenkoLibraries/DisplayCore/tree/master/ImageReaders/BMPFile</a></p> <p>To parse your bitmap into an array you would have to take each 8x8 block of pixels and work out what shape is in it - whether it's all black, all white, a cross, or a border piece.</p>
14047
|serial|
Reading states of multiple toggle switches
2015-08-09T16:41:47.307
<p>I'm working on modifying this <a href="https://www.arduino.cc/en/Tutorial/Switch" rel="nofollow noreferrer">example</a> from the Arduino website to read the state of 3 toggle (SPDT) switches. If I have one toggle switch hooked up, my sketch works as expected...the sketch will log the state of the switch in the serial debugger every-time the state changes, and only when the state changes. </p> <p>However, if I add in two more switches, the serial debugger will continuously output my log messages, without detecting if the state has changed. </p> <p>Here's the code from my sketch: </p> <pre><code>const int switchOnePin = 2; // digital in 2 (pin the switch one is attached to) const int switchTwoPin = 3; // digital in 3 (pin the switch two is attached to) const int switchThreePin = 4; // digital in 4 (pin the switch three is attached to) int switchOneState = 0; // current state of the switch int lastSwitchOneState = 0; // previous state of the switch int switchTwoState = 0; int lastSwitchTwoState = 0; int switchThreeState = 0; int lastSwitchThreeState = 0; void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); int switchOneState = 0; // current state of the switch int lastSwitchOneState = 0; // previous state of the switch switch pins as an input pinMode(switchOnePin, INPUT); pinMode(switchTwoPin, INPUT); pinMode(switchThreePin, INPUT); } void loop() { // read the switch input pins: switchOneState = digitalRead(switchOnePin); delay(50); switchTwoState = digitalRead(switchTwoPin); delay(50); switchThreeState = digitalRead(switchThreePin); // compare the switchState to its previous state if (switchOneState != lastSwitchOneState) { // if the state has changed, increment the counter if (switchOneState == HIGH) { // if the current state is HIGH then the button // went from off to on: Serial.println("Switch one is on"); } else { // if the current state is LOW then the button // went from on to off: Serial.println("Switch one is off"); } if (switchTwoState != lastSwitchTwoState) { if (switchTwoState == HIGH) { Serial.println("Switch two is on"); } else { Serial.println("Switch two is off"); } if (switchThreeState != lastSwitchThreeState) { if (switchThreeState == HIGH) { Serial.println("Switch three is on"); } else { Serial.println("Switch thre is off"); } } } // Delay a little bit to avoid bouncing delay(50); } // save the current state as the last state, //for next time through the loop lastSwitchOneState = switchOnePin; lastSwitchTwoState = switchTwoPin; lastSwitchThreeState = switchThreePin; } </code></pre> <p>And here's what my circuit looks like: </p> <p><a href="https://i.stack.imgur.com/ZLAB6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZLAB6.png" alt="enter image description here"></a> Does anyone have any insight into what I may be doing wrong? I'm not quite sure if it's a circuit or a sketch issue (or both). </p> <p><strong>EDIT</strong> I tried adding a delay of 50ms between each digital input read, but that still did not seem to help the problem. </p>
<p>The problem was two pronged---both the copy/paste error that @Gerben pointed out, as well as the incorrect if-else statements that @BrettAM pointed out. Below is the working code: </p> <pre><code>const int switchOnePin = 2; // digital in 2 (pin the switch one is attached to) const int switchTwoPin = 3; // digital in 3 (pin the switch two is attached to) const int switchThreePin = 4; // digital in 4 (pin the switch three is attached to) int switchOneState = 0; // current state of the switch int lastSwitchOneState = 0; // previous state of the switch int switchTwoState = 0; int lastSwitchTwoState = 0; int switchThreeState = 0; int lastSwitchThreeState = 0; void setup() { //initialize serial communication at 9600 bits per second: Serial.begin(9600); int switchOneState = 0; // current state of the switch int lastSwitchOneState = 0; // previous state of the switch switch pins as an input pinMode(switchOnePin, INPUT); pinMode(switchTwoPin, INPUT); pinMode(switchThreePin, INPUT); } void loop() { // read the switch input pins: switchOneState = digitalRead(switchOnePin); switchTwoState = digitalRead(switchTwoPin); switchThreeState = digitalRead(switchThreePin); // compare the switchState to its previous state if (switchOneState != lastSwitchOneState) { // if the state has changed, increment the counter if (switchOneState == HIGH) { // if the current state is HIGH then the button // went from off to on: Serial.println("Switch one is on"); } else { // if the current state is LOW then the button // went from on to off: Serial.println("Switch one is off"); } } if (switchTwoState != lastSwitchTwoState) { if (switchTwoState == HIGH) { Serial.println("Switch two is on"); } else { Serial.println("Switch two is off"); } } if (switchThreeState != lastSwitchThreeState) { if (switchThreeState == HIGH) { Serial.println("Switch three is on"); } else { Serial.println("Switch thre is off"); } } // Delay a little bit to avoid bouncing delay(50); // save the current state as the last state, //for next time through the loop lastSwitchOneState = switchOneState; lastSwitchTwoState = switchTwoState; lastSwitchThreeState = switchThreeState; } </code></pre>
14052
|programming|c++|
Using STL vector to create an array causes an error
2015-08-09T21:16:12.260
<p>I have installed the STL for arduino, and it has been working fine. Then I tried to create a vector using a custom class, and it gave me a massive error message. When using it on primitive data types (ex. int) it works fine, but in any one of my own classes (including classes from sample code) it gives this error:</p> <pre><code>Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno" Build options changed, rebuilding all C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w - fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -std=gnu++11 -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10603 - DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp -o C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp.o In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\vector:33:0, from Navigation.ino:2: c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h: In instantiation of 'void std::__destroy_aux(_ForwardIterator, _ForwardIterator, __false_type) [with _ForwardIterator = Obstacle*]': c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:78:55: required from 'void std::__destroy(_ForwardIterator, _ForwardIterator, _Tp*) [with _ForwardIterator = Obstacle*; _Tp = Obstacle]' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:83:51: required from 'void std::_Destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = Obstacle*]' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:115:27: required from 'void std::destroy(_ForwardIterator, _ForwardIterator) [with _ForwardIterator = Obstacle*]' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42: required from 'std::vector&lt;_Tp, _Alloc&gt;::~vector() [with _Tp = Obstacle; _Alloc = std::allocator&lt;Obstacle&gt;]' Navigation.ino:36:23: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:66:22: error: 'destroy' was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive] destroy(&amp;*__first); ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_construct.h:114:13: note: 'template&lt;class _ForwardIterator&gt; void std::destroy(_ForwardIterator, _ForwardIterator)' declared here, later in the translation unit inline void destroy(_ForwardIterator __first, _ForwardIterator __last) { ^ Error compiling. </code></pre> <p><strong>EDIT:</strong> Here is the code:</p> <pre><code>#include &lt;iterator&gt; #include &lt;vector&gt; #include &lt;pnew.cpp&gt; class Test { public: int i; }; std::vector&lt;Test&gt; test; </code></pre> <p>Change the last line to </p> <pre><code>std::vector&lt;Test&amp;&gt; test </code></pre> <p>and:</p> <pre><code> Arduino: 1.6.3 (Windows 8.1), Board: "Arduino Uno" C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avr-g++ -c -g -Os -w -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -std=gnu++11 -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10603 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino -IC:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\standard C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp -o C:\Users\OWNER\AppData\Local\Temp\build7240665633604233053.tmp\Navigation.cpp.o In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\vector:35:0, from Navigation.ino:2: c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'class std::_Vector_alloc_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt;, true&gt;': c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:101:8: required from 'struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:155:7: required from 'class std::vector&lt;Obstacle&amp;&gt;' Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:89:8: error: forming pointer to reference type 'Obstacle&amp;' _Tp* _M_start; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:90:8: error: forming pointer to reference type 'Obstacle&amp;' _Tp* _M_finish; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:91:8: error: forming pointer to reference type 'Obstacle&amp;' _Tp* _M_end_of_storage; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:94:8: error: forming pointer to reference type 'Obstacle&amp;' _Tp* _M_allocate(size_t __n) ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:96:8: error: forming pointer to reference type 'Obstacle&amp;' void _M_deallocate(_Tp* __p, size_t __n) ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'class std::vector&lt;Obstacle&amp;&gt;': Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:165:23: error: forming pointer to reference type 'std::vector&lt;Obstacle&amp;&gt;::value_type {aka Obstacle&amp;}' typedef value_type* pointer; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:166:29: error: forming pointer to reference type 'std::vector&lt;Obstacle&amp;&gt;::value_type {aka Obstacle&amp;}' typedef const value_type* const_pointer; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:167:23: error: forming pointer to reference type 'std::vector&lt;Obstacle&amp;&gt;::value_type {aka Obstacle&amp;}' typedef value_type* iterator; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:168:29: error: forming pointer to reference type 'std::vector&lt;Obstacle&amp;&gt;::value_type {aka Obstacle&amp;}' typedef const value_type* const_iterator; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:178:49: error: forming pointer to reference type 'Obstacle&amp;' typedef std::reverse_iterator&lt;const_iterator&gt; const_reverse_iterator; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:179:43: error: forming pointer to reference type 'Obstacle&amp;' typedef std::reverse_iterator&lt;iterator&gt; reverse_iterator; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:189:16: error: no members matching 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}::_M_allocate' in 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}' using _Base::_M_allocate; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:190:16: error: no members matching 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}::_M_deallocate' in 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}' using _Base::_M_deallocate; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:191:16: error: no members matching 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}::_M_start' in 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}' using _Base::_M_start; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:192:16: error: no members matching 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}::_M_finish' in 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}' using _Base::_M_finish; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:193:16: error: no members matching 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}::_M_end_of_storage' in 'std::vector&lt;Obstacle&amp;&gt;::_Base {aka struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;}' using _Base::_M_end_of_storage; ^ In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\iosfwd:22:0, from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\iterator:35, from Navigation.ino:1: c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h: In instantiation of 'class std::allocator&lt;Obstacle&amp;&gt;': Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:638:22: error: forming pointer to reference type 'Obstacle&amp;' typedef _Tp* pointer; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:639:22: error: forming pointer to reference type 'Obstacle&amp;' typedef const _Tp* const_pointer; ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_alloc.h:658:8: error: forming pointer to reference type 'Obstacle&amp;' _Tp* allocate(size_type __n, const void* = 0) { ^ Navigation.ino: In constructor 'std::vector&lt;_Tp, _Alloc&gt;::vector(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;; std::vector&lt;_Tp, _Alloc&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;]': Navigation.ino:36:24: note: when instantiating default argument for call to std::vector&lt;_Tp, _Alloc&gt;::vector(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;; std::vector&lt;_Tp, _Alloc&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;] In file included from c:\program files (x86)\arduino\hardware\tools\avr\avr\include\vector:35:0, from Navigation.ino:2: c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::_Vector_base&lt;_Tp, _Alloc&gt;::~_Vector_base() [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;]': c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:240:16: required from 'std::vector&lt;_Tp, _Alloc&gt;::vector(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;; std::vector&lt;_Tp, _Alloc&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;]' Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:21: error: 'struct std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;' has no member named '_M_deallocate' ~_Vector_base() { this-&gt;_M_deallocate(_Base::_M_start, _Base::_M_end_of_storage - _Base::_M_start); } ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:21: error: '_M_start' is not a member of 'std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;::_Base {aka std::_Vector_alloc_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt;, true&gt;}' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:83: error: '_M_start' is not a member of 'std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;::_Base {aka std::_Vector_alloc_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt;, true&gt;}' ~_Vector_base() { this-&gt;_M_deallocate(_Base::_M_start, _Base::_M_end_of_storage - _Base::_M_start); } ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:117:83: error: '_M_end_of_storage' is not a member of 'std::_Vector_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt; &gt;::_Base {aka std::_Vector_alloc_base&lt;Obstacle&amp;, std::allocator&lt;Obstacle&amp;&gt;, true&gt;}' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::_Vector_alloc_base&lt;_Tp, _Allocator, true&gt;::_Vector_alloc_base(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Allocator = std::allocator&lt;Obstacle&amp;&gt;; std::_Vector_alloc_base&lt;_Tp, _Allocator, true&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;]': c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:110:54: required from 'std::_Vector_base&lt;_Tp, _Alloc&gt;::_Vector_base(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;; std::_Vector_base&lt;_Tp, _Alloc&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;]' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:240:16: required from 'std::vector&lt;_Tp, _Alloc&gt;::vector(const allocator_type&amp;) [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;; std::vector&lt;_Tp, _Alloc&gt;::allocator_type = std::allocator&lt;Obstacle&amp;&gt;]' Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base&lt;_Tp, _Allocator, true&gt;::_M_start' : _M_start(0), _M_finish(0), _M_end_of_storage(0) ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base&lt;_Tp, _Allocator, true&gt;::_M_finish' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:85:53: error: using invalid field 'std::_Vector_alloc_base&lt;_Tp, _Allocator, true&gt;::_M_end_of_storage' c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h: In instantiation of 'std::vector&lt;_Tp, _Alloc&gt;::~vector() [with _Tp = Obstacle&amp;; _Alloc = std::allocator&lt;Obstacle&amp;&gt;]': Navigation.ino:36:24: required from here c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42: error: '_M_start' was not declared in this scope ~vector() { destroy(_M_start, _M_finish); } ^ c:\program files (x86)\arduino\hardware\tools\avr\avr\include\stl_vector.h:284:42: error: '_M_finish' was not declared in this scope Error compiling. </code></pre>
<pre><code>std::vector&lt;Test&amp;&gt; test </code></pre> <p>Yes, well I doubt you can make a vector of references. A vector of <strong>pointers</strong> I could believe.</p> <p>See, for example: <a href="https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references">https://stackoverflow.com/questions/922360/why-cant-i-make-a-vector-of-references</a></p>
14054
|led|attiny|softwareserial|midi|
Interfacing an ATtiny85 with MIDI via Software Serial
2015-08-09T22:58:55.517
<p>In order to finish a synth project that I'm working on I built a MIDI interface. To test it, I drew up some code which (is supposed to) light up an LED when any key is pressed. The light turns off again when the key is released. This will later be merged with another branch of code <a href="https://arduino.stackexchange.com/questions/13354/writing-midi-notes-more-quickly-to-a-shift-register-with-arduino/13362#13362">here</a> to tell me <em>which</em> note is playing. This sounds simple enough but the devil's in the details. Due to my project's size constraints I am using ATMEL's ATtiny85 chip instead of my Arduino Uno. The ATtiny doesn't support the Arduino Serial library and by extension the standard MIDI library. As I can't make use of simple functions like MIDI.read() I've opted to work with an alternative Software Serial technique I adapted from an <a href="http://www.instructables.com/id/Send-and-Receive-MIDI-with-Arduino/?ALLSTEPS" rel="nofollow noreferrer">Instructable</a>. Unfortunately, the results have been less than exemplary. Simply put, the LED almost never lights up. I have conducted two test only 1 of which <em>somewhat</em> succeeded:</p> <p>1)</p> <pre><code>if(velocityByte &gt; 0 ){digitalWrite(LED, HIGH);} if(velocityByte == 0 ){digitalWrite(LED, LOW);} </code></pre> <p>Initially, I had figured that would be the most successful of my options. My keyboard* is binary about its ouput velocity. There are no pressure sensors so "on" is on and "off" is off. Unfortunately, however, the code seems to think otherwise.</p> <p>2)</p> <pre><code>if(commandByte == noteOn ){digitalWrite(LED, HIGH);} if(commandByte != noteOff ){digitalWrite(LED, LOW);} </code></pre> <p>Though originally less sure of this one, I've found it to be better than the other at catching notes. noteOn is the integer 144. While it does in fact trigger it does so only very rarely - once every 10 presses or so.</p> <p>I believe I have however, whittled down the possible number of problems to 2:</p> <p>1) Something is up with one or more of my calls to Serial. I've never really felt super confident with the author's method of obtaining data from Serial. For one, I have no confidence that I can insure I have collected the correct byte. If the code were to somehow "miss" counting a byte would it not assign, say, a commandByte to a noteByte? Is a better method available?</p> <p>2) My keyboard's MIDI protocol is incompatible with my if-statement cases. At first I was under the assumption that my keyboard never sends a true "note off" message of any kind but instead a velocity = 0 message. But my test casts much doubt on this being the case and because of this, I don't <em>really</em> know how the keyboard handles note off messages. Does anyone else know?</p> <p>*A Yamaha YPT-230 </p> <pre><code>//MIDI INPUT LED TEST //Adapted from code written //by Instructables user Amanda Ghassaei #include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(0, 1); //RX, TX #define LED 2 byte commandByte; byte noteByte; byte velocityByte; byte noteOn = 144; byte noteOff = 128; void setup(){ mySerial.begin(31250); digitalWrite(LED, LOW); delay(1000); } void checkMIDI(){ do{ commandByte = mySerial.read();//read first byte noteByte = mySerial.read();//read next byte velocityByte = mySerial.read();//read final byte if (commandByte == noteOn){ digitalWrite(LED, HIGH); } if(commandByte != noteOn){ digitalWrite(LED, LOW); } } while (mySerial.available() &gt; 2);//when at least three bytes available } void loop(){ checkMIDI(); } /* void gotNoteOn(commandByte, noteByte, velocityByte){ digitalWrite(LED,HIGH); } void gotNoteOff(commandByte, noteByte, velocityByte){ digitalWrite(LED,LOW); } */ </code></pre> <p><strong>UPDATE</strong> Following a suggesting, I have replaced the do .. while loop with an ordinary while loop. Relevant changes below:</p> <pre><code>void checkMIDI(){ while(mySerial.available() &gt; 2){ commandByte = mySerial.read(); if (velocityByte &gt; 0x00){//if note on message digitalWrite(LED, HIGH); } if(velocityByte == 0x00){ digitalWrite(LED, LOW); } } } </code></pre> <p>I'd like to think it's an improvement but if so only a slight one. Curiously, it almost works backwards - The default state of the LED is on while pressing a key produces no change pressing and <em>holding</em> causes the light to briefly shut off. But even this is sporadic. It may also be worth noting that I elected to use hex '0x00' as opposed to decimal '0'.</p> <p><strong>UPDATE II / NOTE</strong> Having slept on the problem I think I now understand why I am encountering this issue in the first place. The author of the Instructables code I adapted used an Arduino for both MIDI In as well as MIDI Out. Had they simply hooked one Arduino Uno to the other in an in/out configuration they could have perfectly ensured there were no running status issues by just never sending any running status messages. This would explain the lack of conformity to the actual realities of MIDI on the input side. If you can control exactly what data you are sending on one end (MIDI Out) it becomes fairly trivial to receive that data on the other end (MIDI In). Generalizing, the author may have assumed that a true keyboard behave the same thing and failed to actually verify this. Thoughts?</p> <p><strong>UPDATE III</strong> Following the lead of CL but deviating somewhat because I didn't fully understand what CL was doing, I have written up a highly derivative, new code. It is based around what I now know to be the highly fluid nature of MIDI messages and seeks to intelligently discriminate important messages from non-important messages based on content. It does not work (except for LED test at the beginning) but seems like a promising step nonetheless.</p> <pre><code>//MIDI Input LED Test #include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(0, 1); //RX, TX #define LED 2 //Test LED void setup(){ mySerial.begin(31250); digitalWrite(LED, HIGH); //Test delay(1000); digitalWrite(LED, LOW); delay(1000); } void loop(){ checkMIDI(); } void checkMIDI(){ /*Two of the three independent types of bytes are always distinct and can be identified simply by their values. A Status byte (on channel 1 at least) is always either 0x80 (off) or 0x90 (on). No other type of message (Note, Velocity) can ever take this value and so if this is the value of the byte received I can be assured it is a Status byte. The Note and Velocity bytes are a bit (haha) dicier. They have overlapping ranges with both taking values of anywhere between 0x00 to 0x7F. *Ordinarily*. A caveat is that my Yamaha YPT-230 is binary as far as velocity goes. A YPT-230 data is either 0x00 (full off) or 0x7F (full on). As long as a Note byte is never 0 or 127 I can use this to discriminate between these two types in this manner. */ if(mySerial.available() &gt; 0){ byte b = mySerial.read(); if(b == 0x80 || 0x90){ byte commandByte = b; }else if(b == 0x00 || 0x7F){ if(b == 0x00){ digitalWrite(LED, LOW); //If vel = 0 turn LED off }else if(b == 0x7F){ digitalWrite(LED, HIGH); //If vel = 127 turn LED on } //velocityByte = b; }else{ byte noteByte = b; //Do nothing with this for right now. } } } </code></pre>
<p>Got it! After doing the requisite amount of research... I've developed a <em>much</em> improved checking system which allows me to truly demarcate between messages during running status much like Nick Gammon's code. While the code seems to work perfectly now it was still a bit glitchy when I tried it the other day. Perhaps I accidentally fixed it, most likely it'll crop back up again. How does it look?</p> <pre><code>//MIDI_Input_0x01 #include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(0,1); const int LED = 2; int isStatus(); int isAftertouch(); int isRealTimeCategory(); int dataByte; int velocityByte; int result; void setup() { mySerial.begin(31250); pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); delay(1000); digitalWrite(LED, LOW); delay(1000); } void loop() { while(mySerial.available()) { //This is the protocol for reading new stuff byte myByte = mySerial.read(); if(isRealTimeCategory(myByte)) { ; } else { if(isStatus(myByte)) { result = (myByte | 0x80); //0b10000000 switch(result) { case 0b10000000: digitalWrite(LED, LOW); break; case 0b10010000: digitalWrite(LED, HIGH); break; case 0b10100000: break; case 0b10110000: break; case 0b11000000: break; case 0b11010000: break; case 0b11100000: break; case 0b11110000: break; } } else { byte myByte = mySerial.read(); //This is the protocol for reading new stuff if(isRealTimeCategory(myByte)) { ; } else { if(myByte &gt; 0) { digitalWrite(LED, HIGH); } else { digitalWrite(LED, LOW); } } } } } } //END /********************** //function declarations **********************/ int isStatus(int b) { if( (b &amp; 0x80) == 0x80) { return 1; } else if( (b &amp; 0x80) == 0) { return 0; } } int isAftertouch(int b) { if( (b &amp; 0xf0) == 0xa0) { return 1; } else //if( (b &amp; 0xf0) != 0xa0) { return 0; } } int isRealTimeCategory(int b) { if(b &gt;= 0xF8) { return 1; } else { return 0; } } </code></pre> <p>On top of this, I managed to tweak the code to output particular values to a shift register as I had initially intended. The method I use to differentiate between note and velocity bytes is less than ideal but works on my keyboard. Because of certain limitations it only works over a range of 13 notes but that's fine for now. Code and flowchart below.</p> <pre><code>// MIDI_Input_0x02 #include &lt;SoftwareSerial.h&gt; //The Attiny does not natively support the Serial library so this //is the work-around. SoftwareSerial mySerial(0,1); const int latchPin = 2; const int clockPin = 3; const int dataPin = 4; const int gate = 1; //Note that initially, this was the tx pin. //In this configuration absolutely every Attiny85 pin is used. int isStatus(); int isAftertouch(); int isRealTimeCategory(); int result; int dataByte; int velocityByte; //int noteApprox[13] = {1,3,5,7,9,12,14,17,20,23,26,29,32}; int noteApprox[13] = {32, 29, 26, 23, 20, 17, 14, 12, 9, 7, 5, 3, 1}; //The above numbers are approximately 100 cents //apart from one another. This corresponds to notes of a scale. //They descend here because their corresponding //voltages will later become inverted in the circuit. void setup() { mySerial.begin(31250); pinMode(latchPin, OUTPUT); pinMode(clockPin, OUTPUT); pinMode(dataPin, OUTPUT); pinMode(gate, OUTPUT); //'Gate' controls the level of the //envelope generators. The signal //becomes inverted later. digitalWrite(gate, HIGH); //A simple test to ensure the delay(1000); //circuit is wired correctly digitalWrite(gate, LOW); delay(1000); } void loop() { while(mySerial.available()) { //This is the protocol for reading new stuff byte myByte = mySerial.read(); //Read the oldest byte in the buffer if(isRealTimeCategory(myByte)) //See Function Notes { ; } else { if(isStatus(myByte)) //See Function Notes { result = (myByte | 0x80); //0b10000000 switch(result) { case 0b10000000: digitalWrite(gate, LOW); //0b10000000 is the note Off break; //message case 0b10010000: digitalWrite(gate, HIGH); //10010000 is the note On break; //message case 0b10100000: //Absolutely none of these are important. break; case 0b10110000: break; case 0b11000000: break; case 0b11010000: break; case 0b11100000: break; case 0b11110000: break; } } else //This is the part where I assume it's a data byte. { //this might be causing problems... if( (myByte &gt; 48) &amp;&amp; (myByte &lt; 61) ) //&lt;-- That's 13 notes. An octave and an extra { digitalWrite(latchPin, LOW); shiftOut(dataPin, clockPin, MSBFIRST, noteApprox[myByte - 48]); //Write to the shift digitalWrite(latchPin, HIGH); //register. } else { digitalWrite(gate, LOW); } byte myByte = mySerial.read(); if(isRealTimeCategory(myByte)) { ; } else { if(myByte &gt; 0) { digitalWrite(gate, HIGH); //Velocity Byte } else { digitalWrite(gate, LOW); } } } } } } //END /*************************** function Declarations ***************************/ int isStatus(int b) //Determines if the incoming byte is a Status Byte of some sort. //Returns 1 if so and 0 if not. { if( (b &amp; 0x80) == 0x80) { return 1; } else if( (b &amp; 0x80) == 0) { return 0; } } int isRealTimeCategory(int b) //Determines if the incoming byte is a Real Time Category byte { //I'm not positive what these *are* but they are only 1 byte long if(b &gt;= 0xF8) //a piece and easily detected (they're all greater than 11111000). { return 1; } else { return 0; } } /* Bit Math Notes if(b &amp; 0x80) == 0x80) b = 10000000 0x80 = 10010000 &amp; ________ 10000000 =/= 10010000 Not a Note On byte. Return 0. b = 10010000 0x80 = 10010000 &amp; ________ 10010000 == 10010000 A Note On byte! Hooray! Return 1. */ </code></pre> <p><a href="https://i.stack.imgur.com/NwdwV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NwdwV.jpg" alt="Flowchart"></a></p>
14064
|programming|remote-control|
Run an Arduino without a PC
2015-08-10T09:45:59.630
<p>I would like to use an Arduino to make tasks in my life automatic - maybe to rotate every morning a motor, or to open a door. </p> <p>So, can I run an Arduino as solo with no pc needed? Can i connect it to the Internet and can I setup software like PHP and Apache on it to control it over the internet? Has it any protocols like SSH like a normal server? </p> <p>As an example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino would run a function...</p> <p>Is that possible?</p> <p>thanks ahead</p>
<blockquote> <p>I will use arduino to make tasks in my life automatic maybe to let rotate every morning a motor or to open the door.</p> </blockquote> <p>That's the kind of thing it's designed for.</p> <blockquote> <p>So i will ask can i run arduino as solo so no pc needed, </p> </blockquote> <p>Yes, you only need a PC to program it, once programmed it will run without the PC.</p> <blockquote> <p>Can I connect it to the internet </p> </blockquote> <p>Yes, there are Ethernet and WiFi shields available for connecting it to a network.</p> <blockquote> <p>and can I setup PHP and Apache on it to control it over it; has it any protocols like SSH like an normal server ?</p> </blockquote> <p>No. The Arduino isn't powerful enough to run software like that. You would normally connect it via the network / internet to a server to process data. It would just receive simple instructions or send data to the server for processing.</p> <blockquote> <p>as example: I will send over any protocol a signal to my Arduino with a certification and then the Arduino is running a function...</p> </blockquote> <p>I assume by "a certification" you want to run SSL on the Arduino. That's not going to happen since it's way too underpowered for that. As I mentioned earlier, the Arduino would connect to a server on the internet to receive its instructions, or you could interface to it directly within your local network (say from a smart phone) through a simple web server interface (very simplistic due to lack of memory - a few buttons and text, that sort of thing).</p>
14078
|serial|
Is parity check hardware only or can I read it? ( Arduino Mega )
2015-08-10T21:10:57.727
<p>Maybe a simple question, but I can't seem to find it.</p> <p>Parity check is simple error detection.</p> <p>But is in done in hardware on the arduino and is the data discarded before i can read it from software?</p> <p>The reason I ask this quote from Thomas</p> <blockquote> <p>1 Command bit, set on the first character of each datagram. Reflected in the parity bit of most UARTs. Not compatible with NMEA0183 but well suited for the multiprocessor communications mode of 8051-family microcontrollers (bit SM2 in SCON set).</p> </blockquote> <p>From <a href="http://www.thomasknauf.de/rap/seatalk1.htm#Dat" rel="nofollow">http://www.thomasknauf.de/rap/seatalk1.htm#Dat</a> which might have confused me. So I guess this is not an option ... after the feedback from users.</p> <p>So i need to read the 9 bit and since the hardware support it. The Arduino team won't implement it, since it has a bigger overhead and it's really not used anymore ... I agree ... but the SeaTalk bus uses it ... so I'm stuck here.</p> <p>But after more seaching I found this GitHub repo: <a href="https://github.com/rob42/FreeboardPLC_v1_2" rel="nofollow">https://github.com/rob42/FreeboardPLC_v1_2</a> which have made changes to the HardwareSerial.h and HardwareSerial.cpp but only for version 1.5.7</p> <p>Think I will go for this version unless someone have done the mods to 1.6.x ... have searched the web. Later I will try to see if I can get it to work with 1.6.x ... but since this is all new. I'm taking small steps.</p>
<p>This came up a while back on <a href="http://forum.arduino.cc/index.php?topic=91377.0" rel="nofollow">the Arduino Forum</a> - talking about <a href="http://forum.arduino.cc/index.php?topic=54120" rel="nofollow">Asynchronous SeaTalk</a>.</p> <p>I made a modified version of HardwareSerial which can be downloaded from <a href="http://gammon.com.au/Arduino/HardwareSerial9bit.zip" rel="nofollow">http://gammon.com.au/Arduino/HardwareSerial9bit.zip</a></p> <p>Changes are:</p> <ul> <li><p>The internal buffers have been changed from 8-bit characters to 16-bit characters (to hold the 9th bit). Thus the buffers double in size.</p></li> <li><p>There is a new argument to the Serial.begin() function, which is a boolean, whether or not you want 9-bit mode. It defaults to false.</p></li> <li><p>There is a new function <code>Serial.write9bit ()</code>. This takes an unsigned int argument, letting you supply a character with the 9th bit set. I didn't want to change the existing write function because it is used in the Print class.</p></li> <li><p>The read function, which already returns an int, now will return the 9th bit where required.</p></li> </ul> <hr> <p>Example code:</p> <pre class="lang-C++ prettyprint-override"><code>void setup () { Serial.begin (115200); // debugging prints Serial1.begin (115200, true); // 9 bit mode Serial2.begin (115200, true); // 9 bit mode Serial.println ("--- starting ---"); } // end of setup int i; void loop () { Serial1.write9bit (i++); // send another byte // display incoming on Serial2 if (Serial2.available ()) Serial.println ((int) Serial2.read (), HEX); // check if we have sent all possible characters if (i &gt;= 0x200) { delay (100); while (Serial2.available ()) Serial.println ((int) Serial2.read (), HEX); delay (5000); i = 0; } // end of sent 512 bytes } // end of loop </code></pre> <hr> <p>As Ignacio Vazquez-Abrams said, the hardware supports this 9-bit mode natively, it just takes a bit of fiddling around to make it work.</p> <p>Because of the way that hardware serial is integrated into the IDE it is, unfortunately, necessary to find your existing files:</p> <ul> <li>HardwareSerial.cpp</li> <li>HardwareSerial.h</li> </ul> <p>... and replace them with the ones in the download.</p> <hr> <p>Note that this is for version <strong>1.0.1</strong> of the IDE. No guarantees are given that this will work with other versions. This was written a while back, I'm not sure what changes have been made to HardwareSerial in the meantime.</p> <p>The actual changes are here: <a href="http://gammon.com.au/Arduino/hardwareSerial_diffs.txt" rel="nofollow">http://gammon.com.au/Arduino/hardwareSerial_diffs.txt</a></p> <p>You could use those to guide your implementation on more recent versions, if the file download does not work "as is".</p>
14085
|atmega328|analogread|adc|
Usefulness of measuring 0v using ADC
2015-08-11T15:21:31.470
<p>I'm looking at the datasheet of the ATMega328, and I see the different channels you can select for AD conversion. ADC0..7, ADC8 (temperature), 1.1V (V<sub>BG</sub>), and lastly <strong>0V (GND)</strong>.</p> <ul> <li>What would be the use of measuring 0V? </li> <li>Would it ever result in a reading other than <code>0</code>? I find it very intriguing. </li> </ul> <p>The datasheet doesn't seem to give any additional information about it. </p> <p><a href="http://www.atmel.com/Images/doc8444.pdf" rel="nofollow">AVR126</a> seems to give a hint:</p> <blockquote> <p>configure 0V (GND) in ADC by setting Mux bitfield (MUX3:0) equal to 1111. This is done to discharge the capacitor of ADC. </p> </blockquote> <p>Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz). </p> <p>Is it to protect the ADC from to high a voltage in the ADC capacitor, when changing to a different (lower) reference voltage? Rather odd you need software to protect the IC, and it's not even mentioned in the datasheet. Also I've never seen anyone do this (e.g. when measuring the internal temperature of the ATMega).</p>
<blockquote> <p>Though I find the document rather strange (incomplete, lacking certain info, running the ADC at 500kHz while the datasheet says to not exceed 200kHz). </p> </blockquote> <p>The document actually says:</p> <blockquote> <p>The ADC can prescale the system clock to provide an ADC clock that is between 50kHz and 200kHz <strong>to get maximum resolution</strong>.</p> </blockquote> <p>(My emphasis)</p> <p>It goes on to say:</p> <blockquote> <p>If ADC resolution of less than 10 bits required, then the ADC clock frequency can be higher than 200kHz. At 1MHz it is possible to achieve eight bits of resolution maximum.</p> </blockquote> <p>I did some testing on <a href="http://www.gammon.com.au/adc" rel="nofollow">this page</a> with different prescalers. The results showed that reasonable results could be obtained even with a 1 MHz ADC clock:</p> <pre><code>Prescaler 2 Analog port = 0, average result = 1023 Analog port = 1, average result = 1023 Analog port = 2, average result = 1023 Analog port = 3, average result = 1022 Time taken = 26220 Prescaler 4 Analog port = 0, average result = 673 Analog port = 1, average result = 718 Analog port = 2, average result = 512 Analog port = 3, average result = 193 Time taken = 32780 Prescaler 8 Analog port = 0, average result = 842 Analog port = 1, average result = 677 Analog port = 2, average result = 509 Analog port = 3, average result = 34 Time taken = 46040 Prescaler 16 Analog port = 0, average result = 1022 Analog port = 1, average result = 672 Analog port = 2, average result = 509 Analog port = 3, average result = 0 Time taken = 73164 Prescaler 32 Analog port = 0, average result = 1022 Analog port = 1, average result = 672 Analog port = 2, average result = 508 Analog port = 3, average result = 0 Time taken = 128040 Prescaler 64 Analog port = 0, average result = 1022 Analog port = 1, average result = 672 Analog port = 2, average result = 508 Analog port = 3, average result = 0 Time taken = 240972 Prescaler 128 Analog port = 0, average result = 1022 Analog port = 1, average result = 672 Analog port = 2, average result = 508 Analog port = 3, average result = 0 Time taken = 448108 </code></pre> <p>The four test voltages were, and their results <em>should have</em> been:</p> <ul> <li>5V (should return 1023)</li> <li>3.3V (should return 674)</li> <li>2.5V (should return 511)</li> <li>0V (should return 0)</li> </ul> <hr> <p>The tests were done in rapid succession, no allowing for the ADC to recharge or anything:</p> <pre class="lang-C++ prettyprint-override"><code> unsigned long startTime = micros (); for (int i = 0; i &lt; ITERATIONS; i++) { for (int whichPort = lowPort; whichPort &lt;= highPort; whichPort++) { int result = analogRead (whichPort); totals [whichPort - lowPort] += result; } } unsigned long endTime = micros (); </code></pre>
14106
|arduino-mega|compile|
How do I compile the Marlin firmware?
2015-08-11T22:39:16.320
<p>I have a folder of mostly .h and .cpp files for the Marlin firmware (3D Printing) from <a href="https://nwreprap.com/software/" rel="nofollow">here</a>.</p> <p>How do I compile that so I can upload it to my Arduino Mega with Ramps?</p>
<p>You need to open the .ino file. that is the project file for the Marlin Firmware. then upload that. Also do some research about the settings for Marlin. It isn't just plug and play, you have to enter some information about your individual stepper motors.</p> <p><a href="http://solidutopia.com/marlin-firmware-user-guide-basic/" rel="nofollow">http://solidutopia.com/marlin-firmware-user-guide-basic/</a> - heres a guide for Marlin.</p> <p>the cpp and h files are c++ files that are apart of the project. the Arduino IDE cannot open these individually. the .ino file is the project file that will allow you to open up the entire project and not just one portion of it.</p>
14107
|web-server|threads|
Is it possible to accept multiple web requests at once?
2015-08-12T00:52:37.247
<p>I have an Arduino with ethernet shield and there are 8 different URLs that can be called to perform different actions.</p> <p>The program loads and runs as expected for the most part, but, if it is busy doing an action, it won't accept the next one until the current action has finished.</p> <p>Basically, the code's main loop listens for a client connection, then has a bunch of ifs that look in the URL that was called (for a query string) and then process the command.</p> <p>I have looked at a few answers on here, but none deal with listening to HTTP requests. One recommended a library, but, I couldn't quickly get it to compile, and the other answer recommended a state machine - I do like this approach, however, I haven't had time to implement and it doesn't "feel" right as the listening for a HTTP request works on a <code>if(client)</code> basis.</p> <p>I was wondering if anyone has done this before and/or has any advice?</p>
<p>It can be done. The Arduino is a single tasking environment so you have to make sure your code is non-blocking.</p> <p>BlinkWithoutDelay is a good starting point (thanks @Majenko) but you should also look at the <a href="http://playground.arduino.cc/Code/Timer1" rel="nofollow">Timer1</a> library.</p> <p>Basically your programs needs to do all the steps it can right away and whenever it does something that could block, it must do it asynchronously and during a later loop() run check if it's finished and continue with the next task. The alternative (if you know how long your task will take) is to use the timer interrupt with the library mentioned above.</p>
14111
|wifi|ethernet|
Arduino for delivering a WoL signal over ethernet, when receiving a specific command over WiFi
2015-08-12T05:08:07.277
<p>I'd like to assemble a device that could accomplish the following:</p> <ul> <li>Connect to my home <a href="https://www.arduino.cc/en/Main/ArduinoWiFiShield" rel="nofollow">wifi</a> (WPA2-Personal)</li> <li>Connect to my home PC with via Ethernet cable</li> <li>Able to send <a href="https://en.wikipedia.org/wiki/Wake-on-LAN" rel="nofollow">WoL</a> signal to the PC when getting a signal over wireless connection</li> <li>The whole set up needs to be less than 45USD, desirably much less, otherwise I'd just buy a wireless bridge.</li> </ul> <p>The goal is both to have a useful device (that will allow me to wake up my pc remotely) but also have fun learning something new (arduino).</p> <p>I have no background in Arduino or Electronics in general. I program well though and learn fast.</p> <p>Do you think Adruino is adequate for the above? Is soldering required (I'd rather not, or at least not a lot)? </p>
<p>The Raspberry Pi is definitely the easiest way to do this, however it will use more power.</p> <p>You can do it within your budget by using Arduino clone hardware from places like AliExpress.</p> <p>If you don't mind the extra effort, it certainly can be done using the Arduino and a wireless and ethernet shield.</p> <p>A WiFi shield is around $17, an ethernet shield is less than $6 and an Arduino Uno clone is around $3. Make sure you can combine these shields (I haven't checked). There's also a combined Linux, Ethernet + Wifi Yun shield for around $30.</p>
14125
|eeprom|
Arduino digitalWrite 1 or 0 instead of HIGH or LOW
2015-08-12T16:28:26.320
<p>Is it ok to use </p> <pre><code>digitalWrite(pin, 1) instead of digitalWrite(pin, HIGH) </code></pre> <p>or </p> <pre><code>digitalWrite(pin, 0) instead of digitalWrite(pin, LOW) </code></pre> <p>I want it that way to make the coding lesser because I save values on EEPROM with 1's and 0's. So if I want to use EEPROM value, I can call it this way</p> <pre><code>digitalWrite(pin, EEPROM.read(1)) </code></pre>
<p>When you look at the source code of Arduino, HIGH is defined as 1 and LOW is defined as 0 using #define.</p> <p>You may heard about <strong>Preprocessor, Compiler, and Linker</strong>. When you build the project, preprocessor do its job before the code is compiled. What the preprocessor does is basically converting defined words into corresponding value.</p> <p>For example when you write a syntax like:</p> <pre><code>digitalWrite(1, HIGH); </code></pre> <p>When you build your project, the preprocessor converts the above like into this:</p> <pre><code>digitalWrite(1, 1); </code></pre> <p>Then the code is compiled. Therefore, there is no difference between HIGH and 1. So, if the result of <code>EEPROM.read(1)</code> is either 0 or 1, there should be no problem.</p>
14130
|arduino-uno|wifi|web-server|esp8266|
NODEMCU vs AT for esp8266
2015-08-12T18:35:50.853
<p>I have recently started working on esp8266 wifi module and arduino uno. I am a little confused.</p> <p>I have created a small Web page with esp8266 AT commands. Now I want use it for receiving data such as changes on the Arduino inputs.</p> <p>I have seen many similar implementations using jQuery for that purpose, but I don't know where to place that jQuery file.</p> <p>Furthermore, is it possible to use NODEMCU firmware and still toggle arduino pins and transmit data to esp8266?</p> <p>I want to use Arduino for:</p> <ul> <li>reading voltage levels</li> <li>publish the values read to the Web page</li> <li>toggle a relay when a button on the Web page is pressed.</li> </ul> <p>Please kindly help me out or point me in the right direction to search</p>
<p>This is quite a huge topic to cover in one answer, but I will do my best.</p> <p>The NodeMCU can be used in three distinctly different ways. First is the <em>AT</em> mode, where you have installed the <em>AT</em> firmware. In this mode the NodeMCU is purely a slave device to the Arduino. Once you have got the Arduino to configure the NodeMCU in the right way to receive data on a socket it will send that data back to the Arduino verbatim through the serial port with special tags added (indicating what the data is, and which socket it arrived on, etc). It is then up to you to receive that data, interpret it in whatever way you desire (as a HTTP GET request most likely) and craft the correct response (if any) and send it to the NodeMCU to send back (again using the <em>AT</em> commands).</p> <p>What you send through the socket is entirely up to you. By the sounds of things you will be making a simple GET request from a web browser to perform an operation, and maybe respond with some data to display in the web page. That can be easy, or it can be hard - it's as hard as you want to make it. The simplest way is to rely on an external web server to serve the main content and structure of the page, then use jQuery or Prototype to make an AJAX call to your NodeMCU and receive back any data there may be. In this case everything will be on your external web server except the single (or few) URL(s) that perform operations and return data. That includes the jQuery (which is just Javascript, it's loaded from your web server into the browser and executed), any code for buttons, images, HTML, everything (on the web server, that is).</p> <p>The other two ways the NodeMCU can operate are both very different to that. They differ mainly in the language that is used with them. You can use the NodeMCU with its own LUA language to get it to do almost anything you want. That includes receiving the HTTP GET request and serving the data for it, all without the help of the Arduino. In fact, doing that, there is little need for the Arduino any more - the NodeMCU has an analog input and multiple digital IO lines - it also has SPI available for interfacing with external ADC chips if you want more than one analog input. So you can have everything internal to the NodeMCU without needing the Arduino at all. If you do want to keep the Arduino then you can interface to it through the serial port (as you would in <em>AT</em> mode) but using your own custom protocol in whatever way you see fit.</p> <p>The third way is to program the NodeMCU as if it were itself an Arduino. There is an ESP8266 core for the Arduino IDE (and for <a href="http://uecide.org/beta" rel="nofollow">UECIDE Beta</a> as well) which allows you to program the NodeMCU in the same language and with a similar API, as the Arduino. This even more removes the need for the Arduino. You can get the Arduino core from Github here: <a href="https://github.com/esp8266/Arduino" rel="nofollow">https://github.com/esp8266/Arduino</a></p> <p>Incidentally, the Xtensa core in the ESP8266 is considerably more powerful than your typical Arduino, being 32-bit, having its own DSP, and with much more RAM and Flash memory. It kind of makes the Arduino redundant.</p>
14133
|lcd|button|rtc|
Delay workaround needed for RTC and LCD-shield buttons
2015-08-12T19:46:29.923
<p>Following configuration:</p> <ul> <li>Arduino UNO R3</li> <li>Real Time Clock DS1307RTC</li> <li>LCD1602 Shield with buttons</li> <li>Photo resistor</li> <li>DHT11 (Temp &amp; Humidity Sensor)</li> </ul> <p>I need the function delay(1000) to display the seconds properly from the RTC to the LCD. But, that way I always have to keep the buttons pressed for up to 1 second until they react.</p> <p>How can I workaround or solve this problem?</p> <p>Idea 1: Multitasking would come in handy here :-) pseudocode:</p> <pre><code>task 1: listen for LCD buttons task 2: display seconds with a delay of 1000ms </code></pre> <p>But there isn’t a way Arduino could multitask, isn’t it?</p> <p>Idea 2: As far as I saw in the header files for the RTC, the smallest readable unit is seconds. Otherwise I could have used something like a millisecond reader in a while condition to listen for the buttons; pseudocode:</p> <pre class="lang-C++ prettyprint-override"><code>while (RTC-millisecond &lt; 1000ms) { // listen for buttons // so a second passes, which gives the RTC time to display the seconds values } </code></pre> <p>-</p> <p><strong>EDIT</strong></p> <p>updated code, thanks to @NickGammon and Gerben:</p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;LiquidCrystal.h&gt; #include &lt;Wire.h&gt; #include &lt;Time.h&gt; #include &lt;DS1307RTC.h&gt; #include &lt;DHT.h&gt; // initialize the library with the numbers of the interface pins // RS E D4 D5 D6 D7 (maybe wrong order) LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // pins on which the sensor is connected #define DHTPIN A1 #define PHOTOPIN A2 // initialize DHT sensor #define DHTTYPE DHT11 DHT dht(DHTPIN, DHTTYPE); // define some values used by the panel and buttons int lcd_key = 0; int adc_key_in = 0; //#define btnRIGHT 0 //#define btnUP 1 //#define btnDOWN 2 //#define btnLEFT 3 //#define btnSELECT 4 //#define btnNONE 5 // FSM unsigned long previousMillis1 = 0; unsigned long previousMillis2 = 0; const long interval = 3000; // prototypes void print2digits(int number); int read_LCD_buttons(); void setup() { // open a serial connection to display values on PC Serial.begin(9600); // set up the number of columns and rows on the LCD lcd.begin(16, 2); // start DHT sensor dht.begin(); } void loop() { // set variable from struct tmElements_t tmElements_t tm; /********* Reading from sensors *********/ /*** DHT sensor ***/ // Reading temp or RH takes about 250 milliseconds! // Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor) float humid = dht.readHumidity(); float tempC = dht.readTemperature(); // Check if any reads failed and exit early (to try again). if (isnan(humid) || isnan(tempC)) { lcd.clear(); lcd.setCursor(0, 0); lcd.print("DHT reading failed!"); Serial.println("DHT reading failed!"); return; } // Compute heat index in Celsius (isFahreheit = false) float hiC = dht.computeHeatIndex(tempC, humid, false); /*** Photo resistor ***/ int lightReading = analogRead(PHOTOPIN); /********* Print to PC over serial connection *********/ // ... /********* Print values to LCD *********/ /* --- first line on LCD --- */ /*** RTC ***/ // set the cursor to LCD column 4, line 0 to center the clock lcd.setCursor(4, 0); // starts RTC reading and checks if it's working if (RTC.read(tm)) { static byte oldSecond = 60; // 60, because there is no 60'th second in a clock // display only if time changes if (tm.Second != oldSecond) { oldSecond = tm.Second; print2digits(tm.Hour); lcd.print(':'); print2digits(tm.Minute); lcd.print(':'); print2digits(tm.Second); } } else { lcd.clear(); lcd.setCursor(0, 0); if (RTC.chipPresent()) { lcd.print("Please run SetTime function"); } else { lcd.print("DS1307 read error!"); } delay(9000); } /* --- second line on LCD according to button --- */ lcd_key = ((lcd_key + read_LCD_buttons()) %3); // call button function, modulo 3 to cycle through /** // Test buttons: lcd.setCursor(1, 1); lcd.print("lcd var:"); lcd.print(lcd_key); */ unsigned long currentMillis = millis(); // FSM used for displaying DHT and photo values without flikering switch (lcd_key) { case 0: /*** Weekday and Date ***/ // display only if day changed static byte oldDay = 99; if (tm.Day != oldDay) { oldDay = tm.Day; lcd.setCursor(0, 1); lcd.print(" "); // 16 spaces to clear second line before printing lcd.setCursor(0, 1); //lcd.print(dayShortStr((weekday() + 1) % 7 )); // (day+1)%7 calculation for Swiss layout lcd.print(tm.Wday); // TEST lcd.print(weekday()); // TEST lcd.print(", "); print2digits(tm.Day); lcd.print('.'); print2digits(tm.Month); lcd.print('.'); lcd.print(tmYearToCalendar(tm.Year)); } break; case 1: /*** DHT Sensor ***/ if (currentMillis - previousMillis1 &gt;= interval) { previousMillis1 = currentMillis; lcd.setCursor(0, 1); lcd.print(" "); // 16 spaces to clear second line before printing lcd.setCursor(1, 1); lcd.print(hiC); lcd.print("*C "); lcd.setCursor(10, 1); lcd.print(humid); lcd.setCursor(12, 1); lcd.print("%RH "); } break; case 2: /*** Photo resistor ***/ if (currentMillis - previousMillis2 &gt;= interval) { previousMillis2 = currentMillis; lcd.setCursor(0, 1); lcd.print(" "); // 16 spaces to clear second line before printing lcd.setCursor(0, 1); lcd.print("Light "); lcd.setCursor(6, 1); lcd.print(lightReading); } break; } } // used to print 2 digits in the time values void print2digits(int number) { if (number &gt;= 0 &amp;&amp; number &lt; 10) { lcd.print('0'); } lcd.print(number); } // read the buttons int read_LCD_buttons() { adc_key_in = analogRead(0); //if (adc_key_in &gt; 1000) return btnNONE; // 1st option since it will be the most likely result (speed reasons) //if (adc_key_in &lt; 50) return btnRIGHT; //if (adc_key_in &lt; 195) return btnUP; // replaced by below one if (adc_key_in &lt; 195) return 1; // my button up ! //if (adc_key_in &lt; 380) return btnDOWN; //if (adc_key_in &lt; 555) return btnLEFT; //if (adc_key_in &lt; 790) return btnSELECT; //return btnNONE; // when all others fail, return this... return 0; } </code></pre>
<pre class="lang-C++ prettyprint-override"><code> // clean up screen before printing a new reply lcd.clear(); /* --- first line on LCD --- */ /*** RTC ***/ // set the cursor to LCD column 4, line 0 to center the clock lcd.setCursor(4, 0); </code></pre> <p>Straight away, that will cause flicker, right? For a few milliseconds the screen will go blank, and then get gradually redrawn. Why not omit the clear? You could put it in if you are changing display types (eg. from date to temperature) but you don't need to clear the screen every time. So:</p> <ul> <li><p>Don't call <code>delay()</code></p></li> <li><p>Don't clear the screen unless changing to displaying a different type of thing</p></li> <li><p>Only update the display at all if the new number (or time, or temperature, etc.) is <strong>different</strong> from what you just displayed.</p></li> <li><p>Just do the <code>setCursor()</code> to position the cursor and <strong>overwrite</strong> the information there previously. </p></li> <li><p>Preferably follow by a space or two in case a large number is replaced by a smaller one.</p></li> </ul> <hr> <p>Side-benefit: Since you have removed the delay, your project will now be much more responsive to key presses. Win win!</p> <hr> <h2>References</h2> <ul> <li><p><a href="http://www.gammon.com.au/statemachine" rel="nofollow">State machines</a></p></li> <li><p><a href="http://www.gammon.com.au/blink" rel="nofollow">How to do multiple things at once ... like cook bacon and eggs</a></p></li> </ul> <hr> <blockquote> <p>I am not quite sure how to do it </p> </blockquote> <pre class="lang-C++ prettyprint-override"><code> if (RTC.read(tm)) { static byte oldSecond = 99; // display if time changes if (tm.Second != oldSecond) { oldSecond = tm.Second; print2digits(tm.Hour); lcd.print(':'); print2digits(tm.Minute); lcd.print(':'); print2digits(tm.Second); } } </code></pre> <p>Similarly further down where you display the date / sensor.</p>
14137
|nrf24l01+|
Need help understanding how RF communication works with 2 arduinos
2015-08-12T23:04:36.800
<p>I have two arduinos (uno) and I would like to send the results of a key press on a 5X4 matrix pad to the other arduino. The matrix keypad works great. I can identify which key was pressed with a switch function. </p> <pre><code>switch (keypad()) //switch used to specify which button { case 0: Serial.print("Key A Pressed"); Serial.print(keypad()); messageToSend = 0; break; case 1: Serial.print("Key B Pressed"); Serial.print(keypad()); messageToSend = 1; break; case 2: Serial.print("Key C Pressed"); Serial.print(keypad()); messageToSend = 2; break; } </code></pre> <p>My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.</p> <ol> <li><p>What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?</p></li> <li><p>My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?</p></li> <li><p>Are RF units very different? Is this one particularly difficult?</p></li> <li><p>If I just want to send with one receive with the other shouldn't this simplify the code?</p></li> <li><p>What are pipes? How many can I open? </p></li> <li><p>If I have 3 or more of these what changes will I need to make to the code?</p></li> </ol> <p>Thanks!</p>
<blockquote> <p>My RF units are both nrf24l01. I have tried working with the sample code and I think the issue is I don't understand how the unit works well enough.</p> </blockquote> <p><a href="https://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo" rel="nofollow">Start here, this is the absolutely best resource</a> I could find. I use MIRF libary and there are <a href="https://arduino-info.wikispaces.com/nRF24L01-Mirf-Examples" rel="nofollow">send and receive examples</a>. They are really, really simple. Get them working first.</p> <blockquote> <p>What is the nature of the data sent between units? I want to send integers, possibly even text. Is that possible? Do I need to convert to binary or something?</p> </blockquote> <p><em>Technically</em>, you send between 1 and 32 <em>bytes</em> of information. However, the libraries (see examples above) will take care of the technicality and allow you to send nums, chars or strings. </p> <blockquote> <p>My understanding of "ping" and "pong" is that ping sends a message then pong sends that same message back to ping... is this correct?</p> </blockquote> <p>Not necessarily. Since <a href="/questions/tagged/nrf24l01%2b" class="post-tag" title="show questions tagged &#39;nrf24l01+&#39;" rel="tag">nrf24l01+</a> does all the signal checking for you, and you know that your TX device is the only one sending, you can just reply with "data received". </p> <p>Anyways, why are even concerned with this? Pinging and ponging have nothing to do with your task at hand.</p> <blockquote> <p>Are RF units very different? Is this one particularly difficult?</p> </blockquote> <p>Yes, they are different in frequencies, protocols, power etc. No, this one isn't. It's an amazing, cheap and robust piece of Norwegian ingenuity.</p> <blockquote> <p>If I just want to send with one receive with the other shouldn't this simplify the code?</p> </blockquote> <p>Simplify compared to what exactly? It will simplify the code compared to a two-way communication, obviously.</p> <blockquote> <p>What are pipes? How many can I open? As someone said before me, read the bloody manual, or a tutorial, or the data sheet, or something. The answer is 6.</p> </blockquote> <p>Any unit can send on ONE pipe and receive on SIX pipes. Imagine having 6 phones on your table. You can simultaneously listen to all 6 phones but you can only TALK INTO ONE. You can choose which one to talk into to, at any point. Unless you have a lot of devices talking to each other (more than TWO), don't bother, forget the pipes.</p> <blockquote> <p>If I have 3 or more of these what changes will I need to make to the code?</p> </blockquote> <p>Get two Arduinos talking to each other first. No one has succeeded at making anything work by getting ahead of themselves.</p> <p>Now here is <a href="https://www.youtube.com/watch?v=plDPBVjcckw" rel="nofollow">a video of two Arduinos talking</a>. There's only one button but you can easily change it to a 20-button setup.</p> <p>The code for sending:</p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;SPI.h&gt; #include &lt;Mirf.h&gt; #include &lt;MirfHardwareSpiDriver.h&gt; #include &lt;MirfSpiDriver.h&gt; #include &lt;nRF24L01.h&gt; const int buttonPin = 2; const int ledPin = 3; // sends a string via the nRF24L01 void transmit(const char *string) { byte c; for( int i=0 ; string[i]!=0x00 ; i++ ) { c = string[i]; Mirf.send(&amp;c); while( Mirf.isSending() ) ; } } void setup() { //RADIO Serial.begin(9600); Mirf.spi = &amp;MirfHardwareSpi; Mirf.init(); Mirf.payload = 1; Mirf.channel = 90; Mirf.config(); Mirf.configRegister(RF_SETUP,0x06); Mirf.setTADDR((byte *)"serv1"); //BUTTON AND LED pinMode(buttonPin, INPUT_PULLUP); pinMode(ledPin, OUTPUT); Serial.println("Sending ... "); } void loop() { int buttonState = digitalRead(buttonPin); if (buttonState == LOW) { //pressed digitalWrite(ledPin, HIGH); transmit("X"); } else { digitalWrite(ledPin, LOW); } } </code></pre> <p>The code for receiving:</p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;SPI.h&gt; #include &lt;Mirf.h&gt; #include &lt;MirfHardwareSpiDriver.h&gt; #include &lt;MirfSpiDriver.h&gt; #include &lt;nRF24L01.h&gt; unsigned long lasttime; unsigned long delaytime; unsigned long time; const int ledPin = 3; void setup(){ Serial.begin(9600); //RADIO Mirf.spi = &amp;MirfHardwareSpi; Mirf.init(); Mirf.setRADDR((byte *)"serv1"); Mirf.payload = 1; Mirf.channel = 90; Mirf.config(); Mirf.configRegister(RF_SETUP,0x06); //LED pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); Serial.println("Listening ... "); } void loop() { byte c; if( Mirf.dataReady() ) { Mirf.getData(&amp;c); Serial.write(c); if (c == 'X') { digitalWrite(ledPin, HIGH); } } else { digitalWrite(ledPin, LOW); } } </code></pre>
14138
|arduino-uno|led|c++|
Toggle Button For LED Strip not executing properly
2015-08-13T02:09:14.517
<p>I have been using a library to control a LED Strip with buttons. My current code does not execute properly. It skips the if statement and just runs the code in a loop with no regard to the button and I'm uncertain why. I'm using an Arduino Uno with an LPD8806.</p> <pre><code>#include "LPD8806.h" #include "SPI.h" // Comment out this line if using Trinket or Gemma #ifdef __AVR_ATtiny85__ #include &lt;avr/power.h&gt; #endif int nLEDs = 160; // Chose 2 pins for output; can be any valid output pins: int dataPin = 2; int clockPin = 3; // First parameter is the number of LEDs in the strand. The LED strips // are 32 LEDs per meter but you can extend or cut the strip. Next two // parameters are SPI data and clock pins: LPD8806 strip = LPD8806(nLEDs, dataPin, clockPin); int inPin = 4; boolean lastState = LOW;//storage for last button state void setup(){ pinMode(inPin, INPUT);//this time we will set the pin as INPUT Serial.begin(9600);//initialize Serial connection #if defined(__AVR_ATtiny85__) &amp;&amp; (F_CPU == 16000000L) clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket #endif strip.begin(); // Update the strip, to start they are all 'off' strip.show(); } void loop(){ if (digitalRead(inPin) == HIGH &amp;&amp; lastState == LOW){//if button has just been pressed // Start up the LED strip theaterChase(strip.Color(127, 127, 127), 50); // White delay(100); } else if(digitalRead(inPin) == LOW &amp;&amp; lastState == HIGH){ digitalWrite(dataPin, LOW); digitalWrite(clockPin, LOW); } lastState = digitalRead(inPin); } //Theatre-style crawling lights. void theaterChase(uint32_t c, uint8_t wait) { for (int j=0; j&lt;10; j++) { //do 10 cycles of chasing for (int q=0; q &lt; 3; q++) { for (int i=0; i &lt; strip.numPixels(); i=i+3) { strip.setPixelColor(i+q, c); //turn every third pixel on } strip.show(); delay(wait); for (int i=0; i &lt; strip.numPixels(); i=i+3) { strip.setPixelColor(i+q, 0); //turn every third pixel off } } } } </code></pre>
<p>If you have just connected a switch to the Arduino pin, like the image below, it will just return "random" undefined results:</p> <p><a href="https://i.stack.imgur.com/dbixU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dbixU.png" alt="Floating input on switch"></a></p> <p>There are various ways of avoiding this, including using a pull-down resistor to ensure that, if the switch is open, it will read LOW. For example:</p> <p><a href="https://i.stack.imgur.com/eYepo.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eYepo.png" alt="Pull-down resistor"></a></p> <p>There are other possible techniques as discussed on <a href="http://gammon.com.au/switches" rel="nofollow noreferrer">this page</a>.</p> <p>One is to change:</p> <pre class="lang-C++ prettyprint-override"><code> pinMode(inPin, INPUT);//this time we will set the pin as INPUT </code></pre> <p>to:</p> <pre class="lang-C++ prettyprint-override"><code> pinMode(inPin, INPUT_PULLUP);//this time we will set the pin as INPUT </code></pre> <p>Then wire the switch to <strong>ground</strong>, not +5 V. That way the pull-up resistor pulls the switch HIGH, and when you close the switch it is LOW.</p>
14139
|sketch|arduino-pro-mini|signal-processing|prototype|
Arduino LED lighting up when signal is reading low on multimeter
2015-08-13T03:03:30.507
<p>My code is designed to play a tone when ever pin 3 is high on my Arduino. When I am examine the pins voltage with a multimeter it is always reading below 1 volt. When I examined the voltage off of a osiliscope it is reading the voltage pretty steady at 0.2 to 0.3. </p> <p><strong>My multimeter reads at 0.26</strong></p> <p><a href="https://i.stack.imgur.com/VDZrq.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VDZrq.jpg" alt=""></a>:</p> <p><strong>My code is:</strong></p> <pre><code>void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: int input = digitalRead(3); Serial.println(input); if(input == 1){ tone(A5,4000); } } </code></pre> <p><strong>My board looks like:</strong> <a href="https://i.stack.imgur.com/WxcKw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WxcKw.jpg" alt="enter image description here"></a> <strong>The bottom of the board looks like:</strong> <a href="https://i.stack.imgur.com/VmlpH.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VmlpH.jpg" alt="enter image description here"></a></p>
<p>You left pin 3 floating. The multimeter will lower the voltage, resulting the the led lighting. Try enabling the pull-up resistor in pin 3 by adding <code>pinMode(3, INPUT_PULLUP)</code>.</p> <p>PS you might want to add a resistor in series with that led, or it will burn out and/or damage pin 3 on the arduino.</p>
14153
|arduino-uno|pwm|
Tone() working on all digital pins?
2015-08-13T11:40:34.860
<p>Looking at my Arduino Uno board, it appears the digital PWM pins are #11, #10, #9, #6, #5 and #3. </p> <p>When playing around with the Theremin, it seems that the <code>Tone()</code> message works on all pins regardless of whether they are marked PWM or not?</p> <p>Can anyone explain what is happening or how this is possible?</p>
<p>The Tone library doesn't use the PWM mode timer functions on the atmega, instead it uses an interrupt routine to toggle the pins. You can find the source code for Tone libary here for reference:</p> <p><a href="https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/" rel="nofollow">https://github.com/johnmccombs/arduino-libraries/blob/master/Tone/</a></p>
14157
|c++|arduino-ide|esp8266|
Passing class member function as argument
2015-08-13T13:55:08.927
<p>I need to pass a class member function to server.on, unfortunately i get an error.</p> <blockquote> <p>error: no matching function for call to 'ESP8266WebServer::on</p> </blockquote> <p>I have done some searching but could not understand anything I found. No simple explanation.</p> <p>This works:</p> <pre><code>void handleRoot(){} server.on("/", handleRoot); </code></pre> <p>This doesn't:</p> <pre><code>void myClass::handleRoot(){} void myClass::setup(){ server.on("/", handleRoot); } </code></pre> <p>The second argument to server.on is </p> <pre><code>typedef std::function&lt;void(void)&gt; THandlerFunction; </code></pre> <p>Unfortunately I have no idea what it means.</p>
<p>This will get the job done - using anonymous function syntax:</p> <pre><code>server-&gt;on("/", [&amp;]() { handleRoot(); }); </code></pre>
14159
|arduino-ide|rfid|
Reading RFID tags with Arduino IDE, not using Arduino
2015-08-13T14:10:44.683
<p>I am completely new to this technology, but I'm hoping to build a fairly simple program through the Arduino IDE that takes the serial numbers of RFID cards read through my ID-20LA Innovations RFID reader and send those serial numbers to an API endpoint all through the IDE (as in without using a physical Arduino).</p> <p>Is this possible? Are there any tutorials out there that walk through a stripped down version of this? I don't know where to start code wise, and all tutorials I've found use physical Arduinos to accomplish this.</p>
<p><strong>Short answer:</strong> NO</p> <p><strong>Long Answer:</strong></p> <p>Option 1: Use a USB RFID reader and create a basic processing/python/ app to read from the USB RFID reader and post it where ever you want it to</p> <p>Option 2: Use the arduino to read from the ID-20LA and send the data via UART to your computer and then create a windows app using processing/python/ to send it to your API endpoint</p> <p>Option 3: Use the arduino YUN to read from the ID-20LA and then create a basic python program to run on the YUN itself. Such that it will read data from the atmel microcontroller (on the YUN) and post it to your API endpoint. This is a much cleaner yet slightly more expensive way of doing this. </p>
14163
|display|
How do I use an Arduino as a USB output device for a 2x16 display?
2015-08-13T16:19:32.230
<p>Can I make a USB 2x16 display using an Arduino? I want to control a 2x16 character lcd display using USB, not com port/serial.</p> <p>I need it to appear as a HID device when connected to the computer.</p> <p>Please advise me.</p> <p>Thanks</p>
<p>HID's generally are input devices to your computer, if you do want your computer to send data to the device you will need an application to do it. </p> <p>So your best bet is to have a windows app to communicate with your arduino using a virtual com port ( as it does already) and send data as you require</p>
14170
|serial|arduino-yun|ethernet|baud-rate|
Streaming sensor data over UDP using an Arduino Yún - how to do it and how fast could it be?
2015-08-13T19:08:11.780
<p>The company where I work wants to do a proof of concept for our new product, a force-sensing platform.</p> <p>The platform contains four three-axial load cells, so we have 12 channels, which are to be digitized at 2kHz and 16bits. This gives us 2.000 dataframes per second, with 24 bytes of payload each.</p> <p>Our proposed architecture is as following:</p> <ul> <li>The analog signals from the cells is acquired by a dedicated data-acquisition board;</li> <li>The digital stream is sent to the ATmega on Yún over SPI;</li> <li>The data is then relayed to the Atheros over Serial;</li> <li>Finally, the data is transmitted over UDP (or TCP).</li> </ul> <p>I wonder if it is a sensible way of doing it, with the following questions:</p> <ul> <li>How would one normally use the Ethernet functionality? Can I call a function on the sketch, or do I need to put some program or script in the Linux, calling it from the sketch?</li> <li>What would be the maximum transmission speed (in bytes per second) from the ATmega side to the Linux side?</li> <li>What would be the maximum throughput of the Ethernet?</li> </ul> <p>I have calculated 24 bytes * 2000 = 480 bytes per second, or a baud rate of 480 * 8 = 3840bps. Is that right?</p> <p>I would appreciate any help, it could be just a link to the proper information resources.</p>
<p>The Yun is really two different computers (one AVR and on Linux) connected by a serial link. Basically the AVR is connected to a serial console on the Linux machine, so you can "type" commands into Linux by sending strings out the serial port from the AVR. </p> <p>The serial link normally comes up at 250,000 buad, so that should not be a bottleneck for your application. </p> <p>Typically, the AVR will "type" a command to run a Python program on the Linux side (called the Bridge) that will then communicate with AVR code using a high level protocol. Unfortunately, this "bridge" connections tends to be slow and flaky. </p> <p>But you could do what you want very easily by just pumping netcat commands into the Linux machine from the AVR machine every time you wanted to send a UDP packet out. The overhead would only be a few serial bytes per packet (you'd send "nc -u \r" where everything but data is likely the same for every packet). </p> <p>Here is an example of a program that runs on thew AVR and periodically reads some data from temperature sensors connected via 1-Wire, and then runs a "curl" command on the linux console to record the readings to a server...</p> <p><a href="https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino" rel="nofollow">https://github.com/bigjosh/SimpleTempLoggerYun/blob/master/Arduino/SimpleTempLoggerYun/SimpleTempLoggerYun.ino</a></p> <p>In your case, your replace the 1-Wire reading code with SPI reading code, and replace the "curl" that sends HTTP data command with an "<a href="http://linux.die.net/man/1/nc" rel="nofollow">nc</a>" command that would send a UDP packet (using the "-u" parameter). </p> <p>With this technique, I think you could get something working very very quickly and likely easily meet your data rate requirements. </p> <p>Note that while this is a great technique for getting a proof-of-concept working quickly, I would not use a setup like this in production. Instead consider something like a BeagleBone Black where you could read the SPI data and send the UDP pack in a single C program that ran as a normal Linux process. </p>
14172
|atmega328|
How to update the character table of MAX7456
2015-08-13T20:16:18.507
<p>I've got a <a href="https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf" rel="nofollow">MAX7456 chip</a> and I am using <a href="https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=1" rel="nofollow">this</a> library with it. But the issue is that the character table is not the one the library needs to function like it should. The "Hello world" example is nowhere near to what it should display, because the character table is wrong.</p> <p>All the instructions that talk about character set updating require a USB FTDI cable (I don't have one), I am able to program the board with <a href="http://www.fischl.de/usbasp/" rel="nofollow">USBASP</a> programmer but that's it. I also have a few Nanos, if that helps.</p> <p>How could I update the character table to what the library needs (without a FTDI cable) or how to make the sketch included to update the character set work properly?</p>
<p>To solve this problem one would need to get the builtin character updating sketch work (Max456WriteTable.cpp in examples folder). After the sketch has been compiled one would have to connect either FTDI cable or a USBASP programmer to the board and upload the sketch to it.</p> <p>The character set (array) itself used in the code can be updated with the appropriate program available at <a href="http://theboredengineers.com/2012/12/a-max7456-library-for-arduino/" rel="nofollow">this site</a>.</p> <p>UPDATE: In the end I solved it <a href="https://arduino.stackexchange.com/questions/14739/character-updating-sketch-not-working">this way</a>. </p> <p>Many thanks to Charlie Hanson &amp; Nick Gammon.</p>
14179
|serial|softwareserial|software|
SoftwareSerial Write to return Read in Serial Monitor?
2015-08-14T04:02:29.370
<p>Hoping someone can help me out in my conundrum here...</p> <p>I currently am testing the SoftwareSerial library out to understand how I may use it in my project.</p> <p>I have a wire running from pin 6 to pin 9, so that the TX talks straight to the RX.</p> <p>I have written the following:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(6,9); //RX = 6 TX = 9 void setup() { Serial.begin(1200); mySerial.begin(1200); } void loop() { mySerial.write('F'); delay(100); // attempting to allow time between write and read commands while (mySerial.available()&gt;0) { Serial.println(mySerial.read()); } } </code></pre> <p>The whole point is just to see 'F' return in the Serial Monitor.</p> <p>The output, unfortunately, is absolutely nothing! If I omit the <code>while(mySerial.available&gt;0)</code> I just get -1 's down the lines of the Serial Monitor.</p> <p>Thank you in advance!</p>
<p>SoftwareSerial cannot talk to itself. Since it is implemented in software and not hardware it can either send or receive at one time, but not both.</p> <p>Look at the code for <code>write</code> in SoftwareSerial:</p> <pre class="lang-C++ prettyprint-override"><code>size_t SoftwareSerial::write(uint8_t b) { ... cli(); // turn off interrupts for a clean txmit ... // Write each of the 8 bits for (uint8_t i = 8; i &gt; 0; --i) { if (b &amp; 1) // choose bit *reg |= reg_mask; // send 1 else *reg &amp;= inv_mask; // send 0 tunedDelay(delay); b &gt;&gt;= 1; } ... SREG = oldSREG; // turn interrupts back on ... } </code></pre> <p>Since it turns interrupts off, and interrupts are needed for it to detect incoming data, therefore it cannot detect incoming data while it is sending.</p>
14181
|variables|c-preprocessor|constants|
Why use an int variable for a pin when const int, enum or #define makes much more sense
2015-08-14T07:22:30.677
<p>Why do people use a variable to specify a pin number when the pin is unlikely to change throughout the execution of the code?</p> <p>Many times I see an <code>int</code> being used for a pin definition,</p> <pre><code>int led = 13; </code></pre> <p>when the use of a <code>const int</code></p> <pre><code>const int led = 13; </code></pre> <p>or <a href="http://playground.arduino.cc/Code/Enum" rel="noreferrer"><code>enum</code></a>, or <a href="https://www.arduino.cc/en/Reference/Define" rel="noreferrer"><code>#define</code></a> </p> <pre><code>#define LED 13 </code></pre> <p>makes much more sense.</p> <p>It is even in tutorials on the Arduino site, for example, the first tutorial that most people run, <a href="https://www.arduino.cc/en/tutorial/blink" rel="noreferrer">Blink</a>.</p> <p>I <a href="https://stackoverflow.com/questions/16889213/how-to-use-define-to-assign-pins-in-arduino#comment-24383545">read somewhere</a> that <code>const int</code> is preferred over <code>#define</code>. Why isn't this encouraged right from the beginning, rather than allowing people to develop bad habits, from the outset? I noticed it a while back, but recently it has started to irritate me, hence the question.</p> <p>Memory/processing/computing wise is a <code>const int</code>, <code>enum</code>, or for that matter <code>#define</code>, better than a plain <code>int</code>, i.e. occupies less memory, stored in <a href="https://www.arduino.cc/en/Tutorial/Memory" rel="noreferrer">different memory</a> (Flash, EEPROM, SRAM), faster execution, quicker to compile?</p> <hr> <p>This may appear to be a duplicate of <a href="https://arduino.stackexchange.com/questions/506/is-it-better-to-use-define-or-const-int-for-constants">Is it better to use #define or const int for constants?</a>, but I am addressing the question of why people use variables, and how does the performance improve when they don't, rather than which type of constant is better.</p>
<p>As a 2-week newbie to Arduino I'd pick up on the general idea of Arduino being occupied by non-programmers. Most sketches I have examined, including those on the Arduino site, show a total lack of order, with sketches that do not work &amp; barely a coherent comment in sight. Flow charts are non-existent, and the "Libraries" are an un-moderated jumble.</p>
14188
|arduino-mega|lcd|
Arduino LCD Simple Problem
2015-08-14T10:58:26.263
<p>Hi my lcd doesnt display that i was expected. Can anyone help me???</p> <p>RS-->22 RW-->GROUND E-->23 D4-->24 D5-->25 D6-->26 D7-->27</p> <pre><code> #include &lt;LiquidCrystal.h&gt; LiquidCrystal lcd(22, 23, 24, 25, 26, 27); void setup() { lcd.begin(16,2); lcd.setCursor(0,1); lcd.print("Hello!"); delay(1000); } void loop() { lcd.setCursor(0,1); lcd.print(millis()/1000); } </code></pre> <p><a href="https://i.stack.imgur.com/O8XnG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/O8XnG.jpg" alt="enter image description here"></a></p>
<p>I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.</p>
14189
|library|
How to develop or edit an Arduino library?
2015-08-14T12:46:43.843
<p>I'm not sure if I should split this question in two. I had to edit some libraries and I plan to make some myself but didn't try yet.</p> <p>Editing a library seems very laborious comared to editing a sketch.</p> <p>I have to use an external editor and then compile on the Arduino IDE with the help of a test sketch. </p> <p>I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.</p> <p>The libraries used to be on %home%/Arduino/libraries/etc. but now I have to edit some located at %appdata%\Arduino15\packages\esp8266\hardware\esp8266\1.6.5-947-g39819f0\libraries and it seems these packages might get updated so maybe it is not a good idea to edit them there but I am not sure.</p> <p>What about GitHub and conflicts? I clone the library and edit it but then I have two versions and you can't choose one of them. So I have to delete the original from the arduino instalation or wherever it is to avoid the conflict.</p> <p>I also wish to post the progress to GitHub and maybe receive collaboration there. Do you have any hint about the clone process or something to avoid any trouble with it?</p> <p>And what about the .h/.o? Arduino precompile the headers on startup so if I edit a .h I have to find and delete the .o or restart the IDE.</p> <p>How do you do all of this? Is there any trick that helps?</p> <p>Thank you.</p>
<p>There is one component of your question that remains unanswered:</p> <blockquote> <p>I wish to use the Arduino IDE to edit the libraries but it seems it is not easy, maybe in future reales it is supported.</p> <p>Any good editor if Arduino IDE is not an option? Why is not an option?</p> </blockquote> <p>The rest of your questions already have good answers so I'll limit myself to explaining how the Arduino IDE 1.6.5-r4 and newer can be used to edit libraries:</p> <p>Copy the library you want to modify to {sketchbook folder}/libraries or create a new folder at that location if you're writing a library from scratch. You can find the location of {sketchbook folder} at <strong>File > Preferences > Sketchbook location</strong>.</p> <p>Create a file that matches the folder name that contains the source files with the .ino extension. For example:</p> <pre><code>{sketchbook folder} |_libraries |_FooBar |_FooBar.ino |_FooBar.h |_FooBar.cpp </code></pre> <p>or:</p> <pre><code>{sketchbook folder} |_libraries |_FooBar |_library.properties |_src |_src.ino |_FooBar.h |_FooBar.cpp </code></pre> <p>This dummy .ino file is necessary in order to open the library source files in the Arduino IDE but will not actually be used as part of the library. You can leave it blank. I like to use this file as a "to-do" list for my development work. I add this filename to .git/info/exclude so that it will not be tracked as part of the repository. It's also possible to use this file as a sketch to test the library with. Just remember to use the local file include style: </p> <pre><code>#include "FooBar.h" </code></pre> <p>Note that you will only be able to edit the files that are in the same folder as the .ino file via the Arduino IDE. Luckily most Arduino libraries place all their source files in a single folder so this is not much of a limitation. If you wanted to edit a library that has source files in multiple folders you could always put a dummy .ino file in each folder and open them in separate IDE windows.</p> <p>Add a file named .development to the library root folder. This is necessary because normally the Arduino IDE does not allow saving to the library folders or the examples folder to prevent accidental modification of the example sketches. Using Windows Explorer (and possibly others), you will find that you are not allowed to create files that start with a dot. You can create the .development file using a text editor or the command line. The contents of the file don't matter, only the presence of the file. Note that you should not publish the .development file to repositories that will be included in the Arduino IDE Library Manager as the file will <a href="https://github.com/arduino/Arduino/issues/3512#issuecomment-128029263" rel="nofollow noreferrer">cause the library to be skipped</a> by the job that fetches releases. I also add this filename to .git/info/exclude.</p> <p>If the library does not already contain one, add a library.properties file to the library root folder. You can find the correct format of this file in the Arduino Library Specification:</p> <p><a href="https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format" rel="nofollow noreferrer">https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format</a></p> <p>Now the structure of the example libraries above would look like this:</p> <pre><code>{sketchbook folder} |_libraries |_FooBar |_.development |_FooBar.ino |_FooBar.h |_FooBar.cpp |_library.properties </code></pre> <p>or:</p> <pre><code>{sketchbook folder} |_libraries |_FooBar |_.development |_library.properties |_src |_src.ino |_FooBar.h |_FooBar.cpp </code></pre> <p>Restart the Arduino IDE if it's running.</p> <p>After doing this, when you open any of the source files of the library with the Arduino IDE, all source files in the folder will be opened and you can edit and save them as you would a sketch.</p>
14191
|spi|
MCP23S17: Programming IODIRx-Register works in loop(), but not in setup()
2015-08-14T13:55:41.583
<p>I use a single MCP23S17 connected to an Arduino Uno. I use its port B for output and port A for input. When I first started to use this device I noticed, I could read pins, but using them as output failed. After a lot of debugging and trial and error I found out, that the IODIRx Register was never programmed. I then copied the respective code from the setup() routine — where it belongs IMHO — to the loop() routine.</p> <p>And miraculously the IODIRx Register was written correctly. The code below contains the IODIRx programming snippet in the setup() as well as in loop(). But only in loop() it yields an effect. This means: The output will work only after the first traversal of loop() in my example.</p> <p>The rest of the setup() routine obviously works, which means it is called at least. SPI is initialised correctly there. </p> <p>This drives me nuts. What the hell is a setup routine for, if you can't setup things there. And why on earth doesn't it work then? I don't do strange things there. </p> <pre class="lang-C++ prettyprint-override"><code>#include &lt;Arduino.h&gt; #include &lt;Wire.h&gt; #include &lt;inttypes.h&gt; #include &lt;SPI.h&gt; #include "flanschcontrol.h" #define DEBUGOUTPUT #define PROTOV2 typedef int elem_type; #define ADDRESS (0) #define OPCODEW (0b01000000) // Opcode for MCP23S17 with LSB (bit0) set to write (0), address OR'd in later, bits 1-3 #define OPCODER (0b01000001) // Opcode for MCP23S17 with LSB (bit0) set to read (1), address OR'd in later, bits 1-3 #define ADDR_ENABLE (0b00001000) // Configuration register for MCP23S17, the only thing we change is enabling hardware addressing uint8_t PexSSPin=7; void setup() { Serial.begin(9600); pinMode(PexSSPin, OUTPUT); SPI.begin(); SPI.setClockDivider(2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); delay(1000); PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); SPI.transfer(IODIRB); SPI.transfer(0b10101010); PORTD |= 0b10000000; // Slaveselect high delay(1000); } void loop() { PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); // Send the MCP23S17 opcode, chip address, and write bit SPI.transfer(GPIOB); SPI.transfer(0b00000000); PORTD |= 0b10000000; // Slaveselect high Serial.println("0"); delay(1000); PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); // Send the MCP23S17 opcode, chip address, and write bit SPI.transfer(GPIOB); SPI.transfer(0b11111111); PORTD |= 0b10000000; // Slaveselect high Serial.println("ff"); delay(1000); PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); // Send the MCP23S17 opcode, chip address, and write bit SPI.transfer(GPIOB); SPI.transfer(0b00001111); PORTD |= 0b10000000; // Slaveselect high Serial.println("0f"); delay(1000); PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); // Send the MCP23S17 opcode, chip address, and write bit SPI.transfer(GPIOB); SPI.transfer(0b11110000); PORTD |= 0b10000000; // Slaveselect high Serial.println("f0"); delay(1000); int value; PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODER | (ADDRESS &lt;&lt; 1)); // Send the MCP23S17 opcode, chip address, and read bit SPI.transfer(GPIOA); // Send the register we want to read value = SPI.transfer(0x00); // Send any byte, the function will return the read value (register address pointer will auto-increment after write) value |= (SPI.transfer(0x00) &lt;&lt; 8); // Read in the "high byte" (portB) and shift it up to the high location and merge with the "low byte" PORTD |= 0b10000000; // Slaveselect high Serial.print("pindata: "); Serial.println(value); delay(1000); PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); SPI.transfer(IODIRB); SPI.transfer(0b10101010); PORTD |= 0b10000000; // Slaveselect high } </code></pre> <p>Definitions of some preprocessor thingies:</p> <pre class="lang-C++ prettyprint-override"><code>#define IODIRA (0x00) // MCP23x17 I/O Direction Register #define IODIRB (0x01) // 1 = Input (default), 0 = Output #define GPIOA (0x12) // MCP23x17 GPIO Port Register #define GPIOB (0x13) // Value on the Port - Writing Sets Bits in the Output Latch </code></pre>
<p>You've fallen for the old "slave select pin is already low" trick!</p> <p>Let me show you. First we add a line to bring pin 2 high before starting the sequence (for logic analyzer triggering):</p> <pre class="lang-C++ prettyprint-override"><code>pinMode (2, OUTPUT); // &lt;--- pin 2 output delay(1000); PORTD |= bit (2); // &lt;--- pin 2 HIGH PORTD &amp;= 0b01111111; // Slaveselect low SPI.transfer(OPCODEW | (ADDRESS &lt;&lt; 1)); SPI.transfer(IODIRB); SPI.transfer(0b10101010); PORTD |= 0b10000000; // Slaveselect high delay(1000); </code></pre> <p>This is the logic analyzer output of running your sketch:</p> <p><a href="https://i.stack.imgur.com/c2IPr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c2IPr.png" alt="Slave select low"></a></p> <p>Notice how SS is low all the time, and thus the chip does not respond to the command?</p> <hr> <p>Now we add a line <strong>before</strong> the <code>SPI.begin</code></p> <pre class="lang-C++ prettyprint-override"><code>PORTD |= 0b10000000; // Slaveselect high SPI.begin(); SPI.setClockDivider(2); SPI.setBitOrder(MSBFIRST); SPI.setDataMode(SPI_MODE0); </code></pre> <p>Now look at the results:</p> <p><a href="https://i.stack.imgur.com/Xu2HN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Xu2HN.png" alt="Slave select high"></a></p> <p>This time you get the transition of SS from high to low, the chip notices it, and we have a valid SPI transaction.</p> <p>So without bringing SS high, the <strong>first</strong> thing you sent was always going to fail.</p> <hr> <p>It was nothing to do with it being in <code>setup</code> - it couldn't be. After all the logic is basically this:</p> <pre class="lang-C++ prettyprint-override"><code>init (); setup (); while (true) loop (); </code></pre> <hr> <p>Personally I wouldn't hard code all those bit patterns throughout the code. What if you change the slave select pin one day?</p> <p>How about:</p> <pre class="lang-C++ prettyprint-override"><code>digitalWrite (PexSSPin, LOW); /// write to chip digitalWrite (PexSSPin, HIGH); </code></pre> <p>Isn't that much more readable? And easier to change later?</p>
14193
|arduino-uno|serial|communication|softwareserial|
Sending Data between two boards using SoftwareSerial
2015-08-14T15:47:28.337
<p>I'm attempting to connect two Arduino boards to eachother using SotwareSerial as the title suggests! </p> <p>The two boards are 1) Arduino UNO and 2)MultiWii Controller (MWC) FLIP 1.5 (Uses ATMega328 chip).</p> <p>The idea, is to get Serial TX on the <em>"MWC"</em> FLIP 1.5 to Serial RX on the UNO.</p> <p>These are my connections thus far:</p> <p>MWC Pin ------->UNO Pin</p> <p>Digital 3 (TX)--->Digital 6 (RX)</p> <p>Digital 9 (RX)--->Digital 9 (TX)</p> <p>This is the code on the MWC Chip -- the TX chip. (NOTE: These functions are called to run in a header file)</p> <pre><code>#include "attout.h" #include "SoftwareSerial.h" SoftwareSerial altSerial(9,3); // RX=9 TX=3 void startaltserial(){ altSerial.begin(9600); } void attout(){ pinMode(3,HIGH); pinMode(9,HIGH); altSerial.print('1'); } </code></pre> <p>NOTE: I also tried <code>altSerial.write('1')</code>. Same result (or lack of one).</p> <p>Then, the RX Code on the UNO Board:</p> <pre><code>#include &lt;SoftwareSerial.h&gt; SoftwareSerial mySerial(6,9); // RX=6 TX=9 void setup() { // Open serial communications: Serial.begin(9600); // Set the data rate for the SoftwareSerial port mySerial.begin(9600); } void loop() { while (mySerial.available()&gt;0) { Serial.println(mySerial.read()); } } </code></pre> <p>When I open Serial Monitor for the UNO board, I get nothing but zeroes streaming down. Curiously, if I disconnect the TX OUT wire from MWC, the Serial stream stops!</p> <p>This means, as far as I can tell, that the UNO is doing its job of receiving, and the MWC is doing it's job of transmitting, but something is wrong with the formatting inbetween, so that I end up with zeroes.</p> <p>Additionally, if I change the baud rate, the Serial Monitor output changes. When I go to 1200 baud, I get nothing but '4' followed quickly by '1' and then carriage return, so it looks like '41'.</p> <p>Hope we can find a solution to these quandaries. My next course of action is trying I2C, but I'm not sure about it yet...</p>
<p>Your problem here is that you are streaming out serial data non-stop.</p> <p>See my answer in this thread: <a href="https://arduino.stackexchange.com/questions/1569/what-is-serial-begin9600/14146#14146">What is Serial.begin(9600)?</a> </p> <p>Without having a pause, the receiver just latches onto somewhere in the middle of the data stream and tries to make sense of it, often unsuccessfully.</p> <p>If you add one "character time" delay to the <strong>sender</strong>, the receiver works fine:</p> <pre><code> altSerial.print('1'); delay (2); </code></pre> <p>It might get the first one wrong, but now the receiver has 2 ms to resynchronize on the data stream. At 9600 baud the delay should be 1/960 (second) at least, I used twice that to be sure.</p>
14213
|analogwrite|
Which board/shield to generate (non-PWM) analog outputs?
2015-08-15T09:56:19.527
<p>I am currently building a project involving a laser scanner (two galvanometers with mirrors that deflect a laser beam) that I want to control. The galvos need +-10V differential signals (and I'd like to have a least 12Bit) that I want create with some small board. </p> <p>Most Arduinos I know use PWM to create an analog output which is not usable for this project. I found the Teensy3.1 which has at least one 12Bit DAC so that also doesn't work. An alternative would be a DAC breakout board like <a href="https://www.adafruit.com/products/935" rel="nofollow" title="MCP4725">"MCP4725"</a> but it would be nicer to just have a single board with no additional parts. </p> <p>The best thing would be a small board with already two 12Bit DACs. (even If I had to upscale the voltage +-10v)</p> <p>Is there a board I haven't found so far? Or have I missed a completely different approach?</p>
<p>For 12-bit dual DAC you want the <a href="http://ww1.microchip.com/downloads/en/DeviceDoc/22249A.pdf" rel="nofollow">MCP4822</a> which has two channels of 0-4.095V in 1mV steps.</p> <p>The output of that you would then need to pass through a suitable amplifier arrangement with an op-amp giving a gain of 5 and adding an offset of -10V. The gain would change the 0-4.095V to 0-20.475V, and the -10V offset would change that to -10V to +10.475V. If you want to get more precise you could use an offset of -10.2375V (it's not easy to make an offset voltage that precise) then you would get -10.2375V to 10.2375V in 12-bit resolution.</p> <p>It's doubtful you'll find a board already made up with that specific arrangement (it's fairly specialised) but it's not something that's hard to make - all the components are available as DIP or other through hole components, and the circuit for the amplification stage is pretty simple (check for non-inverting op-amp circuits online, there's millions), so building it up on strip board or matrix board would be easy enough.</p>
14217
|arduino-uno|programming|
Need assistance with program for POV Project
2015-08-15T13:56:20.633
<p>I've created a very basic POV project.</p> <p>It has a 12V DC motor with a piece of wood on it. The wood has 6 LEDs on it as well as a copper ring. The power is delivered to the LEDs from brushes connecting to the copper ring and from the shaft of the motor (the ground is attached to the base of the motor.) I'm using a TCRT5000L Sensor to count the RPM and have attached the LEDs to pin 13 and ground of the Arduino. (I've attached white tape to one side of the wood so that the sensor only counts one rev.)</p> <p>I need help (please) with the program.</p> <p>This is the code that I am using:</p> <pre><code>int pin = 13; volatile int tcnt = 0; volatile int lastcount = 0; volatile int state = LOW; void setup() { Serial.begin(9600); pinMode(pin, OUTPUT); attachInterrupt(1, blink, RISING); } void loop() { Serial.println(tcnt); if (tcnt != lastcount) { digitalWrite(pin, HIGH); delay(10); digitalWrite(pin, LOW); delay(10); lastcount = tcnt; } delay(10); } void blink() { tcnt = tcnt + 1; state = !state; } </code></pre> <p>My first issue is that the when I use the code above, the lights don't seem to switch on / off on the exact same area. They are within 30 degrees but certainly not precise. </p> <p>The second issue (and the biggest) is that I'm sure that this code is not the best way to do what I need. For example, if I wanted to use this as an analog clock, so that the lights would only show on the current hour / minute, how would I do this?</p> <p>Any help is greatly appreciated. </p> <p><a href="https://i.stack.imgur.com/mtp02.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mtp02.jpg" alt="Side View"></a></p> <p><a href="https://i.stack.imgur.com/rmGd4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rmGd4.jpg" alt="Top View"></a></p>
<p>Your <strong>third</strong> delay is the issue. It means you have up to 10 ms before you notice the need to turn on the light. Try this:</p> <pre class="lang-C++ prettyprint-override"><code>const byte pin = 13; volatile bool detected; void setup() { pinMode(pin, OUTPUT); attachInterrupt(1, blink, RISING); } void loop() { if (detected) { delay(10); digitalWrite(pin, LOW); detected = false; } } void blink() { digitalWrite(pin, HIGH); detected = true; } </code></pre> <p>Now that immediately turns on the LED, so it will always happen at the same time. Then in the main loop you notice it is on, wait 10 ms, and then turn it off.</p>
14219
|arduino-uno|
I'm looking for a real small but decent Arduino, that can fit in a watch but power a servo and a gyroscope
2015-08-15T16:16:43.583
<p>I've been scouring the internet looking for a small Arduino that can power two sensors and a servo. Is there a way of getting a custom one? Does anyone know if theres software out there for creating custom Arduinos and having them made?</p>
<p>You might look into building a circuit, on a breadboard, from basic components. Think Atmel, AtMega instead of Arduino. Depending on your experience and willingness to read datasheets, this might be easier than you imagine. After you have a large-scale working prototype, find miniature surface-mount versions of all of the components. Designing an actual circuit board to connect these things might be the real trick, but if you can get it done then you can have the board made. I believe, am uncertain about this, that there are software tools available that help turn schematics into circuit board designs. This part might be expensive. Getting to the point of having a large-scale working prototype, on the other hand, would be inexpensive and fun. Once you have a board designed you'll have to get it made. Testing this prototype might be difficult and perhaps expensive as well. (Engineers are paid well because they tend to know before construction if a design will work.) If you come up with something that works then selling the extras might pay for having it made.</p>
14223
|arduino-uno|c++|wifi|adafruit|
Having issues with sending output to WiFi Shield
2015-08-15T18:37:01.237
<p>I am doing simple proof of concept trying to send C++ program output to Adafruit CC3000 WiFi Shield (using Visual Studio 2013 Desktop Edition on Windows 8.1).</p> <p>In my design laptop is connected to UNO via USB, UNO is connected to WiFi Shield, and WiFi Shield is connected to D-Link router running Adafruit example sketch ("EchoServer"). These connections are working fine.</p> <p>Next, I am using TCP client sample code from Microsoft for WiFi connectivity with client code running on the laptop to connect to WiFi Shield. Tested this code with sample TCP server code from Microsoft, and client was able to communicate with server code but for some reason this client is not able to find WiFi Shield TCP Server. I get "Unable to connect to server" error with CC3000 continue to show it is listening for connections but never finds one</p> <p>I am sure it is due to my lack of understanding TCP/networking world. Below is the client code I am running on laptop using Visual Studio:</p> <pre><code>#define WIN32_LEAN_AND_MEAN #include &lt;windows.h&gt; #include &lt;WinSock2.h&gt; #include &lt;ws2tcpip.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include&lt;iostream&gt; // Need to link with Ws2_32.lib, Mswsock.lib, and Advapi32.lib #pragma comment (lib, "Ws2_32.lib") #pragma comment (lib, "Mswsock.lib") #pragma comment (lib, "AdvApi32.lib") #define DEFAULT_BUFLEN 512 //Default buffer length of port #define DEFAULT_PORT "7" //Change this to change port int main()//int argc, char **argv { WSADATA wsaData; SOCKET ConnectSocket = INVALID_SOCKET; struct addrinfo *result = NULL, *ptr = NULL, hints; char *sendbuf = "100"; char recvbuf[DEFAULT_BUFLEN]; int iResult; int recvbuflen = DEFAULT_BUFLEN; /* // Validate the parameters - not necessary for use if (argc != 2) { printf("usage: %s server-name\n", argv[0]); system("pause"); return 1; } */ // Initialize Winsock iResult = WSAStartup(MAKEWORD(2, 2), &amp;wsaData); if (iResult != 0) { printf("WSAStartup failed with error: %d\n", iResult); system("pause"); return 1; } ZeroMemory(&amp;hints, sizeof(hints)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = IPPROTO_TCP; // Resolve the server address and port iResult = getaddrinfo(NULL, DEFAULT_PORT, &amp;hints, &amp;result); if (iResult != 0) { printf("getaddrinfo failed with error: %d\n", iResult); WSACleanup(); system("pause"); return 1; } // Attempt to connect to an address until one succeeds for (ptr = result; ptr != NULL; ptr = ptr-&gt;ai_next) { // Create a SOCKET for connecting to server ConnectSocket = socket(ptr-&gt;ai_family, ptr-&gt;ai_socktype, ptr-&gt;ai_protocol); if (ConnectSocket == INVALID_SOCKET) { printf("socket failed with error: %ld\n", WSAGetLastError()); WSACleanup(); system("pause"); return 1; } // Connect to server. iResult = connect(ConnectSocket, ptr-&gt;ai_addr, (int)ptr-&gt;ai_addrlen); if (iResult == SOCKET_ERROR) { closesocket(ConnectSocket); ConnectSocket = INVALID_SOCKET; continue; } break; } freeaddrinfo(result); if (ConnectSocket == INVALID_SOCKET) //If failed to get a socket, end program { printf("Unable to connect to server!\n"); WSACleanup(); system("pause"); return 1; } // Send an initial buffer iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0); if (iResult == SOCKET_ERROR) { printf("send failed with error: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); system("pause"); return 1; } printf("Bytes Sent: %ld\n", iResult); // Receive until the peer closes the connection do { iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0); if (iResult &gt; 0) { printf("Bytes received: %d\n", iResult); std::cout &lt;&lt; recvbuf &lt;&lt; std::endl; } else if (iResult == 0) printf("Connection closed\n"); else printf("recv failed with error: %d\n", WSAGetLastError()); } while (iResult &gt; 0); // shutdown the connection since no more data will be sent iResult = shutdown(ConnectSocket, SD_SEND); if (iResult == SOCKET_ERROR) { printf("shutdown failed with error: %d\n", WSAGetLastError()); closesocket(ConnectSocket); WSACleanup(); system("pause"); return 1; } // cleanup closesocket(ConnectSocket); WSACleanup(); return 0; } </code></pre>
<p>At no point in your program are you telling it where to connect to. You are requesting service "7", which of course is resolved to port number 7, but you aren't giving it an IP address or host name to connect to. Ergo, it is trying to connect to port 7 of the same computer that the program is running on - which will fail.</p> <p>You need to specify the IP address of the WiFi shield as the first parameter to <code>getaddrinfo()</code> (currently <code>NULL</code>):</p> <blockquote> <p><code>int getaddrinfo(const char *node, const char *service, const struct addrinfo *hints, struct addrinfo **res);</code></p> <p><code>node</code> specifies either a numerical network address (for IPv4, numbers-and-dots notation as supported by <code>inet_aton(3)</code>; for IPv6, hexadecimal string format as supported by <code>inet_pton(3)</code>), or a network hostname, whose network addresses are looked up and resolved. If <code>hints.ai_flags</code> contains the <code>AI_NUMERICHOST</code> flag, then node must be a numerical network address. The <code>AI_NUMERICHOST</code> flag suppresses any potentially lengthy network host address lookups.</p> <p>If the <code>AI_PASSIVE</code> flag is not set in <code>hints.ai_flags</code>, then the returned socket addresses will be suitable for use with <code>connect(2)</code>, <code>sendto(2)</code>, or <code>sendmsg(2)</code>. <strong>If node is <code>NULL</code>, then the network address will be set to the loopback interface address</strong> (<code>INADDR_LOOPBACK</code> for IPv4 addresses, <code>IN6ADDR_LOOPBACK_INIT</code> for IPv6 address); this is used by applications that intend to communicate with peers running on the same host.</p> <p>-- Extract from the <code>getaddrinfo(3)</code> manual page</p> </blockquote>
14238
|isp|
ISP - Wrong direction frying ATmega
2015-08-16T08:34:22.983
<p>I tried to flash my ATmega328P-PU not over the Arduino but over a self-made programming board and an USBasp. The problem is, I made the board a while ago and didn't mark which direction the 10-pin connector has to go.</p> <p>My question is, can I fry the ATmega if I connect the 10-pin connector the wrong way around? Also, can this harm the USBasp in any way?</p> <p>Connecting it the wrong way around would give me the following connections:</p> <pre><code>USBasp --- ATmega MOSI -| NC -|- GND RST -| SCK -| MISO --- Vcc Vcc --- MISO |- MOSI GND -|- NC |- RST |- SCK </code></pre>
<p>No, connecting it backwards shouldn't do any damage, it just won't work. The clue is in these two connections:</p> <pre><code>NC -|- GND GND -|- NC </code></pre> <p>With it backwards the ground connection doesn't go anywhere. Without that ground connection there's no circuit. With no circuit, no current flows.</p> <p>The only possible danger is to the protection diodes in the IO pins when you try and operate the programmer. The lack of a ground connection could cause some current to flow the wrong way through the circuit (in through the ATMega's MISO pin and out through the MCU's Vcc pin) through the ESD protection diode. That could cause damage to that diode and maybe the rest of the MISO pin's logic, but it's not that likely since the currents involved would be somewhat limited by the route the power then takes through the MISO pin of the programmer.</p>
14243
|arduino-mega|adc|
Hi-speed external ADC
2015-08-16T12:06:54.510
<p>I would like to detect signals in nanosecond scale. For that, an ADC with at least 500 MSPS is required.</p> <p>My question is if its possible to use an external ADC with 500 MSPS with a 16MHz Arduino Mega? If not, is there any additional hardware like FIFO buffer to overcome this problem?</p> <p>Please help, thanks!</p>
<p>From the Arduino reference on AnalogRead: "It takes about 100 microseconds (0.0001 s) to read an analog input, so the maximum reading rate is about 10,000 times a second."</p> <p>500msps is an awfully high rate - my first instinct is, perhaps you need to revisit what you are after, and why.</p> <p>There are indeed chips that will do this for you. It is still not possible with an Arduino, since the Arduino can't even receive the data this fast, let alone process it. Assuming 8-bit sampling, this would generate a stream of data at 4gigabits/second - I doubt any disk drive could write that fast (SATA3 is 4.8gbit/sec, which is 20% more, I suspect that the 20% would be eaten up by overhead - you can't just send raw data to a drive, you also have to tell it where to put it. That just accounts for getting the data to the drive circuitry, not actually storing it).</p> <p>Perhaps what you're looking for is an oscilloscope. An oscilloscope takes high speed readings and displays them. Oscilloscopes are often used for testing circuits (e.g. looking at what an Arduino puts out/reads in when it's being programmed). Looking on National Instruments' websites, their cheapest one I could find that does > 500msps is worth about US$8,000 (ballpark). You will still not be able to store this to disk, or process it in any meaningful way, in realtime - a board like this will typically capture data (based on a trigger, sample until the memory is full, then slowly move the data to the PC to process.</p>
14245
|atmega328|
Updating a sketch to work with IDE 1.6.6
2015-08-16T13:12:19.737
<p>I've got a MAX7456 chip and I am using <a href="https://www.dropbox.com/s/3cp4am1f271odcm/max7456.tar?dl=1" rel="nofollow">this (this is the unmodified one)</a> library with it. There's a sketch inside the examples folder (Max7456WriteTable) that I need to get to work to update the character table.</p> <p>I modified three lines and then I got really stuck as I do not know how to continue. <a href="https://www.dropbox.com/s/sljvyngc27zver4/max7456_new.tar?dl=1" rel="nofollow">This</a> is the modified one.</p> <pre><code>In file included from Max7456Write.ino:2:0: /tmp/build4608284042510222737.tmp/sketch/Max7456WriteTable.h:29:69153: warning: narrowing conversion of '243' from 'int' to 'const char' inside { } is ill-formed in C++11 [-Wnarrowing] </code></pre> <p>This happens for every item in the array. But that is not the only problem. (I'll skip a few hundred lines)</p> <pre><code>/tmp/build8855411239666100148.tmp/sketch/Max7456Write.cpp.o: In function `setup': /home/t/Max7456Write.ino:13: undefined reference to `Max7456::Max7456(unsigned char)' /home/t/Max7456Write.ino:19: undefined reference to `Max7456::activateOSD(bool)' /home/t/Max7456Write.ino:44: undefined reference to `Max7456::getCARACFromProgMem(char const*, unsigned char, unsigned char*)' /home/t/Max7456Write.ino:46: undefined reference to `Max7456::sendCharacter(unsigned char const*, unsigned char, unsigned char)' collect2: error: ld returned 1 exit status Error compiling. </code></pre> <p>It takes a huge amount of time for it to abort the compilation.</p>
<p>If I change <code>prog_uchar</code> to <code>unsigned char</code> in both max7456.h and max7456.cpp the hello world example sketch compiles. </p> <p>In Max7456WriteTable change</p> <pre><code>Max7456::getCARACFromProgMem(i,currentChar); //Because the table is too big for ram memory osd-&gt;sendCharacter(currentChar,i); //We send currentChar at address i. </code></pre> <p>to </p> <pre><code>Max7456::getCARACFromProgMem(tableOfAllCharacters, i,currentChar); //Because the table is too big for ram memory osd-&gt;sendCharacter(currentChar,i, 0); //We send currentChar at address i. </code></pre> <p><code>0</code> is probably the wrong value, but at least it compiles.</p>
14253
|arduino-yun|
LininoIO running "partially"
2015-08-16T18:47:19.663
<p>I installed LininoIO (OS dated 02 06 2015).</p> <p>Everything seems to work fine - but nothing works as expected.</p> <p>I have a running Linux - but when I try to use GPIO, as described on Lilino.org -<a href="http://wiki.linino.org/doku.php?id=wiki:lininoio_sysfs" rel="nofollow noreferrer">GPIO on lininoIO</a>, I run into the first problems.</p> <p>D13 doesn't exist (this should be the little red LED on board of the Yún).</p> <p>Next I tested reading the analog inputs.</p> <p>I can for example use <code>cat /sys/bus/iio/devices/iio:device0/in_voltage_A0_raw</code>. There are no errors, but I always get the value <code>0</code>.</p> <p>Checking with <code>/etc/linino/test_avrdude.sh</code> shows:</p> <pre><code>Testing AVRDUDE on ATMEL 32U4 ... avrdude: Version 6.1-20140519, compiled on Jun 2 2015 at 12:34:59 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is "/etc/avrdude.conf" User configuration file is "/root/.avrduderc" User configuration file does not exist or is not a regular file, skipping Using Port : unknown Using Programmer : linuxgpio Can't export GPIO 11, already exported/busy?: Device or resource busy avrdude done. Thank you. </code></pre> <p>Maybe this is "by design" or another sign of an error.</p> <p>By the way - when I start a serial console I get the message:</p> <pre><code>avr-uart: switched to uart mode: mcuio </code></pre> <p>Further in kernel log I found:</p> <pre><code>[ 42.480000] fuse init (API version 7.18) [ 42.620000] spi_tty_plain spi1.0: spi_tty_probe [ 45.380000] No need to change console settings [ 49.550000] mcuio-hc 0:0.0: unexpected reply [ 49.600000] gpiochip_add: registered GPIOs 100 to 139 on device: generic [ 49.630000] mcuio adc is 0:1:1 [ 49.750000] mcuio-adc 0:1.1: 6 input channels detected [ 49.910000] mcuio-hc 0:0.0: unexpected reply [ 49.970000] mcuio pwm is 0:1:2 [ 49.970000] mcuio-pwm 0:1.2: 6 pwm outputs detected [ 55.790000] busybox: sending ioctl 5310 to a partition! [ 55.800000] busybox: sending ioctl 5310 to a partition! [ 55.820000] busybox: sending ioctl 5310 to a partition! [ 55.830000] busybox: sending ioctl 5310 to a partition! [ 56.290000] EXT4-fs (sda2): couldn't mount as ext3 due to feature incompatibilities [ 56.310000] EXT4-fs (sda2): couldn't mount as ext2 due to feature incompatibilities [ 56.360000] EXT4-fs (sda2): mounted filesystem with ordered data mode. Opts: (null) [ 58.520000] cfg80211: Calling CRDA for country: AT </code></pre> <p>It seems as if there are problems with <code>mcuio-hc</code>.</p> <p>Last thing - when I ran <code>run-avrdude /etc/linino/bathos-one.hex</code> I get an error when comparing the written data (I found information that this can be ignored).</p> <p>How can I fix this / find out what to fix / what's going wrong?</p>
<p>LininoIO has a part which runs on the microcontroller and make the Atheros enable to use the mcu pinout as linux gpios. So you are right, you need to flash the bathos to the mcu.</p> <p>In general to enable/disable lininoIO run:</p> <pre><code>&gt; lininoio start &gt; lininoio stop </code></pre> <p>those commands do everything for you. have also a look <a href="http://www.arduino.org/learning/tutorials/advanced-guides/how-to-pilot-gpio-on-lininoio-2" rel="nofollow noreferrer">here</a></p> <p>Anyway your Linino version seems old, try to upgrade it: <a href="http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini" rel="nofollow noreferrer">http://www.arduino.org/learning/tutorials/advanced-guides/how-to-upgrade-the-linino-distribution-for-arduino-yun-and-yun-mini</a></p>
14256
|programming|temperature-sensor|
Reducing read time for reading DS18B20 temp sensors
2015-08-16T19:41:37.393
<p>I have a number of temperature sensors connected up to an Arduino - I've split it into 3 sections, with each section having a 2-4 sensors on it (due to distances). This works, but the code I'm using would seem to me to be very inefficient - particularly with respect of how long it takes to read all the sensors.</p> <p>I've got 3 code blocks one after each other (which are modified from some code online) which look as below - save, of-course, for the name of the 1wire class.</p> <pre><code>// Dallas 1 Wire (Main Area): // ds.reset_search(); // delay(250); while (ds.search(addr)) { for( i = 0; i &lt; 8; i++) { Serial.print(addr[i], HEX); } if (OneWire::crc8(addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return; } ds.reset(); ds.select(addr); ds.write(0x44, 0); // start conversion, with parasite power on at the end delay(1000); // maybe 750ms is enough, maybe not // we might do a ds.depower() here, but the reset will take care of it. present = ds.reset(); ds.select(addr); ds.write(0xBE); // Read Scratchpad for ( i = 0; i &lt; 9; i++) { // we need 9 bytes data[i] = ds.read(); } raw = (data[1] &lt;&lt; 8) | data[0]; if (type_s) { raw = raw &lt;&lt; 3; // 9 bit resolution default if (data[7] == 0x10) { // "count remain" gives full 12 bit resolution raw = (raw &amp; 0xFFF0) + 12 - data[6]; } } else { byte cfg = (data[4] &amp; 0x60); // at lower res, the low bits are undefined, so let's zero them if (cfg == 0x00) raw = raw &amp; ~7; // 9 bit resolution, 93.75 ms else if (cfg == 0x20) raw = raw &amp; ~3; // 10 bit res, 187.5 ms else if (cfg == 0x40) raw = raw &amp; ~1; // 11 bit res, 375 ms //// default is 12 bit resolution, 750 ms conversion time } celsius = (float)raw / 16.0; Serial.print(":"); Serial.print(celsius); Serial.print(","); } </code></pre> <p>I note that there is a 1000ms delay after each sensor is read, and I'm wondering if I can reduce this to a single 750ms delay for all the sensors. My initial attempts to do this did not meet with success - but I confess that I can't quite get my head around the ds.reset, ds.select etc - and my initial attempts to do this have all failed.</p> <p>Is it possible to remove this delay after reading each sensor ?</p>
<p>In case the &quot;Temperature Conversion Time (tCONV)&quot; of each resolution is not fast enough ([MAX] 9-bit: 93.75ms; 10-bit: 187.5ms; 11-bit resolution: 375ms; 12-bit: 750ms), you can use more sensors.</p> <p>For example, to get a half time (for 9-bit): 47ms:</p> <ul> <li>You can use two sensors at the same measurement point, (they can operate in parallel , as long as the software can operate with each one of them) when reading one, the software starts converting the other.</li> </ul> <p>Each one has its normal conversion time, but when doing the readings in an interleaved way, a shorter reading time can be obtained.</p> <p>For 8 sensors, a time below 11.75ms can be achieved (for 9-bit).</p>
14257
|serial|analogread|
Arduino ,How I can see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0,A1.. pins
2015-08-16T12:40:24.907
<p>I am working in my project and I want to see the output of my sensors as (0 or 5). The maximum read was 770 and the minimum read was 0. So, how can I see the value (0 or 5) on my screen, where I connected my sensors output to analog input A0, A1 pins. I did the following code, but it didn't work:</p> <pre class="lang-c prettyprint-override"><code>void setup(){ Serial.begin(9600); } void loop() { if (analogRead(0)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); if (analogRead(1)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); if (analogRead(2)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); if (analogRead(3)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); if (analogRead(4)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); if (analogRead(5)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); delay(1500); } </code></pre> <p>Note: I have 5 light sensors in my circuit. </p>
<p>Your code has multiple issues.</p> <pre><code>if (analogRead(1)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(' '); </code></pre> <p>Note that <code>Serial.print(' ');</code> is not at all the same as <code>Serial.print(" ");</code></p> <hr> <p>Also, by the indentation it looks like you should be using braces. Amended code:</p> <pre><code>if (analogRead(1)&lt;385) Serial.print("0"); else { Serial.print("5"); Serial.print(" "); } </code></pre> <p>Without the braces only the first statement after the <em>else</em> is conditionally executed.</p> <p>If I am wrong about that, you should indent differently, eg.</p> <pre><code>if (analogRead(1)&lt;385) Serial.print("0"); else Serial.print("5"); Serial.print(" "); </code></pre>
14266
|arduino-uno|spi|eclipse|avr-toolchain|
Arduino in Eclipse IDE: How to add SPI library (core library already added)?
2015-08-17T04:09:34.267
<p>I want to use eclipse for arduino programming, so I followed the guides to set up a static project for the arduino core library. Then I added the library file (.a) and the .h and .cpp files to my new project in the settings.<br> So far, so good.<br> But now I am trying to add the SPI library to my project without success (I only have the .h and .cpp files, <strong>no</strong> .a)! </p> <p>My sample code </p> <pre><code>#include &lt;Arduino.h&gt; #include &lt;SPI.h&gt; int main(void) { init(); pinMode(13, OUTPUT); for (;;) { digitalWrite(13,1); SPI.setBitOrder(0); } } </code></pre> <p>The pinMode and digitalWrite parts work, but with the SPI method I get an error: </p> <pre><code>05:33:26 **** Build of configuration Debug for project ArduinoTestProject **** make all Building file: ../main.cpp Invoking: AVR C++ Compiler avr-g++ -I/home/fabio/Workspace/arduinoLIB/SPI -I/home/fabio/Workspace/arduinoCORE -Wall -g2 -gstabs -Os -ffunction-sections -fdata-sections -fno-exceptions -mmcu=atmega328p -DF_CPU=16000000UL -MMD -MP -MF"main.d" -MT"main.d" -c -o "main.o" "../main.cpp" Finished building: ../main.cpp Building target: ArduinoTestProject.elf Invoking: AVR C++ Linker avr-gcc -s -Os -o"ArduinoTestProject.elf" ./main.o -l"arduinoUNO" -l"m" -lm -Wl,-Map,ArduinoTestProject.map,--cref -mrelax -Wl,--gc-sections -L/home/fabio/Workspace/arduinoCORE/lib -mmcu=atmega328p; avr-nm -C -n "ArduinoTestProject.elf" &gt;ArduinoTestProject.symbol ./main.o: In function `main': ../main.cpp:38: undefined reference to `SPIClass::setBitOrder(unsigned char)' collect2: error: ld returned 1 exit status avr-nm: 'ArduinoTestProject.elf': No such file make: *** [ArduinoTestProject.elf] Error 1 05:33:26 Build Finished (took 72ms) </code></pre> <p>Does anyone see the problem?</p>
<p>As far as I understand you are using eclipse CDT directly. (I mean you are not using an "arduino eclipse plugin" that does the stuff below for you)</p> <p>The first thing to understand is that a arduino library is not treated as a library when compiling a arduino sketch.</p> <p>In other words in the Arduino IDE, a arduino library is compiled like standard source code just like your .ino files.</p> <p>As such there is no SPI.a file created during the compilation process. In CDT you can have both options (with or without .a file) but the Arduino IDE way is the easiest, by far.</p> <p>So lets first assume you want to compile the "Arduino way" aka without SPI.a. What you need to do is simply drag and drop the files in your project. If you want to drop in a subfolder (like libraries/SPI) you will need to add those folders to your include path. That is all there is to it.</p> <p>If you want to treat the library as a real library (saying you want a SPI.a) the best thing I can think of is to create a new library project for each sketch-project . Drag and drop the SPI code in that project (like above) and make your project dependent on the library project. There are probably some include path issues but the .a file should be found and included in the build</p> <p>Note that the second approach makes that you will need a SPI project for each and every (arduino) board you have. If you want to use project defines it is even more difficult.</p> <p>I would strongly advise to start your arduino eclipse development with <a href="http://eclipse.baeyens.it" rel="nofollow">my arduino eclipse plugin</a> because it is simply easier. Later you can evolve to the full freedom of CDT.</p> <p>If you want to drag and drop folders instead of the .h and .cpp files you will have to add exclusion rules to your include path. This because otherwise all the examples of the library will be in your project making you have multiple setup and loop functions.</p>
14276
|bluetooth|shields|
HC-06 module versus 1sheeld
2015-08-17T12:01:25.610
<p>Why would someone buy a <a href="http://1sheeld.com/" rel="nofollow">1sheeld</a>?</p> <p>Why not connect an Arduino to their smartphone using HC-06 bluetooth module and find an appropriate Android app, like for example RoboRemo. What is the advantage of using a 1sheeld?</p>
<p>Giving an equally biased answer as @Majenko, from the other side:</p> <p>Because they're lazy, they don't know anything about electronics, and they don't want to. And they have more money than they know what to do with.</p> <p>I am horrified at people shelling out for an "Arduino Temperature Sensor", "Arduino Shift Register", or "Arduino LED", each of which is a generic component soldered on to a board, with pins, at a 1000% markup</p> <p>I also question the claim that "cobbled together" items are more reliable, or are less likely to have people laugh at you - if you want it to look nice, put it in a nice box (this applies both to "pre-made" items, and to cobbled together).</p> <p>You will also learn a lot more from making it yourself; you will learn how things work, and you have a better idea and have the opportunity to fix when things go wrong. Your projects will also be a lot smaller.</p> <p>If you want something that "just works", go buy an ipad. Then, when it doesn't work, throw it in the rubbish and buy a new one. And if you want it to do something it doesn't do, tough luck.</p>
14281
|isr|millis|pulsein|
Is it correct to use pulseIn() in ISRs?
2015-08-17T16:23:11.293
<p>Since it is not right to use millis() in an ISR to calculate duration of the input, Is it correct to use pulseIn()?</p>
<p>It is quite OK to use <code>millis()</code> or <code>micros()</code> inside an ISR. In fact that is an excellent time to do it, because you are recording the time of the event shortly after it happened. Make sure the variable you are saving it to is <code>unsigned long</code> and <code>volatile</code>. Eg.</p> <pre class="lang-C++ prettyprint-override"><code>volatile unsigned long whenItHappened; volatile bool eventHappened; void myISR () { whenItHappened = millis (); eventHappened = true; } </code></pre> <p>Now in your main loop you can test the <code>eventHappened</code> flag, so you will know if this event has happened, and <code>whenItHappened</code> is when.</p> <p>It is <strong>not</strong> a good idea to use <code>pulseIn()</code> because that can wait quite a long time for a pulse. The default timeout for <code>pulseIn</code> is 1 second, which is far too long to wait inside an ISR.</p> <p>If you want to time something (eg. how long it takes a ball to cross a sensor) use the interrupt twice, once to find the first event, and again to find the second.</p> <hr> <h2>Example</h2> <p>Example code which times how long a ball passes a sensor:</p> <pre class="lang-C++ prettyprint-override"><code>const byte LED = 12; const byte photoTransistor = 2; unsigned long startTime; volatile unsigned long elapsedTime; volatile boolean done; void ballPasses () { // if low, ball is in front of light if (digitalRead (photoTransistor) == LOW) { startTime = micros (); } else { elapsedTime = micros () - startTime; done = true; } digitalWrite (LED, !digitalRead (LED)); } void setup () { Serial.begin (115200); Serial.println ("Timer sketch started."); pinMode (LED, OUTPUT); attachInterrupt (0, ballPasses, CHANGE); } void loop () { if (!done) return; Serial.print ("Time taken = "); Serial.print (elapsedTime); Serial.println (" uS"); done = false; } </code></pre> <p>That code used <code>micros()</code> for a more accurate timing.</p> <hr> <h2>Reference</h2> <ul> <li><a href="http://www.gammon.com.au/interrupts" rel="nofollow">Interrupts</a></li> </ul>
14283
|arduino-mega|lcd|
Help with LCD's menu and seeing values continuously
2015-08-17T18:33:34.650
<p>I want to see the voltage data using <code>void volt();</code>, when I go to the "Item2SubItem3" within <code>void menuChanged</code>. Now I can only see the data <em>at that time</em>: how can I refresh the value every second?</p> <pre><code>void setup() { // setup()... } void loop() { //loop()... } // DC Voltometer float vPow = 4.7; float r1 = 100000; float r2 = 10000; void volt() { lcd.clear(); float v = (analogRead(0) * vPow) / 1024.0; float v2 = v / (r2 / (r1 + r2)); lcd.setCursor(0, 0); lcd.print("DC VOLTOMETER"); lcd.setCursor(0, 1); lcd.print(v2); delay(1000); } void menuChanged(MenuChangeEvent changed) { MenuItem newMenuItem = changed.to; // get the destination menu lcd.setCursor(0, 1); // set start position for lcd // printing to the second row if (newMenuItem.getName() == menu.getRoot()) { lcd.print("Main Menu "); } else if (newMenuItem.getName() == "Item1") { lcd.print("Item1 "); } else if (newMenuItem.getName() == "Item1SubItem1") { lcd.print("Item1SubItem1"); } else if (newMenuItem.getName() == "Item1SubItem2") { lcd.print("Item1SubItem2 "); } else if (newMenuItem.getName() == "Item2") { lcd.print("Item2 "); } else if (newMenuItem.getName() == "Item2SubItem1") { lcd.print("Item2SubItem1 "); } else if (newMenuItem.getName() == "Item2SubItem2") { lcd.print("Item2SubItem2 "); } else if (newMenuItem.getName() == "Item2SubItem3") { lcd.print("Item2SubItem3 "); delay(2000); volt(); } else if (newMenuItem.getName() == "Item3") { lcd.print("Item3 "); } else if (newMenuItem.getName() == "Item4") { lcd.clear(); lcd.setCursor(0, 0); lcd.print("Item4 "); } } </code></pre>
<p>As Gerben implied in a comment, <code>menuChangeEvent</code> is called only when the menu selection changes. Thus, your voltmeter readout will print only whenever you change the menu selection to Item2SubItem3. The code shown below illustrates how to modify your <code>loop()</code> so that it checks the menu selection once per second. Each second the main loop will do whatever function is currently selected, such as displaying a current voltmeter reading. Note, you can make the menu decoding shorter and less tedious as shown in the answer, and can put variable declarations near where they are used instead of in random places.</p> <pre><code>void setup() { } // setup()... // DC voltmeter reading void volt () { const float vPow = 4.7, r1 = 100000, r2 = 10000; lcd.clear(); float v = (analogRead(0) * vPow) / 1024.0; float v2 = v / (r2 / (r1 + r2)); lcd.setCursor (0,0); lcd.print("DC Voltmeter"); lcd.setCursor (0,1); lcd.print (v2); // Don't delay(1000) since loop() takes care of delay. } long int second = 0; uint8_t itemcode = 0; // Will be number nm for Item n, Subitem m int passnumber = 0; void menuChanged(MenuChangeEvent changed) { MenuItem menuitem = changed.to; //get the destination menu String itemname = menuitem.getName(); lcd.clear(); // Make printing spaces at line ends unnecessary lcd.setCursor(0,1); //set lcd printing position = second row if(newMenuItem.getName() == menu.getRoot()){ lcd.print("Main Menu"); itemcode = 0; } else { lcd.print(itemname); itemcode = 10*(itemname[4] &amp; 7); if (itemname.length() &gt; 5) itemcode += itemname[itemname.length()-1] &amp; 7; } passnumber = 0; // Actions can test passnumber if they like second = 0; // Cause actions to take place now } void loop() { long int now = millis()/1000; // Get elapsed-seconds if (now == second) return; // Only do stuff once per second // Update to current second and do chosen menu item second = now; switch (itemcode) { case 0: break; case 10: break; case 11: break; // Fill in with code for different cases case 12: break; case 20: break; case 21: break; case 22: break; case 23: // Item 2, subitem 3, read voltmeter volt(); break; case 30: break; case 40: break; } // You can test passnumber to control for cases that only go once ++passnumber; } // end of loop() </code></pre> <p><em>Edit:</em> I moved the declaration of <code>second</code> and added <code>second = 0</code> within <code>menuChanged()</code> to decrease latency between a menu item being selected and its action taking place. Without <code>second</code> being zeroed in <code>menuChanged()</code>, up to a second could pass between an item's selection and its action; latency would average 0.5 seconds, which is undesirable in a user interface. </p>
14298
|arduino-uno|timers|arduino-micro|
Arduino Uno vs Arduino Micro timers → pins
2015-08-18T09:25:05.253
<p><strong>Where do I find the pins relative to timers of each individual Arduino microcontroller?</strong></p> <p>As I like Arduino's I already have various samples of them. The one I mostly use is the Uno and Micro for now... I'm planning to also get a Mega and others. Most simple things work on all devices, but if you start with complex code to fasten up things, every device is a little different. A problem I could not solve for days now is the relation between pins and timers.</p> <p>I cannot find any information about the Arduino Micro. I also don't know exactly what the proper keywords are that I need to find the relation between timers and pins.</p> <p><strong>Example:</strong> A PWM driver multiplexing</p> <p>As I for now just got some stuff from my local dealer I have no access to shift registers, PWM drivers and other proper integrated circuits.</p> <p>So I used the Arduino as a PWM driver for 8 RGB or 24 (3*8) white LEDs. The code works on Arduino Uno. But as the <strong>Arduino Micro has no <em>Timer2</em></strong>, <code>TCCR2B</code>, I cannot use the same code on the Arduino Micro.</p> <p>Even if I understand the code (I wrote a lot in other languages...), some of the Atmel chip specific parameters are not clear.</p> <p>This function sets the prescaler of the timer:</p> <pre><code>void setPwmFrequency(int pin, int divisor){ byte mode; if(pin==5||pin==6||pin==9||pin==10){ switch(divisor){ case 1:mode=0x01;break; case 8:mode=0x02;break; case 64:mode=0x03;break; case 256:mode=0x04;break; case 1024:mode=0x05;break; default:return; } if(pin==5||pin==6){ TCCR0B=TCCR0B&amp;0b11111000|mode; } else{ TCCR1B=TCCR1B&amp;0b11111000|mode; } }else if(pin==3||pin==11){ switch(divisor){ case 1:mode=0x01;break; case 8:mode=0x02;break; case 32:mode=0x03;break; case 64:mode=0x04;break; case 128:mode=0x05;break; case 256:mode=0x06;break; case 1024:mode=0x7;break; default:return; } TCCR2B=TCCR2B&amp;0b11111000|mode; } } </code></pre> <p>First of all, I probably don't even need this function as soon I know what frequency I want, and so I probably need only two lines to set my three (RGB) pins.</p> <pre><code>//Arduino Uno timer setup for pin 9, 10, and 11 TCCR1B=TCCR1B&amp;0b11111000|0x01; // Pin 9,10 TCCR2B=TCCR2B&amp;0b11111000|0x01; // Pin 11 </code></pre> <ol> <li><p>Correct, I need to set <code>TCCR1B</code> only one time?</p></li> <li><p>What does the <code>0b11111000</code> refer to?</p></li> </ol> <p>In the setup function there is also this line:</p> <pre><code>TIMSK2 = 1&lt;&lt;TOIE2; </code></pre> <ol start="3"> <li>What does this do?</li> </ol> <p>While the above three questions are not so important until it works, <strong>I need to understand how I can convert those timers to work with Arduino Micro</strong>, but also later with other Arduino boards.</p> <hr> <p><strong>On Arduino Micro</strong></p> <p>There is no timer 2</p> <p>Do pin 9, 10, and 12 have the same timer?</p> <pre><code>??????=??????&amp;0b11111000|0x01; </code></pre> <p>Also if I understand correctly the Arduino Micro has:</p> <ol> <li>A higher PWM range 1024 vs 255 (UNO)??</li> <li>A much higher frequency available in on Timer4 only for pin 13</li> </ol> <p><strong>So is there somewhere a table describing the differences between all Arduino timers?</strong></p> <p><strong>Full working (on Arduino Uno) code.</strong></p> <pre><code>unsigned char Prescaler=0; unsigned char CurrentLED=0; unsigned char LEDValues[8][3]; unsigned char ports[8]={ 0b00000100, 0b00001000, 0b00010000, 0b00100000, 0b01000000, 0b10000000, 0b00000001, 0b00010000 };//PINS 2,3,4,5,6,7,8,12 #define PrescalerOverflowValue 4 ISR(TIMER2_OVF_vect){ if(Prescaler&lt;PrescalerOverflowValue){ Prescaler++; }else { Prescaler=0; Multiplex(); } } void Multiplex(void){ PORTD&amp;=0b00000011; PORTB&amp;=0b11101110; analogWrite(9,255-LEDValues[CurrentLED][0]); analogWrite(10,255-LEDValues[CurrentLED][1]); analogWrite(11,255-LEDValues[CurrentLED][2]); CurrentLED&lt;6?(PORTD|=ports[CurrentLED]):(PORTB|=ports[CurrentLED]); CurrentLED++; if(CurrentLED&gt;7)CurrentLED=0; } void setPwmFrequency(int pin, int divisor){ byte mode; if(pin==5||pin==6||pin==9||pin==10){ switch(divisor){ case 1:mode=0x01;break; case 8:mode=0x02;break; case 64:mode=0x03;break; case 256:mode=0x04;break; case 1024:mode=0x05;break; default:return; } if(pin==5||pin==6){ TCCR0B=TCCR0B&amp;0b11111000|mode; }else{ TCCR1B=TCCR1B&amp;0b11111000|mode; } }else if(pin==3||pin==11){ switch(divisor){ case 1:mode=0x01;break; case 8:mode=0x02;break; case 32:mode=0x03;break; case 64:mode=0x04;break; case 128:mode=0x05;break; case 256:mode=0x06;break; case 1024:mode=0x7;break; default:return; } TCCR2B=TCCR2B&amp;0b11111000|mode; } } void setup(void){ pinMode(2,OUTPUT);//1 pinMode(3,OUTPUT);//2 pinMode(4,OUTPUT);//3 pinMode(5,OUTPUT);//4 pinMode(6,OUTPUT);//5 pinMode(7,OUTPUT);//6 pinMode(8,OUTPUT);//7 pinMode(12,OUTPUT);//8 pinMode(9,OUTPUT);//red pinMode(10,OUTPUT);//green pinMode(11,OUTPUT);//blue setPwmFrequency(9,8); setPwmFrequency(10,8); setPwmFrequency(11,8); TIMSK2=1&lt;&lt;TOIE2; } void loop(void){ for(int i=0;i&lt;8;i++){ //LEDValues[i][0]; // Red //LEDValues[i][1]; // Green //LEDValues[i][2]; // Blue } } </code></pre>
<p>You can check <code>pins_arduino.h</code> file as well.</p> <pre><code>// ATMEL ATMEGA32U4 / ARDUINO LEONARDO // // D0 PD2 RXD1/INT2 // D1 PD3 TXD1/INT3 // D2 PD1 SDA SDA/INT1 // D3# PD0 PWM8/SCL OC0B/SCL/INT0 // D4 A6 PD4 ADC8 // D5# PC6 ??? OC3A/#OC4A // D6# A7 PD7 FastPWM #OC4D/ADC10 // D7 PE6 INT6/AIN0 // // D8 A8 PB4 ADC11/PCINT4 // D9# A9 PB5 PWM16 OC1A/#OC4B/ADC12/PCINT5 // D10# A10 PB6 PWM16 OC1B/0c4B/ADC13/PCINT6 // D11# PB7 PWM8/16 0C0A/OC1C/#RTS/PCINT7 // D12 A11 PD6 T1/#OC4D/ADC9 // D13# PC7 PWM10 CLK0/OC4A // // A0 D18 PF7 ADC7 // A1 D19 PF6 ADC6 // A2 D20 PF5 ADC5 // A3 D21 PF4 ADC4 // A4 D22 PF1 ADC1 // A5 D23 PF0 ADC0 // // New pins D14..D17 to map SPI port to digital pins // // MISO D14 PB3 MISO,PCINT3 // SCK D15 PB1 SCK,PCINT1 // MOSI D16 PB2 MOSI,PCINT2 // SS D17 PB0 RXLED,SS/PCINT0 // // TXLED D30 PD5 XCK1 // RXLED D17 PB0 // HWB PE2 HWB </code></pre> <p>There is an array inside the same file with name <code>digital_pin_to_timer_PGM</code> that list the timers also.</p> <pre><code>const uint8_t PROGMEM digital_pin_to_timer_PGM[] = { NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, TIMER0B, /* 3 */ NOT_ON_TIMER, TIMER4A, /* 5 */ TIMER4D, /* 6 */ NOT_ON_TIMER, NOT_ON_TIMER, TIMER1A, /* 9 */ TIMER1B, /* 10 */ TIMER0A, /* 11 */ NOT_ON_TIMER, TIMER4A, /* 13 */ NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, NOT_ON_TIMER, }; </code></pre>
14318
|serial|usb|
Fast Python to arduino communications
2015-08-18T23:31:53.200
<p>I've been communicating with a teensy arduino over USB using pySerial--which has been simple, but slow. With simple write commands from Python and a corresponding read command on the teensy, I can only achieve 200kHz transfer rates. I'm hoping to get over 1MHz at least, but I don't see a path towards that rate.</p> <p>Are Ethernet shields capable of augmenting for rates over the MHz range? How can I get faster data transfer rates between my computer and arduino? I'm mainly interested in one-way communications (computer directs teensy).</p>
<p>First of all, khz and mhz are not data transfer rates. They are frequencies - "something per second" - did you mean kilobits/second or kilobytes/second (both, confusingly, abbreviated to kbps by various people).</p> <p>If you have not already done so, you can specify a bitrate for your communications - serial.begin takes a parameter which specifies the speed - most example seem to use 9600 bits/second, you can crank this all the way up to 115,200 bits/second - 12 times the speed. I don't know if this will work with a Teensy, and/or USB. You will probably at least need to specify this in your terminal program and/or pySerial.</p> <p>I wonder what you are doing that requires 1Mbyte/second communication with an Arduino, and if you can do that a little smarter?</p> <p>At that rate, the 64kbytes of memory can be filled up in 1/16th of a second.</p> <p>You can get a faster "information transfer" by increasing the information density - for example, the English word "True" takes up 4 characters = 32 bits , but a logical true value only takes up 1 bit.</p> <p>If you are processing the data on the Arduino, at 1mbyte/second, you have 72 instructions to do something with that byte before the next one is there - not much time.</p> <p>You could increase the data rate by pushing the data in in parallel, using multiple pins - e.g. 32 bits in parallel, one on each of 32 pins, one data point per cycle. There would be no practical way to assimilate data at that speed.</p> <p>If you are sending this from a PC, perhaps some of the data could be processed on the PC before sending?</p> <p>Another option would be to divide the work over multiple Teensies, with the PC combining the work - e.g. if you have temperature sensors that output 4 byte values, you want to read 250 of them at a rate of 1000 samples per second (= total of 1mbyte/second), then you might be able to run 25 Teensies, each sampling 10 sensors, and each pushing data at 40kbytes/second, rather than one running at 1mbyte/second.</p> <p>Quite frankly, these are all fairly contrived examples - most sensors can't be read that quickly; even an Arduino's analog read is limited to 10,000 reads per second - if you do nothing else. This produces 100 kbits/second, or 20kbytes per second (each 10-bit read is returned as two bytes, with the remaining 6 bits being 0). </p>
14320
|arduino-mega|led|c++|button|
Multiple buttons activating different methods for an LED strip
2015-08-19T04:16:26.780
<p>I am trying to use different buttons to activate different methods for an LED strip. However, when one button is pressed after another has been pressed, I want it to interrupt the first buttons method and begin the second. For example: one button sends a rainbow pattern through the LED strip when pressed, however, while it is cycling through the rainbow, the second button is pressed which sends a white cycle through the LED strip. There will be 24 buttons total. I have gotten this to work with 2 buttons but am having trouble getting it to work for a third. The code is below:</p> <pre><code> void loop(){ if (digitalRead(inPin(1)) == HIGH &amp;&amp; lastState == LOW){//if button has just been pressed stopCycle(); theaterChaseRainbow(50); } if (digitalRead(inPin(2)) == HIGH){ stopCycle(); theaterChase(strip.Color(127, 127, 127), 50); // White } if (digitalRead(inPin(3)) == HIGH){ stopCycle(); rainbowCycle(0); } } //Theatre-style crawling lights. void theaterChase(uint32_t c, uint8_t wait) { for (int j=0; j&lt;100; j++) { //do 100 cycles of chasing if (digitalRead (inPin(1)) == LOW) { //checks that other button(s) have not been pressed if (digitalRead (inPin(3) == LOW)){ for (int q=0; q &lt; 3; q++) { for (int i=0; i &lt; strip.numPixels(); i=i+3) { strip.setPixelColor(i+q, c); //turn every third pixel on } strip.show(); delay(wait); for (int i=0; i &lt; strip.numPixels(); i=i+3) { strip.setPixelColor(i+q, 0); //turn every third pixel off } } } } } } void rainbow(uint8_t wait) { int i, j; for (j=0; j &lt; 384; j++) { if (digitalRead (inPin(2)) == LOW) { // 3 cycles of all 384 colors in the wheel if (digitalRead (inPin(3) == LOW)){ for (i=0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, Wheel( (i + j) % 384)); } strip.show(); // write all the pixels out delay(wait); } } } } uint32_t Wheel(uint16_t WheelPos) { byte r, g, b; switch(WheelPos / 128) { case 0: r = 127 - WheelPos % 128; //Red down g = WheelPos % 128; // Green up b = 0; //blue off break; case 1: g = 127 - WheelPos % 128; //green down b = WheelPos % 128; //blue up r = 0; //red off break; case 2: b = 127 - WheelPos % 128; //blue down r = WheelPos % 128; //red up g = 0; //green off break; } return(strip.Color(r,g,b)); } void rainbowCycle(uint8_t wait) { uint16_t i, j; for (j=0; j &lt; 384 * 5; j++) { // 5 cycles of all 384 colors in the wheel if (inPin(1) == LOW) { if (inPin(2) == LOW) { for (i=0; i &lt; strip.numPixels(); i++) { // tricky math! we use each pixel as a fraction of the full 384-color wheel // (thats the i / strip.numPixels() part) // Then add in j which makes the colors go around per pixel // the % 384 is to make the wheel cycle around strip.setPixelColor(i, Wheel( ((i * 384 / strip.numPixels()) + j) % 384) ); } strip.show(); // write all the pixels out delay(wait); } } } } void stopCycle(){ int i; for (i=0; i &lt; strip.numPixels(); i++) { strip.setPixelColor(i, 0); } strip.show(); // write all the pixels out } </code></pre>
<p>I would normally do this (pseudocode):</p> <pre><code>void loop() { static state=state_off; if (button_1_pushed) { state=state_1; } elseif (button_2_pushed) { state=state_2; } if (state==state_off) { turn_all_leds_off(); } elseif (state==state_2) { shownextframe_rainbow(); } elseif (state==state_2) { shownextframe_chaser(); } delay(1); } </code></pre> <p>In shownextframe_chaser/shownextframe_rainbow, I would probably work out what should be shown based on the current millis() - e.g. if your chaser has 10 lights, and you want it to pulse over 1 second, then each led should be on for 100 millis, so at any instant, the led that should be on is <code>(millis()/100)%10</code> (assuming the led's are numbered for 0 to 9).</p>
14333
|timers|
Arduino timers. How they work
2015-08-19T11:41:43.053
<p><strong>Explain this line in simple words.</strong></p> <pre><code>TCCR0B=TCCR0B&amp;0b11111000|0x01; </code></pre> <p>As the variuos arduinos have different chips. They also have different timers and different pins which use them.</p> <p>Lately i want to rewrite a code(Arduino Uno) to make it work on a Arduino Micro.</p> <p>I need to understand how this works in simple words. I normally write web based code(javascript,php...). Just lately i started writing in c++ or a "simplified" c++ in the arduino ide. It's not that hard. But some specific parameters are hard to understand for me. Shortcuts like the following.</p> <pre><code>TCCR0B=TCCR0B&amp;0b11111000|0x01; </code></pre> <p>What does that?</p> <pre><code>TCCR0B </code></pre> <p><code>TCCR</code> = Prefix for timers. Correct?</p> <p><code>0</code> = Timer1 or 0 call it however you want.</p> <p><code>B</code> = <strong>What is A,B,C and sometimes D for?</strong> What does this?why in that code is the programmer using B and not A,C or D</p> <p><code>TCCR0B=</code> Timer 0 B is equal to:</p> <p><code>TCCR0B&amp;</code> <strong>if Timer 0 B return True .. exists "&amp;" ?</strong></p> <p><code>0b11111000</code> <strong>What is this?</strong> i already asked this and the answer was something like "clears the low-order 3 bits". Like i said, i'm not very familiar with c++, bits and other stuff regarding the arduino. I now less about the various chips and also about how they implemented the various parameters from arduino ide to work with those chips. I know that i have here 8 values that i can change from 0 to 1. What does those values change relative to the timer. Please think of me as a 6 year old.</p> <p><code>|0x01;</code> I got this... it sets the prescaler... 1,8,32.. some timers have differnet values... no problem. I need it at 1.</p>
<p>I understand your question is not about c++ and bit manipulation.</p> <p>It's not about &quot;Arduino&quot; neither, because your code line does only make sense for a certain avr microcontroller with a register named <code>TCCR0B</code>.</p> <p>Sure, some arduinos are based on such microcontrollers and the c++ compiler used in the arduino toolchain allows access to those hardware registers via their names used in the datasheets.</p> <p>Details however are beyond &quot;Arduino&quot; and should be looked up in the corresponding controller datasheet.</p>
14341
|c++|interrupt|timers|rotary-encoder|
counting pulses from encoder on interrupt 0 pin every 50 ms
2015-08-19T12:19:34.060
<p>I want to calculate the number of pulses coming from motor1 encoder pin2 (Int0) as input , and motor 2 encoder pin3 (Int1), I am working now for the first motor (just for the first motor ) so I set timer 2 to count 50 ms then throw flag in this moment I have to send the number of pulses to my screen, but not succeeded cause i see on my screen zeros and ascii caracters but not the number of pulses.:this my code .</p> <pre><code> volatile int pulses = 0; int flag=0; int setbit = 0; int encoder_in = 2; void count() { pulses++; } void setup() { Serial.begin(115200); pinMode(encoder_in, INPUT); digitalWrite(2, HIGH); //Enable pullup // initialize timer2 noInterrupts(); // disable all interrupts TCCR2A = 0x00; TCCR2B = 0x07; TCNT2 = 0x64; //EIMSK = 0x03; // Enable external interrupt INT0 //EICRA = 0x0f; // Trigger INT0 on falling edge TIMSK2 |= 0x01; // enable timer compare interrupt interrupts(); // enable all interrupts attachInterrupt(0,count,RISING); } ISR(TIMER2_OVF_vect) { TCNT2 = 0x64; // preload timer setbit=setbit+1; if(setbit==5) { flag=1; setbit=0; } } //ISR(EXT_INT0_vect) //{ pulses++; } void loop() { if (flag==1) { Serial.println(pulses); pulses=0; } } </code></pre>
<p>Your technique looks convoluted to me. How about this?</p> <pre class="lang-C++ prettyprint-override"><code>volatile bool counting; volatile unsigned long events; unsigned long startTime; const unsigned long INTERVAL = 50; // ms void eventISR () { if (counting) events++; } // end of eventISR void setup () { Serial.begin (115200); Serial.println (); pinMode (2, INPUT_PULLUP); attachInterrupt (0, eventISR, RISING); } // end of setup void showResults () { Serial.print ("I counted "); Serial.println (events); } // end of showResults void loop () { if (counting) { // is time up? if (millis () - startTime &lt; INTERVAL) return; counting = false; showResults (); } // end of if noInterrupts (); events = 0; startTime = millis (); EIFR = bit (INTF0); // clear flag for interrupt 0 counting = true; interrupts (); } // end of loop </code></pre> <hr> <h3>Explanation</h3> <p>Using a timer to detect when 50 ms is up isn't particularly helpful in this case. You can't do printing inside an ISR, so you would have to set a flag that can be checked in the main loop.</p> <p>If you are going to check a flag anyway, you may as well just check if the time is up, as my code does. </p> <p>Inside the ISR, I stop adding to <code>events</code> if the flag <code>counting</code> is false. This is to stop <code>events</code> being changed at the exact moment it is being printed.</p>
14346
|arduino-uno|power|
How to power an Arduino Uno with 3 1.5V batteries?
2015-08-19T21:57:24.283
<p>I have an <strong>Arduino Uno</strong> <em>(a SainSmart model, actually)</em>. I intend to power it with three 1.5V batteries. I measured them and they yield 4.67V in total. The Arduino requires 5V.</p> <h1>The question is, if the arduino will work this way.</h1> <p>I'm not powering complicated microcontroller components here. These components are used:</p> <ul> <li>A buzzer</li> <li>An LED</li> <li>A unit of 4 seven segment displays</li> <li>A couple of buttons as input elements</li> </ul> <p>If the volume or brightness of these components is slightly decreased, it doesn't matter at all. But I would like to know if it will work in the first place.</p> <h1>And also...</h1> <p>Where exactly do I plug the power source in? The power jack, the USB jack, pins, somewhere else?</p> <hr /> <p><strong>The schematic looks like this</strong>, just to illustrate it. I'm not a good drawer, but you'll get the idea...</p> <p><a href="https://i.stack.imgur.com/6OazX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6OazX.png" alt="schematic" /></a></p>
<p>For battery-operated Arduino Uno's I recommend thinking bigger (in terms of power, not physical size). </p> <p>I power several by using 3x 18650 batteries in series, (providing about 14 Volts, connected to a 4x USB 5 Volt module. </p> <p>The Unos are connected to power by a standard USB cable (into the programming port), and then you also have 3 other 5V USB charging or power ports available.</p> <p>Or you can get a small converter unit that provides just one 5V USB.</p> <p>Either way, bringing the power to the UNO is as simple as using the programming cable that comes with the board.</p> <p>Or you can use any other converter and use wires to bring in Vin and GND. </p> <p>You don't need to use 3 of the 18650s. 2 will do fine. Or 4 in series/parallel for longer battery life. No converter would be needed but again you would need wires to bring the voltage into the Unos.</p> <p>18650s are very common, and are inexpensive. They pack a whole lot more mAh than any AA battery you will find. </p> <p>One warning about buying 18650s: There are Chinese companies that advertise 9,800 mA batteries. Don't believe it. 3,000 is about the max any reputable manufacturer will claim. </p>
14351
|serial|programming|
Run a part of code upon call
2015-08-20T01:21:55.930
<p>Lets say I have something that sends a command to the Arduino (for example, a PC sending through serial, Ethernet, etc). I want the Arduino to "check" what command it is and run a specific function linked to that command.</p> <p>I don't need a very explanatory answer, just give me something so I can learn from. A sketch that shows a similar idea would be good, I can try to interpret it and adapt/remake for me.</p> <p>The idea is to use the Arduino for a lot of different things. Let's say:</p> <ol> <li><p>Turn a bunch of leds on/off;</p></li> <li><p>Read data from a sensor and send it through Ethernet/I2C/Serial;</p></li> <li><p>Control a servo. </p></li> </ol> <p>But I want the Arduino to do that when I tell it to (in this case, sending the command through serial, etc). So let's say I send it 1, I'll want it to run the 1 function (turning the LEDs on/off).</p> <p>I already took a <a href="http://sheepdogguides.com/arduino/FA1main.htm" rel="nofollow">tutorial course on Arduino programming</a>, but I'm clueless on how to do this job.</p>
<p>If you want it really barebones and easy, you can checkout the Arduino "Dimmer" example sketch.</p> <p>Instead of changing the brightness of an attached pin, you could take the input you send it over the serial console and execute various functions, depending on what you receive.</p> <p>Something like this:</p> <pre><code>boolean newCommand = false; void setup() { // initialize the serial communication: Serial.begin(9600); // other setup stuff here } void loop() { byte command; // check if data has been sent from the computer: if (Serial.available()) { // read the most recent byte (which will be from 0 to 255): command = Serial.read(); // say that you received a new command newCommand = true; } // is there a new command? if (newCommand == true) { // do something depending on what command you received switch(command) { // if you receive command "1", do something case 1: functionWhatever(); break; // "break" out of the switch. otherwise it would continue executing the following commands as well case 2: functionWhatever2(); break; //for cases that are not caught, send out an error default: Serial.write("invalid command"); break; } } } </code></pre> <hr> <p>If you want to use an existing library, you might want to check out: <a href="https://github.com/madsci1016/Arduino-EasyTransfer" rel="nofollow">EasyTransfer</a>.</p> <p>It can be used for communication between two Arduinos, which you then can use to execute functions on the other side of the line.</p> <p>The code itself is relatively simple, so you might be able to adapt it to communicate with a processing script on your computer for example.</p>
14359
|interrupt|spi|isr|
Usage of SPI inside an ISR
2015-08-20T09:29:41.840
<p>I learned, that SPI-code uses interrupts. So is it true then, that I can't use SPI related code inside an ISR?</p> <p>Background: I want to capture one or more revolution speeds with an MCP23S17. I rewired the interrupt lines to INT1 and INT2 accordingly to get the interrupts at the Arduino.</p> <p>I thought it was good to fetch the port registers from the MCP23S17 inside the ISR, but this apparently doesn't work. </p> <p>Is the only thing I can do in my ISR set a flag for another test in the main loop? And let a routine called from lood() then poll the registers from the port expander? This opposes the idea to fetch the relevant data which issued the interrupt ASAP. </p>
<p>SPI doesn't use interrupts. It references the interrupt flag to know if a transfer has been completed, but it doesn't actually have interrupts enabled:</p> <pre><code>SPDR = data; asm volatile("nop"); while (!(SPSR &amp; _BV(SPIF))) ; // wait return SPDR; </code></pre> <p>It should be perfectly possible to use SPI within the interrupt - indeed there is portions of the SPI API that deal specifically with this - see <a href="https://www.arduino.cc/en/Reference/SPIusingInterrupt" rel="nofollow">https://www.arduino.cc/en/Reference/SPIusingInterrupt</a> for instance.</p>
14363
|mac-os|
Tried to fix ports on Mac OS X Yosemite. Now nothing works
2015-08-20T12:53:31.490
<p>I was having an issue very similar to this one:</p> <p><a href="https://arduino.stackexchange.com/questions/3324/arduino-compatibles-serial-port-not-showing-mac-osx">Arduino compatible&#39;s serial port not showing Mac OSX</a></p> <p>Basically I have a clone (VISduino) and it's made with a different USB chip so it needed a driver. Installing the driver didn't help. </p> <p><a href="http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html" rel="nofollow noreferrer">http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html</a></p> <p>Running:</p> <pre><code> sudo nvram boot-args="kext-dev-mode=1" </code></pre> <p>didn't help. So I decided to delete Arduino and reinstall. Then I went through all of the steps again. </p> <p>Well.... now nothing works. Before doing this I could use:</p> <ul> <li>Adafruit metro </li> <li>An uno clone </li> <li>My genuine uno</li> <li>lightBlue Bean</li> <li>adafruit trinket and trinket pro </li> <li>adafruit trinket pro via USB</li> <li>digikey</li> </ul> <p><a href="https://i.stack.imgur.com/TSdpy.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TSdpy.jpg" alt="enter image description here"></a></p> <p>I've reinstalled the drivers for these but NOTHING is working now. They were all working before. It just says Arduino Uno on COM1, or digikey on COM1 etc.</p> <p><a href="https://i.stack.imgur.com/c6Z1i.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/c6Z1i.jpg" alt="enter image description here"></a></p> <p>And of course my clone (vis duino) isn't working either.</p> <p>How can I fix this? </p> <p><a href="https://i.stack.imgur.com/2VQUA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2VQUA.jpg" alt="enter image description here"></a></p> <p>The com ports just are not there.</p>
<p>I solved this issue by deleting all of the Arduino files and the Arduino app. I put my sketched folder aside but deleted all libraries. </p> <p>Restarted the computer.</p> <p>Installed Arduino fresh.</p> <p>Restarted the computer.</p> <p>Installed the drivers.</p> <p>Ran the command.</p> <p>Restarted the computer.</p> <p>Restarted the computer.</p> <p>Restarted the computer.</p> <p>Then it worked.</p>
14364
|arduino-uno|programming|
Can I use micros() to analyze TX23 anemometer signal?
2015-08-20T13:30:21.727
<p>I'm very new to Arduino, and I'm trying to read data from a LaCrosse TX23 V02(X) anemometer. It's supposed to behave like this <a href="https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/" rel="nofollow">https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/</a>, but it's not...</p> <p>I don't have an oscilloscope, so I made this code, using micros() to try to trace the output from the TX23:</p> <pre><code>void loop() { collectData(); } int collectData(void){ if (bitLength &lt; 0){ bitLength = 1200;// length of bit is equal to approx 1230 micro seconds; } // init sequence pinMode(dataPin, OUTPUT); Serial.print("Send LOW\n"); digitalWrite(dataPin, LOW ); Serial.print("Send HIGH\n"); digitalWrite(dataPin, HIGH); delay(100); Serial.print("Send LOW\n"); digitalWrite(dataPin, LOW ); delay(500); Serial.print("Begin input mode\n"); pinMode(dataPin, INPUT); int state = 0; int oldstate = 0; unsigned long oldmicros = micros(); for (int i = 1; i&lt;5250 ; i++) { state = (digitalRead(dataPin) == LOW)? 0:1; if (i%10 != 0) { Serial.print("-"); } else { Serial.print("+"); } delayMicroseconds(10); if (state != oldstate) { oldstate = state; i = 1; Serial.print(oldstate); Serial.print(" @"); Serial.print(micros() - oldmicros); oldmicros = micros(); Serial.print("\n"); } } Serial.print(state); Serial.println(micros()-oldmicros); } </code></pre> <p>Does it have a chance to provide a quite accurate monitoring of the TX23 output? (eg is using micros() or delayMicroseconds(10) accurate ?)</p>
<p>I'm going to present a third way of working on this. :)</p> <p>First, since I don't have a TX23 I wrote a TX23-simulator:</p> <pre class="lang-C++ prettyprint-override"><code>const byte TESTPIN = 2; const byte test [6] = { 0b00000011, 0b01111011, 0b01010100, 0b00010100, 0b01001010, 0b10111111 }; void setup () { pinMode (TESTPIN, INPUT); delay (100); } // end of setup void loop () { // wait for host to pull pin low while (digitalRead (TESTPIN) == HIGH) { } // wait for host to release it while (digitalRead (TESTPIN) == LOW) { } digitalWrite (TESTPIN, HIGH); pinMode (TESTPIN, OUTPUT); for (byte i = 0; i &lt; 6; i++) for (byte j = 0; j &lt; 8; j++) { delayMicroseconds (1100); digitalWrite (TESTPIN, test [i] &amp; bit (7 - j)); } pinMode (TESTPIN, INPUT); } // end of loop </code></pre> <p>Based on your <a href="https://www.john.geek.nz/2012/08/la-crosse-tx23u-anemometer-communication-protocol/" rel="nofollow noreferrer">linked page about the TX23</a> it outputs a series of low/high pulses corresponding to the example on that page, like this:</p> <p><a href="https://i.stack.imgur.com/pGCKr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pGCKr.png" alt="TX23 simulator"></a></p> <p>Note that you need a 10 k pull-up resistor for this to work properly.</p> <hr> <p>Now the reading code uses interrupts to detect state changes:</p> <pre class="lang-C++ prettyprint-override"><code>const byte READ_PIN = 2; const byte NUMBER_OF_CHANGES = 48; volatile unsigned long bitTime [NUMBER_OF_CHANGES]; volatile byte state [NUMBER_OF_CHANGES]; volatile byte count; void stateChange () { unsigned long now = micros (); if (count &gt;= NUMBER_OF_CHANGES) return; // array full state [count] = digitalRead (READ_PIN); bitTime [count++] = now; } // end of stateChange void setup () { Serial.begin (115200); Serial.println (); } // end of setup void takeReading () { count = 0; digitalWrite (READ_PIN, LOW); // start reading pinMode (READ_PIN, OUTPUT); delay (20); // pulse width pinMode (READ_PIN, INPUT); // release line EIFR = bit (INTF0); // clear flag for interrupt 0 attachInterrupt (0, stateChange, CHANGE); delay (55); // let readings fill up array detachInterrupt (0); } // end of takeReading void loop () { takeReading (); if (count == 0) return; // nothing! delay (500); for (byte i = 0; i &lt; count; i++) { Serial.print ("count: "); Serial.print ((int) i); Serial.print (" = "); Serial.print (bitTime [i]); Serial.print (", state = "); Serial.print (state [i]); if (i &gt; 0) { Serial.print (", width = "); unsigned long width = bitTime [i] - bitTime [i - 1]; Serial.print (width); Serial.print (" ("); int bits = width / 1000; for (byte k = 0; k &lt; bits; k++) Serial.print (state [i - 1]); Serial.print (")"); } Serial.println (); } Serial.println (); } // end of loop </code></pre> <hr> <p>Results were:</p> <pre class="lang-C++ prettyprint-override"><code>count: 0 = 10952804, state = 1 count: 1 = 10953928, state = 0, width = 1124 (1) count: 2 = 10960616, state = 1, width = 6688 (000000) count: 3 = 10962844, state = 0, width = 2228 (11) count: 4 = 10963960, state = 1, width = 1116 (0) count: 5 = 10968412, state = 0, width = 4452 (1111) count: 6 = 10969524, state = 1, width = 1112 (0) count: 7 = 10971752, state = 0, width = 2228 (11) count: 8 = 10972876, state = 1, width = 1124 (0) count: 9 = 10973988, state = 0, width = 1112 (1) count: 10 = 10975104, state = 1, width = 1116 (0) count: 11 = 10976216, state = 0, width = 1112 (1) count: 12 = 10977328, state = 1, width = 1112 (0) count: 13 = 10978440, state = 0, width = 1112 (1) count: 14 = 10984012, state = 1, width = 5572 (00000) count: 15 = 10985124, state = 0, width = 1112 (1) count: 16 = 10986244, state = 1, width = 1120 (0) count: 17 = 10987356, state = 0, width = 1112 (1) count: 18 = 10990700, state = 1, width = 3344 (000) count: 19 = 10991812, state = 0, width = 1112 (1) count: 20 = 10994040, state = 1, width = 2228 (00) count: 21 = 10995156, state = 0, width = 1116 (1) count: 22 = 10996268, state = 1, width = 1112 (0) count: 23 = 10997380, state = 0, width = 1112 (1) count: 24 = 10998500, state = 1, width = 1120 (0) count: 25 = 10999616, state = 0, width = 1116 (1) count: 26 = 11000728, state = 1, width = 1112 (0) </code></pre> <p>This seems to agree with the test data.</p>
14369
|arduino-uno|serial|
Arduino Uno not able to handle 2-dimensional array
2015-08-20T17:11:54.273
<p>Now the code I'm writing in Arduino (Using Arduino) uses multiple 2-dimensional arrays. Now when I print some thing using the Serial Monitor it prints it correctly but when I declare and initialize the 2-dimentional array it won't print it.</p> <p>Code:</p> <pre class="lang-C++ prettyprint-override"><code>void setup() { Serial.begin(9600); int image_width = 56; int image_height = 96; int image_result[image_width][image_height]; for (int i=0; i&lt;image_height; i++) { for (int j=0; j&lt;image_width; j++) { image_result[j][i] = 5; } } Serial.print("code works"); } </code></pre> <p>Now in this case "code works" does not print but when I remove the array declaration and initialization code works is printed. What is the problem?</p> <p>Do 2 dimensional arrays work differently in Arduino or is it a space issue?</p>
<p>In case the matrix is mostly empty or anyway has values that can be calculated programmatically, <a href="https://en.wikipedia.org/wiki/Sparse_array" rel="nofollow">sparse arrays</a> might come to the rescue. It requires memory allocation and hopping, so the access time to individual elements is not deterministic, but you can calculate the worst-case scenario.</p>
14371
|pins|interrupt|
What's the benefits between different interrupts on Arduino
2015-08-16T09:46:34.717
<p>On an Arduino you can have several different interrupt types, two of them being RISING and FALLING. Looking past that RISING is from LOW to HIGH, and FALLING is the opposite, what are the benefits of using one or the other?</p> <p>To clarify; why would you use a RISING interrupt or a FALLING interrupt?</p>
<p>The interrupt will be generated by an external circuit. In many cases, you have the control over the design of the external circuit, and you can choose whether it will be generating low-to-high edges or high-to-low edges. But in some cases you don't have the control over the design of the external circuit which generates the interrupt. Then you have to adapt your firmware code to the interrupt source.</p>
14401
|serial|arduino-due|
Arduino Serial.write sending more than 64 bytes
2015-08-21T08:33:01.673
<p>I am using an Arduino Due to collect a large amount of data from an encoder (about 1kb). Afterwards I need to send the collected data to a C# application I wrote over the serial port. I serialized my tx data into a byte buffer and simply used this code to transmit:</p> <pre class="lang-C++ prettyprint-override"><code>void sendEncoderData() { byte buffer[1024]; /*** some code that populates buffer ***/ int bytesToSend = 1024; Serial.write(buffer, bytesToSend); } </code></pre> <p>When I run the code, nothing seems to get received by the C# application. In fact, I never see the Tx LED light up. However, if I change <code>bytesToSend</code> to a value smaller than 64 bytes everything works. Is this a limitation of <code>Serial.write()</code> or is it something else? What are ways I can work around this limitation?</p> <p>More information: <code>sendEncoderData()</code> is called by an interrupt service routine. However prior to the call, I made sure to 'detachInterrupt()` on all pins including the pin associated with said ISR.</p>
<p>Here's the problem:</p> <blockquote> <p>sendEncoderData() is called by an interrupt service routine.</p> </blockquote> <p>There is an internal 64 byte serial transmit buffer that is filled by Serial.write(). That buffer is empted by sending the data a byte at a time using an interrupt.</p> <p>If you are in an interrupt (at a higher priority than the serial interrupt) then the interrupt that sends the data can never happen, so the buffer just fills up and stops when it gets to 64 bytes. It will hang until there is room for more bytes in the buffer, and that will never happen because you're not allowing the data to be sent.</p> <p>The answer (as I and others have said many times in the past): <strong>Never use Serial in an interrupt.</strong></p>
14411
|serial|power|baud-rate|
Low Power library messing up serial text
2015-08-21T15:00:25.287
<p>I noticed something unusual using the Low Power library today. When printing text in the loop and using <code>LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF);</code> to sleep for one second, all the text in the loop gets messed up in the Serial Monitor as if you chose the wrong baud rate.</p> <p>Example code:</p> <pre class="lang-c prettyprint-override"><code>#include "LowPower.h" void setup() { Serial.begin(9600); Serial.println(F("HELLO")); Serial.println(F("HELLO")); } void loop() { Serial.println(F("HELLO")); LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); } </code></pre> <p>This code just prints </p> <pre><code>����11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11=C!�11= </code></pre> <p>even when using different baud rates. (I used the same baud rate on both the arduino and the monitor). Replacing the low power command with <code>delay(1000);</code> works fine</p>
<p>The problem is most likely that the system is going to sleep <em>while</em> it's still sending the serial data.</p> <p>Forcing all the serial data to be sent before you go to sleep should fix the problem (serial data is sent in the background using an interrupt so as to keep sketch slowdown to a minimum):</p> <pre><code>Serial.flush(); LowPower.powerDown(SLEEP_1S, ADC_OFF, BOD_OFF); </code></pre>
14415
|motor|
Controlling a sliding tray - beginners project
2015-08-21T18:54:56.197
<p>I have a small light metal platform about 30 cm square mounted on horizontal rails. It is well lubricated and slides easily from side to side. I would like to build a device to connect to the underside of the platform that will allow me to programatically move the platform left or right by a defined distance at the touch of a button.</p> <p>While I've never used an Arduino, I've been aware of its existence for a while and felt this might be a good project to begin experimenting with it. For context, I'm a computer programmer by trade, but have limited exposure to electronics in general.</p> <p>Where would be a good place to start? Are there books that are considered the "bible" of Arduino development? Are there existing projects that basically do what I'm hoping to achieve? Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? Any input would be greatly appreciated.</p>
<blockquote> <p>Am I barking up the wrong tree and shouldn't be attempting to find a solution for this with an Arduino? </p> </blockquote> <p>Not at all. For example see <a href="http://reprap.org/" rel="nofollow">Reprap</a> - a 3D printer using an Atmega1280 as the controller. As it says <a href="http://reprap.org/wiki/Generation_2_Electronics" rel="nofollow">here</a>: </p> <blockquote> <p>Arduino is an open source project that has created an easy and powerful microcontroller board based on the Atmel ATmega168. It is the brain of the RepRap electronics.</p> </blockquote> <p>If you can make a 3D printer with an Arduino, then you can make your sliding platform gadget, which sounds simpler if anything.</p> <hr> <blockquote> <p>Are there existing projects that basically do what I'm hoping to achieve?</p> </blockquote> <p>Reprap, for one.</p> <hr> <blockquote> <p>Are there books that are considered the "bible" of Arduino development?</p> </blockquote> <p>This is a broad question, and your original question already has a couple of "flags" that it is <em>too</em> broad. I suggest you narrow it down a bit.</p> <p>There are a number of books about learning Arduino. My advice is to start doing some simple projects (simpler than the platform initially) to get the hang of compiling, uploading, and generally working with microcontrollers. </p> <hr> <p>Also try Google and YouTube. There are a <strong>lot</strong> of Arduino projects out there.</p>
14429
|serial|
Serial communication with two devices
2015-08-22T01:41:14.610
<p>I have two devices connected to my Arduino using the SoftwareSerial library. However, it seems that they cannot communicate at the same time. I can only communiate with both by switching between which one I am listening to every 1000ms (they poll for 1500ms), but this slows down overall communication significantly. Is there anyway to communiate with both at the same time? Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?</p>
<p>See <a href="https://arduino.stackexchange.com/questions/14179/softwareserial-write-to-return-read-in-serial-monitor/14180#14180">SoftwareSerial Write to return Read in Serial Monitor?</a> - SoftwareSerial cannot both read and write at the same time.</p> <p>However HardwareSerial can.</p> <blockquote> <p>Could this be achieved by using SoftwareSerial with one and the hardware serial port with the other?</p> </blockquote> <p>Yes.</p> <hr> <blockquote> <p>So, likewise, there is no way to read from both devices using only SoftwareSerial?</p> </blockquote> <p>That is correct. Not at the same time. SoftwareSerial uses an interrupt to detect the start bit of incoming data. So far so good. But once it gets it, it leaves interrupts disabled while it goes into a timed loop to read all the bits.</p> <p>Thus, it is impossible for it to react to another incoming byte on another pin at the same time.</p> <p>Still, you could receive on SoftwareSerial on one pin, and HardwareSerial on another. With HardwareSerial the hardware will run in the background, receiving the byte.</p>
14448
|arduino-mega|pins|display|
How to wire up 4-digit 7-segment display?
2015-08-22T19:44:00.340
<p>I have an <strong>Arduino Mega</strong> and the <strong>CL5642BH</strong>, a <strong>4-digit 7-segment display.</strong> I found very helpful code <a href="http://www.hobbytronics.co.uk/arduino-4digit-7segment" rel="nofollow">here</a>, but I don't understand how to wire it up on the breadboard.</p> <p>The display has 12 pins: 6 on the top and 6 on the bottom. First I guess I need to find out which one is GND.</p> <p>Then (see the link) there is this code:</p> <pre><code>int digit1 = 11; //PWM Display pin 1 int digit2 = 10; //PWM Display pin 2 int digit3 = 9; //PWM Display pin 6 int digit4 = 6; //PWM Display pin 8 int segA = A1; //Display pin 14 int segB = 3; //Display pin 16 int segC = 4; //Display pin 13 int segD = 5; //Display pin 3 int segE = A0; //Display pin 5 int segF = 7; //Display pin 11 int segG = 8; //Display pin 15 </code></pre> <p>It's 11 pins, that's the correct amount so far. But <strong>how do I wire it up?</strong> The pins on the display are in no way labeled.</p> <p><em>Note: I'm a software developer, but as far as electronics go, I'm still a beginner.</em></p>
<p><a href="https://i.stack.imgur.com/vJzZu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vJzZu.png" alt="enter image description here"></a></p> <p>Apply the pin 1, 2, 3 with 5v from Audrino passing through the resistors. Apply low voltage to pin-a to light up the led, so on so forth. You can use the multi-meter to confirm the common pins and led pin. For example touch the pin1 with (+) and pin-a with (-) of the multimeter. If the pins are correct, led pin-a will light up.</p> <p>Picture Reference:<a href="http://www.circuitstoday.com/voltmeter-using-arduino" rel="nofollow noreferrer">http://www.circuitstoday.com/voltmeter-using-arduino</a></p>
14454
|remote-control|electronics|
433MHz transmitter and receiver pair doesnt work
2015-08-22T19:16:51.677
<p>I have a pair of 433 MHz transmitter and receiver:</p> <p><a href="https://i.stack.imgur.com/xXjyL.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xXjyL.jpg" alt="Transmitter / receiver"></a></p> <p>Transmitter is connected to Arduino pro mini, receiver to Arduino Uno R3. </p> <p>Output of receiver on serial looks like that (it doesn't change much):</p> <p>Basicly I am getting either 75x or zero regardless of transmitter is on or off.</p> <pre><code>in &gt; upper 756 in &gt; upper 758 0 0 0 in &gt; upper 758 0 in &gt; upper 757 in &gt; upper </code></pre> <p>Transmitter code:</p> <pre class="lang-C++ prettyprint-override"><code>#define rfTransmitPin 4 #define ledPin 6 void setup() { pinMode(rfTransmitPin, OUTPUT); pinMode(ledPin, OUTPUT); } void loop() { for(;;) { digitalWrite(rfTransmitPin, HIGH); //Transmit a HIGH signal analogWrite(ledPin, 255); //Turn the LED on delay(500); //Wait for 1 second digitalWrite(rfTransmitPin,LOW); //Transmit a LOW signal analogWrite(ledPin, 0); //Turn the LED off delay(500); //Variable delay } } </code></pre> <p>Receiver code:</p> <pre class="lang-C++ prettyprint-override"><code>const unsigned int upperThreshold = 70; //upper threshold value const unsigned int lowerThreshold = 0; //lower threshold value const int ledPin = 13; #define ReceiverPin A0 void setup() { Serial.begin(19200); pinMode(ledPin, OUTPUT); DiodeTest(); } void loop() { int data = analogRead(ReceiverPin); delay(50); if(data&gt;upperThreshold) { digitalWrite(ledPin, LOW); //If a LOW signal is received, turn LED OFF Serial.println("in &gt; upper"); } if(data&lt;lowerThreshold) { digitalWrite(ledPin, HIGH); //If a HIGH signal is received, turn LED ON Serial.println("in &lt; lower" ); } Serial.println(data); } </code></pre>
<p>See <a href="http://www.gammon.com.au/forum/?id=11506" rel="nofollow noreferrer">this post about a radio-controlled car</a>.</p> <p>I found when using what looks like a similar receiver to yours, that the received data looked like this:</p> <p><a href="https://i.stack.imgur.com/eJWAd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eJWAd.jpg" alt="Radio receiver"></a></p> <p>The cyan line was the receiver, the yellow line is what is being transmitted.</p> <p>The trouble turned out to be the pull-up resistor on the Arduino Rx pin (from the USB chip).</p> <p>Even with SoftwareSerial it wasn't too great:</p> <p><a href="https://i.stack.imgur.com/7aJQe.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7aJQe.jpg" alt="Radio receiver software serial"></a></p> <p>I found that using an op-amp as a buffer helped a lot:</p> <p><a href="https://i.stack.imgur.com/qBQiR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qBQiR.png" alt="Op-amp buffer"></a></p> <hr> <p>I also agree with the comments about adding an aerial wire, just a short length of hookup wire should do it.</p>
14465
|power|analogread|input|
Arduino nano getting powered through analog input?
2015-08-23T11:27:46.697
<p>I noticed something today. I am powering the Arduino Nano from a battery and a 5v step up converter. That works just fine and I'm getting a stable 5v output. I have a second cable coming out from the battery which plugs right into analog input A0 set as input so I can measure the battery voltage. However when I disconnect the battery from the usb plug and leave the voltage sensing cable connected to the analog input the power led stays on. I want it to shut down and be disconnected from the power source and have the voltage sensing cable still connected. How can I fix this? </p>
<p>This addresses a subset of your question which was covered in your added comment-question. I've addressed use of a 20V full scale input range to make the answer more general. The results would be "even better" for your 5V input case. Note that is Vin ~= 5V you would want a measurenet range somewhat above 5V max so that you can handle typical voltage variations. </p> <blockquote> <p>Do you know any transistors/FETs with a very low voltage drop which I need for switching off a sensor?</p> </blockquote> <p>If you used a say 10k resistor in the upper leg of a voltage divider and added a MOSFET switch with an on resistance (Rdson) of 2 Ohms (a terrible spec) between Vin and the divider then the error introduced would be about 2/10k = 1:5000. If measuring a say 12V battery and using a Vinmax voltage of 20V the error in voltage measurement would be in the order of 20V/5000 = 4 mV. If using an Arduino Nano with a 10 but ADC the resolution (not accuracy) is 1 in 2^10 = 1:1024 or 20V/1024 = about 19 mV for a 20V input range. ie the resistor introduces an error of about 1/5th of a bit of available measuring accuracy. Worse (or better) - if you use 1% resistors they will swamp errors caused by ADC resolution. Even use of say 0.1% resistors or calibration is liable to produce a result where ADC resolution is not the main limiting factor.</p> <p>Even with no resistive divider, getting accuracies that are doinated by the 1:1024 ADC resolution and not other factors takes care and effort. At 5V in ax ADC resolution of 1:1024 means that a variation of 1 part in 2048 could cause an erroneous reading. Input offset voltages, thermal effects, board and connector resistances and ground voltage dropsm and offsets can easily provide greater error magnitufes. </p> <p>Test: Take a working design. Set meter to lowest voltage range such that 1 mV can easily be seen. (Ideally 200 mV range. 2V range marginally OK). Measure ground voltages between various "ground" points at various locations in the system. Differences ofm mV to 10's of mV can often be found. Differences are poptentially higher if power current are present - say 10's of mA or more. </p>
14470
|arduino-uno|accelerometer|gyroscope|frequency|
What does a higher clock signal frequency actually mean for my AHRS?
2015-08-23T23:43:38.603
<p>I've got an Arduino with an ATmega328 processor. It can be operated at 3.3V which nets a clock signal frequency of about 12 MHz respectively 16 Mhz at 5V.</p> <p>I've got an IMU connected to the Arduino and a AHRS algorithm turning accelerometer, gyroscope and magnetometer data into orientation data.</p> <p>What does the higher frequency of 16 MHz actually mean in this context?</p> <p>Will the AHRS be calculated faster so I get a lower latency? Can I poll the sensors more often? I want a deeper understanding of what I'm doing here.</p>
<blockquote> <p>What does the higher frequency of 16 MHz actually mean in this context?</p> </blockquote> <p>The Arduino will run a bit faster (33% faster). Therefore it could calculate things faster. Whether you can poll the sensors more often might depend on the sensor. Limiting factors could be how fast you can communicate with the sensor, how often the sensor takes readings, what you are going to do with the readings, and whether it matters if calculations are a bit slower.</p> <p>For a better response I suggest you post a link to the particular sensor, the AHRS algorithm you are using, and describe the application you are using it for.</p>
14474
|programming|digital|gyroscope|
What does “LSB per degree per second” mean?
2015-08-24T01:22:43.523
<p>I'm currently working with a digital output gyroscope. Its sensitivity is given as 120 least-significant bit per degree per second.</p> <p>While every single component of that unit is easy to understand I don't quite get what it means altogether.</p> <p><strong>Can you explain it to me?</strong></p>
<p>With further elaboration on Ignacia's answer:</p> <p>A gyroscope itself is generally an analog device in the sense that in reality, it will have a continous output. This output is digitized using some form of Analog to Digital A/D converter where the analog output is converted to a digital number. The output from the gyroscope is a measurement of angular speed, generally millidegrees/sec. </p> <p>The number read by your Arduino from the gyroscope will be a digital version of your current angular speed at the time of measurement. For example, if you're getting an 8bit number back equal to 121, this in binary is equivalent to 01111001, where the '1' furthest to the right is the least significant bit.</p> <p>The term "lsb per degree per second" means how many bits change with your angular speed. For example, with a gain of 1 (meaning 1 degree/second = 1 bit), an angular speed of 90 degrees/sec will produce a read value of 90 or 01011010. Therefore, 1 bit changes per degree/second. Increasing the essential "gain" (which will most likely be referred to as "dps" will change how many lsb's change per degree/second.</p>
14480
|c++|library|class|pointer|
Pass a member function pointer to a method of a foreign class (EDB Lib)
2015-08-24T08:33:31.823
<p>I'm currently working on my own arduino library and I'm becoming exasperated with the following problem: I want to store data with the extended database library (<a href="https://code.google.com/p/arduino-edb/" rel="nofollow">https://code.google.com/p/arduino-edb/</a>) on a sd card. I tried to follow and adapt the instructions on <a href="http://blog.brauingenieur.de/2014/01/20/extended-database-library-using-an-sd-card/" rel="nofollow">this</a> page and I gave my custom library a property "File dbFile" as well as a property "EDB db". Additionally I have to pass two function pointers to the constructor of the EDB library. So my custom library got two more properties: a writer and a reader function. My class looks roughly like that:</p> <pre><code>class myLib { public: myLib(); ~myLib(); void configWriter( unsigned long address, byte data ); byte configReader( unsigned long address ); File dbFile; EDB configDB; } </code></pre> <p>...so far so good. But here comes the pain in the ... When I'm trying to instantiate a new EDB object in the constructor of my class by passing two pointers to the member functions I'm constantly getting an error. Here is how I call the constructor of the EDB library:</p> <pre><code>configDB = new EDB( &amp;myLib::configWriter, &amp;myLib::configReader ); </code></pre> <p>I get the following error:</p> <blockquote> <p>no matching function for call to 'EDB::EDB()'</p> <p>[...] note: candidates are:</p> <p>note: EDB::EDB(void (<em>)(long unsigned int, uint8_t), uint8_t (</em>)(long unsigned int)) EDB(EDB_Write_Handler *, EDB_Read_Handler *);</p> </blockquote> <p>The prototype of the EDB constructor looks like this:</p> <blockquote> <p>EDB(EDB_Write_Handler *, EDB_Read_Handler *);</p> </blockquote> <p>EDB_Write_Handler and EDB_Read_Handler are defined like so:</p> <blockquote> <p>typedef void EDB_Write_Handler(unsigned long, const uint8_t); typedef uint8_t EDB_Read_Handler(unsigned long);</p> </blockquote> <p>So I assume that my constructor call doesn't work because the functions that I'm passing are from a foreign class: (myLib::<em>) and not just (</em>)</p> <p>I have no idea how to solve that problem. Does someone of you have any idea?</p> <p>Thanks, Andy</p> <p>EDIT: Here is a Minimal, Complete, and Verifiable example:</p> <p>myLib.h:</p> <pre><code>#ifndef myLib_h #define myLib_h #include "Arduino.h" #include &lt;SPI.h&gt; #include &lt;SD.h&gt; #include &lt;EDB.h&gt; #define SD_CS 4 #define SD_SS 10 class myLib { public: myLib(); ~myLib(); void begin(); void configWriter( unsigned long address, byte data ); byte configReader( unsigned long address ); File dbFile; EDB * configDB; }; #endif </code></pre> <p>myLib.cpp:</p> <pre><code>#include "myLib.h" myLib::myLib( void ) {} myLib::~myLib() {} void myLib::begin() { // Init SD pinMode(SS, OUTPUT); SD.begin(SD_CS); // Load Config configDB = new EDB( &amp;myLib::configWriter, &amp;myLib::configReader ); dbFile = SD.open("config.db", FILE_WRITE); } void myLib::configWriter( unsigned long address, byte data ) { dbFile.seek(address); dbFile.write(data); dbFile.flush(); } byte myLib::configReader( unsigned long address ) { dbFile.seek(address); return dbFile.read(); } </code></pre> <p>Arduino sketch:</p> <pre><code>#include &lt;SPI.h&gt; #include &lt;SD.h&gt; #include &lt;EDB.h&gt; #include "myLib.h" myLib* a; void setup() { a = new myLib(); a-&gt;begin(); } void loop() { } </code></pre>
<p>The problem here is a common one with C++. It basically boils down to how C++ handles member functions.</p> <p>You define a member function as, say,</p> <pre><code>class myLib { void myFunc(int val); }; </code></pre> <p>When you call the function it's actually not defined as that - it's instead had its definition change to:</p> <pre><code>void myFunc(myLib *this, int val); </code></pre> <p>The addition of the <code>myLib *this</code> is an <em>implicit</em> parameter, and it's how C++ keeps track of its object instances when calling different functions.</p> <p>So a function which expects a parameter of <code>void (*func)(int)</code> won't accept your method because it's actually <code>void (*func)(myLib *, int)</code>. Hence the error you are seeing.</p> <p>There is no easy, clean, way around it that I have found as yet, I am afraid. The closest you can do is to move the reader and writer functions outside of your class and store a global pointer to the actual class, something like:</p> <pre><code>static myLib *globalLib; void globalConfigWriter( unsigned long address, byte data ) { globalLib-&gt;congigWriter(address, data); } byte globalConfigReader( unsigned long address ) { return globalLib-&gt;configReader(address); } </code></pre> <p>Then in the constructor for your lib you can do:</p> <pre><code>myLib::myLib() { globalLib = this; } </code></pre> <p>You then register the global reader and writer functions with the EDB constructor instead of the class member functions.</p> <p>It does have the rather major down-side that there can only be one instance of your class since there is only one global pointer and only one pair of reader / writer functions. There are ways of supporting a finite number of instances, but it basically involves having a reader/writer pair for each instance and allocating one to an instance when it's constructed and de-allocating it when its destructed. Keeping track of them and knowing which object is associated with which function pair is tricky at best...</p>
14485
|c++|servo|compile|
Arduino Servo.h library returns error in compilation
2015-08-24T11:12:22.980
<p>I have a problem with Servo library. This is my (very short XD) "code":</p> <pre><code>#include &lt;Servo.h&gt; void setup() { Servo.attach(9, 554, 2400); } void loop() { Servo.write(2000); } </code></pre> <p>And it returns:</p> <pre><code>Arduino:1.6.5 (Windows 7), Board:"Arduino Mega or Mega 2560, ATmega2560 (Mega 2560)" sketch_aug24a.ino: In function 'void setup()': sketch_aug24a:4: error: expected unqualified-id before '.' token sketch_aug24a.ino: In function 'void loop()': sketch_aug24a:8: error: expected unqualified-id before '.' token expected unqualified-id before '.' token </code></pre> <p>Like there is no included library. What can I do with it ?</p>
<p><code>Servo</code> is a class not an object. You have to instantiate it, and then call the functions on the instance. For example:</p> <pre><code>#include &lt;Servo.h&gt; Servo sv; void setup() { sv.attach(9, 554, 2400); } void loop() { sv.write(2000); } </code></pre> <p>(Unlike some other libraries, it's done this way so that you can use more than one servo at the same time. You'd make one instance for each servo you want to control.)</p>
14489
|arduino-uno|sensors|
Two sensors on one input
2015-08-24T14:31:30.077
<p>I got this question from my teacher the other day and I can't figure it out:</p> <blockquote> <p>If you have two sensors from two different outputs but want them to go into one input, what do you need, and how can you read the input?</p> </blockquote> <p><a href="https://i.stack.imgur.com/Xb7N2.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/Xb7N2.jpg" alt="enter image description here"></a></p> <p>In short, the project includes an Arduino Uno with two ultrasonic sensors.</p>
<p>The OP does not specify whether the focus is on hardware or software.</p> <p>So I will presume that what the professor might looking for is a solution using minimal circuitry; as close to the diagram as possible. Thus, the solution would be implemented in software.</p> <p>Given all that, I'd propose that the trigger signal be sent out on sensor 1, and the reflection measured at the receiving pin. </p> <p>It is time-gated (the time for the sensor to react to an object at maximum range). If detected, then set a variable saving the distance measured on sensor 1.</p> <p>Then the same could be sent from the second sensor's trigger pin. And if there is a reflection within the time-gate then that can be recorded in another variable. </p> <p>It would require creating two instances of the ultrasonic sensor, and they would just happen to share the same receive pulse pin. </p>
14493
|arduino-uno|library|compile|avr-gcc|
undefined reference to `PPMintIn::PPMintIn(int)'
2015-08-24T18:40:40.737
<p>I am making a new library that will utilize PinChangeInt's library. My intention is to further simplify repetitive code by creating a library. (This is to allow for multiple PPM channels without rewriting a bunch of code for each channel i decide to add.) Since i understand OOP i knew that i could go the route of make my own library.</p> <p>The problem i'm having right now, is that the library is returning an undefined reference. The IDE i'm using is UECIDE with QTcreator on the side to help me with my syntax. The compiler is avr-gcc. The chip is an Arduino Uno. The problem i'm recieving is </p> <blockquote> <p>C:...\RCRoomba_TestPulseV2.cpp.o: In function '__static_initialization_and_destruction_0': <br>C:...\RCRoomba_TestPulseV2.ino:5: undefined reference to 'PPMintIn::PPMintIn(int)' <br>C:...\RCRoomba_TestPulseV2.cpp.o: In function 'setup': <br>C:...\RCRoomba_TestPulseV2.ino:9: undefined reference to 'PPMintIn::begin()' <br>Failed linking sketch</p> </blockquote> <p>I tried to define the variables in my h and cpp files but it doesn't seem to be fixing the problem.</p> <p>Here is the .ino code. <br>for some reason UECIDE can't see the Pinchange and PPMint libraries</p> <pre><code>#include "arduino.h" #include "C:\Users\User\Documents\UECIDE\libraries\PinChangeInt\PinChangeInt.h" #include "C:\Users\User\Documents\UECIDE\libraries\PPMintIn\PPMintIn.h" PPMintIn CH1(A0); void setup(){ Serial.begin(115200); CH1.begin(); } void loop(){ } </code></pre> <p>Here is the .cpp code</p> <pre><code>#include "arduino.h" #include "ppmintin.h" #include "PinChangeInt.h" //defined these volatile int pwm_value = 0; volatile int prev_time = 0; uint8_t latest_interrupted_pin = 0; PPMintIn::PPMintIn(int pin){ pinMode(pin, INPUT);\ digitalWrite(pin, HIGH); _pin = pin; } void PPMintIn::rising(){ PPMintIn::latest_interrupted_pin = PCintPort::arduinoPin; PCintPort::attachInterrupt(latest_interrupted_pin, &amp;rising, RISING); PPMintIn::pwm_value = micros()-PPMintIn::prev_time; } void PPMintIn::falling(){ PPMintIn::latest_interrupted_pin=PCintPort::arduinoPin; PCintPort::attachInterrupt(latest_interrupted_pin, &amp;rising, RISING); PPMintIn::pwm_value = micros()-PPMintIn::prev_time; } void PPMintIn::begin(){ PCintPort::attachInterrupt(_pin, &amp;rising, RISING); } void PPMintIn::getSignal(){ return(PPMintIn::pwm_value); } </code></pre> <p>Here is the .h code</p> <pre><code>#ifndef PPMINTIN_H #define PPMINTIN_H #if defined(ARDUINO) &amp;&amp; ARDUINO &gt;= 100 #include "Arduino.h" #else #include "WProgram.h" #endif #include "PinChangeInt.h" class PPMintIn{ public: PPMintIn(int pin); void begin(); void getSignal(); int _pin; volatile int pwm_value; volatile int prev_time; uint8_t latest_interrupted_pin; private: void rising(); void falling(); }; #endif // PPMINTIN_H </code></pre> <p>here is the full thing in github in case I didn't supply it here. <a href="https://github.com/tisaconundrum2/PPMintIn" rel="nofollow">https://github.com/tisaconundrum2/PPMintIn</a></p>
<p>As both Majenko and I tried to explain in <a href="https://arduino.stackexchange.com/questions/14480/pass-a-member-function-pointer-to-a-method-of-a-foreign-class-edb-lib">Pass a member function pointer to a method of a foreign class (EDB Lib)</a> you can't pass a class member function where a static function is expected.</p> <hr> <p>Your error is on:</p> <pre class="lang-C++ prettyprint-override"><code>PCintPort::attachInterrupt(latest_interrupted_pin, &amp;rising, RISING); </code></pre> <p>Error:</p> <pre class="lang-none prettyprint-override"><code>/home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp: In member function ‘void PPMintIn::rising()’: /home/nick/sketchbook/libraries/PPMintIn/ppmintin.cpp:22: error: ISO C++ forbids taking the address of an unqualified or parenthesized non-static member function to form a pointer to member function. Say ‘&amp;PPMintIn::rising’ </code></pre> <hr> <p>PCintPort::attachInterrupt expects a <code>PCIntvoidFuncPtr</code> variable:</p> <pre class="lang-C++ prettyprint-override"><code>int8_t PCintPort::attachInterrupt(uint8_t arduinoPin, PCIntvoidFuncPtr userFunc, int mode) </code></pre> <p>That is:</p> <pre class="lang-C++ prettyprint-override"><code>typedef void (*PCIntvoidFuncPtr)(void); </code></pre> <p>That is a static function (not a class function).</p> <p>However you have it as a class function:</p> <pre class="lang-C++ prettyprint-override"><code>class PPMintIn{ public: PPMintIn(int pin); void begin(); void getSignal(); int _pin; volatile int pwm_value; volatile int prev_time; uint8_t latest_interrupted_pin; private: void rising(); void falling(); }; </code></pre> <p>Now you can make <code>rising</code> and <code>falling</code> static but now they can't access any of the class variables (eg. pwm_value, prev_time, latest_interrupted_pin).</p> <p>The whole thing needs a redesign. You could try making PPMintIn a namespace rather than a class.</p> <hr> <p>Regarding one of the comments:</p> <p><a href="https://i.stack.imgur.com/Sm1q3.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Sm1q3.png" alt="Error message"></a></p> <p>Unless your class implements <code>operator()</code> this line doesn't make sense:</p> <pre class="lang-C++ prettyprint-override"><code>chan1(15); </code></pre> <hr> <p><em>Please copy and paste error messages into the post, don't make people go to Imgur to find a screenshot of some text.</em></p>
14499
|frequency|
Buzzer - Does the voltage change with the frequency?
2015-08-24T21:52:43.960
<p>So I have this project where the component "buzzer" is implementet. I was wondering if the voltage is changing along the change of frequency given to the buzzer?</p> <p>Note that the project just says "buzzer" - not any more details.</p> <p>Project: <a href="http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS" rel="nofollow">http://www.instructables.com/id/Arduino-Distance-Detector-with-a-Buzzer-and-LEDs/?ALLSTEPS</a></p>
<p>No, the frequency of the "buzzer" has no relationship to the voltage.</p> <p>The <em>duty cycle</em> of the generated tone is proportional to the <em>average voltage</em> though. Typically the duty cycle is 50% - that is it's turned on for half the time, and turned off the other half the time, to make a square wave. This means that the <em>average</em> voltage is 50% of the supply voltage.</p> <p>If you were to low-pass filter the signal (say through an RC filter as many people do to create a crude DAC) you would end up with a voltage around 2.5V.</p> <p>Changing the frequency doesn't change the duty cycle, it only changes the audio pitch.</p> <p>The only caveat to that is that if the buzzer draws more current that the IO pin (or the power supply) can source then it may cause the voltage on that IO pin to <em>droop</em>. That has nothing to do with the frequency though and it would droop just the same at all frequencies. Basically the IO pin has a small resistance to Vcc through the MOSFET that drives it internally - the higher the current the more voltage is dropped across that resistance, and the lower your resultant output voltage. Draw too much current and the heat dissipated by that MOSFET's resistance becomes too great and damages the chip.</p>
14506
|arduino-uno|sensors|
UltraSonic sensor in rain?
2015-08-25T06:53:29.267
<p>I am onto a simple project with Arduino, SR04 and a buzzer for "Car reverse parking assistance". The aim here is to make a buzz when the car gets too close to the objects.</p> <p>I was thinking what if it's raining when a person is driving (assuming I somehow achieved to water proof the sensor) - will the buzzer make continuous sounds?</p> <p>Is there any alternative solution for ultrasonic sensors?</p>
<p>Just a thought, a lot of cars use them, why not try your local salvage yard you may be able to get them on the cheap.</p>
14507
|arduino-due|port-mapping|
Enabling pins of Arduino Due with direct port manipulation
2015-08-25T07:13:21.210
<p>I want to enable pin 13 on my SAM3X8E using direct port manipulation. On this chip the pin is bit 27 in port B, so I used <code>PIOB-&gt;PIO_PER = 1&lt;&lt;27;</code> to enable this pin, but it doesn't work. This pin keeps at 3.08V, the default value of non-initialized pins.</p> <p>Here's my complete code:</p> <pre><code>#include &lt;asf.h&gt; int main (void) { // Insert system clock initialization code here (sysclk_init()). board_init(); sysclk_init(); delay_init(sysclk_get_cpu_hz()); PIOB-&gt;PIO_PER = 1&lt;&lt;27; PIOB-&gt;PIO_OER = 1&lt;&lt;27; while(1) { REG_PIOB_ODSR = 1&lt;&lt;27; delay_ms(1000); REG_PIOB_ODSR = 0&lt;&lt;27; delay_ms(1000); } } </code></pre> <p>Can anyone tell me how I can get this to work?</p>
<pre><code> #define Led_ON REG_PIOB_ODSR |= 0x8000000 #define Led_OFF REG_PIOB_ODSR &amp;= ~0x8000000 //for Arduino Due PIOB-&gt;PIO_PER |= 0x8000000;//led PIOB-&gt;PIO_OER |= 0x8000000;//led </code></pre> <p>And then call Led_ON and Led_OFF</p>
14509
|programming|c++|
Problem with codebender project not compiling
2015-08-25T09:07:15.210
<p>I have written a codebender project which returns this error:</p> <pre><code>Oops! Looks like there was a serious issue with your project. If you are not sure what could be wrong please contact us /mnt/tmp/compiler.amxHJ9/files/Many Games.o: In function `gamesMaster::gamesMaster()': Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xa): undefined reference to `vtable for gamesMaster' Many Games.cpp:(.text._ZN11gamesMasterC2Ev+0xc): undefined reference to `vtable for gamesMaster' </code></pre> <p>What does it mean by <code>vtable</code>?</p> <p>The code uses basic classes and inheritance.</p> <p>The program is designed to select and play the game of your choice. I have only programmed the basic structure.</p> <p>Class <code>games</code> contains a ref to the class <code>gamesMaster</code>.</p> <p>Class <code>gamesMaster</code> contains a ref to <code>simpleTimer</code>.</p> <p>Classes <code>playHiLow</code> and <code>playSimon</code> are children of <code>gamesMaster</code>.</p> <p>Class <code>games</code> handles and input and outputs, <code>win</code> and <code>lose</code> control and keeps track of lives.</p> <p>Class <code>gamesMaster</code> handles the <code>simpleTimer</code>, displays a new round, checks for the correct answer, and checks if game has finished successfully.</p> <p>The <code>main()</code> function runs a routine in the <code>games</code> class.</p> <p>The code is listed here: <a href="https://codebender.cc/sketch:144869" rel="nofollow">https://codebender.cc/sketch:144869</a></p> <pre><code>class simpleTimer { private: unsigned long _previousMillis; unsigned long _interval; public: simpleTimer() { } void start(float mins) { _interval = (unsigned long) (mins * 60 * 1000); _previousMillis = millis(); } bool stillRunning() { return (millis() - _previousMillis &lt; _interval); } }; class gamesMaster { public: unsigned short lives; gamesMaster() { timeOutTimer = new simpleTimer(); gameTimer = new simpleTimer(); gameTimer-&gt;start(1.5); lives = 5; } void right() { Serial.println("Correct"); } void wrong() { Serial.println("Wrong"); } void winGame() { Serial.println("**********"); Serial.println("* WINNER *"); Serial.println("**********"); } void loseGame() { Serial.println("\\ / \\ /"); Serial.println(" X LOST X"); Serial.println("/ \\ / \\"); } void startTimeOut(float mins) { timeOutTimer-&gt;start(mins); } bool notTimedOut() { return timeOutTimer-&gt;stillRunning(); } bool gameTimerOver() { return !gameTimer-&gt;stillRunning(); } simpleTimer *timeOutTimer; simpleTimer *gameTimer; virtual void setupForNewRound(void); virtual bool checkAnswer(unsigned short); virtual bool reachedEnd(void); }; class gameHiLow: public gamesMaster { public: gameHiLow() : gamesMaster() {} void setupForNewRound() { Serial.println(" -&gt;(HiLow) New round"); } bool checkAnswer(unsigned short answer) { Serial.println(" -&gt;(HiLow) Correct Answer"); return HIGH; } bool reachedEnd() { Serial.println(" -&gt;(HiLow) End of game"); return HIGH; } }; class gameSimon: public gamesMaster { public: gameSimon() : gamesMaster() {} void setupForNewRound() { Serial.println(" -&gt;(Simon) New round"); } bool checkAnswer(unsigned short answer) { Serial.println(" -&gt;(Simon) Correct Answer"); return HIGH; } bool reachedEnd() { Serial.println(" -&gt;(Simon) End of game"); return HIGH; } }; class games { private: unsigned short _gameToPlay; unsigned short _levelToPlay; gamesMaster *myGame; unsigned short _getAnswer() { if (Serial.available() &gt; 0) { int inByte = Serial.read(); Serial.println(" -&gt;(games) Decode Answer"); switch (inByte) { case '&lt;': return 1; break; case '&gt;': return 2; break; } } return 0; } bool _respond() { unsigned short answer; while(myGame-&gt;notTimedOut()) { if((answer = _getAnswer()) != 0) { if(myGame-&gt;checkAnswer(answer) == HIGH) return HIGH; } } return LOW; } public: games(unsigned short gameToPlay, unsigned short levelToPlay) { _gameToPlay = gameToPlay; _levelToPlay = levelToPlay; switch(_gameToPlay) { case 1: myGame = new gameHiLow(); Serial.println(" -&gt;(game) play Higher or Lower Game"); break; case 2: myGame = new gameSimon(); Serial.println(" -&gt;(game) play Simon Game"); break; } } void play() { unsigned short answer; while(!myGame-&gt;gameTimerOver()) { myGame-&gt;setupForNewRound(); myGame-&gt;startTimeOut(.5); if(_respond() == HIGH) { myGame-&gt;right(); if(myGame-&gt;reachedEnd()) { myGame-&gt;winGame(); return; } } else { myGame-&gt;wrong(); if(--myGame-&gt;lives &lt;= 0) { myGame-&gt;loseGame(); return; } } } myGame-&gt;loseGame(); } }; ////////////////////////////////////////////////////////////////////////////////// games *game; void setup() { Serial.begin(9600); unsigned short gameToPlay = 1; unsigned short levelToPlay = 1; game = new games(gameToPlay, levelToPlay); } void loop() { Serial.println("Let the games begin"); game-&gt;play(); Serial.println("Program Complete"); delay(5000); exit(0); } </code></pre>
<p>I agree with @GeryOshlike. But that's not the only option.</p> <p>Yes, you can make them <em>pure virtual</em>:</p> <pre><code>virtual void setupForNewRound(void) = 0; virtual bool checkAnswer(unsigned short) = 0; virtual bool reachedEnd(void) = 0; </code></pre> <p>Or you can make them virtual with a default function:</p> <pre><code>virtual void setupForNewRound(void) { } virtual bool checkAnswer(unsigned short) { return false; } virtual bool reachedEnd(void) { return false; } </code></pre> <p>Pure virtual will complain when you compile if you haven't implemented those functions in your child class. By providing a default function body it will not complain if you haven't implemented it, and will just use the default body.</p> <p>If it's a function which you know will always have to be implemented at the child level (will always be different) then go the pure virtual route. If it's a function that will be the same in a number of children but differ in only a few, then providing the default body and overriding with different ones when needed is the better way to go.</p>
14515
|atmega328|
Atmega328 board output voltage
2015-08-25T13:50:35.720
<p>I'm thinking about making my own "arduino" low power board but I have a question about the atmega328. Is the output voltage on the pins always 5v or it depends on the input voltage I gave to the atmega?</p> <p>Thanks in advance.</p>
<p>It depends on the input voltage you give it. If you run the ATMega328p at 3.3V then you get 3.3V out. If you run it at 5V you get 5V out.</p> <p>A word of caution about running at lower voltages: The chip can't run as fast when it has a lower supply voltage - that's why you will see the 3.3V Arduino boards running at 8MHz (or 12MHz at a pinch).</p>
14526
|arduino-mega|power|bootloader|avrdude|
Reversed Input Voltage Arduino Mega timeout communication with programmer error
2015-08-25T19:58:06.570
<p>On the barrel connector I accidentally reversed the input voltage to an Arduino Mega. The center post received ground while the outer connection received +12DVC, basically I have the Arduino -12VDC. I have since fixed this problem. When I power the Arduino with the USB I am able to program the Arduino without a problem. When I power the Arduino with the +12VDC the program still runs (confirmed by programming the blink sketch). If I have the +12VDC connected and try to program the Arduino then I get the timeout communication error.</p> <p>Do I just need to re-burn the bootloader? The Arduino's symptoms match those listed here when both cables are connected: <a href="https://arduino.stackexchange.com/questions/864/arduino-mega-timeout-communication-with-programmer-error">Arduino Mega timeout communication with programmer error</a></p> <p>Is there anything else I should verify? Or is the Arduino always going to be damaged?</p> <p>Also as a note I did the same thing to an Arduino Uno (same rail going to both) and the Uno has no problems when both USB and power are connected.</p>
<p>The Mega has a reverse polarity protection diode (<a href="https://www.arduino.cc/en/uploads/Main/arduino-mega-schematic.pdf" rel="nofollow">D1</a>) on the board, so you plugging in the wrong polarity barrel didn't damage anything.</p> <p>So your current problem in unrelated to this.</p>
14527
|power|
Removing the barrel jack connector?
2015-08-25T20:23:20.060
<p>My project is battery powered and it has it's own usb port for charging. Can I snip off the HUGE DC barrel jack which is making it hard for me to fit this into an enclosure.</p> <p>Or could that cause problems? </p>
<p>Unless you have some really specific reason to use a UNO, for example using the 2nd ATMega on the board, you would be much better off with an Micro Pro.</p> <p>On ebay you can find both 3.3V and 5V versions. You can even find ones that have redundant pins, to accommodate for a permanent installation of the ISP programmer.</p> <p>Even if you happen to have a shield that is compatible with the UNO pinout, you could still wire it with a flat cable and save space.</p> <p>Said this, using mechanical means on a PCB is always putting at risk the tracks, which might come off.</p> <p>Desoldering is better, since it's reversible.</p> <p>But you might find that it takes an unusually powerful soldering iron, compared to what is used nowadays for smd components, as you will have to heat up simultaneously several large pads, which have connected large tracks and ground areas that act as heat sink.</p> <p>In case you do not have desoldering braid and or pump, there's a hackish method to remove large components with multiple pads: flood them in molten solder and literally shake them off the board by hitting the workbench sideways, while the solder is still fluid.</p> <p>Not nice and at risk of adding splash shorts to the board, not to mention the splash damage to the operator: it can cause burns on unprotected skin or organs.</p> <p>However, if done correctly, it works without pump or braid.</p>
14543
|arduino-uno|
What is the overhead time of using Serial library compared to coding it up in AVR C (not using Arduino code)?
2015-08-26T06:44:00.013
<p>I am using an Arduino UNO to drive a UART throughput test and to also test the latency of the slave microcontroller. </p> <p>The setup is as follows:</p> <p>Arduino|---UART--------------------------|MCU2</p> <p>Arduino|---FLOW_CONTROL_PIN---|MCU2</p> <p>I am sending data to the MCU2 over the UART with a specified delay between writes, and in MCU2 I have a certain buffer threshold where I set an overflow pin indicator back to the Arduino (using INT0), where when the interrupt is triggered, I stop sending data (hardware based flow control).</p> <p>At this point I log the amount of bytes sent and compare that to the buffer threshold level. If the bytes sent are equal to the threshold point, I know the latency of the path (threshold-->toggle flow pin-->Arduino interrupt and stop transmit) is ok (if not, we are having latency issues and probably need to do a software based flow control). I then do the whole process again, with a shorter delay. I then can find the delay point that will result in the fastest continuous transfer rate (this is testing throughput as well as latency of the slave MCU).</p> <p>A problem can arise if the Arduino api is providing more latency than the path under test. I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial api. I used Arduino to get something running quickly, but if it doesn't allow me to actually test the system, need to go to using all AVR C or use another MCU for the transmit side.</p>
<p>There's no reason to doubt the Arduino hardware. We need to put some figures on what you are experiencing, such as the baud rate and buffer sizes.</p> <p>I would expect with this sort of hardware flow-control that you would potentially send a byte or so more than expected, because it takes a finite time to react to the flow-control signal. This is to be expected, particularly as the hardware has a buffer, so it can be starting to send a byte at the moment you get the signal to stop sending.</p> <p>I expect you would have a leeway (say of 10 bytes) where you expect the sender to stop sending within that time.</p> <blockquote> <p>A problem can arise if the Arduino API is providing more latency than the path under test</p> </blockquote> <p>I'm not sure what you mean by this. However the HardwareSerial class has a 64-byte buffer (if you are using a Uno) which means you potentially have put 64 bytes into it, before noticing that the sender wants you to stop sending.</p> <p>This is probably what you are experiencing. See HardwareSerial.cpp:</p> <pre class="lang-C++ prettyprint-override"><code>// Define constants and variables for buffering incoming serial data. We're // using a ring buffer (I think), in which head is the index of the location // to which to write the next incoming character and tail is the index of the // location from which to read. #if (RAMEND &lt; 1000) #define SERIAL_BUFFER_SIZE 16 #else #define SERIAL_BUFFER_SIZE 64 #endif </code></pre> <p>For this test you might want to edit that file and reduce that number, substantially.</p> <p>Alternatively, use SoftwareSerial. I don't think that buffers writes (as it doesn't have hardware to do them in the background) so that would reduce the latency to a single byte.</p> <blockquote> <p>I believe this is most likely the case, but wanted to see if there has been any concrete numbers on the overhead of Arduino, particularly in regard to its Serial API.</p> </blockquote> <p>It's not an overhead, it's a design issue. If you do what I suggested it should work fine.</p> <hr> <blockquote> <p>What I mean by Arduino API overhead is the fact that the actual hardware interface is substantially abstracted away from the register level implementation ...</p> </blockquote> <p>Well, not really. When you write a byte it puts it into a circular buffer, as you would expect. When the hardware is free to output another byte (generally called by an interrupt) it outputs it. What else could it do?</p> <p>However you are absolutely free to address the hardware registers yourself and not use HardwareSerial.</p> <p>To keep things simple though, what you really need to do here is <strong>not buffer</strong> because that makes reacting to the flow-control flag somewhat slow. And here is how to do it:</p> <pre class="lang-C++ prettyprint-override"><code>Serial.write ('a'); // or whatever Serial.flush (); // wait until everything is sent </code></pre> <p>Now you have thrown away the buffering, and you can just send at the rate that the hardware can (probably slightly less).</p>
14548
|arduino-uno|sensors|current|
Which device to use to measure AC current using Arduino?
2015-08-26T08:32:27.097
<p>I'm building a home automation product and want to measure AC current using Arduino (as of now). I've used ACS712 5A Hall Effect Current module but there's a lot of electrical noise and also the accuracy is not good. There's a lot of deflection in value when no current passes through it. I want to pack the whole kit in a box. So how to make sure that there will be no magnetic interference?</p> <p>Can you suggest some other module to use for the same? Also that can last long enough.</p>
<p>Some sort of Current Transformer usually does the trick. You run the AC line (not the neutral) through a ferrite core and it converts current into an output voltage. You can find them packaged like <a href="http://www.dx.com/p/yqj010504-single-phase-ac-current-sensor-module-w-active-output-deep-blue-5a-294209#.Vd20A_lVhBc" rel="nofollow">this one</a> with a <a href="https://www.google.com/search?q=ac%20current%20sensor" rel="nofollow">web search</a>.</p>
14560
|arduino-uno|midi|
Unable to add multiple potentiometer in Midi controller
2015-08-26T15:29:28.070
<p>I am building a simple arduino based midi controller to send cc midi messages. However I am able to send messages only through A0 (analog input).. Any help on this will be appreciated,..</p> <pre><code> #include &lt;MIDI.h&gt; int pot[] = {A0,A1,A2}; int AnaPinsNum = 3; int potIn[] = {0,0,0}; int analogValue = 0; int lastAnalogValue[] = {0,0,0}; void setup() { MIDI.begin(4); // 115200 hairless MIDI Serial.begin(115200); int i; for (i = 0; i &lt; 3; i++); } void loop() { int i; for (i = 0; i &lt; AnaPinsNum; i++) potIn[i] = analogRead(pot[i])/8; // potentiometer could be too sensitive and // give different (+-1) values. // send CC only when the difference between last value // is more than 1 if ((potIn[i]-lastAnalogValue[i]) &gt; 1 || (potIn[i]-lastAnalogValue[i]) &lt; -1) { // value changed? if (potIn[i] != lastAnalogValue[i]) { // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1) // more info: http://arduinomidilib.sourceforge.net/a00001.html MIDI.sendControlChange(1, potIn[i], 1); lastAnalogValue[i] = potIn[i]; } } } </code></pre>
<p>Your logic is flawed here:</p> <pre class="lang-C++ prettyprint-override"><code> int i; for (i = 0; i &lt; AnaPinsNum; i++) potIn[i] = analogRead(pot[i]) / 8; // potentiometer could be too sensitive and // give different (+-1) values. // send CC only when the difference between last value // is more than 1 if ((potIn[i] - lastAnalogValue[i]) &gt; 1 || (potIn[i] - lastAnalogValue[i]) &lt; -1) { // value changed? if (potIn[i] != lastAnalogValue[i]) { // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1) // more info: http://arduinomidilib.sourceforge.net/a00001.html MIDI.sendControlChange(1, potIn[i], 1); lastAnalogValue[i] = potIn[i]; } } </code></pre> <p>The first three lines read all three analog pins:</p> <pre class="lang-C++ prettyprint-override"><code> int i; for (i = 0; i &lt; AnaPinsNum; i++) potIn[i] = analogRead(pot[i]) / 8; </code></pre> <p>However then, outside the loop, you are using the value of <code>i</code> which will now be 4, and outside the array bounds. You need to bracket the whole lot, eg.</p> <pre class="lang-C++ prettyprint-override"><code> int i; for (i = 0; i &lt; AnaPinsNum; i++) { // &lt;------------------------------- add this potIn[i] = analogRead(pot[i]) / 8; // potentiometer could be too sensitive and // give different (+-1) values. // send CC only when the difference between last value // is more than 1 if ((potIn[i] - lastAnalogValue[i]) &gt; 1 || (potIn[i] - lastAnalogValue[i]) &lt; -1) { // value changed? if (potIn[i] != lastAnalogValue[i]) { // send serial value (ControlNumber 1, ControlValue = analogValue, Channel 1) // more info: http://arduinomidilib.sourceforge.net/a00001.html MIDI.sendControlChange(1, potIn[i], 1); lastAnalogValue[i] = potIn[i]; } // end of not same as before } // end of value changed } // &lt;----------------- add this </code></pre> <hr> <blockquote> <p>If pot one is sending out Controller number 1 and channel number 1, 2nd pot should send Controller number 2 and channel no 2.</p> </blockquote> <p>If I understand your question correctly:</p> <p>Change:</p> <pre class="lang-C++ prettyprint-override"><code>MIDI.sendControlChange(1, potIn[i], 1); </code></pre> <p>to:</p> <pre class="lang-C++ prettyprint-override"><code>MIDI.sendControlChange(i, potIn[i], i); </code></pre>
14564
|programming|arduino-mega|sketch|arduino-motor-shield|
Arduino Program uses less RAM then expected and doesn't run
2015-08-26T16:34:43.963
<p>I am trying to make a program for my Arduino that will run 4 motors with random actions (forward,backward,left,right) and execution is determined by a random number generator. When I compile there is no errors, and The COM port is connected correctly to my Arduino Mega, but when it uploads the log says this:</p> <pre><code>Sketch uses 668 bytes (0%) of program storage space. Maximum is 253,952 bytes. Global variables use 9 bytes (0%) of dynamic memory, leaving 8,183 bytes for local variables. Maximum is 8,192 bytes. </code></pre> <p>That means only 677 B is being used, but the Arduino file is <em>6 KB</em>. I know that the program gets somewhat smaller when it is compiled, but not ten times smaller.</p> <p>What's happening here?</p> <p><strong>EDIT</strong></p> <pre><code>// Arduino pins for the shift register #define MOTORLATCH 12 #define MOTORCLK 4 #define MOTORENABLE 7 #define MOTORDATA 8 // 8 bit bus #define MOTOR1_A 2 #define MOTOR1_B 3 #define MOTOR2_A 1 #define MOTOR2_B 4 #define MOTOR3_A 5 #define MOTOR3_B 7 #define MOTOR4_A 0 #define MOTOR4_B 6 // Motor pins: #define MOTOR1_PWM 11 #define MOTOR2_PWM 3 #define MOTOR3_PWM 6 #define MOTOR4_PWM 5 // LED Pins #define led_r 22 #define led_l 23 // Actions #define RIGHT 0 #define LEFT 1 #define FORWARD 2 #define STOP 3 // Codes for the motor function. #define GO 1 #define REVERSE 2 #define BRAKE 3 #define RELEASE 4 // Probability #define rProb 5 #define lProb 5 #define fProb 88 #define stopProb 2 // other globals #define defSpd 255 void setup() {} void execute(int action) { if (action == FORWARD) { motor(1,FORWARD,defSpd); motor(2,FORWARD,defSpd); motor(3,FORWARD,defSpd); motor(4,FORWARD,defSpd); digitalWrite(led_r, LOW); digitalWrite(led_l, LOW); } else if (action == RIGHT) { motor(1,REVERSE,defSpd); motor(2,REVERSE,defSpd); motor(3,FORWARD,defSpd); motor(4,FORWARD,defSpd); digitalWrite(led_l, LOW); digitalWrite(led_r, HIGH); delay(150); } else if (action == LEFT) { motor(1,FORWARD,defSpd); motor(2,FORWARD,defSpd); motor(3,REVERSE,defSpd); motor(4,REVERSE,defSpd); digitalWrite(led_l, HIGH); digitalWrite(led_r, LOW); delay(150); } else if (action == STOP) { motor(1,BRAKE,defSpd); motor(2,BRAKE,defSpd); motor(3,BRAKE,defSpd); motor(4,BRAKE,defSpd); digitalWrite(led_r, HIGH); digitalWrite(led_l, HIGH); delay(1000); } } void loop() { // put your main code here, to run repeatedly: // Random action int i = (1, 101); if (i &gt; 0 &amp;&amp; i &lt;= rProb) { execute(RIGHT); } else if (i &gt; rProb &amp;&amp; i &lt;= rProb + lProb) { execute(LEFT); } else if (i &gt; rProb + lProb &amp;&amp; i &lt;= rProb + lProb + fProb) { execute(FORWARD); } else if (i &gt; rProb + lProb + fProb &amp;&amp; i &lt;= rProb + lProb + fProb + stopProb) { execute(STOP); } } void motor(int nMotor, int command, int speed) { int motorA, motorB; if (nMotor &gt;= 1 &amp;&amp; nMotor &lt;= 4) { switch (nMotor) { case 1: motorA = MOTOR1_A; motorB = MOTOR1_B; break; case 2: motorA = MOTOR2_A; motorB = MOTOR2_B; break; case 3: motorA = MOTOR3_A; motorB = MOTOR3_B; break; case 4: motorA = MOTOR4_A; motorB = MOTOR4_B; break; default: break; } switch (command) { case GO: motor_output (motorA, HIGH, speed); motor_output (motorB, LOW, -1); // -1: no PWM set break; case REVERSE: motor_output (motorA, LOW, speed); motor_output (motorB, HIGH, -1); // -1: no PWM set break; case BRAKE: // The AdaFruit library didn't implement a brake. // The L293D motor driver ic doesn't have a good // brake anyway. // It uses transistors inside, and not mosfets. // Some use a software break, by using a short // reverse voltage. // This brake will try to brake, by enabling // the output and by pulling both outputs to ground. // But it isn't a good break. motor_output (motorA, LOW, 255); // 255: fully on. motor_output (motorB, LOW, -1); // -1: no PWM set break; case RELEASE: motor_output (motorA, LOW, 0); // 0: output floating. motor_output (motorB, LOW, -1); // -1: no PWM set break; default: break; } } } void motor_output (int output, int high_low, int speed) { int motorPWM; switch (output) { case MOTOR1_A: case MOTOR1_B: motorPWM = MOTOR1_PWM; break; case MOTOR2_A: case MOTOR2_B: motorPWM = MOTOR2_PWM; break; case MOTOR3_A: case MOTOR3_B: motorPWM = MOTOR3_PWM; break; case MOTOR4_A: case MOTOR4_B: motorPWM = MOTOR4_PWM; break; default: // Use speed as error flag, -3333 = invalid output. speed = -3333; break; } if (speed != -3333) { // Set the direction with the shift register // on the MotorShield, even if the speed = -1. // In that case the direction will be set, but // not the PWM. shiftWrite(output, high_low); // set PWM only if it is valid if (speed &gt;= 0 &amp;&amp; speed &lt;= 255) { analogWrite(motorPWM, speed); } } } void shiftWrite(int output, int high_low) { static int latch_copy; static int shift_register_initialized = false; // Do the initialization on the fly, // at the first time it is used. if (!shift_register_initialized) { // Set pins for shift register to output pinMode(MOTORLATCH, OUTPUT); pinMode(MOTORENABLE, OUTPUT); pinMode(MOTORDATA, OUTPUT); pinMode(MOTORCLK, OUTPUT); // Set pins for shift register to default value (low); digitalWrite(MOTORDATA, LOW); digitalWrite(MOTORLATCH, LOW); digitalWrite(MOTORCLK, LOW); // Enable the shift register, set Enable pin Low. digitalWrite(MOTORENABLE, LOW); // start with all outputs (of the shift register) low latch_copy = 0; shift_register_initialized = true; } // The defines HIGH and LOW are 1 and 0. // So this is valid. bitWrite(latch_copy, output, high_low); // Use the default Arduino 'shiftOut()' function to // shift the bits with the MOTORCLK as clock pulse. // The 74HC595 shiftregister wants the MSB first. // After that, generate a latch pulse with MOTORLATCH. shiftOut(MOTORDATA, MOTORCLK, MSBFIRST, latch_copy); delayMicroseconds(5); // For safety, not really needed. digitalWrite(MOTORLATCH, HIGH); delayMicroseconds(5); // For safety, not really needed. digitalWrite(MOTORLATCH, LOW); } </code></pre>
<p>What is:</p> <pre><code>// Random action int i = (1, 101); </code></pre> <p>supposed to achieve?</p> <pre><code>/tmp/untitled1/untitled1.ino: In function 'void loop()': /tmp/untitled1/untitled1.ino:110:13: warning: left operand of comma operator has no effect [-Wunused-value] </code></pre> <p>Ergo, <code>i</code> is always going to be 101. So all the <code>if</code> constructs will be false, so they get optimized out (they are all constants). Because of that the other functions are never getting called, so they are optimized out.</p> <p>So you are left with next to nothing.</p> <p>I think you may have missed the word <code>random</code> out from there...</p> <ul> <li>Program size: 2798 bytes</li> <li>Memory size: 17 bytes</li> <li>Compilation took 0.227 seconds</li> </ul>
14565
|pins|input|
Why should a pin be set as an input if it can read input when set as output?
2015-08-26T17:10:01.027
<p>I recently created a circuit to read the value from two sets of buttons using only two analog pins. It involves setting one pin <code>HIGH</code> and reading the input on the other pin and then swapping. With both pins set to <code>OUTPUT</code> I can still read in values with <code>analogRead()</code> without having to keep switching pin modes.</p> <p>My question is why is that the case? What is the point of setting a pin to <code>INPUT</code> if <code>OUTPUT</code> can still read in values? Are there any disadvantages of doing so?</p>
<p>It is good practice to define them, especially if you program something other then an arduino. For example a port pin on the PCF8574 (Peripheral device) is written as a 1 so you can read it, it has a small internal pull up. If you pull it low in this condition you will read a zero. If you write a zero you will always read a zero. Driving it to a 1 when set to zero can destroy the part. This configuration is also used on microcontrollers. There are hundreds of different port configurations and programming options, it is best to read the data and understand it first otherwise you may be purchasing another.</p>
14576
|c++|arduino-leonardo|
Request for member is Non-class type
2015-08-26T22:42:46.753
<p>Im getting this error:</p> <pre><code>iotHook.ino: In function 'void setup()': iotHook:13: error: request for member 'begin' in 'esp', which is of non-class type 'Esp8266()' request for member 'begin' in 'esp', which is of non-class type 'Esp8266()' </code></pre> <p>When I try to lunch my begin function of my class:</p> <pre><code>class Esp8266 { public: Esp8266(); void begin(HardwareSerial *wifiCom, HardwareSerial *debugCom); ... private: HardwareSerial *wifiCom; HardwareSerial *debugCom; ... } Esp8266::Esp8266() { } void Esp8266::begin(HardwareSerial *wifiCom, HardwareSerial *debugCom) { this-&gt;wifiCom = wifiCom; this-&gt;debugCom = debugCom; this-&gt;debugCom-&gt;begin(115200); while (!this-&gt;debugCom) { ; } } </code></pre> <p><a href="https://i.stack.imgur.com/LsAdO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LsAdO.png" alt="enter image description here"></a></p> <p>EDIT 1: Updated image with new code <a href="https://i.stack.imgur.com/Io6tr.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Io6tr.png" alt="enter image description here"></a></p> <p>Why is not picking up the begin function?</p>
<p>Your current problem is that the USB Serial interface of the Leonardo isn't a hardware serial device, it's a CDC/ACM device, and the class for that isn't HardwareSerial, it's Serial_.</p> <p>So you can't pass it to a function that expects a HardwareSerial.</p> <p>What you should be using, instead, is the Stream class. That will allow you to pass any object that is based on the Stream class, such as HardwareSerial, Serial_, Client, etc. Many different things, including serial and networking protocols, use Stream as their base class.</p> <p>It does have the down side, though, that you have to initialize the Stream objects in your sketch (that is, do the Serial.begin(...) and Serial1.begin(...) in your sketch not your class) because the Stream class doesn't have the concept of a baud rate, and so no begin(baud) function.</p> <p>This is what I mean:</p> <pre><code>class Esp8266 { public: Esp8266(); void begin(Stream &amp;wifiCom, Stream &amp;debugCom); private: Stream *_wifiCom; Stream *_debugCom; }; Esp8266::Esp8266() { } void Esp8266::begin(Stream &amp;wifiCom, Stream &amp;debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; while (!_debugCom) { ; } } Esp8266 esp; void setup() { Serial.begin(115200); Serial1.begin(115200); esp.begin(Serial, Serial1); } // end of setup void loop() { } // end of </code></pre> <p>Note, as well, my use of pass-by-reference (Stream &amp;whatever) so you don't have to pass a pointer in your begin function. Also notice the use of unique variable names in the class (I always prefix my member variables with <code>_</code>) so you don't have to keep putting <code>this-&gt;</code> in everywhere.</p> <hr> <p>To be able to move the <code>.begin()</code> function inside your class you will have to use both <code>HardwareSerial</code> and <code>Serial_</code> object types within your class. There's two ways this may be done.</p> <p>First is <a href="http://en.cppreference.com/w/cpp/language/dynamic_cast" rel="nofollow"><em>dynamic casting</em></a>:</p> <pre><code>void Esp8266::begin(Stream &amp;wifiCom, Stream *debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; HardwareSerial *hard; Serial_ *cdc; if (hard = dynamic_cast&lt;HardwareSerial*&gt;(_wifiCom)) { hard-&gt;begin(115200); } else if (cdc = dynamic_cast&lt;Serial_*&gt;(_wifiCom)) { cdc-&gt;begin(115200); } if (hard = dynamic_cast&lt;HardwareSerial*&gt;(_debugCom)) { hard-&gt;begin(115200); } else if (cdc = dynamic_cast&lt;Serial_*&gt;(_debugCom)) { cdc-&gt;begin(115200); } } </code></pre> <p>I haven't tested this, and I don't know if the Arduino's cut-down C++ library is even capable of it, but it's worth a try.</p> <p>The other method is to <em>overload</em> the <code>.begin()</code> function of your class with multiple versions that take different parameters:</p> <pre><code>void Esp8266::begin(Serial_ &amp;wifiCom, HardwareSerial *debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; wifiCom.begin(115200); debugCom.begin(115200); } void Esp8266::begin(HardwareSerial &amp;wifiCom, HardwareSerial *debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; wifiCom.begin(115200); debugCom.begin(115200); } void Esp8266::begin(HardwareSerial &amp;wifiCom, Serial_ *debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; wifiCom.begin(115200); debugCom.begin(115200); } </code></pre> <p>You're still storing them internally as <code>Stream</code> objects in all cases, but within the <code>begin()</code> function itself you also have them available as their child classes. It does mean you have duplicate code copied between the different versions of <code>begin()</code>. You could modularize it a little more though by moving the duplicated code into functions which would only need to be duplicated twice, not three times - one to act on a single <code>Serial_</code> object and one to act on a single <code>HardwareSerial</code> object:</p> <pre><code>void Esp8266::initSerial(Serial_ *ser) { ser-&gt;begin(115200); } void Esp8266::initSerial(HardwareSerial *ser) { ser-&gt;begin(115200); } void Esp8266::begin(Serial_ &amp;wifiCom, HardwareSerial *debugCom) { _wifiCom = &amp;wifiCom; _debugCom = &amp;debugCom; initSerial(&amp;wifiCom); initSerial(&amp;debugCom); } ... etc x3 ... </code></pre>
14590
|wifi|web|
Can a WiFi enabled Arduino make a HTTPS request to my Web Server?
2015-08-27T12:20:40.447
<p>I need my Arduino to connect to my web server through HTTPS, can the Arduino handle it?</p> <p>It only has to act as a client.</p>
<p>It sounds like a better way to do it would be to have a PHP script act as handoff server (maybe protected by originating IP address) to access the HTTPS site and provide the data over a less processor-intensive protocol.</p> <p><a href="https://arduino.stackexchange.com/questions/4/how-to-get-https-on-arduino">How to get HTTPS on Arduino?</a></p> <p>However, another answer suggests that we are working towards a solution to your issue, but it's not quite there yet (~12 seconds to encrypt a packet). </p> <p><a href="https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/" rel="nofollow">https://evothings.com/is-it-possible-to-secure-micro-controllers-used-within-iot/</a></p>
14596
|arduino-uno|accelerometer|
Need help in modifying the design
2015-08-27T16:09:34.493
<p>I am planning to do a project on Sequential tilt motion lock using Arduino uno and accelerometer. I would like to present the accelerometer <strong>within</strong> a rotatable object. So what other components do i have to add to be able to do it i.e.. for wireless transmission of data from the object(that has the acc. meter) to the Uno board. <a href="https://i.stack.imgur.com/QHbnk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QHbnk.jpg" alt="Tilt lock circuit "></a></p>
<p>If you do a google search for "arduino wireless serial" you'll get several results. Plugging them into the arduino should be trivial. Most suppliers (other than ebay) will also have examples for you to reference where it comes to coding your project to use the module. </p> <p>You should also be aware that you will usually need a transceiver, and a receiver.</p> <p>You might take a look into the XBEE solutions, as they appear to be popular. </p>
14597
|arduino-uno|
What are the basics in writing a program in Arduino?
2015-08-27T16:16:07.750
<p>I am an undergrad in ICE. I was searching for ideas to do mini projects on and found this Arduino boards and programs. So actually what are the basics to develop our own gadgets? Any guidelines...? </p>
<p>There are some excellent books available as well as videos and articles on the Internet which will walk you through basic projects. The most common method of programming is to use the free <a href="https://www.arduino.cc/en/Main/Software" rel="nofollow">Arduino IDE</a> which will talk to the board from your Mac or PC. You can run the board straight from the USB port's power, or from an external source if you need it to be portable.</p> <p>The programming language is very similar to C. The program structure is basically a setup portion and then a continuous main loop that runs until the board is powered off.</p> <p>If you want to experiment without actually purchasing one, there are some emulators available which will let you build entire project on a virtual breadboard before buying any actual components. <a href="http://fritzing.org/" rel="nofollow">Fritzing</a> is a great board planner that you can install, or if you would rather, you can use <a href="https://123d.circuits.io/" rel="nofollow">123D Circuits</a> from your web browser which will let you edit and simulated the circuits.</p> <p>Basic knowledge of electrical circuits will be helpful for getting started, and is a great asset when designing larger projects.</p>
14600
|arduino-micro|linux|
How to differentiate between 2 Micros on Linux
2015-08-27T19:03:55.827
<p>I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine. I need them to have unique serial ports. Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible). </p> <p>This is the serial number that I get for both:</p> <pre><code>$ udevadm info -a -p $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial ATTRS{serial}=="0000:00:14.0" </code></pre> <p>Is there any way to manually set the serial number on an Arduino Micro? Or is there any other unique identifying properties I can use for udev rules? </p> <p>Typically, I do something like this in my <code>/etc/udev/rules.d/99-usb-serial.rules</code> file: </p> <pre><code>SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice" </code></pre> <p>Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.</p>
<p>That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.</p> <p>Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: <a href="http://forum.arduino.cc/index.php?topic=503703.0" rel="nofollow noreferrer">http://forum.arduino.cc/index.php?topic=503703.0</a></p> <p>Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are <em>supposed</em> to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.</p> <p>Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I <em>think</em> that's also true for the CP2102, but I'm not certain.</p> <p>You <em>may</em> be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.</p>
14616
|arduino-uno|c++|remote-control|
PPM from remote control is very noisy
2015-08-28T03:08:12.267
<p>I tried to use a function that could smooth out the PPM by using 10 input values and finding the averages. But even this still doesn't seem to be a good way prevent the noise that is occurring when using my Remote. Is there any way to fix this? Here is the code from the smoothing project. (Although i feel it's not really necessary to add it here, but here it is anyways.) </p> <p>My code is using the PPMrcIn library. An int is created and then using if statements I make an object do work. My problem is that i have a very small window for work.</p> <p>My values are between 50 and 200 <br>Where 140 is the preferred midpoint i'd like to work with. <br>This is my somewhat cryptic number line. <br>140 is in the middle. Where my window of stability is between 130 and 150 <br>and values below 100 and above 180 are where the robot does some work. <br> 50 ---x---&lt;100-----130--&lt;140>--150----180>---x---200</p> <pre class="lang-C++ prettyprint-override"><code> /* Smoothing Reads repeatedly from an analog input, calculating a running average and printing it to the computer. Keeps ten readings in an array and continually averages them. The circuit: * Analog sensor (potentiometer will do) attached to analog input 0 Created 22 April 2007 By David A. Mellis &lt;dam@mellis.org&gt; modified 9 Apr 2012 by Tom Igoe http://www.arduino.cc/en/Tutorial/Smoothing This example code is in the public domain. */ // Define the number of samples to keep track of. The higher the number, // the more the readings will be smoothed, but the slower the output will // respond to the input. Using a constant rather than a normal variable lets // use this value to determine the size of the readings array. const int numReadings = 10; int readings[numReadings]; // the readings from the analog input int index = 0; // the index of the current reading int total = 0; // the running total int average = 0; // the average int inputPin = A0; void setup() { // initialize serial communication with computer: Serial.begin(9600); // initialize all the readings to 0: for (int thisReading = 0; thisReading &lt; numReadings; thisReading++) readings[thisReading] = 0; } void loop() { // subtract the last reading: total= total - readings[index]; // read from the sensor: readings[index] = analogRead(inputPin); // add the reading to the total: total= total + readings[index]; // advance to the next position in the array: index = index + 1; // if we're at the end of the array... if (index &gt;= numReadings) // ...wrap around to the beginning: index = 0; // calculate the average: average = total / numReadings; // send it to the computer as ASCII digits Serial.println(average); delay(1); // delay in between reads for stability } </code></pre> <p>also link to my code in github <a href="https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino" rel="nofollow">https://github.com/tisaconundrum2/RCRoomba/blob/master/RCRoomba2.2.ino</a></p> <p>Since this is being asked. Let me clarify on this black voodoo thing called a PPM. </p> <p>Many RC Transmitters and Receivers provide access to the PPM Stream, this is a single stream of pulses which includes the information for all of the receiver channels in a single connection.<br> The stream is made up of a series of short pulses, the first pulse is the start marker. The time between the start marker and the start of the next pulse defines the pulse length for channel one. The time to the next pulse defines the pulse length for channel 2 and so on. The end of the pulse stream is marked by a gap know as the frame space. This gap indicates that there are no more channels to receive and the next pulse will be the start of a new frame. Each frame contains the pulse widths for all of your receiver channels. Note - unlike servo signals, in a PPM Stream it is the gaps between pulses that defines the pulse width for a channel, not the duration of the pulse itself which can be very short. -<a href="http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html" rel="nofollow">http://rcarduino.blogspot.com/2012/11/how-to-read-rc-receiver-ppm-stream.html</a></p> <p>As discussed above. My PPM signal is highly varied. I want to be able to just get a solid 140. However, the signal will jump irratically between 135 and 142 for reasons I do not completely understand. In an attempt to clear this fuzziness I tried to go for smoothing.</p>
<p>First, I want to thank you for making this post. I have a few remote-controlled cars/boats/helicopters, and I've often wondered how the remote control works. :)</p> <hr> <p>To answer your question - and because I was too lazy to work out how to connect to an actual controller - I made a "remote simulator" like this:</p> <pre class="lang-C++ prettyprint-override"><code>// PPM generator const byte SIGNAL_PIN = 3; const int SIGNAL_COUNT = 6; const unsigned long PULSE_WIDTH = 300; // µs const unsigned long BLANK_TIME = 25; // ms const int widths [SIGNAL_COUNT] = { 600, 2000, 1000, 1500, 2200, 2400 }; void setup () { pinMode (SIGNAL_PIN, OUTPUT); } // end of setup void loop () { delay (BLANK_TIME); digitalWrite (SIGNAL_PIN, HIGH); // start delayMicroseconds (PULSE_WIDTH); digitalWrite (SIGNAL_PIN, LOW); // end of start pulse for (byte i = 0; i &lt; SIGNAL_COUNT; i++) { delayMicroseconds (widths [i] - PULSE_WIDTH); digitalWrite (SIGNAL_PIN, HIGH); // start of pulse delayMicroseconds (PULSE_WIDTH); digitalWrite (SIGNAL_PIN, LOW); // end of pulse } // end of for loop delay (1000); } // end of loop </code></pre> <p>This is intended to generate a series of pulses (six in this case) which might be generated by some fancy <s>toy</s> fun device.</p> <hr> <p>Output from it:</p> <p><a href="https://i.stack.imgur.com/XBAjj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/XBAjj.png" alt="PPM generator"></a></p> <p>As you can see from the cursor, it is doing what it is bid. The pulse width shown by the scope cursor is indeed 2000 µs, as per the table of widths.</p> <p><em>Note</em>: Output on pin 3 on the Uno.</p> <hr> <p>Now we need a decoder. So let's use interrupts:</p> <pre class="lang-C++ prettyprint-override"><code>const byte SIGNAL_PIN = 2; const int SIGNAL_COUNT = 6; volatile unsigned long widths [SIGNAL_COUNT + 1]; volatile byte count; unsigned long lastPulse; // ISR void gotPulse () { unsigned long now = micros (); // a long gap means we start again if ((now - lastPulse) &gt;= 25000) count = 0; lastPulse = now; if (count &gt;= (SIGNAL_COUNT + 1)) return; widths [count++] = now; } void setup () { Serial.begin (115200); Serial.println (); attachInterrupt (0, gotPulse, RISING); EIFR = bit (INTF0); // clear flag for interrupt 0 } // end of setup void loop () { if (count &gt;= SIGNAL_COUNT) { Serial.println (F("Got sequence.")); for (int i = 1; i &lt; SIGNAL_COUNT + 1; i++) { Serial.print ("Channel "); Serial.print (i); Serial.print (" = "); Serial.println (widths [i] - widths [i - 1]); } count = 0; } } // end of loop </code></pre> <p>This uses an interrupt (on pin 2 on the Uno) on the rising edge to detect the start of the pulses. It stores them, and then works out their widths later.</p> <hr> <p>Results?</p> <pre class="lang-C++ prettyprint-override"><code>Got sequence. Channel 1 = 612 Channel 2 = 2020 Channel 3 = 1016 Channel 4 = 1512 Channel 5 = 2220 Channel 6 = 2428 Got sequence. Channel 1 = 612 Channel 2 = 2020 Channel 3 = 1016 Channel 4 = 1512 Channel 5 = 2220 Channel 6 = 2424 Got sequence. Channel 1 = 616 Channel 2 = 2020 Channel 3 = 1012 Channel 4 = 1516 Channel 5 = 2220 Channel 6 = 2424 Got sequence. Channel 1 = 616 Channel 2 = 2020 Channel 3 = 1012 Channel 4 = 1516 Channel 5 = 2216 Channel 6 = 2432 </code></pre> <p>Highly consistent results, with a small error factor of around 16 µs compared to <code>600, 2000, 1000, 1500, 2200, 2400</code></p> <hr> <p>In case it isn't clear, this test required two Unos. One to generate the pulses and a second one to decode them:</p> <p><a href="https://i.stack.imgur.com/DxH0K.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DxH0K.jpg" alt="PPM Test setup"></a></p> <p>The one with the USB cable is the decoder, which writes to the serial port. The other one is powered by 5V/Gnd from the first one, and the white wire is the data with the pulses.</p>
14619
|lcd|
Split a string as 2x16 for LCD
2015-08-28T07:34:28.320
<p>How do I split a string into two based on it's length to display on a 2x16 LCD?</p> <p>I have seen a function called length() to get the length of a string. But, any ideas how to split it in to 2x16 and trim the rest of the string?</p> <p>Thanks</p>
<p>String::Substring does take a start and an end value. So you can do something like this:</p> <pre><code>String s1 = longtext.substring(0,15); String s2 = longtext.substring(16,31); </code></pre>