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
|
---|---|---|---|---|---|
14631 | |lcd|hardware| | Cheap LCD with Few Pins | 2015-08-28T16:05:38.263 | <p>I am working on a project with an Arduino Nano that includes a keypad, screen, and the NRF4001 transceiver. The keypad requires 7 digital pins to operate, the wireless transceiver uses pins D9 - D13 with the RF24 library I am using. Now, that leaves me with 1 Digital Pin left for a screen unless there is an I2C screen I could use.</p>
<p>That would be easy enough to find except that I have some limitations. If at all possible I would like the screen to be under 5 dollars and about the size of a Nokia 5110. The Nokia uses to many pins and does not tolerate 5v logic levels I've heard. An OLED 0.96 inch is only a 4 bucks and is I2C, but it is too small. I could make a board for the keypad that used different values of resistors and one analog pin to detect different buttons but would rather not go that route if there is any easier way to get around this.</p>
<p>Are there any options out there that would suffice my pin, cost and size conditions or am I being too picky?</p>
| <p>You can use a single analog pin to read an entire keypad.</p>
<p>First, read up on voltage dividers - they let you convert a resistance into a voltage. You will need to know this later on.</p>
<p>A keypad typically has 4 inputs, and 3 outputs (or vice-versa). Label the 4 pins A,B,C,D and the 3 pins E, F, G. You will be wiring A up to a voltage supply, and G up to an analog pin, and via a suitable resistor to ground. This becomes your voltage divider.</p>
<p>Then, put a resistor between A+B, B+C, C+D, and between E+F, F+G. So, if you press the button that connects A to G, there will be no resistance (=+5V). If you press the button that connects A to F, then the resistance will be that of the resistance F->G. If you press the button that connect D and E, the circuit goes: VCC-A-resistor-B-resistor-C-resistor-D-pushbutton-E-resistor-F-resistor-G - Arduino analog pin. With no button pressed, the voltage will be 0.</p>
<p>You will need to work out different resistors in advance, to give you as even a range as possible between 0 and 5 volts (the critical thing being the smallest difference). You can calculate the resistance of any combination here: <a href="http://www.calculator.net/resistor-calculator.html" rel="nofollow">http://www.calculator.net/resistor-calculator.html</a> and you can use Ohm's law to calculate the final voltage. This depends on what you have in your kit. I ended up making a spreadsheet, and then trying random resistor values until I got a good spread.</p>
<p>DO NOT use any resistors under 1kOhm.</p>
<p>Once you have the right spread, make it up on a solderless breadboard. Measure the voltage with your arduino (use the "readanalogvoltage" sketch, take out <code>* (5.0 / 1023.0)</code> , and make up a table - press button 1, you get a reading if A, press button 2, get a reading of B. Include the reading when no button is pressed, which should be 0.</p>
<p>Then find the numbers exactly in between.</p>
<p>For example, if the lowest three readings are 0,20,37 for no button, A, and B pressed, respectively, then in your code, you will say: if the pin measures less than (half way between 0 and 20=) 10, then no button is pressed; else if the pin measures less than (half way between 20 and 37=) 29, then button A is pressed... and so forth.</p>
|
14632 | |atmega328| | How to do a software reset on MAX7456? | 2015-08-28T16:27:54.497 | <p>I messed around with the <a href="https://www.sparkfun.com/datasheets/BreakoutBoards/MAX7456.pdf" rel="nofollow">MAX7456</a> chip for a while, even the character set updating sketch seemed to work after a few modifications. But now it is not displaying anything with the Hello World sketch that worked before. No signal seems to pass through it, the screen is just black.</p>
<p>The datasheet says that one must write Video Mode 0 Register (VM0) at address 00H bit 1 to 1 via SPI to reset it, how would I do it? Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards? (The board looks like <a href="http://www.ebay.co.uk/itm/On-Screen-Ardupilot-Mega-Display-MinimOSD-Rev-1-1-OSD-diy-drones-APM2-2-5-2-6-/321843140980" rel="nofollow">this</a>)</p>
|
<p>The datasheet says:</p>
<blockquote>
<p>The SPI commands are 16 bits long with the 8 most significant bits (MSBs) representing the register address and the 8 least significant bits (LSBs) representing the data ...</p>
</blockquote>
<p>Thus, you need to write address / data after selecting the chip.</p>
<pre class="lang-C++ prettyprint-override"><code>digitalWrite (SS, LOW); // select the chip
SPI.transfer (0x00); // select address 0x00 (Video Mode 0)
SPI.transfer (bit (1)); // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done
</code></pre>
<p>According to the datasheet you need to wait around 20 µs for the operation to complete. You could, of course, just wait 20 µs but it might be nice to see if the bit gets cleared.</p>
<pre class="lang-C++ prettyprint-override"><code> byte result;
do
{
digitalWrite (SS, LOW); // select the chip
SPI.transfer (0x80); // select address 0x00 (Video Mode 0) - read mode
result = SPI.transfer (0); // read it
digitalWrite (SS, HIGH); // done
} while (result & bit (1)); // loop while not reset yet
</code></pre>
<hr>
<blockquote>
<p>Also, how would one verify that the chip indeed did reset itself and responds to the commands given to it afterwards?</p>
</blockquote>
<p>I'm not sure, without the chip in hand, what other tests you can make, but if you added a counter into the above loop, you could probably verify that it was doing something. eg.</p>
<pre class="lang-C++ prettyprint-override"><code> // reset chip
digitalWrite (SS, LOW); // select the chip
SPI.transfer (0x00); // select address 0x00 (Video Mode 0) - write mode
SPI.transfer (bit (1)); // write bit 1 (Software Reset Bit)
digitalWrite (SS, HIGH); // done
byte result;
unsigned int counter = 0;
// wait for it to become ready, or time-out
do
{
digitalWrite (SS, LOW); // select the chip
SPI.transfer (0x80); // select address 0x00 (Video Mode 0) - read mode
result = SPI.transfer (0); // read it
digitalWrite (SS, HIGH); // done
if ((result & bit (1)) == 0)
counter++; // count times not ready
} while ((result & bit (1)) && (counter < 1000) ); // loop while not reset yet
if (counter == 0 || counter >= 1000)
{
// chip does not seem to be responding
}
else
{
// all OK!
}
</code></pre>
|
14634 | |display| | Arduino Pro Mini and GDEW0154T1 ePaper (e ink) display | 2015-08-28T18:39:16.417 | <p>I just got my Arduino Pro Mini and GDEW0154T1 ePaper display (<a href="http://www.good-display.com/products_detail/&productId=305.html" rel="nofollow">GDEW0154T1 display)</a> and I'm trying to figure out a way to make them "talk". I started reading documentation and multiple sites but I still have no idea. I bought Breadboard, USB connector for Arduino and cables.</p>
<p>I think I need some port to connect display to Breadboard. Could you tell me where to look for it? What next?</p>
<p>Thank you for any advice!</p>
| <p>You need to build a special driver board. Most of the drive circuitry is on the main chip built into the display, which is convenient, but it requires a number of capacitors (which are too big to fit into the display itself) on the various voltage pins, and a special power control circuit to ensure that the different voltages get enabled at the right time.</p>
<p>The datasheet details the capacitors that need connecting (Figure 7.5(2)), as well as the power control circuit (Figure 7.5(4)).</p>
<p>There is another small circuit snippet there as well (Figure 7.5(3), temperature sensor) but I haven't worked out the relevance of that yet.</p>
<p>Also you will need the right FPC connector, and a surface mount PCB to solder it on to, as well as the ability to solder it (reflow oven), so it's not a trivial task. You may be able to find the right connector already soldered onto a breakout board if you look around - but make sure it <em>is</em> the right one, since there are many variations - number of pins, pitch of pins, upper or lower connection, etc.</p>
|
14644 | |arduino-uno| | Arduino code of making a LED digit display not functioning properly | 2015-08-29T06:59:56.187 | <p>I want to make an LED one digit display using 14 leds used in pairs so I have 7 pairs which show number. (Similar to the display in calculators). Now the problem is that my code won't function properly. The problem that is arising is that the leds won't go off, all of them would work at the same time, here's the code</p>
<pre><code>int a = 2;
int b = 3;
int c = 4;
int d = 5;
int e = 6;
int f = 7;
int g = 8;
void setup()
{
for(int i = 2; i++ ; i<9)
{
pinMode (i, OUTPUT);
}
}
void _1()
{
digitalWrite ( b, HIGH);
digitalWrite ( f, HIGH);
delay(1000);
}
void _2()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( e, HIGH);
digitalWrite ( g, HIGH);
delay(1000);
}
void _3()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( g, HIGH);
delay(1000);
}
void _4()
{
digitalWrite ( c, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( b, HIGH);
delay(1000);
}
void _5()
{
digitalWrite ( a, HIGH);
digitalWrite ( c, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( g, HIGH);
delay(1000);
}
void _6()
{
digitalWrite ( a, HIGH);
digitalWrite ( c, HIGH);
digitalWrite ( e, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( g, HIGH);
digitalWrite ( d, HIGH);
delay(1000);
}
void _7()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( f, HIGH);
delay(1000);
}
void _8()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( c, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( e, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( g, HIGH);
delay(1000);
}
void _9()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( c, HIGH);
digitalWrite ( d, HIGH);
digitalWrite ( f, HIGH);
delay(1000);
}
void _0()
{
digitalWrite ( a, HIGH);
digitalWrite ( b, HIGH);
digitalWrite ( c, HIGH);
digitalWrite ( e, HIGH);
digitalWrite ( f, HIGH);
digitalWrite ( g, HIGH);
delay(1000);
}
void wait()
{
digitalWrite ( a, LOW);
digitalWrite ( b, LOW);
digitalWrite ( c, LOW);
digitalWrite ( d, LOW);
digitalWrite ( e, LOW);
digitalWrite ( f, LOW);
digitalWrite ( g, LOW);
delay(100);
}
void loop()
{
_0();
wait();
_1();
wait();
_2();
wait();
_3();
wait();
_4();
wait();
_5();
wait();
_6();
wait();
_7();
wait();
_8();
wait();
_9();
wait();
}
</code></pre>
<p>The problem is that it stays at _0 and then never changes. Any suggestions?</p>
| <p>The <code>for</code> loop in your <code>setup()</code> function isn't quite right. The condition (<code>i<9</code>) and the iterator (<code>i++</code>) need to be the other way round, like this:</p>
<pre><code>for (int i = 2; i<9; i++)
{
pinMode (i, OUTPUT);
}
</code></pre>
|
14647 | |pins|arduino-nano| | How can I detect a disconnected pin? | 2015-08-29T07:51:06.133 | <p>I'm trying to build a system where if a cable gets disconnected from a pin (any pin), an action is executed. </p>
<p>I am wondering how to set this up. Can I simply wire the 5V to a pin and read its status or will this mess up the Arduino? Should I use any resistors? How should I connect this to the GND? </p>
<p>Please bear in mind that I'm pretty new to all of this.</p>
| <p>Alternatively, if this is a digital input, you can just use a pull-up or pull-down resistor to give the input pin a default value. Let's say you use a pull-up resistor to make the default high. Then you connect a low cable to this input so that the input reads low. Now, if the cable goes high or if it is disconnected, you get a high value in the input pin. </p>
<p>I know this was not quite what you were asking but maybe such a solution could help with your original problem. In my case, I have a flame detection module that gives low output by default and turns high when there is a flame. I don't want to miss the flame because of my cable disconnecting, so I use a pull-up resistor that will make the input high not only when there is a flame, but also when there is a disconnection. This way I make sure that I don't miss a fire because of the sensor cable disconnecting. </p>
|
14654 | |arduino-uno|serial|arduino-mega|arduino-ide|lcd| | How would i capture and split serial data? | 2015-08-29T15:23:50.307 | <p>How would i capture the following serial data, and split it into parts?
<code><Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000></code></p>
<p>the parts i need from this is
Alarm - This is a state. i.e Alarm, Idle, Paused, Working
MPos: - This is a series of positions X,Y,Z
WPos: - This is a series of positions X,Y,Z</p>
<p>What i want to do is capture the string from serial (See above for formatting)
Then display the information on the LCD. </p>
<p>i.e.
X: 0.000 Y:0.000
Z: 0.000 Idle</p>
<p>I've managed to figure out how to do all the LCD display stuff, and send commands to the serial, but it appears there are so many variations on how to split the data up, that i't really confusing to me, as well, almost all of the examples i find use loop to do this, but i would like to have this done in a function, that way i can display this info only when needed, not constantly, as i'll be useing the LCD for a menu system.</p>
| <p>This string is actually fairly easy to split up, because everything is separated by commas nice and regularly.</p>
<p>Assuming you have the string in a char array (aka a C string) and not a String object (I and most other programmers abhor the String class) you can use the function <code>strtok()</code> to split the string up into parts.</p>
<p>So you have the string:</p>
<pre><code>char string[] = "<Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>";
</code></pre>
<p>The function <code>strtok()</code> takes, on its first call, the string you want to split and the delimiter that you want to split on. It returns a pointer to the chunk:</p>
<pre><code>char *alarm = strtok(string, ",");
</code></pre>
<p><code>alarm</code> now contains <code><Alarm</code> and <code>strtok()</code> moves its internal pointer to point at the next character, so it sees the string as <code>MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000></code></p>
<p>With the next and subsequent calls to <code>strtok()</code> you don't give it the string, or it will reset its internal pointer. You just pass it <code>NULL</code> and it gives you the next block:</p>
<pre><code>char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");
</code></pre>
<p>Note that I changed the delimiter on the last one to <code>></code> so it chops off that extra character that we don't want (and there is no <code>,</code> after the last part).</p>
<p>So now you have 7 variables that point to chunks of the string, which has internally been chopped up and modified into individual substrings:</p>
<pre><code>*alarm = "<Alarm";
*mposX = "MPos:0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "WPos:0.000";
*wposY = "0.000";
*wposZ = "0.000";
</code></pre>
<p>So now we can clean up the three entries that have extra stuff in them, and that is a simple as adding an offset value to the pointers we have:</p>
<pre><code>alarm += 1;
mposX += 5;
wposX += 5;
</code></pre>
<p>Our list of pointers now looks like this:</p>
<pre><code>*alarm = "Alarm";
*mposX = "0.000";
*mposY = "0.000";
*mposZ = "0.000";
*wposX = "0.000";
*wposY = "0.000";
*wposZ = "0.000";
</code></pre>
<p>The position variables can now be passed through strtod() to convert them to float values:</p>
<pre><code>float mx = strtod(mposX, NULL);
float my = strtod(mposY, NULL);
float mz = strtod(mposZ, NULL);
float wx = strtod(wposX, NULL);
float wy = strtod(wposY, NULL);
float wz = strtod(wposZ, NULL);
</code></pre>
<p>You can do different things depending on the content of the <code>*alarm</code> string by using <code>strcmp()</code>:</p>
<pre><code>if (strcmp(alarm, "Busy") == 0) {
// Something to do when Busy
}
</code></pre>
<p>etc.</p>
<p>Or you can just use it to print the content to the LCD.</p>
|
14659 | |arduino-uno|arduino-ide|atmega328|programmer| | Cannot upload sketch to Atmega328p TQFP soldered on PCB | 2015-08-29T18:56:10.477 | <p>After creating a working prototype with DIP ATMega328 chip/ Arduino UNO I recently got PCBs assembled with SMD components and ATMega328P TQFP soldered onto them, but now I'm having a hard time trying to upload the Arduino program.</p>
<p><strong>This is the schematic of the PCB with ATMega328P TQFP with ISP headers for programming:</strong>
<a href="https://i.stack.imgur.com/agw3N.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/agw3N.png" alt="enter image description here"></a></p>
<p>I'm using USBasp programmer with upgraded firmware to upload the code. The chip gets detected and also I can upload sketches to it but the problem is the code runs slow, which I found out is due to the default 8MHz internal clock.(the blink program makes LED blink every 16 seconds instead of 1 second,i.e. with delay(1000))</p>
<p>Now to switch to the external 16MHz clock which I want to use I found out <a href="http://forum.arduino.cc/index.php?topic=71580.0" rel="nofollow noreferrer">here</a> that I have to change the fuse values from the default </p>
<blockquote>
<p><strong>lfuse: 0x62 hfuse: 0xD9 efuse: 0x3F</strong></p>
</blockquote>
<p>to</p>
<blockquote>
<p><strong>lfuse: 0xFF hfuse: 0xDE efuse: 0x05</strong></p>
</blockquote>
<p>I tried it two times and both the times it screwed up the ATMega328P chip</p>
<pre><code>C:\Users\p>avrdude -p m328p -c usbasp -U lfuse:w:0xFF:m -U hfuse:w:0xDE:m -U efu
se:w:0x05:m
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.03s
avrdude: Device signature = 0x1e950f
avrdude: reading input file "0xFF"
avrdude: writing lfuse (1 bytes):
Writing | ################################################## | 100% 0.02s
avrdude: 1 bytes of lfuse written
avrdude: verifying lfuse memory against 0xFF:
avrdude: load data lfuse data from input file 0xFF:
avrdude: input file 0xFF contains 1 bytes
avrdude: reading on-chip lfuse data:
Reading | ################################################## | 100% 0.01s
avrdude: verifying ...
avrdude: 1 bytes of lfuse verified
avrdude: reading input file "0xDE"
avrdude: writing hfuse (1 bytes):
Writing | ################################################## | 100% 0.03s
avrdude: 1 bytes of hfuse written
avrdude: verifying hfuse memory against 0xDE:
avrdude: load data hfuse data from input file 0xDE:
avrdude: input file 0xDE contains 1 bytes
avrdude: reading on-chip hfuse data:
Reading | ################################################## | 100% 0.01s
avrdude: verifying ...
avrdude: 1 bytes of hfuse verified
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):
Writing | ################################################## | 100% 0.03s
avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:
Reading | ################################################## | 100% 0.01s
avrdude: verifying ...
avrdude: 1 bytes of efuse verified
avrdude: safemode: Fuses OK
avrdude done. Thank you.
C:\Users\p>avrdude -p m328p -c usbasp
avrdude: error: programm enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
Double check connections and try again, or use -F to override
this check.
avrdude done. Thank you.
</code></pre>
<p>Both of the PCBs are not responding to the USBasp programmer and now I have only got one PCB left. I desperately want to get the final one working.</p>
<p>This is my first time using the SMD ATMega328P chips and any help would be appreciated.</p>
| <p>It looks like the capacitors on your crystal are considerably bigger than they should be.</p>
<p>You are switching the clock to the external crystal, and because you have such massive capacitors on it it's failing to oscillate. Without that oscillation the chip can't run, and so it can't respond to the programming.</p>
<p>The crystal capacitors should be roughly 2x the "load capacitance" of the crystal you are using.</p>
<blockquote>
<p>C<sub>X1</sub> = C<sub>X2</sub> = 2(C<sub>L</sub> - C<sub>STRAY</sub>)</p>
</blockquote>
|
14661 | |serial|arduino-leonardo|eeprom| | Handling serial streams biggers than the available ram | 2015-08-29T19:15:10.747 | <p>I need to parse text coming into my MC (Leonardo) over the hardware serial port. The data comes in burst, and the parsing routine manage the data flow with easy when it is less than the serial buffer.</p>
<p>I will like to be able to receive around 512Kb of serial data, save it somewhere (not in the arduino memory of course) and the execute the parsing routine on it. I think saving the stream to an external EEPROM and then retrieving it slowly so my parsing code can actually fallows will do the trick. I can control the speed of the serial stream from 300 bauds (not optimal) up to 112000 bauds. </p>
<p>Is the approach correct? Can I write to the EEPROM faster than a 9600 bauds serial stream without collapsing the arduino?</p>
| <p>You can parse indefinitely large amounts of data with a state machine parser.</p>
<p>General description: <a href="http://www.gammon.com.au/statemachine" rel="nofollow">State machines</a></p>
<p>As an example, I wrote recently an <a href="http://www.gammon.com.au/forum/?id=12942" rel="nofollow">HTTP server</a> which parses incoming HTTP data (eg. cookies, parameters, POST data, GET data) on-the-fly. </p>
<p>You need enough RAM for <strong>one</strong> item of data, naturally. But then you act upon it, and then discard it. In the case of the web server, you could conceivably process a complex form with thousands of actions on it (eg. turn on switch 5, pump 3, heater 22). It parses each action, and then you act on it, then you parse another action.</p>
<hr>
<p>You can even consider the Arduino bootloader as an example of this. The Optiboot bootloader is 512 bytes on a Uno, but it can re-flash 32 KB of program memory. How? The programming data comes down in bursts (packets, if you like) and it processes each packet at a time, then discards it and reads the next one.</p>
|
14662 | |arduino-ide|core-libraries| | Including libraries from header files sometimes doesn't work | 2015-08-29T21:35:16.160 | <p>I, once again have difficulties including libraries from code files other than my .ino file. </p>
<p>I have several .cpp and .h files in my project to keep it sorted and clean.
However one of my header files starting like this:</p>
<pre><code>#ifndef DPLANDEF
#define DPLANDEF
#include <Arduino.h>
#include <EEPROM.h>
#include "syssettings.h"
</code></pre>
<p>yields the following errors:</p>
<blockquote>
<p>In file included from
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.cpp:2:0:
/var/folders/jl/nv1qvh6n569cxq9xxfd6dx980000gn/T/build4605486877500371361.tmp/dplan.h:5:20:
fatal error: EEPROM.h: No such file or directory #include
^ compilation terminated. Fehler beim Kompilieren.</p>
</blockquote>
<p>EEPROM.h should be known to the IDE, because I can find it in the libraries menu, too. If it was a custom library, I might have botched something during installation, but this is a standard library. It should work out of the box. What's the problem here?</p>
| <p>The problem here is that it's a header file. The IDE doesn't treat header files like it does INO files - it doesn't parse them for included libraries, etc.</p>
<p>In order for it to work you must also include EEPROM.h in your main INO file so that the IDE knows that you want to include it in the rest of your files.</p>
|
14681 | |serial|arduino-mega|arduino-ide| | How can i read serial data into a string until a certain character is recieved? | 2015-08-30T15:08:51.390 | <p>This is not a duplicate of my other question. This question deals with reading specific data within a serial stream. The other question deals with reading and adding data into a manageable data string.</p>
<p>What I'm trying to do is send a command to serial, get the response, and put it into a string, and then break that string up into usable parts of data. </p>
<p>The problem I'm having, is there is a delay between the time the serial command is sent, and the response. meaning the serial data isn't being captured before the function moves onto the next line. Using delay() doesn't appear to work, as i believe it halts everything for that delay period.</p>
<p>What I'm hoping to do, is read the data from serial and if the character '<' is received, place it, and everything after it into the buffer until the character ">" is received. After the last character is received, and placed into the buffer, continue on with the script.</p>
<p>Unless of coarse someone has a better idea on how to approach this.
i would also like to note that this is just a part of a larger project. If you need to see the entire project, please let me know and i will provide a link where you can download it.</p>
<p>The string i'm expecting as a response would be similar to this:</p>
<pre><code><Alarm,MPos:0.000,0.000,0.000,WPos:0.000,0.000,0.000>
</code></pre>
<p>Here is the code i have so far:</p>
<pre><code>float mx;
float my;
float mz;
float wx;
float wy;
float wz;
String dAlarm;
char buffer;
void gPos() {
Serial1.print("?\n");
buffer = Serial1.read();
char string[80];
string[buffer];
char *alarm = strtok(string, ",");
char *mposX = strtok(NULL, ",");
char *mposY = strtok(NULL, ",");
char *mposZ = strtok(NULL, ",");
char *wposX = strtok(NULL, ",");
char *wposY = strtok(NULL, ",");
char *wposZ = strtok(NULL, ">");
alarm += 1;
mposX += 5;
wposX += 5;
mx = strtod(mposX, NULL);
my = strtod(mposY, NULL);
mz = strtod(mposZ, NULL);
wx = strtod(wposX, NULL);
wy = strtod(wposY, NULL);
wz = strtod(wposZ, NULL);
if (strcmp(alarm, "Idle") == 0) {
dAlarm = "Idle";
} else if (strcmp(alarm, "Run") == 0) {
// Something to do when Busy
dAlarm = "Run";
} else if (strcmp(alarm, "Hold") == 0) {
// Something to do when Busy
dAlarm = "Hold";
} else if (strcmp(alarm, "Door") == 0) {
// Something to do when Busy
dAlarm = "Door";
} else if (strcmp(alarm, "Home") == 0) {
// Something to do when Busy
dAlarm = "Home";
} else if (strcmp(alarm, "Alarm") == 0) {
// Something to do when Busy
dAlarm = "ALARM!";
} else if (strcmp(alarm, "Check") == 0) {
// Something to do when Busy
dAlarm = "Check";
}
dispPos();
}
void dispPos() {
int state = 0;
int x = analogRead (0);
if (x < 800) {
state = 1;
}
if (state == 1) {
dPos = false;
}
if (dPos == true) {
lcd.clear();
lcd.setCursor(0, 0);
lcd.print("X");
lcd.print(mx);
lcd.setCursor(8, 0);
lcd.print("Y");
lcd.print(my);
lcd.setCursor(0, 1);
lcd.print("Z");
lcd.print(mz);
lcd.setCursor(8, 1);
//lcd.print(" ");
lcd.print(dAlarm);
delay(3000);
} else {
mainMenu();
}
}
</code></pre>
| <p>What you need to do here is implement a small <em>finite state machine</em>.</p>
<p>Basically you need to look at each character as it comes in and make a decision what to do with it <em>depending on what state you're in at the moment</em>.</p>
<p>Basically the operational decisions you need to make are:</p>
<ul>
<li>Is the character a < and am I currently not reading a string?
<ul>
<li>Yes, start reading the string.</li>
</ul></li>
<li>Is the character a > and am I currently reading a string?
<ul>
<li>Yes, finish reading the string and process it</li>
</ul></li>
<li>Is it any other character and I am currently reading the string?
<ul>
<li>Yes, add it to the buffer.</li>
</ul></li>
</ul>
<p>So you can see there some common questions:</p>
<ul>
<li>What is the character?</li>
<li>What am I doing at the moment?</li>
</ul>
<p>So you need to have a simple state variable that remembers if you're reading the string or not, and something to say where in the buffer you are so you know where in the buffer to add any incoming characters.</p>
<pre><code>boolean readingString = false;
</code></pre>
<p>A simple true/false will suffice to depict if we're reading the string or not. Start off not reading the string.</p>
<pre><code>char buffer[80] = "";
</code></pre>
<p>A buffer to store the text - maximum of 80 characters (<em>including the NULL terminating character</em>)</p>
<pre><code>int charPointer = 0;
</code></pre>
<p>Something to know where in the buffer are currently.</p>
<p>Now to read the characters:</p>
<p>First get the next character from the serial port:</p>
<pre><code>loop() {
if (Serial.available()) {
int incoming = Serial.read();
</code></pre>
<p>Now decide what to do with it. We have a number of possible situations, some of which can be combined into single options. For instance, if we get a "<" while reading a string it's an error condition - but do we really care? It could be that we lost the end of the last string and have just started a fresh one - so we can just treat it as the start of a string regardless of what state we're in. Let's use a <code>switch</code> for this since it's nice and tidy:</p>
<pre><code> switch (incoming) {
case '<':
readingString = true; // Start reading string
charPointer = 0; // Set the buffer pointer to the start
buffer[0] = 0; // Make the string empty
break;
case '>':
if (readingString) {
processBufferData(); // Do something with the buffer
}
readingString = false; // Finish reading
break;
default: // Anything that's not > or <
// If we are reading the string and the buffer isn't full
if (readingString && charPointer < 78) {
// Add the character to the buffer and increment the pointer
buffer[charPointer++] = incoming;
buffer[charPointer] = 0; // Don't forget to terminate the string
}
}
}
}
</code></pre>
<p>So the reception of a < starts the string reading, the reception of a > stops it and triggers the processing of the string, and anything else (while we are reading the string) gets added to the buffer.</p>
|
14686 | |sensors|hardware|system-design| | Which sensor is best for obstacle detecting with retroreflector? | 2015-08-30T19:42:51.560 | <p>Distance is about 3m. IR or visible light - does not matter.</p>
<p>It is possible that object/obstacle can be shiny, so for correct detection necessary large amount of reflected light.</p>
<p>Maybe for this task better to use specific retroreflector?</p>
<p><strong>UPDATE:</strong></p>
<p>there will be two sensors with distance about 3-4 cm between.
Object must cross 1st sensor's reflector but do not cross the 2nd one.</p>
<p>The scheme of this sensor should be this:
<a href="https://i.stack.imgur.com/TXiTh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TXiTh.png" alt="Scheme of sensor"></a></p>
<p>But the use will be this:</p>
<p><a href="https://i.stack.imgur.com/WYjFY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WYjFY.png" alt="scheme of use"></a></p>
| <p>I think you're better off with a set-up like this.</p>
<p><em>A shiny object might bounce the laser as if it were a mirror.
But we wan't to know if the laser was interrupted.</em></p>
<p>So. If we place the sensor on the other side, we can accurately say if the light reaches the sensor. Thus if there is an object between (shiny or not).</p>
<p><em>But what if another light-source shines into my sensor? It'll think that there is no object.</em></p>
<p>We can encapsulate the sensor, so that only light from the direction of the laser can shine into it. And we can filter out other light "colors".
Also the strength of the laser should be bigger as any other ambien light (not too strong also). You could even choose to make the laser pulse a specific pattern and let the sensor check if it's right.</p>
<p><a href="https://i.stack.imgur.com/QNIRf.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QNIRf.png" alt="enter image description here"></a></p>
|
14692 | |avr| | How to program a CLK signal and its inverse with Arduino/AVR | 2015-08-31T00:48:13.003 | <p>Is it possible to simultaneously output a clock signal and it's inverse using the timer register(s)? </p>
<p>I'm using the following code in arduino to output a 1MHz signal on OC1A:</p>
<pre><code>//Use Timer/Counter1 to generate a 1MHz square wave on Arduino pin 9.
//J.Christensen 27Apr2012
void setup(void)
{
DDRB = _BV(DDB1); //set OC1A/PB1 as output (Arduino pin D9, DIP pin 15)
TCCR1A = _BV(COM1A0); //toggle OC1A on compare match
OCR1A = 7; //top value for counter
TCCR1B = _BV(WGM12) | _BV(CS10); //CTC mode, prescaler clock/1
}
void loop(void)
{
}
</code></pre>
|
<p>How about this?</p>
<pre class="lang-C++ prettyprint-override"><code>void setup()
{
// Defining PB1 and PB2 as outputs by setting PORTB1 and PORTB2
// Setting DDB1 and DDB2
DDRB |= bit (DDB1) | bit (DDB2);
// stop timer 1
TCCR1A = 0;
TCCR1B = 0;
TCCR1A = bit (COM1B0) | bit (COM1B1) // Set OC1B on Compare Match, clear
// OC1B at BOTTOM (inverting mode)
| bit (COM1A1) // Clear OC1A on Compare Match, set
// OC1A at BOTTOM (non-inverting mode)
| bit (WGM11); // Fast PWM, top at ICR1
TCCR1B = bit (WGM12) | bit (WGM13) // ditto
| bit (CS11); // Start timer, prescaler of 8
// Initialize OCR1A = 300 (pulse_width = 150us), OCR1B, and ICR1
ICR1 = 0xFFFF;
OCR1B = 299;
OCR1A = ICR1 - OCR1B;
} // end of setup
void loop()
{
}
</code></pre>
<p>Results on a Uno:</p>
<p><a href="https://i.stack.imgur.com/mc8Sk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mc8Sk.png" alt="Normal and inverted timer output"></a></p>
<p>Output on Uno pins 9 and 10.</p>
<p>Change the prescalers and counters to your desired frequency.</p>
<hr>
<p>The screenshot doesn't show one signal exactly the inverse of the other. The <em>pattern</em> is inverted. If you had a 50% duty cycle, it would be an exact inverse.</p>
<hr>
<blockquote>
<p>It looks good except they overlap (slightly) by 50ns. If I set them to 16 and 8, respectively, they don't overlap but they are slightly asymmetrical</p>
</blockquote>
<p>OK, make OCR1A and OCR1B both 7:</p>
<pre class="lang-C++ prettyprint-override"><code> ICR1 = 15;
OCR1B = 7;
OCR1A = 7;
</code></pre>
<p><em>Why 7? And why 15?</em></p>
<p>The counts are zero-relative. So by counting to 15 on a 16 MHz processor we are actually getting 1/16th of the clock, namely 1 MHz. And half of that is 8 (which, zero-relative, is 7). So we are really doing:</p>
<ul>
<li>Period: 16 ticks of the 16 MHz clock</li>
<li>Duty cycle: 8 ticks of the 16 MHz clock</li>
</ul>
<hr>
<p>Now, one cycle:</p>
<p><a href="https://i.stack.imgur.com/YefHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YefHP.png" alt="Scope shot 1"></a></p>
<p>They change over at the same instant - pulse width exactly 500 ns.</p>
<p><a href="https://i.stack.imgur.com/dNPMd.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dNPMd.png" alt="Scope shot 2"></a></p>
<p>And they change back at the same moment - pulse width also 500 ns.</p>
|
14702 | |arduino-uno|analogread|multiplexer| | Issue with CD74HC4067 MUX on high values | 2015-08-31T06:56:59.760 | <p>I'm having a small issue with the CD74HC4067 multiplexer/demultiplexer: I am using it to receive data from an array of sensors (at the moment I have only 2, but in a near future they will grow). Specifically I have a light sensor and a sound sensor.</p>
<p>Mux output is connected to A0 since the readings I do are analog. The pins I use to switch the channels are A3 and A2 (when the other sensors will arrive also A1 will be dedicated to that).</p>
<p>My problem is that when switching between one channel and another, my readings highly fluctuate, but only when the reading value is > 500 or so, and I don't understand why. In a simple sketch I've tried adding some delay (40 msec) and the issue goes away. But in my project which is far more complex and uses also other analog channels I need a delay of ~1 second to get a correct reading, which is absolutely unacceptable since I need it to run in real-time(ish). I also tried using the digital pins to control the mux but to no avail. The only thing that seems to stabilize everything is connecting a capacitor between the MUX out and ground, and using a 20msec delay, but it only works for a bit.</p>
<p>I hope I've been clear enough and that someone can point me the right way!</p>
<p>EDIT:</p>
<p>Here is the schematic
<a href="https://i.stack.imgur.com/NQGZI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/NQGZI.png" alt="Schematic" /></a></p>
<p>(Error in the drawing: "temp" is actually a "light sensor" as in the bottom of the post...)</p>
<p>And my code:</p>
<pre><code>#define MUX A0
#define S0 A2
#define S1 A3
void setup() {
Serial.begin(9600);
pinMode(S0, OUTPUT);
pinMode(S1, OUTPUT);
selectMux(1);
}
void loop() {
//selectMux(0);
//Serial.println(analogRead(MUX));
//selectMux(1);
Serial.println(analogRead(MUX));
}
void selectMux(byte port) {
// pinMode(MUX, mode);
int r0 = bitRead(port, 0);
int r1 = bitRead(port, 1);
digitalWrite(S0, r0);
digitalWrite(S1, r1);
analogRead(MUX);
}
</code></pre>
<p>the <code>analogRead(MUX)</code> in the selectMux function was added because I read in a post that they suggested to do that in order to get a more accurate reading.
With this code only the results already fluctuate:</p>
<pre><code>Output:
76
41
77
76
76
75
36
75
74
76
77
106
76
76
76
76
</code></pre>
<p>but it goes crazy when the input is higher, close to 5V:</p>
<pre><code>Output:
948
780
340
948
948
635
437
949
948
499
551
949
950
396
684
950
</code></pre>
<p>If you enable the commented code that starts to switch the outputs it is even worse. As I said, adding delays helps, but in my final application I cannot afford to have 1s delays.</p>
<p>I also show that in the circuit there is a timer that uses other Analog pins, but in the code I didn't include that part. If you need I'll add that too.</p>
<p><a href="http://www.dx.com/p/157205" rel="nofollow noreferrer">Sound Sensor</a>,
<a href="http://www.dx.com/p/152409" rel="nofollow noreferrer">Light Sensor</a></p>
| <p>I don't think you should leave s2 and s3 floating. A floating pin does not mean nor 0 nor 1.</p>
<p>Connect them both to ground. </p>
|
14708 | |arduino-mega|motor| | Is Roboteq motor driver compatible with Arduino? | 2015-08-31T12:38:42.890 | <p>I'm planning use Roboteq motor driver for 24V brushed DC motor but I can't be sure that it's true or wrong. You know, Roboteq controller is too expensive and I don't want to spend money in vain. Have you any experience this controller? Are they compatible with Arduino?</p>
<p><a href="http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail" rel="nofollow">http://www.roboteq.com/index.php/roboteq-products-and-services/brushed-dc-motor-controllers/mdc2230-detail</a> Roboteq Controller Link</p>
<p>I also think, Pololu RoboClaw driver. <a href="https://www.pololu.com/product/1499" rel="nofollow">https://www.pololu.com/product/1499</a> I don't know is it enough for wheelchair. Because, I already have used Pololu VNH5019 and it is not enough. (synchronicity and noise problems etc.)</p>
<p>If you have any ideas, I will be glad. Thank you.</p>
| <p>It is not directly supported. But the device description lists RS232 port that can be interfaced with an Arduino using a TTL to RS232 converter. The description also mentions "several Analog, Pulse and Digital I/Os which can be remapped as command or feedback inputs, limit switches, or many other functions" so it is totally possible to control the controller with an Arduino, but depending on the method you choose it may require some effort.</p>
|
14713 | |programming|arduino-mega|c++|signal-processing| | digitalWrite queued signals? | 2015-08-31T16:08:25.937 | <p>I have this simple code who send a signal to a android phone when I press a button:</p>
<pre class="lang-C++ prettyprint-override"><code>const int botonPinD = 8;
const int relayPin = 12;
int retardo = 100;
int finBoton=1000;
void setup() {
pinMode(relayPin, OUTPUT);
pinMode(botonPinA, INPUT);
pinMode(botonPinB, INPUT);
pinMode(botonPinC, INPUT);
pinMode(botonPinD, INPUT);
}
void loop(){
botonD = digitalRead(botonPinD);
if (botonD == HIGH){
// for simplicity remove botonA, botonB and botonC code, but it's the same with a few digitalWrite
digitalWrite(relayPin, HIGH);
delay(retardo);
digitalWrite(relayPin, LOW);
delay(retardo);
digitalWrite(relayPin, HIGH);
delay(retardo);
digitalWrite(relayPin, LOW);
delay(retardo);
digitalWrite(relayPin, HIGH);
delay(retardo);
digitalWrite(relayPin, LOW);
delay(retardo);
digitalWrite(relayPin, HIGH);
delay(retardo);
digitalWrite(relayPin, LOW);
delay(retardo);
delay(finBoton);
}
else{
digitalWrite(relayPin, LOW);
}
}
</code></pre>
<p>But if I press the button fast (maybe a half a second between clicks) I only receive once the signal.</p>
<p>I'm not very sure about what's happened here (I'm an Arduino newbie). The first signal, has it locked the channel? Can signals be queued? Can I control the way that they are queued?</p>
| <p>The code below is closer to what you seem to be asking about:</p>
<pre class="lang-C++ prettyprint-override"><code>// For Mega2560
const int BUTTONS = 4;
const int FIRST_SWITCH = 18;
const int FIRST_RELAY = 41;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20; // ms
int retardo = 300;
int finBoton = 1000;
volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];
void doInterrupts (const int which)
{
// debounce
if (millis () - lastPress [which] < DEBOUNCE_TIME)
return;
lastPress [which] = millis ();
counts [which]++;
} // end of doInterrupts
void pin18Pressed ()
{
doInterrupts (0);
} // end of pin18Pressed
void pin19Pressed ()
{
doInterrupts (1);
} // end of pin19Pressed
void pin20Pressed ()
{
doInterrupts (2);
} // end of pin20Pressed
void pin21Pressed ()
{
doInterrupts (3);
} // end of pin21Pressed
void setup()
{
// configure inputs / outputs
for (int i = 0; i < BUTTONS; i++)
{
pinMode (FIRST_SWITCH + i, INPUT_PULLUP);
pinMode (FIRST_RELAY + i, OUTPUT);
}
attachInterrupt (5, pin18Pressed, FALLING);
attachInterrupt (4, pin19Pressed, FALLING);
attachInterrupt (3, pin20Pressed, FALLING);
attachInterrupt (2, pin21Pressed, FALLING);
} // end of setup
// turn relay on for a particular switch
void handleSwitchPress (const int which)
{
for (int i = 0; i < CLICKS; i++)
{
digitalWrite(FIRST_RELAY + which, HIGH);
delay(retardo);
digitalWrite(FIRST_RELAY + which, LOW);
delay(retardo);
}
delay(finBoton);
} // end of handleSwitchPress
// main loop
void loop()
{
for (int i = 0; i < BUTTONS; i++)
if (counts [i] > 0)
{
handleSwitchPress (i);
counts [i]--;
}
} // end of loop
</code></pre>
<hr>
<p>I'll explain parts of it from above:</p>
<h3>Interrupts</h3>
<p>To queue up switch presses we can use an interrupt. The Mega has quite a few external interrupts (See: <a href="https://www.arduino.cc/en/Reference/AttachInterrupt" rel="nofollow">attachInterrupt()</a>) so I'll use those. You can read about interrupts on my page about interrupts.</p>
<p>This code attaches four interrupts handlers:</p>
<pre class="lang-C++ prettyprint-override"><code> attachInterrupt (5, pin18Pressed, FALLING);
attachInterrupt (4, pin19Pressed, FALLING);
attachInterrupt (3, pin20Pressed, FALLING);
attachInterrupt (2, pin21Pressed, FALLING);
</code></pre>
<p>Because of the way the hardware works we have to use pins 18, 19, 20 and 21 (there are a couple more but these are in sequence).</p>
<p>I set the switches to be INPUT_PULLUP so that they are normally HIGH when not pressed, and go LOW when you press them. Hence the interrupts are looking for a FALLING edge.</p>
<hr>
<h3>Handle one interrupt</h3>
<p>An interrupt handler is like this:</p>
<pre class="lang-C++ prettyprint-override"><code>void pin18Pressed ()
{
doInterrupts (0);
} // end of pin18Pressed
</code></pre>
<p>Since they all do much the same thing I put all of the switch management into one function and used an array of switches, like this:</p>
<pre class="lang-C++ prettyprint-override"><code>volatile byte counts [BUTTONS];
unsigned long lastPress [BUTTONS];
void doInterrupts (const int which)
{
// debounce
if (millis () - lastPress [which] < DEBOUNCE_TIME)
return;
lastPress [which] = millis ();
counts [which]++;
} // end of doInterrupts
</code></pre>
<p>In order to "queue" presses the interrupt handler adds one to a counter, for that array item. (So, pin 18 is position 0, pin 19 is position 1 and so on).</p>
<hr>
<h3>Debouncing</h3>
<p>Debouncing of the switches is done by ignoring multiple presses in quick succession:</p>
<pre class="lang-C++ prettyprint-override"><code> // debounce
if (millis () - lastPress [which] < DEBOUNCE_TIME)
return;
lastPress [which] = millis ();
</code></pre>
<hr>
<h3>Handling a queued press</h3>
<p>Now in the main loop we just check if the counter has gone up, for each switch:</p>
<pre class="lang-C++ prettyprint-override"><code> for (int i = 0; i < BUTTONS; i++)
if (counts [i] > 0)
{
handleSwitchPress (i);
counts [i]--;
}
</code></pre>
<p>If so, we call <code>handleSwitchPress</code> which toggles the relay for the desired number of times.</p>
<hr>
<h3>Code for Uno</h3>
<p>If you are using a Uno instead of a Mega2560 you don't have four external interrupts. The alternative version below uses <em>pin change interrupts</em> instead of external interrupts. </p>
<p>Pin change interrupts work on all pins of the Uno, however they are in batches of three: Pins A0 to A5, pins D0 to D7 and pins D8 to D13. In the code below I use pins 2, 3, 4 and 5 which are in the batch D0 to D7.</p>
<p>With a pin-change interrupt you only get notification of a <em>change</em> to the pin, so the code has to detect whether the pin changed from high to low or low to high.</p>
<pre class="lang-C++ prettyprint-override"><code>// For Atmega328 (eg. Uno)
const int BUTTONS = 4;
const int FIRST_BUTTON = 2;
const int FIRST_RELAY = 8;
const int CLICKS = 5;
const unsigned long DEBOUNCE_TIME = 20; // ms
int retardo = 300;
int finBoton = 1000;
volatile bool oldState [BUTTONS];
volatile byte counts [BUTTONS];
unsigned long lastPress;
// handle pin change interrupt for D0 to D7 here
ISR (PCINT2_vect)
{
// debounce
if (millis () - lastPress < DEBOUNCE_TIME)
return;
lastPress = millis ();
// check each switch
for (int i = 0; i < BUTTONS; i++)
{
byte state = digitalRead (FIRST_BUTTON + i);
if (state != oldState [i])
{
oldState [i] = state; // detect state changes
if (state == LOW)
counts [i]++;
} // end of state change
} // end of for each button
} // end of PCINT2_vect
void setup()
{
// configure inputs / outputs
for (int i = 0; i < BUTTONS; i++)
{
pinMode (FIRST_BUTTON + i, INPUT_PULLUP);
oldState [i] = HIGH;
pinMode (FIRST_RELAY + i, OUTPUT);
}
// pin change interrupt (example for D9)
PCMSK2 |= bit (PCINT18) | bit (PCINT19) | bit (PCINT20) | bit (PCINT21); // want pins 2, 3, 4, 5
PCIFR |= bit (PCIF2); // clear any outstanding interrupts
PCICR |= bit (PCIE2); // enable pin change interrupts for D0 to D7
} // end of setup
// turn relay on for a particular switch
void handleSwitchPress (const int which)
{
for (int i = 0; i < CLICKS; i++)
{
digitalWrite(FIRST_RELAY + which, HIGH);
delay(retardo);
digitalWrite(FIRST_RELAY + which, LOW);
delay(retardo);
}
delay(finBoton);
} // end of handleSwitchPress
// main loop
void loop()
{
for (int i = 0; i < BUTTONS; i++)
if (counts [i] > 0)
{
handleSwitchPress (i);
counts [i]--;
}
} // end of loop
</code></pre>
|
14718 | |arduino-uno|serial|arduino-mega|adafruit| | Execute Code sent over Serial | 2015-08-31T19:16:55.830 | <p>I was wondering if its possible to send code to the Arduino, and then have it execute this code. </p>
<p>What I'm trying to do is use an Arduino Mega with a bunch of stuff connected to it send code to an Uno with a TFT LCD display to do whatever the Mega tells it to do with the Adafruit GFX Library. I want to add things to this 'system' gradually so I want the whole program hosted on the Arduino Mega, and a minimal amount of code on the Uno.</p>
<p>Sorry I'm really new at this so if its not possible at all let me know!<br>
Thanks in advance,</p>
<p>-Will</p>
| <p>No, it's not possible as you describe it.</p>
<p>The Arduino's main chip, the ATMega328p, is what is known as <em>Harvard Architecture</em>. This means that the Flash memory and RAM both occupy completely separate memory address spaces. The CPU in the chip is only able to fetch its instructions from the memory space the Flash is connected to (the <em>Instruction Bus</em>) and not the memory space the RAM is connected to (the <em>Data Bus</em>). This means it can only run instructions that are in Flash and not RAM.</p>
<p>It is possible to re-program the flash on the fly - after all, that's what the bootloader does, and while the actual act of reprogramming flash is fairly trivial, generating the instructions in the right way is far from trivial.</p>
<p>There are other options though.</p>
<ol>
<li>Use an interpreted language. I believe there are versions of BASIC available for the Arduino that would allow you to upload a program through the serial port and execute it.</li>
<li>Define a protocol (or use an existing protocol) to send pre-defined control commands to the Uno. Firmata might be of use here.</li>
</ol>
|
14725 | |avr| | Optimizing an Arduino code | 2015-08-31T22:42:09.187 | <p>I am working on project and using Arduino Pro Mini (Atmega328p running on 2xAA) to measure the time to charge a capacitor (when the volt level is high). This is the code I used while testing:</p>
<pre><code>int counter = 0;
// Charge the capacitor
digitalWrite(8,HIGH);
while (digitalRead(7) == LOW) {
counter = counter +1;
if (counter > 250) {
break; // CHARGING FAILED!
}
}
</code></pre>
<p>The code was working fine when the board was running at 16MHz since the loop was fast enough to give good result. ( counter =~ 28 when the test cap is charged). </p>
<p>However, the intention is to run the system on a battery with clock of 1MHz (to reduce power consumption) and when tested at that speed the counter only reaches 2~3 because the loop it too slow now that the cap will charge in about two to three cycles.</p>
<p>So I did two changes which are using byte instead of int for the counter, and reading the value of the pin directly from the PIND register:</p>
<pre><code>byte counter = 0;
// Charge the capacitor
digitalWrite(8,HIGH);
while ((PIND & (1<<PD7)) == 0) {
counter = counter +1;
if (counter > 250) {
break; // CHARGING FAILED!
}
}
</code></pre>
<p>Both of these changes increased the speed and now counter reads ~20 which is much better and almost close to the 16MHz.</p>
<p>Is there any further optimizations?</p>
<p>Can I use one of the general registers instead of the counter, if yes then how? and will that improve the speed?</p>
<p>Is there a more clever and faster way to do this loop?</p>
<hr>
<ul>
<li>Update:</li>
</ul>
<p>I am going to follow the suggested answer and use the analog comparator, but I also wanted to add to my finding which might help others with general optimization.</p>
<p>Instead of incrementing the counter and comparing if it is larger than some value, it is faster to decrements and compare if it is equal to zero. The counter improved to ~23.</p>
|
<p>It looks like Ignacio Vazquez-Abrams and I have been doing similar things. :)</p>
<p>I have a page about making a capacitor tester:</p>
<p><a href="http://www.gammon.com.au/forum/?id=12075" rel="nofollow noreferrer">Turn your Arduino into a capacitor tester</a></p>
<p>However since link-only replies are frowned on (the link might go down) I'll summarize it here.</p>
<p>The simple approach is to charge the capacitor until it reaches 63.2% of the charging voltage.</p>
<p>That is because:</p>
<pre class="lang-C++ prettyprint-override"><code>1 - e^(-1) = 0.63212
</code></pre>
<p>See <a href="http://en.wikipedia.org/wiki/RC_time_constant" rel="nofollow noreferrer">RC Time constant - Wikipedia</a>.</p>
<p>We can use the Analog Comparator to trigger an interrupt when the voltage reaches that level.</p>
<p>We need the capacitor to be on pin D6 on the Uno and a reference voltage on pin D7.</p>
<p>See <a href="http://www.gammon.com.au/forum/?id=11916" rel="nofollow noreferrer">Using the Arduino Analog Comparator</a> for more details about the Analog Comparator.</p>
<p>This is much faster than using analogRead, because it triggers on an exact voltage.</p>
<p>Your basic objective is to find how long it takes to reach 63.2% of the supplied voltage (in the example being 1 volt):</p>
<p><a href="https://i.stack.imgur.com/3uMaN.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3uMaN.png" alt="Capacitor tester 1"></a></p>
<p>In this particular example it took 47 µs for a 47 nF capacitor:</p>
<p><a href="https://i.stack.imgur.com/K1r42.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/K1r42.png" alt="Capacitor tester 2"></a></p>
<p>Instead of using an exact reference voltage (ie. 63.2% of 5 volts) you can do some fancy maths instead. Here is my test circuit:</p>
<p><a href="https://i.stack.imgur.com/snZkL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/snZkL.png" alt="Capacitor test circuit"></a></p>
<p><em>DUT = Device Under Test</em></p>
<p>We plug the values of the resistors into the code like this:</p>
<pre class="lang-C++ prettyprint-override"><code>const float Rc = 10000; // charging resistor
const float R1 = 1000; // between ground and D7
const float R2 = 1800; // between +5V and D7
const float clockRate_us = 16; // 16 MHz
const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));
</code></pre>
<p><strong>Note</strong>: For high accuracy you should use the <em>measured</em> resistance values, not just the nominal ones.</p>
<hr>
<p>Now with some fairly simple code we can use the constant <strong>k</strong> to work out the capacitance:</p>
<pre class="lang-C++ prettyprint-override"><code>/*
Capacitance meter
Author: Nick Gammon
Date: 2 July 2013
Pulse pin (D2): Connect to capacitor via 10K resistor (Rc)
Reference voltage connected to D7 (AIN1) as per below.
Measure pin (D6 - AIN0) connected to first leg of capacitor, other leg connected to Gnd.
Like this:
Capacitor to test:
D2 ----> Rc ----> D6 ----> capacitor_under_test ----> Gnd
Reference voltage:
+5V ----> R2 ---> D7 ---> R1 ----> Gnd
*/
const byte pulsePin = 2; // the pin used to pulse the capacitor
const float Rc = 10000; // charging resistor
const float R1 = 1000; // between ground and D7
const float R2 = 1800; // between +5V and D7
const float clockRate_us = 16; // 16 MHz
const float k = 1000 / (clockRate_us * Rc * log ((R1 + R2) / R2));
volatile boolean triggered;
volatile boolean active;
volatile unsigned long timerCounts;
volatile unsigned long overflowCount;
ISR (TIMER1_OVF_vect)
{
++overflowCount; // count number of Counter 1 overflows
} // end of TIMER1_OVF_vect
ISR (TIMER1_CAPT_vect)
{
// grab counter value before it changes any more
unsigned int timer1CounterValue;
timer1CounterValue = ICR1; // see datasheet, page 117 (accessing 16-bit registers)
unsigned long overflowCopy = overflowCount;
if (active)
{
// if just missed an overflow
if ((TIFR1 & bit (TOV1)) && timer1CounterValue < 0x7FFF)
overflowCopy++;
// calculate total count
timerCounts = (overflowCopy << 16) + timer1CounterValue; // each overflow is 65536 more
triggered = true;
digitalWrite (pulsePin, LOW); // start discharging capacitor
TCCR1B = 0; // stop the timer
} // end if active
} // end of TIMER1_CAPT_vect
void setup ()
{
pinMode (pulsePin, OUTPUT);
digitalWrite (pulsePin, LOW);
Serial.begin (115200);
Serial.println ("Started.");
ADCSRB = 0; // (Disable) ACME: Analog Comparator Multiplexer Enable
ACSR = bit (ACIC); // Analog Comparator Input Capture Enable
DIDR1 |= bit (AIN1D) | bit (AIN0D); // Disable digital buffer on comparator inputs
PRR = 0;
} // end of setup
void startTiming ()
{
active = true;
triggered = false;
noInterrupts ();
// prepare timer
overflowCount = 0; // no overflows yet
// reset Timer 1
TCCR1A = 0;
TCCR1B = 0;
TCNT1 = 0; // Counter to zero
// Timer 1 - counts clock pulses
TIMSK1 = bit (TOIE1) | bit (ICIE1); // interrupt on Timer 1 overflow and input capture
// get on with it
digitalWrite (pulsePin, HIGH); // start charging capacitor
// start Timer 1, no prescaler
TCCR1B = bit (CS10) | bit (ICES1); // plus Input Capture Edge Select
interrupts ();
} // end of startTiming
void finishTiming ()
{
active = false;
Serial.print ("Capacitance = ");
float capacitance = (float) timerCounts * k;
Serial.print (capacitance);
Serial.println (" nF");
triggered = false;
delay (3000);
} // end of finishTiming
void loop ()
{
// start another test?
if (!active)
startTiming ();
// if the ISR noted the time interval is up, display results
if (active && triggered)
finishTiming ();
} // end of loop
</code></pre>
<hr>
<p>For extra accuracy the code uses the Input Capture Unit, which is something that remembers the exact value in Timer 1 when the match occurs. This avoids the delay of 2 to 3 µs while the ISR kicks into action.</p>
<hr>
<h3>Results</h3>
<p>I measured a few values using a capacitance-substitution box. To check on the box I measured also with a high-precision multimeter. The value on the right is what the sketch gave (rounded).</p>
<p><em>(All values in nF)</em></p>
<pre class="lang-C++ prettyprint-override"><code>Nominal Meter Sketch
Value Measure Measure
40 42 42
100 98 102
200 202 201
300 312 313
400 389 391
1000 1004 1010
2000 2011 2012
3000 2950 2953
4000 4160 4170
</code></pre>
<p>The sketch output certainly seems to be close to the nominal and measured values.</p>
<hr>
<blockquote>
<p>What about using the internal voltage reference (1.1v) instead of AIN0? which one will be better as the 2xAA batteries voltage drops over time?</p>
</blockquote>
<p>The voltage doesn't matter as it is not in the equation. It is the <strong>ratio</strong> that matters, and that will scale with battery drop (ie. the ratio between the two resistors will always be the same).</p>
<p>You need to use Vcc because it is turned on and off at an output pin (to start charging the capacitor).</p>
<hr>
<blockquote>
<p>Also what is the difference between TIMER1_CAPT_vect which you used here and ANALOG_COMP_vect which you used in the example in your site? </p>
</blockquote>
<p>If you are <strong>not</strong> using the Input Capture Unit, then you need to get the Analog Comparator interrupt. However if you use the Input Capture Unit then you use the Timer1 Capture Event which is triggered when you get the capture.</p>
|
14734 | |arduino-uno|audio| | Microphone input into Arduino uno R3 | 2015-09-01T16:35:59.837 | <p>I have an amplifier circuit for a microphone.The output of the circuit(the microphone signal amplified) is connected to the arduino A0 .Now the circuit works(I think ,the output voltage is 4.30 V) and the arduino serial monitor output 875 874... fluctuates with one or 1,2 or more points.The problem is that this value just goes down from 875....800.... .</p>
<p>Is it a correct value?(circuit taken from here <a href="http://wiring.org.co/learning/basics/microphone.html" rel="nofollow">http://wiring.org.co/learning/basics/microphone.html</a>)</p>
<p>EDIT: If I put my finger on it the values go up a bit like 792 ,794,800</p>
| <p>The amplifier circuit you refer to puts out 2.5 volts even without input from microphone. The LM386 has internal circuitry to make the output 1/2 of the +5 volts. Then, audio signal goes above and below the 2.5 volts.</p>
<p>The amplifier circuit will only be putting out the PEAK of your audio signal (because D1 and C2 is a peak detector) </p>
<p>So, when all is quiet, take that ADC value as meaning zero microphone input. </p>
|
14737 | |wifi|communication| | How can I configure Arduino after programming it (for post upload wifi configuration)? | 2015-09-01T19:17:42.040 | <p>I would like to make a device that can take a photo, and send it to a website over wifi. I'm using an Arduino Uno, a ArduCam OV2640 module, and ESP8266 Serial WIFI module. Eventually I'd like to take it off the board as a stand alone project for permanent use. </p>
<p>The wifi works fine, but requires a serial communication to configure. I would like to make it so that I can plug the device into a computer (via something like micro usb), change the WIFI settings, and save those settings for future reboots.</p>
<p>If there anyway I can do this with an Arduino interface? If not, what could I use instead?</p>
| <p>I like Gerben's suggestion about putting the ESP8266 into Wireless Access Point mode and then providing access to your configuration settings via a web interface. I've been dealing with the same question myself and this might be a workable solution. The only downside is the amount of code required to get an ESP8266 to function as a WAP, provide a web-based UI, switch between configuration and running mode, etc.</p>
<p>Another idea that isn't as elegant, but would require a lot less code: Just store your configuration on an SD card, and add an SD card to your project using a separate board or shield. You could edit the configuration by plugging it into a PC and editing the configuration file, then plug the card into your project which would read its configuration from the SD Card.</p>
|
14754 | |arduino-uno|c++|debounce| | Can anyone identify why this incrementer is losing count? | 2015-09-02T14:15:03.823 |
<p>I am working on a project where the end result is to count the number of cycles of a moving piece of metal using an inductive sensor.</p>
<p>For now I am using an Arduino Uno and have created a breadboard version for testing. The sensor has been replaced by a momentary push button. To check the count data I am viewing the number using Serial Monitor</p>
<p>All the elements of this set-up are working, apart from one major issue. When pressing the button the incrementer (++) occasionally adds 2 instead of 1 from only one button press. As a rough guide to the error frequency, it seems to count 11 for every 10 button presses. The error has never presented as not counting enough.</p>
<p>I am new to software, as such I cannot seem to see the error</p>
<p>Any help and guidance would be greatly appreciated</p>
<p>Here is the code I have written so far:</p>
<pre class="lang-C++ prettyprint-override"><code>//Libraries
#include <EEPROM.h>
//Constants
const int counterPin = 2; //Input from counter (looking for HIGH as external pulldown resistor is used)
const int EEPROMadress = 3; //holds the EEPROM address
//Variables
int counterState = 0; //current button state
int counterStatePrv = 0; //previous button state
int storedValue;
int presetCount = 100;
unsigned long countNumber; //unsigned 32bit variable
void setup() {
for (int i = 0; i < 255; i++) {
// this performs as EEPROM.write(i, i)
EEPROM.update(i, i);
}
for (int i = 0; i < 255; i++) {
// write "presetCount" value to cell "EEPROMaddress" only the first time
// will not write the cell the remaining 254 times
EEPROM.update(EEPROMadress, presetCount);
}
pinMode(counterState, INPUT);
Serial.begin(9600);
countNumber = EEPROM.read(3); //Start the counter at the presetCount value
}
void loop() {
counterState = digitalRead(counterPin); //Read the status of the counter input
storedValue = EEPROM.read(EEPROMadress);
if (counterState != counterStatePrv) { //check that pulse went off
if (counterState == HIGH) { //check for pulse
countNumber++; //increment (add 1) to the stored count value
delay(10);
Serial.print("Count Value: ");
Serial.println(countNumber);
Serial.print("Stored Value: ");
Serial.println(storedValue);
Serial.println();
}
}
counterStatePrv = counterState;
}
</code></pre>
| <p>Buttons bounce (at least they appear to, electrically), meaning that if you're fast enough, you can detect multiple pulses per button-press. Usually we don't count the button as being pressed until we read the same value {n} times in a row or for {m} mSec, or some similar technique. </p>
<p>Because you call <code>EEPROM.read()</code> immediately after testing the button, perhaps most times the bouncing will have ceased when the call returns, but once in a while one last bounce slips through. </p>
<p>Nick Gammon, a regular contributer here, has a good discussion of <a href="http://www.gammon.com.au/switches" rel="nofollow">de-bouncing</a> on his web site. Have a look at that and pick a technique that's compatible with what you're trying to do.</p>
|
14763 | |c++|struct| | Assigning value inside structure array outside setup and loop functions | 2015-09-02T20:02:23.707 | <p>I'm having some difficulty assigning a value to a variable in a struct array outside the loop and setup functions. Assigning a value to an int or char array works completely fine but this doesn't. </p>
<p>The example code and error message returned after trying to compile are below. Any help is greatly appriciated. Thanks</p>
<pre><code>void setup()
{
}
struct trap_game_detail {
byte flush_quantity;
byte flush_interval;
byte random_min;
byte random_max;
byte random_quantity;
} trap_game_details[2];
trap_game_details[0].random_min = 1;
void loop()
{
}
</code></pre>
<p>src/sketch.ino:13:5: error: ‘trap_game_details’ does not name a type
trap_game_details[0].random_min = 1;
^
.build/uno/Makefile:166: recipe for target '.build/uno/src/sketch.o' failed</p>
| <blockquote>
<p>Assigning a value to an int or char array works completely fine but this doesn't. </p>
</blockquote>
<p>It only works fine if you do it on the declaration.</p>
<p>eg.</p>
<p>This works:</p>
<pre><code>int foo = 42; < ---- declare and define with initial value
</code></pre>
<p>This doesn't:</p>
<pre><code>int foo; // < ---- declare and define
foo = 42; // < ---- assignment statement
</code></pre>
<p>Your code was like the second example.</p>
<hr>
<p>Majenko has shown one way. He split the declaration into two parts. The first part declared the <strong>type</strong> trap_game_detail, and the second part is an <strong>instance</strong> of that type, like this:</p>
<pre><code>struct trap_game_detail {
byte flush_quantity;
byte flush_interval;
byte random_min;
byte random_max;
byte random_quantity;
};
struct trap_game_details trap_game_details[2] = {
{ 10, 5, 1, 100, 4 },
{ 8, 23, 5, 95, 8 }
};
</code></pre>
<hr>
<p>Alternatively, and a bit closer to what you were doing, just keep going with the initialization values after you define the structure, like this:</p>
<pre><code>struct trap_game_detail {
byte flush_quantity;
byte flush_interval;
byte random_min;
byte random_max;
byte random_quantity;
} trap_game_details[2] =
{
{ 10, 5, 1, 100, 4 },
{ 8, 23, 5, 95, 8 }
};
</code></pre>
|
14790 | |power| | Stepper Motor Power Supply | 2015-09-03T16:24:04.787 | <p>Just a quick question. Picking up some stepper motors, but confused at what voltage/current things are running off.</p>
<p>Ordering:<br>
2 x <a href="https://www.sparkfun.com/products/9238" rel="nofollow">Stepper Motor</a><br>
2 x <a href="https://www.sparkfun.com/products/12779" rel="nofollow">EasyDriver</a></p>
<p>An article says</p>
<blockquote>
<p>You need some 12V source to the EasyDriver (the motor in this article
is 12V) - This will be powering the stepper - Im using a 12V adapter -
similar to the one in the illustration. Just make sure it is rated at
least 750ma - A higher rating is better, and just means it wont burn
out.</p>
</blockquote>
<p>So does that mean if I got a plug which is regulated 12V 1A and powered the Arduino from that I could power a rail with VIN pin and that would safely supply the EasyDrivers? And I could then use the 5V pin to power everything else?</p>
<p>Just don't want to break anything! Thanks</p>
| <p>Stepper Motor Control - one step at a time</p>
<p>This program drives a unipolar or bipolar stepper motor.<br>
The motor is attached to digital pins 8 - 11 of the Arduino.</p>
<p>The motor will step one step at a time, very slowly. You can use this to test that you've got the four wires of your stepper wired to the correct pins. If wired correctly, all steps should be in the same direction.</p>
<p>Use this also to count the number of steps per revolution of your motor, if you don't know it. Then plug that number into the oneRevolution example to see if you got it right.</p>
<pre class="lang-cpp prettyprint-override"><code>#include <Stepper.h>
const int stepsPerRevolution = 200; // change this to fit the number of steps per revolution
// for your motor
// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);
int stepCount = 0; // number of steps the motor has taken
void setup() {
// initialize the serial port:
Serial.begin(9600);
}
void loop() {
// step one step:
myStepper.step(1);
Serial.print("steps:");
Serial.println(stepCount);
stepCount++;
delay(500);
}
</code></pre>
|
14791 | |serial|rs485| | How can I get a unique address for all my Arduino boards while in RS485? | 2015-09-03T16:49:07.837 | <p>My attempt is to know how to identify the board I'll be sending parameters to in a serial connection like rs485. I'm asking because I will have about 11 or so mcu's as "Rx slaves" while my pc is the Master "Tx". I want to know how my code block is being sent to a specific board will be received by just that board and not all the other boards connected to that Rx port COM? </p>
<p>If I send 'LT2|LP3|LM5|LR4|LI6' and I want that to be for one specific Arduino, I don't want all the other 10 arduinos to take those parameters in this serial Rx line.</p>
<p>@Federico Fissore you mentioned in another post "Some boards, when connected to a computer, publish their serial number. My Arduino Uno R3 says"</p>
<pre><code>[16818.451423] usb 3-2: SerialNumber: 85235353137351E02242
</code></pre>
<p>how and where can i find this info? </p>
|
<blockquote>
<p>I dont think that could have sounded more advanced for me then anything thus far. Any links on how to go about that? </p>
</blockquote>
<p>First, run a sketch like this for each board:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <EEPROM.h>
const int SERIAL_NUMBER_ADDRESS = 1023;
const byte SERIAL_NUMBER = 42;
void setup ()
{
// don't do it if it has been done before
if (EEPROM.read(SERIAL_NUMBER_ADDRESS) != SERIAL_NUMBER)
EEPROM.write(SERIAL_NUMBER_ADDRESS, SERIAL_NUMBER);
} // end of setup
void loop () { }
</code></pre>
<p>The serial number <strong>address</strong> can be any address in range for that chip - a Uno has 1024 bytes. I chose 1023 to leave the other addresses free, but it could be 0. Anything you don't need for any other purpose.</p>
<p>Then write a different serial number to each board (eg. 42, 43, 44, 45). Obviously you change the sketch each time you upload to a different board.</p>
<hr>
<p>Once you have done this (once per board) now each board "knows" its serial number. You can detect this in your main sketch:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <EEPROM.h>
const int SERIAL_NUMBER_ADDRESS = 1023;
byte serialNumber;
void setup ()
{
Serial.begin (115200);
Serial.println ();
serialNumber = EEPROM.read(SERIAL_NUMBER_ADDRESS);
Serial.print (F("Serial number of this board is: "));
Serial.println (int (serialNumber));
} // end of setup
void loop () { }
</code></pre>
<p>Output for me in this case was:</p>
<pre class="lang-none prettyprint-override"><code>Serial number of this board is: 42
</code></pre>
<hr>
<p>Also I have a post about <a href="http://www.gammon.com.au/forum/?id=11428" rel="nofollow">RS485</a> on my forum.</p>
|
14794 | |arduino-mega|pins|analogread|digital-in| | Are there any Analog pins on the mega that can not be used as Digital? | 2015-09-03T18:27:00.797 | <p>I am using both Arduino nano and Arduino mega boards in my projects. I got a nasty surprise the other day when I learned that, on the nano, Analog pins 6 and 7 can not be used as digital pins.</p>
<p>Are there any Analog pins on the mega that can not be used as Digital?</p>
| <p>No, the ATmegaXXX0 has no analog pins without GPIO capability.</p>
<p>Additionally, the ATmegaXX8P<strong>B</strong> <em>adds</em> GPIO capability to the other analog pins plus a couple of the supply pins, so if you can convince someone to slip one of those on instead then you will gain two GPIOs (a respin will be required to access the ones on supply pins). Note that the core will also need to be modified, but it's only a couple of quick changes.</p>
|
14803 | |arduino-uno|sensors|led|c++| | Running both sensor and addressable LED strips at a same time? | 2015-09-04T00:43:17.163 |
<p>I'm trying to obtain the sensors' readings as well as making the LED strips to light up at this particular pattern, if the sensor readings reaches certain values. But since both of these codes are inside the void <code>loop()</code>, there will be a problem. How can I do this correctly?</p>
<pre class="lang-C++ prettyprint-override"><code>void loop()
{
currentSensorReading = analogRead(sensorPin);
Serial.println(currentSensorReading );
if(currentSensorReading is in range of certain values){
rainbowCycle(20);
} else { turn LEDs off }
}
void rainbowCycle(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
for(i=0; i< strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}
strip.show();
delay(wait);
}
}
</code></pre>
|
<p>Rewrite without using <code>delay()</code>. Or alternatively, do the test inside the <code>for</code> loop as well, eg.</p>
<pre class="lang-C++ prettyprint-override"><code>void rainbowCycle(uint8_t wait) {
uint16_t i, j;
for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
for(i=0; i< strip.numPixels(); i++) {
strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
}
strip.show();
delay(wait);
// ----------- ADD THESE THREE LINES ---------------
currentSensorReading = analogRead(sensorPin);
if(currentSensorReading is NOT in range of certain values)
return;
}
}
</code></pre>
|
15814 | |arduino-uno|serial| | Arduino reads bogus from serial | 2015-09-04T12:30:33.713 | <p>Recently I've started playing around with an Arduino Uno (rev 3), and I've set up a communication bridge between the Arduino and my computer using Python. So I send a command in Python ("ping" for instance), which is then read and interpreted. I've had it working before, using the Python commands to control a motor, but today it became non-responsive. However, only if I boot the serial monitor from the Arduino IDE, it suddenly accepts my commands again. Further inspection reveals that the Arduino is probably reading empty or corrupted data, interpreting it as <code>ð</code>, <code>à</code> and <code>ÿ</code> and such.</p>
<p>Here is an excerpt of the Python code I'm using:</p>
<pre><code>import sys, glob, serial, time, re
class interface:
timeout = 2 # 10 second time-out
def __init__(self):
port = "/dev/ttyACM0"
self.connect(port)
pass
def connect(self, port="/dev/ttyACM0"):
global arduino
arduino = serial.Serial(port, baudrate=115200, bytesize=8, parity=serial.PARITY_NONE, stopbits=1, timeout=0.1) # Establishing connection
time.sleep(3) # Allowing the connection to settle
arduino.flush()
print "Connection established..."
def ping(self):
arduino.flush()
arduino.write("ping")
msg = self.listen_arduino()
print msg
if msg == "ping_ok":
print "pinged"
return True
return False
def listen_arduino(self):
timeout = self.timeout
matcher = re.compile("\n")
buff = ""
t0 = time.time()
buff += arduino.read(128)
while (time.time() - t0) < timeout and (not matcher.search(buff)):
buff += arduino.read(128)
return buff.strip()
</code></pre>
<p>And here is the Arduino C code:</p>
<pre><code>String readString;
void setup() {
Serial.begin(115200); // use the same baud-rate as the python side
}
void loop() {
readString = listen(); // listen for any commands
if (readString.length() > 0) {
Serial.println(readString); // print the command
if(readString == "ping") {
Serial.write("ping_ok");
}
}
}
String listen() {
String readString;
while (!Serial.available());
while (Serial.available()) {
delay(1); // Allow the buffer to fill
if (Serial.available() > 0) {
char c = Serial.read();
readString += c;
}
}
return readString;
}
</code></pre>
<p>I suspect there is something fishy with the connection I'm making on the Python side, as the Arduino IDE serial monitor works just fine. I hope anyone can spot the problem in this code, I'm willing to provide more details on request.</p>
<p>Thanks</p>
| <p>I've discovered that there was another program trying to access the Arduino, interfering with the code above and causing corruption of the signal. After terminating the intrusive program, the code worked just fine.</p>
|
15815 | |arduino-uno|programming|frequency|sound| | How to use a grove speaker without using delayMicroseconds? | 2015-09-04T12:30:59.900 | <p>is there another way to replace <strong>delayMicroseconds(BassTab[note_index])</strong> as I cannot have delays in my loop due to the need of having multi-tasking in my sketch.</p>
<p>Grove speaker: <a href="http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html" rel="nofollow">http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html</a></p>
<pre><code>/*macro definition of Speaker pin*/
#define SPEAKER 8
int BassTab[]={1911,1702,1516,1431,1275,1136,1012};//bass 1~7
void setup()
{
pinMode(SPEAKER,OUTPUT);
digitalWrite(SPEAKER,LOW);
}
void loop()
{
sound(5);
delay(5000); //Wait 5second and play the sound again
}
void sound(uint8_t note_index)
{
for(int i=0;i<100;i++)
{
digitalWrite(SPEAKER,HIGH);
delayMicroseconds(BassTab[note_index]);
digitalWrite(SPEAKER,LOW);
delayMicroseconds(BassTab[note_index]);
}
}
</code></pre>
| <p>It's just a small amplifier and speaker - what you put into the SIG pin gets amplified and sent out the speaker.</p>
<p>Instead of doing the audio generation manually like that I would suggest using the <code>tone()</code> function which will generate an audio tone at a desired frequency in the background.</p>
<ul>
<li><a href="https://www.arduino.cc/en/Reference/Tone" rel="nofollow">https://www.arduino.cc/en/Reference/Tone</a></li>
</ul>
|
15817 | |arduino-uno|programming|led|c++|digital| | How to blink a series of LED alternately only one at a time | 2015-09-04T13:58:13.777 | <p>I am very much new to Arduino. I recently bought an adruino uno. i can blink an LED alternately. Such as, 1st blink red, then blink green, then blue like that. once only one LED should blink. </p>
<p>I have provided the code blinking an LED. How to modify this to blink multiple LED one after another.</p>
<pre><code>void setup() {
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
</code></pre>
|
<p>You could always copy and paste:</p>
<pre class="lang-C++ prettyprint-override"><code>void setup() {
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}
void loop() {
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(13, HIGH);
delay(1000);
digitalWrite(13, LOW);
delay(1000);
}
</code></pre>
<hr>
<p>A bit better would be to learn about functions:</p>
<pre class="lang-C++ prettyprint-override"><code>void setup() {
pinMode(11, OUTPUT);
pinMode(12, OUTPUT);
pinMode(13, OUTPUT);
}
void blink (const byte which)
{
digitalWrite(which, HIGH);
delay(1000);
digitalWrite(which, LOW);
delay(1000);
} // end of blink
void loop() {
blink (11);
blink (12);
blink (13);
}
</code></pre>
<hr>
<p>And you could learn about loops:</p>
<pre class="lang-C++ prettyprint-override"><code>void setup() {
for (int i = 11; i <= 13; i++)
pinMode(i, OUTPUT);
}
void blink (const byte which)
{
digitalWrite(which, HIGH);
delay(1000);
digitalWrite(which, LOW);
delay(1000);
} // end of blink
void loop() {
for (int i = 11; i <= 13; i++)
blink (i);
}
</code></pre>
<hr>
<p>There is a whole world of stuff to learn. Enjoy the process!</p>
|
15818 | |arduino-uno|led|sound| | Speaker not producing the right sound after a led strip was introduced | 2015-09-04T14:13:17.283 | <ul>
<li>Grove speaker:
<a href="http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html" rel="nofollow">http://www.seeedstudio.com/depot/Grove-Speaker-p-1445.html</a></li>
<li>ws2812-led strip</li>
</ul>
<p>Hi, I have been working to produce tones on a speaker and it works with the following code</p>
<pre><code> int melody[] = { NOTE_C4, NOTE_G3,NOTE_G3, NOTE_A3, NOTE_G3, NOTE_B3, NOTE_C4};
...
...
tone(pin, melody[pitch]);
</code></pre>
<p>After I included my addressable LED strip sketch codes, the speaker does not produce the same tone as normally it does. It sounded distorted this time round.</p>
<pre><code>void loop()
{
strip.Update(); //NeoPatterns strip(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800, &StripComplete);
}
</code></pre>
<p>Class:</p>
<pre><code>// NeoPattern Class - derived from the Adafruit_NeoPixel class
class NeoPatterns : public Adafruit_NeoPixel
{
public:
// Member Variables:
...
...
void (*OnComplete)(); // Callback on completion of pattern
// Constructor - calls base-class constructor to initialize strip
NeoPatterns(uint16_t pixels, uint8_t pin, uint8_t type, void (*callback)())
: Adafruit_NeoPixel(pixels, pin, type)
{
OnComplete = callback;
}
// Update the pattern
void Update()
{
if ((millis() - lastUpdate) > Interval) // time to update
{
lastUpdate = millis();
switch (ActivePattern)
{
case RAINBOW_CYCLE:
RainbowCycleUpdate();
break;
default:
break;
}
}
}
// Initialize for a RainbowCycle
void RainbowCycle(uint8_t interval, direction dir = FORWARD)
{
ActivePattern = RAINBOW_CYCLE;
Interval = interval;
TotalSteps = 255;
Index = 0;
Direction = dir;
}
// Update the Rainbow Cycle Pattern
void RainbowCycleUpdate()
{
for (int i = 0; i < numPixels(); i++)
{
setPixelColor(i, Wheel(((i * 256 / numPixels()) + Index) & 255));
}
show(); // When I comment this line, the speaker will work properly. What is happening?
Increment();
}
</code></pre>
| <p>The <code>tone()</code> command is interrupt driven.</p>
<p>To get the tight timing needed by the LED strips interrupts are disabled while sending the data.</p>
<p>That means the tone() command stops while you're updating the LED strips and starts again afterwards.</p>
<p>The end result will be the sound is corrupted - maybe sounding like it's bubbly or underwater or just "rough".</p>
<p>The two basically can't work together and I'm not sure what to suggest to make them work together on a low-end MCU like the AVR.</p>
|
15828 | |led|audio|signal-processing| | Advice on setting up a real-time audio equaliser | 2015-09-04T20:01:32.960 | <p>First time Arduino user here.</p>
<p>We have a microphone set-up which feeds back loudly on particular frequencies and need an equalizer to (preferably automatically) detect spikes in particular frequency bands and attenuate them before sending them on to the speakers. The dB level that has been cut from that frequency channel would then be displayed on an LED matrix such as this one:</p>
<p><a href="https://i.stack.imgur.com/Uk5b1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Uk5b1.jpg" alt="LED Matrix" /></a></p>
<p>Does the Arduino have the processing capabilities to keep up with the audio without noticeable lag? As the LEDs will only be a visual indication of the affect the attenuation is having on the frequencies, it is not particularly important that these be fast. Unfortunately, as the audio stream will be vocals, even a slight delay will render the thing useless. What delay might I expect with a single mono channel going through the arduino?</p>
<p>I expect that I will eventually have to revert to the less-interesting project of an RTA which takes a split of the audio sends to the speakers and simply displays the frequency band intensities rather than altering them.</p>
<p>I'd appreciate any thoughts.</p>
| <p>Somewhat possible if you accept that the Arduino won't be doing most of the work:</p>
<ul>
<li>Yes, the Arduino can sample audio and perform FFT on it, though not fast and not at high frequencies</li>
<li>Yes, the Arduino can decide what to do depending on the power of different buckets</li>
<li>Yes, the Arduino can display the results</li>
<li>No, the Arduino cannot do realtime audio filtering.</li>
</ul>
<p>If you accept that the filtering will have to be done with a bank of analogue band-cut filters that the Arduino turns on and off as needed then it may be possible.</p>
<p>The Arduino Due might be a more suitable candidate since it will be able to sample and do the FFT much faster so you'll be able to respond to the peaks much quicker, and the displaying won't get in the way so much, but actively filtering inside the chip really requires a DSP.</p>
|
15834 | |arduino-mega|ethernet|modbus|rs485| | How to interconnect multiple Arduinos with a Rpi to control home-lights/switches | 2015-09-04T23:37:32.057 | <p>While planning the lightning infrastructure (wall-switches and lights) of my new home (it's still under-construction) I choosed to go through the "automated route" way and due to my background (I'm an "old" system/network administrator with programming skills and plenty of Open-Source "passion" and "advocacy") I'm seriously trying to implement it with three Arduinos and one RPi2. </p>
<p>Due to number/location of wall-push-buttons and lights, I'd like to use three MEGA interfacing both wall-push-buttons and lights of surrouding rooms. Furthermore, a RPi2 (or similar) will be used as a "controller" to properly programs MEGAs, when needed, and interfacing some other equipments (touch-screen; wifi tablet/smartphone; remote-controls; etc.) via the IP-network.</p>
<p>The schema I'm trying to implement is similar to this one:</p>
<p><a href="https://i.stack.imgur.com/eyX3P.png" rel="noreferrer"><img src="https://i.stack.imgur.com/eyX3P.png" alt="Draft Schema"></a>
where you see:</p>
<ul>
<li>9 lights (L1 to L9) each one controlled by its own dedicated relay (R1 to R9);</li>
<li>7 wall push-buttons (WPB1 to WPB7), to be used to turn on/off one or more lights;</li>
<li>3 MEGAs interfacing wall-push-buttons and lights;</li>
<li>1 RPi2, acting as "supervisor" and "Internet/Ethernet gateway".</li>
</ul>
<p>My main architectural problem relates to the interconnection between RPI2 and MEGAs. As each device will be located several tens of meters aways from each other, I ended with two only option (please, correct me if I'm wrong):</p>
<ol>
<li>Ethernet</li>
<li>RS485</li>
</ol>
<p>(<em>BTW: I'm explicitely excluding "wireless connections", as I've already placed all the electrical pipes in a "compatible" way. In other words: I'd like to avoid wireless technologies within the "controlling network"</em>)</p>
<p>As for Ethernet, I'll choose it as a 2nd option, due both to a slightly higher cost and complexity (need a switch to be powered on; additional cabling issues; etc.).</p>
<p>I've extensively researched the "<strong>RS485 bus</strong>" and found that it's relatively easy --from a physical point of view-- to implement it with <a href="https://arduino-info.wikispaces.com/RS485-Modules" rel="noreferrer">two wires in a multidrop configuration</a>.</p>
<p>Unfortunately, from an "application point of view", things are more complex as it supports only "half-duplex" communications and, even worse, there is <strong>no</strong> provision to avoid "collisions" when communicating (that's why, probably, the MODBUS protocol --tipically employed on RS485 bus-- provides a "single-master; multiple-slaves" scenario).</p>
<p>Before the questions, I need to add another constraint: I want the infrastructure to be "as much fault-tolerant as possible", expecially towards problems with the BUS and/or with the "controller" (the RPI2). In other words:</p>
<ul>
<li>each MEGA should allow to turn on its own lights when one of its own push-button requires this. For example:
<ul>
<li>if WPB1 controls L2 and L3, it need to be working even if the BUS is broken or the RPI2 is powered off;</li>
<li>if WPB3 controls L4 and L9, then should the bus/RPI2 have problems, only L4 will be powered on when WPB3 is pressed;</li>
</ul></li>
</ul>
<p>So, after all of the above, here are my questions:</p>
<ol>
<li><p>is a two-wire RS485 multidrop bus, a suitable choice for my scenario?</p></li>
<li><p>if not, which (possibly cheap and simple) other solutions may I investigate?</p></li>
<li><p>if yes, which is the logic that I need to implement on MEGAs, as:</p>
<ul>
<li>a) they need to act as "slave", with respect to RPI2 when turning on lights commanded by push-button connected to other MEGAs or when the RP2 decide to turn-on some lights (for example, due to remote/Internet access);</li>
<li>b) they need to act as "master", when one of their push-buttons is pressed and... this need to be communicated to RPI2 so to send commands to other MEGAs so to turn on "hosted" lights;</li>
</ul></li>
<li><p>as for 3b), insted of having MEGAs acting as master when a WPB is pressed, may I implement a "frequent-polling" logic on the RPI2? If yes, which is a reasonable value for such a polling (1 poll per second? 5 polls per second? too much? too low?)</p></li>
</ol>
<p>I understand that this is a too-wide question, but I really did <strong>lots</strong> of researches and despite lots, and lots, and lots of on-line documentation, I've been unable to find an answer to those questions.</p>
<hr>
<h1>Update 1</h1>
<ul>
<li>in terms of total numbers, I'll have 31 lights to be controlled by 46 wall push-buttons, more or less equally distributed in 4 distinct panel-boards;</li>
<li>As for the choise of MEGA (vs. UNO), I've choosed MEGA due to the bigger number of I/O PINs. I simply choosed the board with the maximun number of PINs;</li>
<li>As for the RPI2, I choosed to employ a proper "computer" (vs. an additional microcontroller), 'cause I want a sort of "decoupling" between the "physical controlling network" and the "User Management Interface". In other words, I want the management of physical buttons/relais to be handled by PLC-like device (Arduino: very quick power on; sort of real-time performance; very reliable; minor/no external "computing" factors introducing delays/problems); while, at the same time, all the user-interface be handled by a real-computer where I can easily write powerful HTTP web-services and/or really complex "logics", using technologies and languages that doesn't fit well with Arduino (later on --much later on--, I plan to add several 150$ full-HD 10.1" android tablets allaround the house, that will act as wireless "clients" towards what need to be a "powerful" (in terms of computing capacities) web-server; Also I plan to add various sensors [temperature; humidity; contacts; power-meters; etc.] whose data need to be stored for trending/archiving reasons). Hence, I tought about RPi2, than can easily be replaced with something more powerful, should it be needed.</li>
</ul>
| <p>I think the CDBUS protocol for RS485 is exactly what you want, it introduce an arbitration mechanism that automatically avoids conflicts like the CAN bus. I can even transfer video stream through it:</p>
<p><a href="https://i.stack.imgur.com/09PiM.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/09PiM.jpg" alt="enter image description here"></a>
Full video:
<a href="https://youtu.be/qX5dh4wcfSk" rel="nofollow noreferrer">https://youtu.be/qX5dh4wcfSk</a></p>
<p>The Raspberry Pi can output preview video and control command at the same time. We can monitor the recognition process on the PC. When problems are encountered, it is convenient to know the reason and adjust the parameters, and disconnecting the PC will not affect the demo operation.</p>
<p><a href="https://i.stack.imgur.com/R7KJt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/R7KJt.png" alt="enter image description here"></a>
In addition, the Raspberry Pi can access the internet at any time through the PC, and it is easy to update software and for remote control.</p>
<p>Details about the CDBUS:</p>
<ul>
<li><a href="https://github.com/dukelec/cdbus_doc" rel="nofollow noreferrer">https://github.com/dukelec/cdbus_doc</a> (Introduction)</li>
<li><a href="https://github.com/dukelec/cdbus_ip" rel="nofollow noreferrer">https://github.com/dukelec/cdbus_ip</a> (Protocol details & FPGA IP core)</li>
</ul>
<p>Update:
Connect the CDCTL-Bx controller to an Arduino:
<a href="https://i.stack.imgur.com/uKIOh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uKIOh.jpg" alt="arduino and cdctl"></a></p>
|
15837 | |wifi|arduino-yun|ssh| | SSH and web interface broken on Yun | 2015-09-05T03:43:17.777 | <p>I have two Arduino Yuns that are not accessible <em>at all</em> on the network. I can't go to the arduinoname.local, ssh arduinoname.local, as I previously could. I know at least one it working because it sends emails as I programmed it, yet it seems there is no longer a way to ssh into it. Any ideas?</p>
<p>Yes, I have unplugged, plugged in the router, and the yuns.</p>
| <p>It turns out the problem is a fairly common one - Actiontec wireless access points break this way when set to Both, not AES - see <a href="https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network">https://superuser.com/questions/522781/unable-to-ssh-from-any-wireless-ip-to-another-wireless-ip-on-home-network</a></p>
<p>Apparently on other routers this bug is marked as a feature, "Wireless Isolation" or something.</p>
|
15840 | |code-optimization| | Using for loop to set pinMode | 2015-09-05T04:59:56.950 | <p>I notice problems with my output pins when I use this method of setting their <code>pinMode</code>:</p>
<pre><code>int allOutputPins[] = {3, 4, 9, 10, 5, A3, 11, 12, 7, 8, A1, A2};
for(int a = 0; a < sizeof(allOutputPins); a++){
pinMode(allOutputPins[a], OUTPUT);
}//end for
</code></pre>
<p>Am I doing something wrong?</p>
| <p>Re “Am I doing something wrong?”, yes :)</p>
<p>The <code>sizeof(allOutputPins)</code> expression returns the size of <code>allOutputPins[]</code> in terms of bytes, so is 24 because the array contains 12 two-byte integers. The loop's last 12 <code>pinMode()</code> calls will be garbage.</p>
<p>Among other ways of fixing the problem, you could change the expression to <code>sizeof(allOutputPins)/sizeof(int)</code> [which has the same value, 12, as <code>(sizeof allOutputPins)/sizeof(int)</code>; eg see the syntax entries for the <a href="http://en.cppreference.com/w/cpp/language/sizeof" rel="nofollow">sizeof operator</a> at cppreference.com] or you could change the base type of the array to <code>byte</code> or <code>uint8_t</code>.</p>
|
15842 | |class|rgb-led|neopixel| | Inheritance: error in calling the constructor of the base class? | 2015-09-05T07:55:01.570 | <p>I want to write a library for the RGBDigit shield (<a href="http://rgbdigit.com/" rel="nofollow">http://rgbdigit.com/</a>), which essentially is an Adafruit Neopixel strip, packed as a 7 segment display. The shield also has a DS3231 clock and an IR receiver.</p>
<p>So my plan was to make a class <em>RGBDigit</em>, which inherits from the <em>Adafruit_NeoPixel</em> class and add private objects <em>DS3231</em> and <em>IRrecv</em>.</p>
<p>This is my RGBDigit.h:</p>
<pre class="lang-c prettyprint-override"><code>#ifndef RGBDigit_h
#define RGBDigit_h
#include <Arduino.h>
#include "Wire.h"
#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"
class RGBDigit : public Adafruit_NeoPixel {
public:
RGBDigit(int nDigits);
~RGBDigit();
private:
int _nDigits;
DS3231 _clock;
IRrecv* _ir;
};
#endif
</code></pre>
<p>This is RGBDigit.cpp:</p>
<pre class="lang-c prettyprint-override"><code>#include "RGBDigit.h"
RGBDigit::RGBDigit(int nDigits)
: Adafruit_NeoPixel(8 * nDigits, 12, NEO_GRB + NEO_KHZ800),
_nDigits(nDigits)
{
_ir = new IRrecv(10);
_ir->enableIRIn(); // Start the receiver
Adafruit_NeoPixel::begin();
}
RGBDigit::~RGBDigit()
{
delete _ir;
}
</code></pre>
<p>And this is my Arduino sketch:</p>
<pre class="lang-c prettyprint-override"><code>#include <Wire.h>
#include <RGBDigit.h>
RGBDigit display = RGBDigit(4);
void setup() {
// put your setup code here, to run once:
}
void loop() {
// put your main code here, to run repeatedly:
}
</code></pre>
<p>I get al lot of "undefined reference" errors:</p>
<pre><code>RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::RGBDigit(int)':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `Adafruit_NeoPixel::Adafruit_NeoPixel(unsigned int, unsigned char, unsigned char)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:23: undefined reference to `DS3231::DS3231()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:25: undefined reference to `IRrecv::IRrecv(int)'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:26: undefined reference to `IRrecv::enableIRIn()'
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:27: undefined reference to `Adafruit_NeoPixel::begin()'
RGBDigit/RGBDigit.cpp.o: In function `RGBDigit::~RGBDigit()':
/home/ralph/Arduino/libraries/RGBDigit/RGBDigit.cpp:30: undefined reference to `Adafruit_NeoPixel::~Adafruit_NeoPixel()'
collect2: error: ld returned 1 exit status
</code></pre>
<p>But I don' t understand why. What am I doing wrong?</p>
| <pre><code>#include "../Adafruit_NeoPixel/Adafruit_NeoPixel.h"
#include "../IRremote/IRremote.h"
#include "../DS3231/DS3231.h"
</code></pre>
<p>What you're doing there is telling the <em>compiler</em> where, relative to where it's performing the compiling (or one of its include directories), the header files you list are.</p>
<p>What you're <em>not</em> doing is telling the <em>IDE</em> where the CPP files are to compile and link with your sketch.</p>
<p>When including <em>anything</em> external to the sketch folder that is <em>more</em> than <em>just a header file</em> you <em>must</em> treat it as an Arduino library - that is, place it in one of the standard library folders and name it properly (libraries should be named <code>LibraryName/LibraryName.h</code>).</p>
<p>Then you include the libraries properly:</p>
<pre><code>#include <Adafruit_NeoPixel.h>
#include <IRremote.h>
#include <DS3231.h>
</code></pre>
<p>You must do that in <em>both</em> your sketch <em>and</em> your custom library. That way the IDE knows where to look for the files to compile - the compiler doesn't understand the concept of an Arduino library (and thus the CPP files associated with a header file) - that is purely down to the IDE gathering the data by examining your sketch and locating the right files to then pass to the compiler.</p>
|
15852 | |avrdude| | AVRdude + Arduino leonardo: can't flash over bootloader, not in sync: resp=0x3f | 2015-09-05T09:26:50.617 | <p>I would like to program an arduino leonardo board with atmega32u4 on win8.1 x64.
I have the latest AVRdude.
I installed the necessary drivers, after reset it can be enter programming mode, and I can program with <strong>arduino studio</strong>.
But now, the avrude gives this:</p>
<pre><code> C:\>avrdude -carduino -P COM5 -n -p m32u4 -b19200 -v
avrdude: Version 6.1-svn-20131205, compiled on Dec 5 2013 at 17:34:22
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2009 Joerg Wunsch
System wide configuration file is "c:\GNU_GCC_ARM\bin\avrdude.conf"
Using Port : COM5
Using Programmer : arduino
Overriding Baud Rate : 19200
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x3f
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x3f
avrdude done. Thank you.
</code></pre>
<p>I tried also with 57600 baud.
Any idea? Thanks.</p>
| <p>You're specifying the wrong bootloader protocol via -carduino. The Arduino bootloader is for boards using the Diecimila bootloader. The Leonardo uses the "AVR109" bootloader - named after the <a href="http://www.atmel.com/Images/doc1644.pdf" rel="nofollow">Atmel Application Note</a> which describes its protocol.</p>
<p>Try this command on for size:</p>
<pre><code>avrdude -cavr109 -P COM5 -n -p m32u4 -b57600 -v
</code></pre>
<p>Don't forget to press the reset button (or open and close COM5 at 1200 baud) first to run the bootloader.</p>
|
15874 | |arduino-uno|piezo|buzzer| | Drive 12V Piezo Buzzer (Arduino) | 2015-09-05T13:27:24.363 | <p>I want to drive this 12V piezo buzzer:
<a href="http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V" rel="nofollow noreferrer">http://www.conrad.com/ce/en/product/130256/Kemo-L001-High-Freqeuncy-Piezo-Speaker-Component-12-24-V</a></p>
<p>This is the circuit I am using.</p>
<p><a href="https://i.stack.imgur.com/dIxDl.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dIxDl.png" alt="Circuit"></a></p>
<p>The Arduino is powered by a 12V DC adapter trough the DC IN jack.</p>
<p>I have tested the following code:</p>
<pre class="lang-c prettyprint-override"><code>void setup() {
}
void loop() {
int pinOut = 9;
int freq = 10;
int duration = 100;
while(1)
{
for(int i=0; i<1000 ; i++)
{
tone(pinOut, freq*i, duration);
delay(duration * 1);
noTone(pinOut);
}
}
}
</code></pre>
<p>When run I can hear the tones changing but is really really low. I have measured the voltage between buzzer pins and it is 12V (as expected) so the MOSFET seems to be properly working.</p>
<p>This piezo buzzer should be louder (I have tested it with this 12V tone generator <a href="http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php" rel="nofollow noreferrer">http://www.kemo-electronic.de/en/Car/Modules/M048N-Ultrasonic-Generator.php</a> )</p>
<p>I am making any mistake?
Thanks in advance!</p>
| <p>The piezo element acts like a capacitor, not like a more-or-less resistive element as in a conventional speaker. You need to discharge the capacitor during the 'off' time or you just get a click and little sound after that. That's why your resistor helps. Push-pull would be much better, and an H-bridge would give you much more output (maybe too much for the speaker). </p>
<p>Also the IRZ44 is not specified to be driven from 5V (it's specified at 10V Vgs) so you may not get much current. Further, if you're trying to get 10's of kHz, you won't be able to drive the MOSFET gate that fast with a 1K resistor, in fact the Arduino may not be able to source enough current and you may have to use a gate driver. </p>
<p>If you can measure the capacitance and provide the frequency of interest, more specific recommendations would be possible. At 2kHz about 3K would be okay with a 10nF element, but that resistance would decrease with increasing resistance and with increasing capacitance, and at some point the power dissipation in the resistor will become excessive. </p>
<p>Edit: You can do something like the below with a 10nF/20kHz requirement: </p>
<p><img src="https://i.stack.imgur.com/PhsXe.png" alt="schematic"></p>
<p><sup><a href="/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2fPhsXe.png">simulate this circuit</a> – Schematic created using <a href="https://www.circuitlab.com/" rel="nofollow">CircuitLab</a></sup></p>
<p>You could even duplicate the above circuit and add an inverter in series with one of the halves and get 24Vpp across the piezo, but you might want to use somewhat beefier transistors (Zetex perhaps). </p>
|
15888 | |arduino-uno|button| | Newbie Question with 4 pin button | 2015-09-07T15:28:17.170 | <p>I suspect this is a very Naive question.<br>
But the answer will teach me a lot.</p>
<p>Why does <a href="https://www.arduino.cc/en/Tutorial/ButtonStateChange" rel="nofollow">this circuit</a> work when I connect the Digital Input (Digial Pin 2) to Pin 4 of the push button. But does not when I connect the push button to Pin 3. I missing something about how power flows when the button is pushed. </p>
<p>Ray K</p>
| <p>Internally those little tactile switches look like this:</p>
<p><a href="https://i.stack.imgur.com/74KLh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/74KLh.png" alt="enter image description here"></a></p>
<p>That means that the two pins on the same <em>long</em> side are connected together. So you can use, when you hold the switch vertically as in the image on the page you link to the two left-hand pins are linked together, and the two right-hand pins are linked together.</p>
<p>So you can use either both the top pins, both the bottom pins, or the top left and bottom right or the top right and bottom left.</p>
<p>Using either both left hand pins or both right hand pins will be as if you were sat on the button and it was permanently pressed.</p>
|
15890 | |arduino-uno|serial|potentiometer| | Problem with reading multiple potentiometer values on Arduino Uno | 2015-09-07T17:20:55.763 | <p>I'm working on an Arduino sketch that will read in values from two potentiometers. The code for this is below:</p>
<pre><code>int lastPotentiometerOneValue = 0;
int lastPotentiometerTwoValue = 0;
void setup() {
// initialize serial communication at 57600 bits per second:
Serial.begin(57600);
}
void loop() {
delay(10);
readAndSendPotentiometerDataIfChanged();
}
void readAndSendPotentiometerDataIfChanged(void) {
//Potentiometer One
int newPotentiometerOneValue = analogRead(A0) / 10.2;
if (newPotentiometerOneValue == lastPotentiometerOneValue) return;
Serial.print("!pos1");
Serial.print(newPotentiometerOneValue);
Serial.print(";");
lastPotentiometerOneValue = newPotentiometerOneValue;
//Potentiometer Two
int newPotentiometerTwoValue = analogRead(A1) / 10;
if (newPotentiometerTwoValue == lastPotentiometerTwoValue) return;
Serial.print("!pos2");
Serial.print(newPotentiometerTwoValue);
Serial.print(";");
lastPotentiometerTwoValue = newPotentiometerTwoValue;
}
</code></pre>
<p>The schematic for my circuit is below (I've left out the code for reading the state of the push-button in my listing above, as that's in a separate method from the method that reads in the potentiometer data):</p>
<p><a href="https://i.stack.imgur.com/Y3X7R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Y3X7R.png" alt="enter image description here"></a></p>
<p>However, there seems to be a rather subtle error I'm experiencing. If I turn Potentiometer One, it will display the correct output in the serial monitor. If I turn Potentiometer Two, no value will be displayed. <em>However</em>, if I remove Potentiometer Two from the circuit board and turn Potentiometer One, then the serial monitor will display the Potentiometer Two as having the same data as Potentiometer Two. </p>
<p>I'm sure the problem is with my circuit, but I'm not quite sure what I'm doing wrong. Does anyone have some insight? Thank you! </p>
| <p>One problem is that if the value for pot1 has not changed, the value for pot2 will never be sent, even if it has changed, due to the early return when checking the value of pot1. You could fix this by changing to:</p>
<pre><code>void readAndSendPotentiometerDataIfChanged(void) {
//Potentiometer One
int newPotentiometerOneValue = analogRead(A0) / 10.2;
if (newPotentiometerOneValue != lastPotentiometerOneValue) {
Serial.print("!pos1");
Serial.print(newPotentiometerOneValue);
Serial.print(";");
lastPotentiometerOneValue = newPotentiometerOneValue;
}
//Potentiometer Two
int newPotentiometerTwoValue = analogRead(A1) / 10.2;
if (newPotentiometerTwoValue != lastPotentiometerTwoValue) {
Serial.print("!pos2");
Serial.print(newPotentiometerTwoValue);
Serial.print(";");
lastPotentiometerTwoValue = newPotentiometerTwoValue;
}
}
</code></pre>
|
15893 | |compile| | How to compile, upload and monitor via the Linux command line? | 2015-09-07T19:13:34.227 | <p>Interfacing an Arduino Uno (uploading etc.) with the Arduino IDE (using the Fedora package) works fine under Fedora 21.</p>
<p>But I rather want to use vim + make + vim-quickfix-mode etc.</p>
<p>How can I do that?</p>
<p>Preferably via the tools available from the Fedora repositories.</p>
<p>I assume that the IDE calls externals command line utilities for the uploading etc.</p>
<p>The equivalent to the IDE's serial monitor is probably connecting a terminal emulator (e.g. <code>screen</code>) to <code>/dev/ttyACM0</code>, right?</p>
<p>Perhaps there is a good example project one can look at the makefile?</p>
| <p>A great way to compile for and flash an Arduino device from the command line and integrate with Vim is to use <a href="https://docs.platformio.org/en/latest/core/index.html" rel="nofollow noreferrer">PlatformIO Core (CLI)</a>.</p>
<p>Since it's written in Python it's easy to install even when it's not packaged for your Linux distribution. PlatformIO supports <a href="https://platformio.org/platforms" rel="nofollow noreferrer">many microcontroller devices</a>, not just Arduino ones. Thus, you don't have to switch your development environment when you target another platform. PlatformIO takes care of downloading the right toolchain (compiler etc.) for your target.</p>
<h2>Example</h2>
<p>Getting started with PlatformIO and an Arduino Pro Mini 3.3v clone on Fedora 35:</p>
<pre><code>mkdir -p ~/local
cd ~/local
python -m venv platformio
source platformio/bin/activate
pip install platformio
</code></pre>
<p>This installs PlatformIO (CLI) in a virtual environment, i.e. its main command is then available from <code>~/local/platformio/bin/pio</code> and <code>pio</code> is found in your <code>PATH</code> when the virtual environment is activated.</p>
<p>Next, we need to find the right board ID for setting up a new project:</p>
<pre><code>pio boards arduino | less
</code></pre>
<p>That means search for <code>Pro.*Mini</code> in the listing. There are several versions of the Pro Mini, in our example the <code>pro8MHzatmega328</code> (3.3 V, 8 MHz, ATmega328, 30 kb flash, 2 kB RAM) is the right one as can be validated by looking at the board markings as well as its voltage regulator, and CPU markings.</p>
<p>To set up a new project</p>
<pre><code>mkdir ~/project/some_new_project
cd ~/project/some_new_project
pio project init --board pro8MHzatmega328 --ide vim
</code></pre>
<p>Which prints:</p>
<pre><code>The current working directory /home/juser/project/arduino/pro-mini will be used for the project.
The next files/directories have been created in /home/juser/arduino/pro-mini
include - Put project header files here
lib - Put here project specific (private) libraries
src - Put project source files here
platformio.ini - Project Configuration File
Platform Manager: Installing atmelavr
Downloading [####################################] 100%
Unpacking [####################################] 100%
Platform Manager: atmelavr @ 3.4.0 has been installed!
Tool Manager: Installing platformio/toolchain-atmelavr @ ~1.70300.0
Downloading [####################################] 100%
Unpacking [####################################] 100%
Tool Manager: toolchain-atmelavr @ 1.70300.191015 has been installed!
The platform 'atmelavr' has been successfully installed!
The rest of the packages will be installed later depending on your build environment.
Project has been successfully initialized including configuration files for `vim` IDE.
</code></pre>
<p>For a first test one can copy a simple blink-led example using the usual <code>setup()</code>/<code>loop()</code> functions. It's possible to re-use an existing 'sketch' from the Arduino IDE, one just has to add <code>#include <Arduino.h></code> at the top and place it under <code>src/some-name.cc</code> or <code>src/some-name.cpp</code>.</p>
<p>To compile everything:</p>
<pre><code>pio run
</code></pre>
<p>Which prints:</p>
<pre><code>Processing pro8MHzatmega328 (platform: atmelavr; board: pro8MHzatmega328; framework: arduino)
--------------------------------------------------------------------------------
Verbose mode can be enabled via `-v, --verbose` option
CONFIGURATION: https://docs.platformio.org/page/boards/atmelavr/pro8MHzatmega328.html
PLATFORM: Atmel AVR (3.4.0) > Arduino Pro or Pro Mini ATmega328 (3.3V, 8 MHz)
HARDWARE: ATMEGA328P 8MHz, 2KB RAM, 30KB Flash
DEBUG: Current (avr-stub) On-board (avr-stub, simavr)
PACKAGES:
- framework-arduino-avr 5.1.0
- toolchain-atmelavr 1.70300.191015 (7.3.0)
LDF: Library Dependency Finder -> https://bit.ly/configure-pio-ldf
LDF Modes: Finder ~ chain, Compatibility ~ soft
Found 5 compatible libraries
Scanning dependencies...
No dependencies
Building in release mode
Compiling .pio/build/pro8MHzatmega328/src/sos-switch.cc.o
Linking .pio/build/pro8MHzatmega328/firmware.elf
Checking size .pio/build/pro8MHzatmega328/firmware.elf
Advanced Memory Usage is available via "PlatformIO Home > Project Inspect"
RAM: [ ] 0.4% (used 9 bytes from 2048 bytes)
Flash: [ ] 3.8% (used 1170 bytes from 30720 bytes)
========================= [SUCCESS] Took 0.51 seconds =========================
</code></pre>
<p>So for this example I created <code>src/sos-switch.cc</code> which is compiled to <code>.pio/build/.../sos-switch.cc.o</code>.</p>
<p>To upload (flash) the device:</p>
<pre><code>pio run --target upload
</code></pre>
<p>As always, a common pitfall are the permissions of the USB device. For example, on Fedora, my USB2TTL serial device registers as <code>/dev/ttyUSB0</code> with read-write permissions for just <code>root:dialout</code>. Thus, you have to add your user to the <code>dialout</code> group or adjust the permissions by other means.</p>
<h2>Vim Quickfix Mode</h2>
<p>For integrating with Vim's quickfix mode a simple makefile is sufficient, e.g.:</p>
<pre><code>
.PHONY: all
all: build
.PHONY: build
build:
pio run
.PHONY: upload
upload:
pio run --target upload
</code></pre>
<p>Thus, everything is built when <code>:make</code> is invoked in Vim, and there one can navigate the quickfix mode as usual.</p>
<h2>Serial Monitoring</h2>
<p>An easy way to monitor the serial interface is to use <a href="https://github.com/npat-efault/picocom" rel="nofollow noreferrer">picocom</a>, e.g.:</p>
<pre><code>picocom --baud 9600 --echo --imap lfcrlf --noreset /dev/ttyUSB0
</code></pre>
<p>where:</p>
<ul>
<li><code>--imap lfcrlf</code> maps newline to carriage return + newline such that we can just write <code>Serial.print("multi\nlines\n')</code> instead of <code>Serial.print("multi\r\nlines\r\n")</code> in our program</li>
<li><code>--noreset</code> tells picocom to <strong>not</strong> clear DTR - without it, when DTR is connected, the Anrdoid device is reset</li>
</ul>
<p>Of course, one has to terminate picocom when uploading.</p>
<hr />
<p>Alternatively, one can use the PlatformIO monitor command:</p>
<pre><code>pio device monitor
</code></pre>
<p>In contrast to picocom, it doesn't require explicit mapping or DTR handling. However, as with picocom, it must be terminated when uploading/flashing. That means PlatformIO doesn't automatically suspends monitoring when <code>pio run --target upload</code> is invoked.</p>
<h2>Closing Remarks</h2>
<ul>
<li>PlatformIO is <a href="https://bugzilla.redhat.com/show_bug.cgi?id=2021751" rel="nofollow noreferrer">currently packaged</a> for Fedora and thus might be directly available in Fedora 36 or so</li>
<li>the classic Arduino IDE was packaged for Fedora, but isn't available anymore in Fedora 35 because of the big Java package exodus</li>
<li>there is also a PlatoformIO plugin for VSCode which seems to be quite popular</li>
</ul>
|
15896 | |neopixel| | Loop though array values at end of each for loop cycle | 2015-09-07T20:34:08.650 | <p>I'm using the <a href="https://github.com/adafruit/Adafruit_NeoPixel/blob/master/Adafruit_NeoPixel.h" rel="nofollow">NeoPixel</a> Ring from Adafruit and trying to pulse though and array of colors. However, I'm having trouble with having the loop go to the next color at the end of each pulse (end of loop). Here is what I currently have:</p>
<pre><code>uint32_t color[] = {red, green, blue,yellow,teal,magenta};
void pulseUp(uint8_t speed){
int fadeAmount = 10; //how much to increase each loop
int n = 0; //get first color
for(int b = 100; b >= 10; b = b - fadeAmount) { //start pulse for loop
for (int i = 0; i < strip.numPixels(); i++) { //select all pixels
strip.setPixelColor(i, color[n]); //set color from our array
}
strip.setBrightness(b); //set brightness based on b
strip.show(); // send the changes to the strip
delay(speed); //wait before running again
//if at the end of the loop (brightness is 10) change color
if (b == 10){
if( n > 6){ //if we are at last color in our loop start over
n = 0;
}
else{
n++; //auto increment color value
}
}
}
}
</code></pre>
<p>I'm sure the problem is with the if statements but not sure how to fix it. </p>
|
<p>I can't quite make out what your <code>if</code> test is supposed to be doing, but don't you want a loop within a loop? Like this?</p>
<pre class="lang-C++ prettyprint-override"><code>uint32_t color[] = {red, green, blue,yellow,teal,magenta};
void pulseUp(uint8_t speed)
{
const int fadeAmount = 10; //how much to increase each loop
for (int currentColor = 0; currentColor < 6; currentColor++)
{
for (int i = 0; i < strip.numPixels(); i++)
{ //select all pixels
strip.setPixelColor(i, color[currentColor]); //set color from our array
}
for(int brightness = 100; brightness >= 10; brightness -= fadeAmount)
{ //start pulse for loop
strip.setBrightness(brightness); //set brightness based on brightness
strip.show(); // send the changes to the strip
delay(speed); //wait before running again
} // end of brightness loop
} // end of colour loop
} // end of pulseUp
</code></pre>
|
15903 | |arduino-uno|c++|spi| | Arduino Uno and Agilent ADNS-3080 not reading from SPI | 2015-09-08T02:46:18.423 | <p>I am trying to interface with a mouse sensor and am not able to get data back.
<a href="http://prototypejax.com/datasheets/Agilent%20ADNS-3080.pdf" rel="nofollow">datasheet link</a>
I have it still soldered to the original PCB but have cut the traces to pins 1-4,6,7 (NCS [SS], MISO, SCLK, MOSI, RESET, NPD [power down {set to 3.3v}])</p>
<p>PLEASE LET ME KNOW IF ANYTHING SEEMS WRONG HERE.</p>
<p>According to the Datasheet, by default the sensor is setup with the pull-up resistors enabled [pg. 29] which enables the open-drain, allowing me to directly connect NCS,MISO,SCLK,MOSI directly to the 5v microcontroller [pg. 15]. This also requires the SPI speed set to 500khz [pg. 10]. RESET is in a (10k)(10k+10k) resistor bridge.</p>
<p>SPI should be set to Mode3 as SCLK is normally high and data should be captured on the rising edge of the clock pulse [pg. 16]</p>
<p>Here is my code:</p>
<pre><code>#include <SPI.h>
const int MOUSEVERSION = 0x00; //mouse version
const int CSmouse = 10;
const int mouseReset = 2;
char val;
void setup() {
Serial.begin(9600);
SPI.beginTransaction(SPISettings(500000, MSBFIRST, SPI_MODE3));
pinMode(CSmouse, OUTPUT);
pinMode(mouseReset, OUTPUT);
digitalWrite(CSmouse, HIGH);
//pull reset pin high for a half second to make sure mouse is ready to go after powering on [pg. 22]
digitalWrite(mouseReset, HIGH);
Serial.println("setup");
delay(500); //half a second
digitalWrite(mouseReset, LOW);
Serial.println("end setup");
}
void loop() {
Serial.println("Start loop");
digitalWrite(CSmouse, LOW); //CS enable
SPI.transfer(MOUSEVERSION); //0x00 = read register Product_ID, should reply 0x17
delayMicroseconds(75);
Serial.println(SPI.transfer(0)); //actually just gives 0
delay(500);
}
</code></pre>
| <p>You have <code>SPI.beginTransaction</code> but no <code>SPI.begin()</code>.</p>
<p><code>SPI.begin()</code> is needed to initialize the SPI hardware.</p>
<p>More details about SPI at <a href="http://www.gammon.com.au/spi" rel="nofollow">SPI - Serial Peripheral Interface - for Arduino</a>.</p>
|
15911 | |arduino-uno|sensors|i2c|accelerometer|wire-library| | Function not successfully reading sensor registers | 2015-09-08T08:06:18.410 | <p>I'm trying to write a library for an accelerometer/magnetometer sensor. The sensor is a LSM303D chip (<a href="https://www.pololu.com/file/0J703/LSM303D.pdf" rel="nofollow">https://www.pololu.com/file/0J703/LSM303D.pdf</a>).</p>
<p>I've written a function, <code>readRegister()</code> (below) that's supposed to get the data from the sensor. However, I put in many different registers into the function into the function, but it always returns the same number. That number changes every time I unplug my Arduino from my computer.</p>
<pre><code>byte fp::readRegister(byte register_address, int numBytes) {
Wire.requestFrom(register_address, numBytes);
byte c;
Serial.println(Wire.read());
while (Wire.available()) {
c = Wire.read();
}
Serial.print("0x");
Serial.print(register_address, HEX);
Serial.print("\t");
Serial.print(c);
Serial.print("\t");
Serial.println(millis());
return c;
}
</code></pre>
<p>Here's an example of the problem output:</p>
<pre><code>0x8 190 2
0x9 190 3
0xA 190 11
</code></pre>
<p>And here is something more like what I'd expect:</p>
<pre><code>0x8 193 [time]
0x9 189 [time]
0xA 195 [time]
</code></pre>
<p>Here is the Git repo with the rest of the code: <a href="https://github.com/fpdotmonkey/fp_accel" rel="nofollow">https://github.com/fpdotmonkey/fp_accel</a></p>
<p>Thank you in advance for your help.</p>
|
<pre class="lang-C++ prettyprint-override"><code> Wire.requestFrom(register_address, numBytes);
byte c;
Serial.println(Wire.read());
while (Wire.available()) {
c = Wire.read();
}
</code></pre>
<p>This has a number of problems. For one thing your (I presume) debugging print consumes the data from Wire.read, so when you go to get it into c, you have already printed it. In other words, you are reading byte #1 and printing it, but using byte #2. This seems an odd thing to do.</p>
<p>Next, what is this doing?</p>
<pre class="lang-C++ prettyprint-override"><code> while (Wire.available()) {
c = Wire.read();
}
</code></pre>
<p>You are reading an indefinite number of bytes, and retaining the last one. Why?</p>
<p>Possible rework:</p>
<pre class="lang-C++ prettyprint-override"><code>byte fp::readRegister(byte register_address, int numBytes) {
Wire.requestFrom(register_address, numBytes);
byte c = Wire.read()
Serial.println(c);
Serial.print("0x");
Serial.print(register_address, HEX);
Serial.print("\t");
Serial.print(c);
Serial.print("\t");
Serial.println(millis());
return c;
}
</code></pre>
<hr>
<blockquote>
<p>Here is the Git repo with the rest of the code: <a href="https://github.com/fpdotmonkey/fp_accel" rel="nofollow">https://github.com/fpdotmonkey/fp_accel</a></p>
</blockquote>
<p>From your linked code:</p>
<pre class="lang-C++ prettyprint-override"><code> byte xlm = readRegister(fp::OUT_X_L_M, 1);
byte xhm = readRegister(fp::OUT_X_H_M, 1);
byte ylm = readRegister(fp::OUT_Y_L_M, 1);
byte yhm = readRegister(fp::OUT_Y_H_M, 1);
byte zlm = readRegister(fp::OUT_Z_L_M, 1);
byte zhm = readRegister(fp::OUT_Z_H_M, 1);
</code></pre>
<p>You have the wrong end of the stick here.</p>
<pre class="lang-C++ prettyprint-override"><code> Wire.requestFrom(register_address, numBytes);
</code></pre>
<p>You request from the <strong>I2C address</strong> - that is the device address. The register is something else.</p>
<p>Judging by the datasheet you first have to send the register address, and then request the data. Something along the lines of:</p>
<pre class="lang-C++ prettyprint-override"><code>byte fp::readRegister(byte register_address, int numBytes) {
Wire.beginTransmission (DEVICE_ADDRESS);
Wire.write (register_address);
Wire.endTransmission (false); // repeated start
Wire.requestFrom(DEVICE_ADDRESS, 1);
byte c = Wire.read()
Serial.println(c);
Serial.print("0x");
Serial.print(register_address, HEX);
Serial.print("\t");
Serial.print(c);
Serial.print("\t");
Serial.println(millis());
return c;
}
</code></pre>
<p>Similarly for writing to a register:</p>
<pre class="lang-C++ prettyprint-override"><code>void fp::writeRegister(byte register_address, byte val) {
Wire.beginTransmission(DEVICE_ADDRESS);
Wire.write (register_address);
Wire.write(val);
Wire.endTransmission();
}
</code></pre>
<p>This is untested because I don't have the device here, but I know that what you had won't work. To check the actual device address run the <a href="http://www.gammon.com.au/i2c" rel="nofollow">I2C scanner</a> I mentioned before.</p>
|
15914 | |rotary-encoder| | Sampling rate issue | 2015-09-08T09:44:41.533 | <p>I have an Arduino code which runs decently.</p>
<pre><code>// Read in 10-bits Magnetic Encoder AEAT-6010-A06 into Arduino Uno
// Sampling
// Declarate
const int CSn = 4; // Chip select
const int CLK = 7; // Clock signal
const int DO = 8; // Digital Output from the encoder which delivers me a 0 or 1, depending on the bar angle..
int analogPin = 3;
int val = 0;
unsigned int sensorWaarde = 0;
void setup() {
Serial.begin(115200);
//Fix de tris
pinMode(CSn, OUTPUT);
pinMode(CLK, OUTPUT);
pinMode(DO, INPUT);
//Let's start here
digitalWrite(CLK, HIGH);
digitalWrite(CSn, HIGH);
}
void loop() {
val = analogRead(analogPin);
// val = val - 670;
sensorWaarde = readSensor();
delayMicroseconds(1); //Tcs waiting for another read in
}
unsigned int readSensor() {
unsigned int dataOut = 0;
digitalWrite(CSn, LOW);
delayMicroseconds(1); //Waiting for Tclkfe
//Passing 10 times, from 0 to 9
for (int x = 0; x < 10; x++) {
digitalWrite(CLK, LOW);
delayMicroseconds(1); //Tclk/2
digitalWrite(CLK, HIGH);
delayMicroseconds(1); //Tdo valid, like Tclk/2
dataOut = (dataOut << 1) | digitalRead(DO); //shift all the entering data to the left and past the pin state to it. 1e bit is MSB
}
digitalWrite(CSn, HIGH); //
Serial.print(dataOut);
Serial.print("");
Serial.print(" ");
Serial.println(val);
Serial.print(" ");
delay(2);
return dataOut;
}
</code></pre>
<p>From the delay data i assumed that i will be having approximately a sampling rate of 500 Hz, however it seems that the sampling rate is approximately 300+- Hz, without a proper confirmation.</p>
<p>My system is to be run in a Magnetic Encoder by Avago, but i have difficulties determining the sampling rate.</p>
<p>If possible, may i know what code should i use to indicate the time and sampling number?</p>
|
<p>At 115200 baud your serial prints will take 1/11520 seconds per byte.</p>
<hr>
<pre class="lang-C++ prettyprint-override"><code>Serial.print("");
</code></pre>
<p>What does that do?</p>
<hr>
<p>I count 14 bytes here:</p>
<pre class="lang-C++ prettyprint-override"><code> Serial.print(dataOut); // 5 bytes, say
Serial.print(""); // zero bytes, lol
Serial.print(" "); // one byte
Serial.println(val); // 5 bytes + cr/lf = 7 bytes
Serial.print(" "); // 1 byte
</code></pre>
<p>Multiply 1/11520 (0.0000868) by 14 and you get 1215 µs.</p>
<hr>
<p>Now add in your delays: </p>
<pre class="lang-C++ prettyprint-override"><code> delay(2); // 2000 µs
</code></pre>
<hr>
<p>And this:</p>
<pre class="lang-C++ prettyprint-override"><code> for (int x = 0; x < 10; x++) {
...
delayMicroseconds(1); //Tclk/2
...
delayMicroseconds(1); //Tdo valid, like Tclk/2
}
</code></pre>
<p>Another 20 µs.</p>
<hr>
<pre class="lang-C++ prettyprint-override"><code> val = analogRead(analogPin); // 104 µs
...
delayMicroseconds(1); // 1 µs
</code></pre>
<hr>
<p>Total:</p>
<pre class="lang-C++ prettyprint-override"><code>1215 + 2000 + 20 + 104 + 1 = 3340 µs
</code></pre>
<p>Inverse:</p>
<pre class="lang-C++ prettyprint-override"><code>1 / 0.003340 = 299
</code></pre>
<hr>
<p>So yes, I would expect around 299 iterations per second. That isn't counting the time for the other code to execute.</p>
<hr>
<h3>Suggestions</h3>
<ul>
<li>Get rid of the serial prints</li>
<li>Get rid of <code>delay(2)</code></li>
</ul>
|
15921 | |serial|arduino-mini| | How to troubleshoot the Arduino Mini and Arduino usb2serial? | 2015-09-08T17:07:34.457 | <p>I am trying to get an Arduino Mini (R5, mega 328p) working.</p>
<p>Just connecting it to power has following effect: the on-board LED lights up. It's the power-on-led, I presume.</p>
<p>Since other Arduino devices often come with the blink-example pre-flashed I hooked up a LED to pin 13 - result: no blinking.</p>
<p>Curiously, connecting the LED to pin 12: blinking</p>
<p>Does the Mini come pre-flashed with a blink 'sketch' that blinks pin 12 instead of 13?</p>
<p>To test uploading I've connected it to an Arduino USB2Serial module. The module is labeled with 'made in Italy' and has printed 'USB2SERIAL LIGHT' on it where the LIGHT is overwritten with a blue marker.</p>
<p>I've connected it like described in the <a href="https://www.arduino.cc/en/Guide/ArduinoMini" rel="nofollow">arduino mini guide</a>.</p>
<p>In the IDE I've selected the board 'Arduino Mini' and the '328' CPU.</p>
<p>Unfortunately, uploading fails with:</p>
<pre><code>avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
</code></pre>
<p>The external reset is connected like in the guide. But I also tried to manually press the reset button (immediately before the upload, or long press and release after upload button is clicked). Still, the same error.</p>
<p>When the manual reset is pressed the pin-12-blinking stops for a while (perhaps the bootloader is then executed) but then starts again.</p>
<p>The Arduino2serial has 3 LEDs. The ON-LED lights up when connected to the USB. When hitting the upload button in the IDE, the RX-LED flashed shortly one time after a while. That's it.</p>
<p>Thus my question: How to I troubleshoot this? Can I test the arduino usb2serial on its own? What's up with the pin-12 blinking of the mini?</p>
<p>In case this matters, I am on Fedora Linux, uploading to other Arduino devices (Uno, Micro) works as expected.</p>
<p><strong>update usb2serial</strong>: I just hooked up the Arduino usb2serial and connected the TX/RX pins via a jumper cable - a minicom session then results in text being displayed and the rapid flashing of the RX/TX LEDs. Disconnecting RX/TX again shows no display of any text inside minicom, and no flashing of the RX/TX LEDs.</p>
<p>I used following command line:</p>
<pre><code>$ minicom -D /dev/ttyACM0 -b 115200
</code></pre>
<p>Thus, the usb2serial module seems to work.</p>
<p><strong>update:</strong> I've checked all the jumper cables and there was a faulty one. With that replaced flashing works. After hitting the reset-button. The 'ext reset' pin is connected but the remote-reset does seem to work. Anyways, hitting the reset-button is easy-enough, for now.</p>
<p><strong>final update:</strong> The root cause for remote-reset (a.k.a. auto reset) that the capacity of the used capacitor was too small. After exchanging it with a 100 nF one (as specified in the guide) the remote-reset works as expected. That means just hitting the upload button in the IDE automatically resets the device and the sketch is uploaded.</p>
| <p>As always, it makes sense to check the parts in isolation, if possible.</p>
<p>Host system (Linux):</p>
<ul>
<li>Tail the system log for errors</li>
<li>Check that ModemManager does not occupies the <code>/dev/ttyACM0</code> device</li>
</ul>
<p>USB2Serial:</p>
<ul>
<li>Connect it via USB to the host without anything else connected -> the ON-LED should be on, the RX/TX LEDs should be off, the system log should display some udev progress messages (including vendor ids), the system should have a new serial device, e.g. <code>/dev/ttyACM0</code></li>
<li>Open the serial port with a terminal (e.g. via <code>minicom -D /dev/ttyACM0 [-b baudrate]</code>, disable local echo and type something -> nothing should be displayed</li>
<li>Connect the RX/TX pins to each other with a jumper cable -> typing in the terminal session should now result in rapid flashing of the TX/RX LEDs and the echoing of the text</li>
</ul>
<p>Arduino Mini:</p>
<ul>
<li>Connect just the minimum, e.g. just power from a 9V battery/5V power supply and the reset pin to +5 (with a 10KOhm resistor in series) -> the power-on led should turn on</li>
<li>The chance is high that the device comes with a pre-flashed blink examples that either uses pin 12 or 13 -> connect external LEDs to pin 12 and 13 (in series with 220 Ohm resistors) -> one LED blinks after power on</li>
<li>Hit the reset button on the mini -> any LED blinking should stop for a while and then continue</li>
</ul>
<p>Arduino Mini with USB2Serial:</p>
<ul>
<li>Make sure that both RX/TX pairs are crosslinked (like a nullmodem cable), i.e. RX <-> TX and TX <-> RX.</li>
<li>Follow the mini guide on <a href="https://www.arduino.cc/en/Guide/ArduinoMini" rel="nofollow">arduino.cc</a> or <a href="http://labs.arduino.org/Getting+Started+with+Arduino+Mini" rel="nofollow">arduino.org</a> it includes a picture of the cabling</li>
<li>Verify that the capacitor connected between the USB2Serial 'ext reset' pin and the Mini reset pin has a capacity of 100 nF, otherwise, the auto-reset might not work</li>
<li>In case the automatic reset does not work, press the on-board-reset-button just before the upload</li>
<li>In case the error persists, check for dodgy cables with a multi-meter</li>
</ul>
<p>IDE:</p>
<ul>
<li>Make sure that it works with 'easier' stuff, e.g. flashing to a Uno (the Uno is easier because the USB-2-Serial part is integrated)</li>
<li>Enable verbose logging during upload (in the preferences)</li>
<li>Update the IDE in case it is very old</li>
</ul>
|
15922 | |arduino-leonardo|uploading|usb| | Did I break my new Arduino Leonardo Eth by restarting it? | 2015-09-08T17:36:58.913 | <p>I just bought a new Arduino Leonardo Eth, and, it was working perfectly.</p>
<p>I probably uploaded about 30 different sketches, and it did everything as expected.</p>
<p>The basic sketch was using the fade demo on pin 9 to ground with a LED attached.</p>
<p>I was then curious on how long the unit takes to restart, so, I unplugged the USB and put it back in.</p>
<p>When it started back up, the LED was on solid. I then restarted it again, and I honestly can't remember the state of it.</p>
<p>When I plug it in, it gets detected in the Arduino application and I see the port, but, after about 20 seconds, I get a popup on Windows saying about a malfunctioning USB device.</p>
<p>Pressing reset on the Arduino or unplugging/plugging it back does the same - I get about 20 seconds, and then it "goes bad".</p>
<p>Even if I am real quick in the IDE, or press restart after compiling/before upload, it just hangs.</p>
<p>I'm really annoyed with myself if I did break it, but, I'm not really sure what else I could have done differently... after all, there isn't an off switch.</p>
<p>Does anyone know what I have done, and, is there anyway to fix it?</p>
| <p>You should be able to use my <a href="http://www.gammon.com.au/forum/?id=11633" rel="nofollow noreferrer">board detector</a> sketch on one of your other Arduinos to check out the problem board. </p>
<p>See also <a href="https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board">Have I bricked my Arduino Uno? Problems with uploading to board</a></p>
<p>Also my <a href="http://www.gammon.com.au/bootloader" rel="nofollow noreferrer">bootloader uploader</a> sketch will reflash bootloaders on quite a few devices. I'm assuming that the "Arduino Leonardo Eth" has the same bootloader as the Leonardo.</p>
<p>Hmmm - I see that the "Arduino Leonardo Eth" is from Arduino.org, not Arduino.cc. The bootloader is probably slightly different. I'm really not an expert on what those boards use.</p>
<hr>
<p>Before worrying too much, try the approach of holding down Reset and then uploading a sketch, letting go of Reset as the sketch starts to actually upload.</p>
<hr>
<p><em>Comment by William Hilsum</em></p>
<blockquote>
<p>I didn't realise there was a difference between .org and .cc, and, I guess by using the leonardo template from .cc, I broke "something". The moment I downloaded the IDE from .org, & uploaded with the eth template , it worked flawlessly. I guess there are some changes between leonardo and leonardo eth. I wanted an arduino with ethernet, so I didn't need a separate shield. No idea if I picked the right "side" after reading all the crap with cc vs org! </p>
</blockquote>
<p>That is very annoying that the split of the Arduino camps now produces a support nightmare for people who just want to use their virtually identical products, but have to go through this.</p>
<p>Thanks for the update.</p>
|
15923 | |arduino-mega| | Lost Source Sketch | 2015-09-08T19:26:16.540 | <p>I wrote an interface to a radio about 1-year ago. I have since rebuilt that machine. Is there any way to retrieve the code. Now I do not expect it to be sources code.
I know the radio code still works as I tried it the other day. Part of the problem is that I am using about 30 wires all on the rear end of the card
and have to figure out which pins that they go to in my radio. My interface has two DB25 connectors. And the decoder 2 of 5 negative going signals. </p>
| <p>Asusming the lock bits on the MCU haven't been set, you can use avrdude to download the contents of flash and EEPROM to your system. From there you can use avr-objdump to disassemble the .hex file and try to figure out how it works. I recommend looking at the disassembly of a .elf file from a current project as well as having both the avr-gcc and avr-libc documentation as well as the ATmegaXXX0 datasheet close at hand at all times.</p>
|
15926 | |atmega328|bootloader|frequency|fuses| | Uploading to atmega328 over serial with arduino bootloader running at 2MHz | 2015-09-08T19:51:24.563 | <p>I want to run an atmega328 on a breadboard at 2MHz and upload to it via the serial pins (pins 2 and 3). So I am setting the clock divide by 8 fuse bit to enable this, meaning the atmega runs at 2MHz eith the 16MHz crystal. But I can't upload, probably because the bootloader is not expecting the clock to be running at 2MHz. The baud rates are probably mismatched by 8 times, the IDE is trying to upload at 57600 but since the bootloader code is not aware its being clocked at 2MHz, its probably running 8 times too slow. I've messed around a bit with the arduino conf files changing baud rates but had no joy. I was wondering if anyone knows how to do this off the top of their head.</p>
<p>Thanks, Pete</p>
| <p>Unprogram the CKDIV8 fuse and add the following to the sketch instead, near the beginning:</p>
<pre><code>#include <avr/power.h>
void setprescaler(void) __attribute__ ((naked)) \
__attribute__ ((section(".init1")));
void setprescaler(void)
{
clock_prescale_set(clock_div_8);
}
</code></pre>
<p>This will do essentially the same thing as the fuse, but won't interfere with the bootloader.</p>
|
15930 | |arduino-uno| | Going from arduino & sketch to production | 2015-09-08T20:26:12.143 | <p>I've got a little proof of concept thing going here with an arduino & Ethernet shield. The basic idea is for it to ping out much like a heartbeat monitor every so often so I can see if my house still has internet connectivity. </p>
<p>The arduino works nicely and does exactly what I want. I've ordered a board to be made with just the basic components needed and now want to put the code on to it. They gave me an option to load the code (Dragon AVR) during checkout and I'd love to try that out. So, the question is - how on earth do I package up code for something like that? I've seen a number of people ask the same thing for large manufacturing scales / similar setup where they don't fancy using the arduino & IDE as a programmer. </p>
<p>I've asked around on IRC and various other places but nobody seems to be able to give me specific and clear advice on whether it's possible and how to go about doing it. </p>
| <p>"Intel Hex" is pretty much an industry standard and I'm quite certain the .hex files produced by the GNU AVR tools is Intel Hex format. Your vendor is almost certainly prepared to load your sketch from the .hex file.</p>
|
15936 | |arduino-uno|bootloader| | What happens when code is uploaded using the bootloader? | 2015-09-09T03:15:53.653 | <p>When I upload a new sketch to my Arduino Uno using the Optiboot bootloader, what <em>really</em> happens?</p>
<ul>
<li>What is sent to the Arduino?</li>
<li>How does it respond?</li>
<li>What does "not in sync mean"?</li>
<li>What is "in sync" anyway?</li>
</ul>
<hr>
<p><em>Note: This is intended as a "reference question"</em>.</p>
| <p>When you reset a Uno running the Optiboot loader, the bootloader first flashes pin 13 three times.</p>
<p><a href="https://i.stack.imgur.com/py9om.png" rel="noreferrer"><img src="https://i.stack.imgur.com/py9om.png" alt="Pin 13 being flashed"></a></p>
<p>Top line (gray) is sent <strong>to</strong> the Arduino, middle line (orange) is sent <strong>from</strong> the Arduino.</p>
<p>While that is happening, the program <code>avrdude</code> running on your computer is sending a query to the device:</p>
<pre><code>STK_GET_SYNC / CRC_EOP (0x30/0x20)
</code></pre>
<p>The Arduino doesn't notice the first "get sync" because it is busy flashing pin 13. Once it is done it notices the "get sync" (it would be buffered by the serial hardware) and replies:</p>
<pre><code>STK_INSYNC / STK_OK (0x14/0x10)
</code></pre>
<p>It looks like avrdude got a bit impatient, and timed out, because it tries again with the "get sync" query. This time Optiboot responds immediately.</p>
<hr>
<p>The rest of the uploading is described in the next image. Example produced uploading the stock "Blink" program.</p>
<p><a href="https://i.stack.imgur.com/9htH8.png" rel="noreferrer"><img src="https://i.stack.imgur.com/9htH8.png" alt="Optiboot upload process"></a></p>
<p><em>(Click on the image above for a larger version)</em></p>
<hr>
<p>The steps are:</p>
<ul>
<li>Query: Get Sync? Reply: In Sync.</li>
<li>Query: Get parameter? (major version) Reply: version 4.</li>
<li>Query: Get parameter? (minor version) Reply: version 4.</li>
<li><p>Set device parameters. The following device parameters are sent to the chip:</p>
<pre><code>0x42 // STK_SET_DEVICE
0x86 // device code
0x00 // revision
0x00 // progtype: “0” – Both Parallel/High-voltage and Serial mode
0x01 // parmode: “1” – Full parallel interface
0x01 // polling: “1” – Polling may be used
0x01 // selftimed: “1” – Self timed
0x01 // lockbytes: Number of Lock bytes.
0x03 // fusebytes: Number of Fuse bytes
0xFF // flashpollval1
0xFF // flashpollval2
0xFF // eeprompollval1
0xFF // eeprompollval2
0x00 // pagesizehigh
0x80 // pagesizelow
0x04 // eepromsizehigh
0x00 // eepromsizelow
0x00 // flashsize4
0x00 // flashsize3
0x80 // flashsize2
0x00 // flashsize1
0x20 // Sync_CRC_EOP
</code></pre>
<p>Optiboot <strong>ignores all those</strong> and replies with In Sync/OK. :)</p></li>
<li><p>Set extended device parameters:</p>
<pre><code>0x45 // STK_SET_DEVICE_EXT
0x05 // commandsize: how many bytes follow
0x04 // eeprompagesize: EEPROM page size in bytes.
0xD7 // signalpagel:
0xC2 // signalbs2:
0x00 // ResetDisable: Defines whether a part has RSTDSBL Fuse
0x20 // Sync_CRC_EOP
</code></pre>
<p>Optiboot <strong>ignores all those</strong> as well and replies with In Sync/OK.</p></li>
<li><p>Enter program mode. Reply: In Sync/OK.</p></li>
<li><p>Read signature. Optiboot replies with <code>0x1E 0x95 0x0F</code> <strong>without actually reading the signature</strong>.</p></li>
<li><p>Write fuses (four times). Optiboot <strong>does not write the fuse</strong> but just replies In Sync/OK.</p></li>
<li><p>Load address (initially 0x0000). The address is in words (ie. a word is two bytes). This sets the address for where the next page of data will be written.</p></li>
<li><p>Program page (up to 128 bytes are sent). Optiboot replies "In Sync" immediately. Then there is a pause of about 4 ms while it actually programs the page. Then it replies "OK".</p></li>
<li><p>Load address (now 0x0040). This is address 64 in decimal, ie. 128 bytes from the start of program memory.</p></li>
<li><p>Another page is written. This sequence continues until all the pages are written.</p></li>
<li><p>Load address (back to 0x0000). This is for verifying the write.</p></li>
<li><p>Read page (up to 128 bytes are read). This is for verifying. Note that even if the verify fails, the bad data has already been written to the chip.</p></li>
<li><p>Leave programming mode.</p></li>
</ul>
<hr>
<h2>What does "not in sync" mean?</h2>
<p>As you can see from the above, every step through the programming sequence the Arduino is expected to reply with "In Sync" (0x14), possibly followed by some data, followed by "OK" (0x10). </p>
<p>If it is "not in sync" that means that avrdude did not get the "in sync" response. Possible reasons could be:</p>
<ul>
<li>Wrong baud rate used </li>
<li>Wrong serial port selected in IDE</li>
<li>Wrong board type selected in IDE</li>
<li>No bootloader installed</li>
<li>Wrong bootloader installed</li>
<li>Board not configured to use the bootloader (in the fuses)</li>
<li>Some device plugged into pins D0 and D1 on the Arduino, interfering with serial commications</li>
<li>The USB interface chip (ATmega16U2) not working properly</li>
<li>Wrong clock for the board</li>
<li>Wrong fuse settings on the Atmega328P (eg. "divide clock by 8")</li>
<li>Board/chip damaged</li>
<li>Faulty USB cable (some USB cables provide power only, and are not for data, eg. cheap cables for USB fans)</li>
</ul>
<hr>
<h2>What is "in sync"?</h2>
<p>As mentioned above, the response "In sync" means that the Arduino (bootloader) is synchronised with the uploading program.</p>
<hr>
<h2>What protocol is being used?</h2>
<p>The protocol is the STK500 protocol as documented by Atmel. See the references below.</p>
<hr>
<h2>References</h2>
<ul>
<li><a href="https://github.com/Optiboot/optiboot" rel="noreferrer">Optiboot source code - GitHub</a></li>
<li><a href="http://www.atmel.com/Images/doc2525.pdf" rel="noreferrer">AVR061: STK500 Communication Protocol</a></li>
<li><a href="http://www.atmel.com/Images/doc2591.pdf" rel="noreferrer">AVR068: STK500 Communication Protocol version 2</a></li>
<li><a href="https://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno-problems-with-uploading-to-board">Have I bricked my Arduino Uno? Problems with uploading to board</a></li>
<li><a href="http://savannah.nongnu.org/projects/avrdude" rel="noreferrer">AVR Downloader/UploaDEr - avrdude</a></li>
</ul>
<p><em>Note</em>: STK500 Version 2 is not used in Optiboot, but it is included for information in case you are using boards like the Mega2560.</p>
<hr>
<h2>STK500 constants</h2>
<pre class="lang-C++ prettyprint-override"><code>/* STK500 constants list, from AVRDUDE */
#define STK_OK 0x10
#define STK_FAILED 0x11 // Not used
#define STK_UNKNOWN 0x12 // Not used
#define STK_NODEVICE 0x13 // Not used
#define STK_INSYNC 0x14 // ' '
#define STK_NOSYNC 0x15 // Not used
#define ADC_CHANNEL_ERROR 0x16 // Not used
#define ADC_MEASURE_OK 0x17 // Not used
#define PWM_CHANNEL_ERROR 0x18 // Not used
#define PWM_ADJUST_OK 0x19 // Not used
#define CRC_EOP 0x20 // 'SPACE'
#define STK_GET_SYNC 0x30 // '0'
#define STK_GET_SIGN_ON 0x31 // '1'
#define STK_SET_PARAMETER 0x40 // '@'
#define STK_GET_PARAMETER 0x41 // 'A'
#define STK_SET_DEVICE 0x42 // 'B'
#define STK_SET_DEVICE_EXT 0x45 // 'E'
#define STK_ENTER_PROGMODE 0x50 // 'P'
#define STK_LEAVE_PROGMODE 0x51 // 'Q'
#define STK_CHIP_ERASE 0x52 // 'R'
#define STK_CHECK_AUTOINC 0x53 // 'S'
#define STK_LOAD_ADDRESS 0x55 // 'U'
#define STK_UNIVERSAL 0x56 // 'V'
#define STK_PROG_FLASH 0x60 // '`'
#define STK_PROG_DATA 0x61 // 'a'
#define STK_PROG_FUSE 0x62 // 'b'
#define STK_PROG_LOCK 0x63 // 'c'
#define STK_PROG_PAGE 0x64 // 'd'
#define STK_PROG_FUSE_EXT 0x65 // 'e'
#define STK_READ_FLASH 0x70 // 'p'
#define STK_READ_DATA 0x71 // 'q'
#define STK_READ_FUSE 0x72 // 'r'
#define STK_READ_LOCK 0x73 // 's'
#define STK_READ_PAGE 0x74 // 't'
#define STK_READ_SIGN 0x75 // 'u'
#define STK_READ_OSCCAL 0x76 // 'v'
#define STK_READ_FUSE_EXT 0x77 // 'w'
#define STK_READ_OSCCAL_EXT 0x78 // 'x'
</code></pre>
|
15943 | |arduino-uno| | Distance sensor - Not working on fabric surface | 2015-09-09T15:32:23.797 | <p>I am using ultrasonic HC-SO04, not giving reading on fabric. I lost many hours on testing my obstacle avoidance robot car in front of my sofa, every time it hits hard but works fine on other hard surfaces. Is there any other distance sensor which can detect soft objects like fabric from long or short distance? </p>
<p>Also looking any other accurate long distance cheap sensor which can work easily with Arduino. Please let me know. Thanks</p>
| <p>If you are using HC-SR04 then I would suggest you to first check it out on simulation. I use Proteus software for simulation purposes and you should download the <a href="http://www.theengineeringprojects.com/2015/02/ultrasonic-sensor-library-proteus.html" rel="nofollow">Ultrasonic Sensor Library for Proteus</a>, using this library you can easily simulate your Ultrasonic sensor in Proteus and can design your code. It will save you from hardware testing.</p>
|
15945 | |usb|bootloader|reset| | How to reset Arduino Uno over BLE just like over USB? | 2015-09-08T09:00:35.793 | <p>I'm working on wireless upload to Arduino and i've succeed for Mega2560. But when trying to upload to Uno it does not wait for upload commands. I'm doing reset using GPIO and HM-10 BLE module wired with capacitor and resistor and wired to MCU's reset pin just it's done for USB. I think it remembers somehow how it was reset - by pressing hardware RESET button, by USB DTR/RTS or other way. The problem is that when resetting for USB it waits for upload commands after reset and for BLE it does not.</p>
<p>I've viewed optiboot bootloader code but i'm not sure i understand it correctly. Any clue on how to do it?</p>
<p>Update1:</p>
<pre><code>2015-09-05 15:51:36.682 xctest[60180:7754033] [TRACE ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]
2015-09-05 15:51:36.682 xctest[60180:7754033] [TRACE ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-05 15:51:36.735 xctest[60180:7754033] [DEBUG ] [OUT]: Sending 8 bytes
2015-09-05 15:51:36.736 xctest[60180:7754033] [TRACE ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]
2015-09-05 15:51:36.736 xctest[60180:7754033] [TRACE ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-05 15:51:36.788 xctest[60180:7754033] [DEBUG ] [ ]: Draining for 300 ms ...
2015-09-05 15:51:36.788 xctest[60180:7754033] [TRACE ] [IN ]: Start reading
2015-09-05 15:51:37.053 xctest[60180:7754082] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-05 15:51:37.053 xctest[60180:7754082] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-05 15:51:37.093 xctest[60180:7754033] [TRACE ] [IN ]: Finish reading
2015-09-05 15:51:37.093 xctest[60180:7754033] [TRACE ] [IN ]: Ble clear buffer
2015-09-05 15:51:37.093 xctest[60180:7754033] [DEBUG ] [IN ]: Drained 18 bytes
2015-09-05 15:51:37.094 xctest[60180:7754033] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-05 15:51:37.094 xctest[60180:7754033] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-05 15:51:37.094 xctest[60180:7754033] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-05 15:51:37.095 xctest[60180:7754033] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.096 xctest[60180:7754033] [TRACE ] [IN ]: Start reading
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-05 15:51:37.450 xctest[60180:7754084] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-05 15:51:37.452 xctest[60180:7754033] [TRACE ] [IN ]: Finish reading
2015-09-05 15:51:37.452 xctest[60180:7754033] [TRACE ] [IN ]: Receive: . [0x14]
2015-09-05 15:51:37.452 xctest[60180:7754033] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-05 15:51:37.453 xctest[60180:7754033] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-05 15:51:37.453 xctest[60180:7754033] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE ] [IN ]: Having current receive buffer: . [0x10]
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE ] [IN ]: Start reading
2015-09-05 15:51:37.454 xctest[60180:7754033] [TRACE ] [IN ]: Finish reading
2015-09-05 15:51:37.455 xctest[60180:7754033] [TRACE ] [IN ]: Receive: . [0x10]
2015-09-05 15:51:37.455 xctest[60180:7754033] [DEBUG ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-05 15:51:37.455 xctest[60180:7754033] [TRACE ] [IN ]: Ble clear buffer
2015-09-05 15:51:37.455 xctest[60180:7754033] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-05 15:51:37.456 xctest[60180:7754033] [TRACE ] [OUT]: Send: A [0x41] . [0x81] [0x20]
2015-09-05 15:51:37.456 xctest[60180:7754033] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-05 15:51:37.457 xctest[60180:7754033] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-05 15:51:37.457 xctest[60180:7754033] [TRACE ] [IN ]: Start reading
2015-09-05 15:51:37.701 xctest[60180:7754084] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-05 15:51:37.701 xctest[60180:7754084] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-05 15:51:38.451 xctest[60180:7754082] [TRACE ] [IN ]: Rx value received 5 bytes: h [0x68] e [0x65] l [0x6C] l [0x6C] o [0x6F]
2015-09-05 15:51:38.452 xctest[60180:7754033] [TRACE ] [IN ]: Finish reading
</code></pre>
<p>Update 2 (this is uploading to Uno over USB log):</p>
<pre><code>2015-06-29 16:34:10.829 xctest[36585:3703900] [TRACE ] [ ]: DTR/RTS supported by Serial, resetting
2015-06-29 16:34:11.140 xctest[36585:3703900] [DEBUG ] [IN ]: Draining ...
2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG ] [IN ]: Drain done
2015-06-29 16:34:11.392 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.392 xctest[36585:3703900] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-06-29 16:34:11.393 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.531 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.531 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.532 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 3 bytes
2015-06-29 16:34:11.532 xctest[36585:3703900] [TRACE ] [OUT]: Send: A [0x41] . [0x81] [0x20]
2015-06-29 16:34:11.533 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.535 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x04]
2015-06-29 16:34:11.536 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.536 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 3 bytes
2015-06-29 16:34:11.537 xctest[36585:3703900] [TRACE ] [OUT]: Send: A [0x41] . [0x82] [0x20]
2015-06-29 16:34:11.537 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.540 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x04]
2015-06-29 16:34:11.540 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.541 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG ] [ ]: STK500:initialize: n_extparms = 4
2015-06-29 16:34:11.541 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 22 bytes
2015-06-29 16:34:11.542 xctest[36585:3703900] [TRACE ] [OUT]: Send: B [0x42] . [0x86] . [0x00] . [0x01] . [0x00] . [0x01] . [0x01] . [0x01] . [0x03] . [0xFF] . [0xFF] . [0xFF] . [0xFF] . [0x00] . [0x80] . [0x04] . [0x00] . [0x00] . [0x00] . [0x80] . [0x00] [0x20]
2015-06-29 16:34:11.542 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.548 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.548 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 7 bytes
2015-06-29 16:34:11.549 xctest[36585:3703900] [TRACE ] [OUT]: Send: E [0x45] . [0x05] . [0x04] . [0xD7] . [0xC2] . [0x00] [0x20]
2015-06-29 16:34:11.549 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.552 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.552 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.553 xctest[36585:3703900] [TRACE ] [OUT]: Send: P [0x50] [0x20]
2015-06-29 16:34:11.553 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14]
2015-06-29 16:34:11.556 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 1 bytes
2015-06-29 16:34:11.556 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x10]
2015-06-29 16:34:11.569 xctest[36585:3703900] Reading | | 0% 0ms
2015-06-29 16:34:11.570 xctest[36585:3703900] [DEBUG ] [OUT]: Sending 2 bytes
2015-06-29 16:34:11.571 xctest[36585:3703900] [TRACE ] [OUT]: Send: u [0x75] [0x20]
2015-06-29 16:34:11.571 xctest[36585:3703900] [DEBUG ] [IN ]: Receiving 5 bytes
2015-06-29 16:34:11.572 xctest[36585:3703900] [TRACE ] [IN ]: Received: . [0x14] . [0x1E] . [0x95] . [0x0F] . [0x10]
2015-06-29 16:34:11.572 xctest[36585:3703900] Reading | ################################################## | 100% 2ms
</code></pre>
<p>Update 3:</p>
<p>i've modified bootloader (optiboot) to wait 4 seconds (instead of 1 second by default) and added blinking when character 0x41 (STK_GET_PARAMETER) arrives. Also i've uploaded 'echo' sketch to return what back everything that is sent to the board.</p>
<p>bootloader modifications (part):</p>
<pre><code>// Set up watchdog to trigger after 4s
watchdogConfig(WATCHDOG_4S); // 4ntoine: was WATCHDOG_1s
/* Set LED pin as output */
LED_DDR |= _BV(LED);
#ifdef SOFT_UART
/* Set TX pin as output */
UART_DDR |= _BV(UART_TX_BIT);
#endif
// #if LED_START_FLASHES > 0
/* Flash onboard LED to signal entering of bootloader */
// flash_led(2); // 4ntoine
// #endif
/* Forever loop */
for (;;) {
/* get character from UART */
ch = getch();
if(ch == STK_GET_PARAMETER) {
flash_led(2); // 4ntoine
unsigned char which = getch();
verifySpace();
if (which == 0x82) {
/*
* Send optiboot version as "minor SW version"
*/
putch(OPTIBOOT_MINVER);
} else if (which == 0x81) {
putch(OPTIBOOT_MAJVER);
} else {
/*
* GET PARAMETER returns a generic 0x03 reply for
* other parameters - enough to keep Avrdude happy
*/
putch(0x03);
}
}
</code></pre>
<p>uploaded arduino sketch:</p>
<pre><code>int LED = 13;
void setup() {
// avoid misleading blinking
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
// to let us know when sketch starts
Serial.begin(115200);
Serial.write("hello");
}
void loop() {
while (Serial.available()) {
int incomingByte = Serial.read();
Serial.write(incomingByte);
}
}
</code></pre>
<p>log:</p>
<pre><code>2015-09-13 20:52:57.011 xctest[55099:2968978] [INFO ] [ ]: Found peripheral: <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = disconnected>
2015-09-13 20:52:57.011 xctest[55099:2968978] [DEBUG ] [ ]: Stop scanning
2015-09-13 20:52:57.012 xctest[55099:2968978] [INFO ] [ ]: Connecting to <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = disconnected>
2015-09-13 20:52:57.236 xctest[55099:2968989] [DEBUG ] [ ]: Connected to peripheral <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = connected>
2015-09-13 20:52:57.238 xctest[55099:2968989] [TRACE ] [ ]: Discovered services for peripheral <CBPeripheral: 0x100400af0 identifier = D92ECAAB-51A5-44D5-8C6C-536CD797867E, Name = "BleIos", state = connected>
2015-09-13 20:52:57.238 xctest[55099:2968989] [DEBUG ] [ ]: Discovered service <CBService: 0x10010d950>
2015-09-13 20:52:57.381 xctest[55099:2968989] [TRACE ] [ ]: Discovered characteristics for service <CBService: 0x10010d950>
2015-09-13 20:52:57.381 xctest[55099:2968989] [TRACE ] [ ]: Discovered characteristic <CBCharacteristic: 0x100304d10>
2015-09-13 20:52:57.382 xctest[55099:2968989] [DEBUG ] [ ]: Tx characteristic supports WriteWithResponse: NO
2015-09-13 20:52:57.382 xctest[55099:2968989] [TRACE ] [ ]: Subscribing to Rx value
2015-09-13 20:52:57.392 xctest[55099:2968940] [INFO ] [ ]: Connected successfully
2015-09-13 20:52:57.392 xctest[55099:2968940] [TRACE ] [ ]: DTR/RTS supported by Serial, resetting
2015-09-13 20:52:57.392 xctest[55099:2968940] [TRACE ] [ ]: Waiting until subscribed to Rx value ...
2015-09-13 20:52:58.387 xctest[55099:2968989] [DEBUG ] [IN ]: Updated notifications state for RX characteristic: isNotifying=YES
2015-09-13 20:52:58.408 xctest[55099:2968940] [DEBUG ] [OUT]: Sending 8 bytes
2015-09-13 20:52:58.408 xctest[55099:2968940] [TRACE ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 1 [0x31]
2015-09-13 20:52:58.408 xctest[55099:2968940] [TRACE ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-13 20:52:58.463 xctest[55099:2968940] [DEBUG ] [OUT]: Sending 8 bytes
2015-09-13 20:52:58.463 xctest[55099:2968940] [TRACE ] [OUT]: Send: A [0x41] T [0x54] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] 0 [0x30]
2015-09-13 20:52:58.463 xctest[55099:2968940] [TRACE ] [OUT]: BLE sending bytes range from 0 length 8
2015-09-13 20:52:58.518 xctest[55099:2968940] [DEBUG ] [ ]: Draining for 300 ms ...
2015-09-13 20:52:58.518 xctest[55099:2968940] [TRACE ] [IN ]: Start reading
2015-09-13 20:52:58.784 xctest[55099:2968989] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-13 20:52:58.785 xctest[55099:2968989] [WARNING] [IN ]: Removing 'OK+PIO2:1' (9 bytes) from incoming buffer (9 bytes)
2015-09-13 20:52:58.785 xctest[55099:2968989] [WARNING] [IN ]: Got 0 bytes in incoming buffer
2015-09-13 20:52:58.786 xctest[55099:2968989] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-13 20:52:58.786 xctest[55099:2968989] [WARNING] [IN ]: Removing 'OK+PIO2:0' (9 bytes) from incoming buffer (9 bytes)
2015-09-13 20:52:58.787 xctest[55099:2968989] [WARNING] [IN ]: Got 0 bytes in incoming buffer
2015-09-13 20:52:58.820 xctest[55099:2968940] [TRACE ] [IN ]: Finish reading
2015-09-13 20:52:58.820 xctest[55099:2968940] [TRACE ] [IN ]: Ble clear buffer
2015-09-13 20:52:58.821 xctest[55099:2968940] [DEBUG ] [IN ]: Drained 0 bytes
2015-09-13 20:52:58.821 xctest[55099:2968940] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-13 20:52:58.821 xctest[55099:2968940] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-13 20:52:58.821 xctest[55099:2968940] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-13 20:52:58.822 xctest[55099:2968940] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:58.822 xctest[55099:2968940] [TRACE ] [IN ]: Start reading
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:52:59.193 xctest[55099:2968978] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-13 20:52:59.194 xctest[55099:2968978] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-13 20:52:59.194 xctest[55099:2968940] [TRACE ] [IN ]: Finish reading
2015-09-13 20:52:59.195 xctest[55099:2968940] [TRACE ] [IN ]: Receive: . [0x14]
2015-09-13 20:52:59.195 xctest[55099:2968940] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-13 20:52:59.195 xctest[55099:2968940] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-13 20:52:59.196 xctest[55099:2968940] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE ] [IN ]: Having current receive buffer: . [0x10]
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE ] [IN ]: Start reading
2015-09-13 20:52:59.196 xctest[55099:2968940] [TRACE ] [IN ]: Finish reading
2015-09-13 20:52:59.197 xctest[55099:2968940] [TRACE ] [IN ]: Receive: . [0x10]
2015-09-13 20:52:59.197 xctest[55099:2968940] [DEBUG ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-13 20:52:59.197 xctest[55099:2968940] [TRACE ] [IN ]: Ble clear buffer
2015-09-13 20:52:59.198 xctest[55099:2968940] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-13 20:52:59.198 xctest[55099:2968940] [TRACE ] [OUT]: Send: A [0x41] . [0x81] [0x20]
2015-09-13 20:52:59.198 xctest[55099:2968940] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-13 20:52:59.199 xctest[55099:2968940] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-13 20:52:59.199 xctest[55099:2968940] [TRACE ] [IN ]: Start reading
2015-09-13 20:52:59.268 xctest[55099:2968978] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:52:59.268 xctest[55099:2968978] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:53:02.955 xctest[55099:2968940] [ERROR ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-13 20:53:02.955 xctest[55099:2968940] [TRACE ] [IN ]: Finish reading
2015-09-13 20:53:02.955 xctest[55099:2968940] [TRACE ] [IN ]: Ble clear buffer
2015-09-13 20:53:02.955 xctest[55099:2968940] [ERROR ] [IN ]: STK500:receive: programmer is not responding
2015-09-13 20:53:02.956 xctest[55099:2968940] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-13 20:53:02.956 xctest[55099:2968940] [TRACE ] [OUT]: Send: A [0x41] . [0x82] [0x20]
2015-09-13 20:53:02.956 xctest[55099:2968940] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-13 20:53:02.956 xctest[55099:2968940] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-13 20:53:02.957 xctest[55099:2968940] [TRACE ] [IN ]: Start reading
2015-09-13 20:53:03.018 xctest[55099:2968978] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-13 20:53:03.018 xctest[55099:2968978] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-13 20:53:03.280 xctest[55099:2968989] [TRACE ] [IN ]: Rx value received 5 bytes: h [0x68] e [0x65] l [0x6C] l [0x6C] o [0x6F]
2015-09-13 20:53:03.280 xctest[55099:2968989] [WARNING] [IN ]: Got 5 bytes in incoming buffer
2015-09-13 20:53:03.281 xctest[55099:2968940] [TRACE ] [IN ]: Finish reading
</code></pre>
<p>i can see blinking so the character arrives so the characters arrive correctly to the board. also i've tested wiring (sketch returns exactly the same as it was sent and it sends 'hello' after start). So i'm pretty sure:
1. characters arrive correctly to the bootloader
2. wiring is correct (as i can see back what i've sent - i'm using LightBlue mac app to open HM-10 as BLE device, subscribe to the characteristics and send characters and i can see it's changing to what i've sent).
3. bootloader waits for 4 seconds (i can see it in Arduino IDE terminal).</p>
<p>Update 4 :</p>
<p>my understanding now is that optiboot sets wrong baud rate for 115200 passed in bootloader mode as it replies with 0x11 and transmits characters correctly in sketch mode:</p>
<pre><code>2015-09-17 09:39:25.628 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-17 09:39:25.628 xctest[60179:4253160] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-17 09:39:25.629 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-17 09:39:25.629 xctest[60179:4253160] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-17 09:39:25.630 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:25.630 xctest[60179:4253160] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.351 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:27.351 xctest[60179:4253117] [TRACE ] [IN ]: Ble clear buffer
2015-09-17 09:39:27.351 xctest[60179:4253117] [DEBUG ] [IN ]: Drained 18 bytes
2015-09-17 09:39:27.352 xctest[60179:4253117] [DEBUG ] [ ]: Draining incoming buffer (0 bytes)
2015-09-17 09:39:27.352 xctest[60179:4253117] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-17 09:39:27.352 xctest[60179:4253117] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-17 09:39:27.353 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-17 09:39:27.353 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.353 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:27.424 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.424 xctest[60179:4253160] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.424 xctest[60179:4253149] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x11] . [0xFC]
2015-09-17 09:39:27.425 xctest[60179:4253149] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-17 09:39:27.425 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:27.425 xctest[60179:4253117] [TRACE ] [IN ]: Receive: . [0x11]
2015-09-17 09:39:27.425 xctest[60179:4253117] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-17 09:39:27.426 xctest[60179:4253117] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-17 09:39:27.426 xctest[60179:4253117] [ERROR ] [ ]: STK500:synchronize: attempt 1 of 3: no sync: received [0x11]
2015-09-17 09:39:27.426 xctest[60179:4253117] [DEBUG ] [ ]: Draining incoming buffer (1 bytes)
2015-09-17 09:39:27.426 xctest[60179:4253117] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-17 09:39:27.427 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.427 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:27.499 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.499 xctest[60179:4253160] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:27.500 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-17 09:39:27.500 xctest[60179:4253160] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-17 09:39:27.500 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE ] [IN ]: Receive: . [0x14]
2015-09-17 09:39:27.501 xctest[60179:4253117] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-17 09:39:27.501 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.501 xctest[60179:4253117] [TRACE ] [IN ]: Having current receive buffer: . [0x10]
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:27.502 xctest[60179:4253117] [TRACE ] [IN ]: Receive: . [0x10]
2015-09-17 09:39:27.508 xctest[60179:4253117] [DEBUG ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE ] [IN ]: Ble clear buffer
2015-09-17 09:39:27.509 xctest[60179:4253117] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE ] [OUT]: Send: A [0x41] . [0x81] [0x20]
2015-09-17 09:39:27.509 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-17 09:39:27.510 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:27.510 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:27.574 xctest[60179:4253149] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:27.574 xctest[60179:4253149] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:31.325 xctest[60179:4253117] [ERROR ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-17 09:39:31.326 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:31.326 xctest[60179:4253117] [TRACE ] [IN ]: Ble clear buffer
2015-09-17 09:39:31.326 xctest[60179:4253117] [ERROR ] [IN ]: STK500:receive: programmer is not responding
2015-09-17 09:39:31.327 xctest[60179:4253117] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-17 09:39:31.327 xctest[60179:4253117] [TRACE ] [OUT]: Send: A [0x41] . [0x82] [0x20]
2015-09-17 09:39:31.327 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-17 09:39:31.328 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:31.328 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:31.399 xctest[60179:4253160] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:31.400 xctest[60179:4253160] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-17 09:39:35.173 xctest[60179:4253117] [ERROR ] [OUT]: BLE read timeout: 3.000965 (timeout = 3.000000)
2015-09-17 09:39:35.173 xctest[60179:4253117] [TRACE ] [IN ]: Finish reading
2015-09-17 09:39:35.174 xctest[60179:4253117] [TRACE ] [IN ]: Ble clear buffer
2015-09-17 09:39:35.174 xctest[60179:4253117] [ERROR ] [IN ]: STK500:receive: programmer is not responding
2015-09-17 09:39:35.174 xctest[60179:4253117] [DEBUG ] [ ]: STK500:initialize: n_extparms = 3
2015-09-17 09:39:35.175 xctest[60179:4253117] [DEBUG ] [OUT]: Sending 22 bytes
2015-09-17 09:39:35.175 xctest[60179:4253117] [TRACE ] [OUT]: Send: B [0x42] . [0x86] . [0x00] . [0x01] . [0x00] . [0x01] . [0x01] . [0x01] . [0x03] . [0xFF] . [0xFF] . [0xFF] . [0xFF] . [0x00] . [0x80] . [0x04] . [0x00] . [0x00] . [0x00] . [0x80] . [0x00] [0x20]
2015-09-17 09:39:35.175 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 0 length 20
2015-09-17 09:39:35.176 xctest[60179:4253117] [TRACE ] [OUT]: BLE sending bytes range from 20 length 2
2015-09-17 09:39:35.177 xctest[60179:4253117] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-17 09:39:35.177 xctest[60179:4253117] [TRACE ] [IN ]: Start reading
2015-09-17 09:39:35.224 xctest[60179:4253149] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-17 09:39:35.224 xctest[60179:4253149] [TRACE ] [IN ]: Ignoring single 0x00 char
</code></pre>
<p>Should it work if i wire pins 0 and 1 at Uno to RX/TX (it does work for Mega2560)? Here is soft uart code from optiboot:</p>
<pre><code>#ifndef SOFT_UART
#ifdef __AVR_ATmega8__
UCSRA = _BV(U2X); //Double speed mode USART
UCSRB = _BV(RXEN) | _BV(TXEN); // enable Rx & Tx
UCSRC = _BV(URSEL) | _BV(UCSZ1) | _BV(UCSZ0); // config USART; 8N1
UBRRL = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#else
UCSR0A = _BV(U2X0); //Double speed mode USART0
UCSR0B = _BV(RXEN0) | _BV(TXEN0);
UCSR0C = _BV(UCSZ00) | _BV(UCSZ01);
UBRR0L = (uint8_t)( (F_CPU + BAUD_RATE * 4L) / (BAUD_RATE * 8L) - 1 );
#endif
#endif
#ifdef SOFT_UART
/* Set TX pin as output */
UART_DDR |= _BV(UART_TX_BIT);
#endif
</code></pre>
<p>Should RX be set as input separately too (like Tx as output)? Why it tries to set 'Double speed'?</p>
| <p>Eventually i've found the reason. And it was bug in HM-10 firmware.
In mode 0 it does not accept control commands and in modes 1 and 2 it accepts AT commands to control PIO and commands are look like 'AT+...', f.e. 'PIO set value 1 to pin 1' command is 'AT+PIO11' and change mode to 0 look like 'AT+MODE0'. I need mode 1 to set PIO to 1 and 0 to reset arduino board. The problem is that some of upload commands look like 'A [0x41] . [0x81] [0x20]' (starts from 'A' too) and it makes HM-10 think it's control command which also starts from 'A'. If i add changing mode to 0 after pin control commands (in order to make HM-10 stop accepting control commands) it starts uploading:</p>
<pre><code>2015-09-18 10:27:32.144 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 1 [0x31]
2015-09-18 10:27:32.145 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-18 10:27:32.145 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 9 bytes: O [0x4F] K [0x4B] + [0x2B] P [0x50] I [0x49] O [0x4F] 2 [0x32] : [0x3A] 0 [0x30]
2015-09-18 10:27:32.146 xctest[94852:4603627] [WARNING] [IN ]: Got 9 bytes in incoming buffer
2015-09-18 10:27:32.146 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 8 bytes: O [0x4F] K [0x4B] + [0x2B] S [0x53] e [0x65] t [0x74] : [0x3A] 0 [0x30]
2015-09-18 10:27:32.147 xctest[94852:4603627] [WARNING] [IN ]: Got 8 bytes in incoming buffer
2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.147 xctest[94852:4603627] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.207 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG ] [IN ]: Drained 26 bytes
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG ] [ ]: Draining incoming buffer (0 bytes)
2015-09-18 10:27:32.208 xctest[94852:4603578] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-18 10:27:32.208 xctest[94852:4603578] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-18 10:27:32.209 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.209 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.561 xctest[94852:4603630] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.561 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x11] . [0xFC]
2015-09-18 10:27:32.561 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x11]
2015-09-18 10:27:32.563 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.563 xctest[94852:4603578] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.563 xctest[94852:4603578] [ERROR ] [ ]: STK500:synchronize: attempt 1 of 3: no sync: received [0x11]
2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG ] [ ]: Draining incoming buffer (1 bytes)
2015-09-18 10:27:32.564 xctest[94852:4603578] [DEBUG ] [OUT]: Sending 2 bytes
2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE ] [OUT]: Send: 0 [0x30] [0x20]
2015-09-18 10:27:32.564 xctest[94852:4603578] [TRACE ] [OUT]: BLE sending bytes range from 0 length 2
2015-09-18 10:27:32.565 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.565 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.636 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 2 bytes: . [0x14] . [0x10]
2015-09-18 10:27:32.636 xctest[94852:4603627] [WARNING] [IN ]: Got 2 bytes in incoming buffer
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x14]
2015-09-18 10:27:32.638 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.638 xctest[94852:4603578] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.639 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE ] [IN ]: Having current receive buffer: . [0x10]
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.639 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.640 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x10]
2015-09-18 10:27:32.644 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-18 10:27:32.644 xctest[94852:4603578] [TRACE ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE ] [OUT]: Send: A [0x41] . [0x81] [0x20]
2015-09-18 10:27:32.645 xctest[94852:4603578] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-18 10:27:32.645 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.646 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.711 xctest[94852:4603630] [TRACE ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
2015-09-18 10:27:32.711 xctest[94852:4603630] [WARNING] [IN ]: Got 3 bytes in incoming buffer
2015-09-18 10:27:32.712 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x14]
2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 3 bytes
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE ] [IN ]: 2 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.713 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.713 xctest[94852:4603578] [TRACE ] [IN ]: Having current receive buffer: . [0x04] . [0x10]
2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.714 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.728 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x04]
2015-09-18 10:27:32.728 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 2 bytes
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE ] [IN ]: 1 bytes in incoming buffer remaining for next receive
2015-09-18 10:27:32.729 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE ] [IN ]: Having current receive buffer: . [0x10]
2015-09-18 10:27:32.729 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE ] [IN ]: Receive: . [0x10]
2015-09-18 10:27:32.730 xctest[94852:4603578] [DEBUG ] [IN ]: Read 1 bytes, actually received 1 bytes
2015-09-18 10:27:32.730 xctest[94852:4603578] [TRACE ] [IN ]: Ble clear buffer
2015-09-18 10:27:32.731 xctest[94852:4603578] [DEBUG ] [OUT]: Sending 3 bytes
2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE ] [OUT]: Send: A [0x41] . [0x82] [0x20]
2015-09-18 10:27:32.731 xctest[94852:4603578] [TRACE ] [OUT]: BLE sending bytes range from 0 length 3
2015-09-18 10:27:32.732 xctest[94852:4603578] [DEBUG ] [IN ]: Reading 1 bytes ...
2015-09-18 10:27:32.732 xctest[94852:4603578] [TRACE ] [IN ]: Start reading
2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 1 bytes: . [0x00]
2015-09-18 10:27:32.786 xctest[94852:4603627] [TRACE ] [IN ]: Ignoring single 0x00 char
2015-09-18 10:27:32.787 xctest[94852:4603627] [TRACE ] [IN ]: Rx value received 3 bytes: . [0x14] . [0x04] . [0x10]
2015-09-18 10:27:32.787 xctest[94852:4603627] [WARNING] [IN ]: Got 3 bytes in incoming buffer
2015-09-18 10:27:32.788 xctest[94852:4603578] [TRACE ] [IN ]: Finish reading
2015-09-18 10:27:32.788 xctest[94
</code></pre>
<p>I was working for Mega2560 since it uses different bootloader and upload commands do not start from 'A'. It's definitely HM-10 firmware bug as it can understand it's not control command since the second byte is not 'T'.</p>
<p>If i had oscilloscope i'd find the reason in 1 hour but for casual engineering i don't need it. I've reported a bug to HM-10 manufacturer but i'm not sure when they fix it. HM-10 firmware version is v532.</p>
|
15949 | |arduino-uno|c++| | How to print a line with a variable in it? | 2015-09-09T22:10:03.410 | <p>I want to know if there is a way to write like in C programming:</p>
<pre><code> printf("the num is %d",num);
</code></pre>
<p>I know that to print a line or a variable the command will be Serial.println
when I write:</p>
<pre><code> Serial.println("the num is %d",num);
</code></pre>
<p>It's not working.</p>
<p>Is there a way to write it in just one line? </p>
| <p>I use:</p>
<pre><code>Serial.println("The temperature is " + String(temperature) + " degrees C");
</code></pre>
<p>With this solution you can't format the variable's value but I find this quick and dirty for debug messages.</p>
|
15960 | |arduino-uno|serial|programming|usb|communication| | Serial comms failure after long time - can't open COM port | 2015-09-10T13:55:26.133 | <p>I've been using an Arduino UNO to log data: it's queried by a LabView VI over a VISA connection. It'll happily sit there and log for days, but very occasionally one of the VISA functions will fail. </p>
<p>After this, I can't open the COM port again (in LabView or elsewhere) and the only way to restore communication is to unplug and replug the USB cable. The Arduino hasn't crashed because I can see the other results of the program it's running working fine, but Serial comms are a gonner. </p>
<p>Has anyone experienced this? Do you know if this is an Arduino problem, a Labview problem, a Windows problem? Or something else? </p>
<p>I'm writing a minimum working example to try and catch this happening in the most simple code possible, but since the error usually takes several days to show up I can't tell you the results yet!</p>
| <p>In the end I found a solution, more or less through trial and error. </p>
<p>Labview default its VISA VIs to "asynchronous" mode: I found that by switching them to "synchronous" (right click on them and select "synchronous") this problem disappeared.</p>
<p>I think this is caused by the computer occasionally getting ahead of the Arduino and asking for the next measurement before it's finished receiving the first one. Switching to synchronous mode forces execution to wait until the VISA exchange is complete before it continues. </p>
|
15963 | |arduino-uno|c++|pointer| | C++ Pointer Issues - Mangled Data | 2015-09-10T16:31:16.560 | <p>I am having trouble getting my head around pointers in C++, specifically how they behave when passed around or used within objects. As far as my understanding goes as long as pointers, or more specifically values/objects pointed <em>to</em> - do not go out of scope, I should be able to use that pointer.</p>
<p>I have been playing around with some test code on my Arduino Uno and I am bumping into behaviour I cannot explain.</p>
<p>I have read rather a lot on the topic of pointers in C++ and thought I had a good grasp of it. However, practice doesn't seem to match the theory in my head. I don't know if this is a lack of understanding or if the Arduino platform has idiosyncrasies that I am not aware of.</p>
<p>In my test code I have created two classes, <code>Alpha</code> and <code>Beta</code>. Alpha simply holds a C-type string in a member variable called <code>alpha</code>. <code>Beta</code> is designed to hold two <code>Alpha</code> instances in an array*. </p>
<p>*While this is "toy" code, the general structure mirrors my actual project. I have used this toy code as it more succinctly describes the set up and the issue I am facing.</p>
<p><strong>pointers.h</strong></p>
<pre><code>#import "Arduino.h"
class Alpha {
private:
char alpha[20];
public:
Alpha();
~Alpha();
char* getAlpha(char* s, int size=20);
void setAlpha(char* value, int size=20);
void debug();
};
class Beta {
private:
Alpha** alphas;
public:
Beta();
~Beta();
Alpha* getAlpha(int index);
void setAlpha(Alpha* alpha, int index);
void doStuffWithAlpha(int index);
};
</code></pre>
<p><strong>pointers.cpp</strong></p>
<pre><code>#import "pointers.h"
Alpha::Alpha() {
setAlpha("Initial");
}
Alpha::~Alpha() {}
char* Alpha::getAlpha(char* s, int size/*=20*/) {
*s = *alpha;
return s; //return not strictly needed here since s is passed in
}
void Alpha::setAlpha(char* value, int size/*=20*/) {
strncpy(alpha, value, size-1);
alpha[size-1] = '\0';
}
void Alpha::debug() {
Serial.println(alpha);
}
Beta::Beta() {
alphas = new Alpha*[2];
}
Beta::~Beta() {}
Alpha* Beta::getAlpha(int index) {
return alphas[index];
}
void Beta::setAlpha(Alpha* alpha, int index) {
alphas[index] = alpha;
}
void Beta::doStuffWithAlpha(int index) {
Alpha* alpha = getAlpha(index);
/* Alpha* alpha = alphas[index]; */ //This doesn't work either - same outcome.
alpha->debug();
}
</code></pre>
<p><strong>sketch.ino</strong></p>
<pre><code>#import "pointers.h"
Alpha a1;
Alpha a2;
Beta b1;
void setup() {
Serial.begin(9600);
Serial.println("SETUP()");
Serial.println();
a1 = Alpha();
a1.setAlpha("Hello");
Serial.println("----- a1.debug -----");
Serial.println("Expected: Hello");
Serial.print("Actual: "); a1.debug();
Serial.println();
a2 = Alpha();
a2.setAlpha("Goodbye");
Serial.println("----- a2.debug -----");
Serial.println("Expected: Goodbye");
Serial.print("Actual: "); a2.debug();
Serial.println();
Beta b1 = Beta();
b1.setAlpha(&a1, 0);
b1.setAlpha(&a2, 1);
Serial.println("----- b1.doStuffWithAlpha -----");
Serial.println("Expected: Hello");
Serial.print("Actual: "); b1.doStuffWithAlpha(0);
Serial.println("Expected: Goodbye");
Serial.print("Actual: "); b1.doStuffWithAlpha(1);
Serial.println();
}
void loop() {
Serial.println("LOOP()");
Serial.println();
Serial.println("----- a1.debug -----");
Serial.println("Expected: Hello");
Serial.print("Actual: "); a1.debug();
Serial.println();
Serial.println("----- b1.doStuffWithAlpha(0) ------");
Serial.println("Expected: Hello");
Serial.print("Actual: "); b1.doStuffWithAlpha(0);
Serial.println();
Serial.println("----- a2.debug -----");
Serial.println("Expected: Goodbye");
Serial.print("Actual: "); a2.debug();
Serial.println();
Serial.println("----- b1.doStuffWithAlpha(1) ------");
Serial.println("Expected: Goodbye");
Serial.print("Actual: "); b1.doStuffWithAlpha(1);
Serial.println();
delay(10000);
}
</code></pre>
<p>This sketch is quite straight-forward. It creates 2 <code>Alpha</code> objects and a <code>Beta</code> object and passes the two Alphas into Beta. The myriad <code>Serial.print()</code> statements produces the output below.</p>
<p><strong>output</strong></p>
<pre><code>SETUP()
----- a1.debug -----
Expected: Hello
Actual: Hello
----- a2.debug -----
Expected: Goodbye
Actual: Goodbye
----- b1.doStuffWithAlpha -----
Expected: Hello
Actual: Hello
Expected: Goodbye
Actual: Goodbye
//everything is fine up to this point...
LOOP()
----- a1.debug -----
Expected: Hello
Actual: Hello
----- b1.doStuffWithAlpha(0) ------
Expected: Hello
Actual: CÃoçëyc=Lä^ÜŽYw¸Nv†Ý¿ //uh oh...
----- a2.debug -----
Expected: Goodbye
Actual: Goodbye
----- b1.doStuffWithAlpha(1) ------
Expected: Goodbye
Actual: ÿß/ï //uh oh again...
</code></pre>
<p>Everything works as expected when running <code>a1</code> or <code>a2.debug()</code> or <code>b1.doStuffWithAlpha()</code> in the <code>setup()</code> function. </p>
<p>The result of <code>a1.debug()</code> and <code>a2.debug()</code> works as expected in the <code>loop()</code> function.</p>
<p>The issue, as you can see, is when running <code>b1.doStuffWithAlpha(0)</code> or <code>b1.doStuffWithAlpha(1)</code>. The output is usually junk, which suggests to me the pointer has been mangled and points in the wrong place.</p>
<p>I don't understand what is happening between the transition from <code>setup()</code> to <code>loop()</code>. At first I thought the issue was the "Hello" and "Goodbye" strings going out of scope, but <code>Alpha::setAlpha()</code> makes a copy of the C-string. Also, accessing <code>Alpha::debug()</code> in <code>loop()</code> works, as shown above.</p>
<p>I have tried variations on the above code, such as using a struct or an int for <code>alpha</code> instead of a C-string and the results are the same: Mangled values.</p>
<p>Have I done something obviously silly that my scant C++ experience hasn't picked up on, or is there some fundamental Arduino shenanigans at play?</p>
| <p>Problem is local shadow variable <code>b1</code> in setup() function declared as <code>Beta b1 = Beta();</code>. In <code>loop()</code> is considered uninitialized global variable <code>b1</code>.</p>
|
15964 | |arduino-uno|millis|pulsein| | Measurement of pulse duration greater than 3mins | 2015-09-10T17:17:36.987 | <p>Is it possible to measure the width of a pulse which is longer than 3 minutes? The pulseIn function can only measure duration of maximum 3 minutes accurately.
I've tried using interrupts but haven't come up with a correct solution yet.</p>
<p>I'm measuring the duration of pulse (HIGH) generated by AND gate connected to the outputs of two comparators. AND gate output voltage is around <strong>4.9 volts</strong>. </p>
<p>Any logical solution or idea would be appreciated. Thanks!</p>
|
<p>Here is some code I used to time a ball running down a ramp:</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 high, start timing
if (digitalRead (photoTransistor) == HIGH)
{
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>Using <code>micros()</code> here is probably overkill, but that should be good for an interval up to 71 minutes.</p>
|
15966 | |arduino-yun| | How does Yun identify itself to Windows? | 2015-09-10T17:34:00.400 | <p>When I plug in my Yun, Windows pops up a box saying <code>Windows needs to install driver software for your Arduino Yun</code>.</p>
<p>What does Windows use to identify my device as an Arduino Yun? Is it written in a file somewhere, so I could for example, <i>remove</i> that driver prompt, or <i>change</i> it to <code>Windows needs to install driver software for your Foo Bar?</code></p>
| <p>It is written in what is called the <em>USB String Descriptor</em>. I don't have my Yun to hand right now (it's acting as a wireless bridge temporarily), but all USB devices have these <em>USB String Descriptors</em>. Here's an example for the Leonardo (which you can easily inspect on Linux):</p>
<pre><code>$ sudo lsusb -v -d 2341:0036
Bus 001 Device 015: ID 2341:0036 Arduino SA
Device Descriptor:
bLength 18
bDescriptorType 1
bcdUSB 1.10
bDeviceClass 2 Communications
bDeviceSubClass 0
bDeviceProtocol 0
bMaxPacketSize0 8
idVendor 0x2341 Arduino SA
idProduct 0x0036
bcdDevice 0.01
iManufacturer 2 Arduino LLC <<== String descriptor ID 2
iProduct 1 Arduino Leonardo <<== String descriptor ID 1
iSerial 0
... etc ...
</code></pre>
<p>Internally the strings are stored as an indexed table - there's two there, ID 1 and ID 2. The <em>Device Descriptor</em> then has a couple of bytes in it that says "The manufacturer is string ID 2, and the product name is string ID 1". The operating system then requests those string descriptors so it can display the friendly message for you.</p>
<p>If you want to change that name you basically have to both re-program the bootloader (which has the USB descriptors when in program upload mode) and the Arduino core (that has the string descriptors programmed into it).</p>
|
15971 | |arduino-uno|arduino-mega|clones| | Can I stack an Arduino to another Arduino? | 2015-09-10T19:41:55.150 | <p>I'm using Arduino clones, which have pin headers the same as Arduino's shields have (with extended "legs" below the board to be stackable).</p>
<p>Can I stack my Arduino (Mega) clone to an Arduino (Uno) clone without destroying both? Wouldn't it explode or something?</p>
<p>Just asking before trying it.</p>
<p>Thanks!</p>
| <p>No, I don't think that is a good idea. You would basically short the pins of each of them together, plus their power supplies. The only way it might conceivably work was if one Arduino had all its pins as inputs and the other as outputs, otherwise they would be "fighting" each other to drive a pin high or low. You would also have connected together their Reset pins so they would both reset at the same time. And doing serial comms would be problematic as the serial ports would be fighting each other.</p>
<hr>
<p>Also, uploading sketches would be virtually impossible, as when you started the upload, both would be reset, both bootloaders would try to read the incoming data, and reply at the same time. Plus, the Mega and the Uno have different uploading protocols. So at the very least, you would have to separate them every time you uploaded new code, to either one.</p>
|
15980 | |arduino-uno|serial|i2c|teensy| | Unexpected output form Serial.println | 2015-09-11T03:17:41.450 | <p>So I have a teensy and an arduino uno connected together via I2C, however some very odd behavior is occurring, when monitoring the serial connection for shorter data sent over I2C I receive the expected serial output. However if the data is longer I only receive 2 characters. More strange even is that if I send the longer data again I receive none, but if I send the shorter data I receive the expected output. After sending the shorter data again sending the longer data will result is the odd 2 characters.</p>
<p>Uno code
//#include </p>
<pre><code> #include <Wire.h>
boolean pinout = 0;
byte current[512];
void setup() {
// put your setup code here, to run once:
Wire.begin(1);
Serial.begin(115200);
Wire.onReceive(data);
//DmxSimple.usePin(3);
//DmxSimple.maxChannel(30);
}
void loop() {
}
void data(int numBytes){
//Serial.println("DATA RECIVED");
delay(500);
char input[20];
int pos = 0;
while(Wire.available()){
input[pos++] = Wire.read();
}
input[pos++] = '\0';
Serial.print("Recived \"");
Serial.print(input);
Serial.println("\"");
char* next = strchr(input, ',');
while(next != 0){
*next = 0;
next++;
char* splitter = strchr(next, ':');
if(splitter != 0){
*splitter = 0;
splitter++;
int channel = atoi(next);
int value = atoi(splitter);
//DmxSimple.write(channel,value);
Serial.print(channel); Serial.print(":"); Serial.println(value);
}
}
}
</code></pre>
<p>Teensy code</p>
<pre><code> #include <i2c_t3.h>
//#include <ArduinoPebbleSerial.h>
/*
static const uint16_t SERVICE_ID = 0x1001;
static const uint16_t UPTIME_ATTRIBUTE_ID = 0x0002;
static const size_t UPTIME_ATTRIBUTE_LENGTH = 4;
static const uint16_t LAMP_ATTRIBUTE_ID = 0x0003;
static const size_t LAMP_ATTRIBUTE_LENGTH = 20;
static const uint16_t SERVICES[] = {SERVICE_ID};
static const uint8_t NUM_SERVICES = 1;
static const uint8_t PEBBLE_DATA_PIN = 1;
static uint8_t buffer[GET_PAYLOAD_BUFFER_SIZE(4)];
typedef struct __attribute__((packed)){
uint8_t channel;
uint8_t value;
} DMXP;*/
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Wire.begin();
Serial.begin(9600);
/*
#if defined(__MK20DX256__) || defined(__MK20DX128__)
// Teensy 3.0/3.1 uses hardware serial mode (pins 0/1) with RX/TX shorted together
ArduinoPebbleSerial::begin_hardware(buffer, sizeof(buffer), Baud57600, SERVICES, NUM_SERVICES);
#elif defined(__AVR_ATmega32U4__)
// Teensy 2.0 uses the one-wire software serial mode
ArduinoPebbleSerial::begin_software(PEBBLE_DATA_PIN, buffer, sizeof(buffer), Baud57600, SERVICES,
NUM_SERVICES);
#else
#error "This example will only work for the Teensy 2.0, 3.0, or 3.1 boards"
#endif
*/
/*for(int i = 1; i < 8; i++){
sendChannel(i,0);
}
*/
}
/*
void handle_dmx_request(RequestType type, size_t length) {
if (type != RequestTypeWrite) {
return;
}
DMXP cmd = *(DMXP*)buffer;
sendChannel(cmd.channel, cmd.value);
// ACK that the write request was received
ArduinoPebbleSerial::write(true, NULL, 0);
ArduinoPebbleSerial::notify(SERVICE_ID, UPTIME_ATTRIBUTE_ID);
}
*/
void loop() {
/*
if (ArduinoPebbleSerial::is_connected()) {
digitalWrite(13,true);
} else {
digitalWrite(13,false);
}
uint16_t service_id;
uint16_t attribute_id;
size_t length;
RequestType type;
if (ArduinoPebbleSerial::feed(&service_id, &attribute_id, &length, &type)) {
// process the request
if (service_id == SERVICE_ID) {
switch (attribute_id) {
case LAMP_ATTRIBUTE_ID:
handle_dmx_request(type, length);
break;
default:
break;
}
}
}
*/
}
void serialEvent(){
if(Serial.read() == 't'){
digitalWrite(13,true);
Serial.println("Starting Controller");
int chans[8] = {1,2,3,4,5,6,7,8};
int vals[8] = {2,4,6,8,16,32,64,128};
sendChannel(chans,vals,4);
} else {
sendChannel(1,1);
}
while(Serial.available()){
Serial.println(Serial.read());
}
}
void sendChannel(int chan, int val){
char chno[8];
itoa(chan,chno,10);
char vano[8];
itoa(val,vano,10);
char message[20];
int messagei = 0;
for(int i = 0; i < 7; i++){
if(chno[i] == '\0'){
break;
}
message[messagei++] = chno[i];
}
message[messagei++] = ':';
for(int i = 0;i < 7; i++){
if(vano[i] == '\0'){
break;
}
message[messagei++] = vano[i];
}
//message[messagei++] = '\n';
//message[messagei++] = '\r';
message[messagei++] = '\0';
Serial.println(message);
Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();
}
void sendChannel(int chan[], int val[], int num){
char message[20*num + 1];
int at = 0;
for(int i = 0; i < num; i++){
char chno[8];
itoa(chan[i],chno,10);
char vano[8];
itoa(val[i],vano,10);
for(int i = 0; i < 7; i++){
if(chno[i] == '\0'){
break;
}
message[at++] = chno[i];
}
message[at++] = ':';
for(int i = 0;i < 7; i++){
if(vano[i] == '\0'){
break;
}
message[at++] = vano[i];
}
if(i+1!=num){
message[at++] = ',';
} else {
message[at++] = 0;
}
}
char finalMessage[at+1];
for(int i = 0; i <= at; i++){
finalMessage[i] = message[i];
}
Serial.println(finalMessage);
Wire.beginTransmission(1);
Wire.write(message);
Wire.endTransmission();
}
</code></pre>
<p>(If modifying the teensy code to run on a second arduino replace the line <code>#include <i2c_t3.h></code> with <code>#include <Wire.h></code> no other changes should be necessary)</p>
<p>To use the Teensy code open a serial terminal to access it, press 't' to send a long packet, or any other character to send a shorter one.</p>
|
<p>Your code which I will reproduce here as it wasn't in the question has a major issue:</p>
<pre class="lang-C++ prettyprint-override"><code>//#include <DmxSimple.h>
#include <Wire.h>
boolean pinout = 0;
byte current[512];
void setup() {
// put your setup code here, to run once:
Wire.begin(1);
Serial.begin(115200);
Wire.onReceive(data);
//DmxSimple.usePin(3);
//DmxSimple.maxChannel(30);
}
void loop() {
}
void data(int numBytes){
//Serial.println("DATA RECIVED");
delay(500);
char input[20];
int pos = 0;
while(Wire.available()){
input[pos++] = Wire.read();
}
input[pos++] = '\0';
Serial.print("Recived \"");
Serial.print(input);
Serial.println("\"");
char* next = strchr(input, ',');
while(next != 0){
*next = 0;
next++;
char* splitter = strchr(next, ':');
if(splitter != 0){
*splitter = 0; Wire.onReceive(data);
//DmxSimple.usePin(3);
//DmxSimple.maxChannel(30);
}
</code></pre>
<hr>
<p>Your function <code>data</code> does <code>Serial.print</code>s. It is called as an interrupt service routine effectively, and thus should not do serial prints:</p>
<pre class="lang-C++ prettyprint-override"><code> Wire.onReceive(data);
}
void loop() {
}
void data(int numBytes){
...
Serial.print("Recived \"");
Serial.print(input);
Serial.println("\"");
</code></pre>
<hr>
<blockquote>
<p>More strange even is that if I send the longer data again I receive none, ...</p>
</blockquote>
<p>Yep, that will definitely happen. The serial printing "blocks" if you print a lot, and thus the code will hang indefinitely.</p>
<hr>
<pre class="lang-C++ prettyprint-override"><code> delay(500);
</code></pre>
<p>You definitely should not use <code>delay</code> in an interrupt routine. It will almost certainly hang because the timer interrupts which are needed for <code>delay</code> to work are not being serviced.</p>
<hr>
<pre class="lang-C++ prettyprint-override"><code> Wire.begin(1);
</code></pre>
<p>You should not be choosing to use I2C address 1. It is reserved. See:</p>
<p><a href="http://www.totalphase.com/support/articles/200349176" rel="nofollow">7-bit, 8-bit, and 10-bit I2C Slave Addressing</a> and <a href="http://www.nxp.com/documents/user_manual/UM10204.pdf" rel="nofollow">I2C specification (pdf)</a></p>
<pre class="lang-none prettyprint-override"><code>Slave Address R/W Bit Description
000 0000 0 General call address
000 0000 1 START byte(1)
000 0001 X CBUS address(2)
000 0010 X Reserved for different bus format (3)
000 0011 X Reserved for future purposes
000 01XX X Hs-mode master code
111 10XX X 10-bit slave addressing
111 11XX X Reserved for future purposes
</code></pre>
<blockquote>
<p>(1) No device is allowed to acknowledge at the reception of the START byte.</p>
<p>(2) The CBUS address has been reserved to enable the inter-mixing of CBUS compatible and I2C-bus compatible devices in the same system. I2C-bus compatible devices are not allowed to respond on reception of this address.</p>
<p>(3) The address reserved for a different bus format is included to enable I2C and other protocols to be mixed. Only I2C-bus compatible devices that can work with such formats and protocols are allowed to respond to this address.</p>
</blockquote>
|
15984 | |edison| | Unable to set up Intel Edison on Windows | 2015-09-11T05:32:57.027 | <p>I am new to hobby electronics and have hit a dead end with my Intel Edison (which hopefully will not join the pile of useless components I have wasted my money on), and would appreciate some help with the setup procedure. The main problem is that I cannot connect to my Edison via the middle (lets call it "A") micro-USB port in order to get it into a working condition. </p>
<p>My objective is to connect to it's build-in Linux via SSH with the USB cables connected after installing the latest flash image.</p>
<p>I am using an Edison with an Arduino breakout board.</p>
<p>Here is the sequence of steps I followed:</p>
<ol>
<li>I connected a 12V 2.6A AC to DC adapter to power the board. (Via the barrel connector). The green light came on to indicate it is powered.</li>
<li>I connected the "A" micro-USB port (i.e. not the one on the edge) to my computer.</li>
</ol>
<p>At this point I could access the drive through Windows Explorer, however this changed when I executed the next step:</p>
<ol start="3">
<li>I installed the software from step 2 at <a href="https://software.intel.com/en-us/iot/library/edison-getting-started" rel="nofollow">https://software.intel.com/en-us/iot/library/edison-getting-started</a>.</li>
<li>Something went wrong during the subsequent installation process. I don't know what.</li>
</ol>
<p>At this point I could no longer access the drive. It would only appear as an "Unknown device" in Windows Device Manager. In order to try and fix this I gave up on the option where it is mounted as a Windows Drive.</p>
<ol start="5">
<li>I connected to the micro-USB port at the edge of the Arduino board and disconnected A.</li>
<li>I went to Windows Device Manager and found the connected device on COM6</li>
<li>I installed Putty and connected to COM6 with a baud of 115200.</li>
<li>The console showed a blank screen with a green cursor in the top left.</li>
<li>I waited 30 seconds for it to boot.</li>
<li>I hit Cntrl+C because I still saw the same screen from step 9.</li>
</ol>
<p>I then saw this on the console:</p>
<pre>
Unknown boot mode: boot
Saving Environment to MMC...
Writing to MMC(0)... done
Resetting to default boot mode and reboot...
resetting ...
******************************
PSH KERNEL VERSION: b0182b2b
WR: 20104000
******************************
SCU IPC: 0x800000d0 0xfffce92c
PSH miaHOB version: TNG.B0.VVBD.0000000c
microkernel built 11:24:08 Feb 5 2015
******* PSH loader *******
PCM page cache size = 192 KB
Cache Constraint = 0 Pages
Arming IPC driver ..
Adding page store pool ..
PagestoreAddr(IMR Start Address) = 0x04899000
pageStoreSize(IMR Size) = 0x00080000
*** Ready to receive application ***
U-Boot 2014.04 (Jun 19 2015 - 12:05:55)
Watchdog enabled
DRAM: 980.6 MiB
MMC: tangier_sdhci: 0
In: serial
Out: serial
Err: serial
Hit any key to stop autoboot: 0
Target:ifwi
Partitioning already done...
Partitioning already done...
Saving Environment to MMC...
Writing to redundant MMC(0)... done
GADGET DRIVER: usb_dnl_dfu
</pre>
<p>I have no idea what to do next.</p>
| <p>I fixed it by following these steps (through trial and error, I don't really understand what I did but it works ...)</p>
<p>I am using Windows 8.1, 64 bit edition.</p>
<ol>
<li>Download the Edison firmware from <a href="https://software.intel.com/en-us/iot/hardware/edison/downloads" rel="nofollow">https://software.intel.com/en-us/iot/hardware/edison/downloads</a>. For me it was <a href="http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip" rel="nofollow">http://downloadmirror.intel.com/25028/eng/edison-image-ww25.5-15.zip</a>.</li>
<li>Extract the zip file.</li>
<li>Start the Windows Command Prompt as Administrator.</li>
<li>The extracted archive should contain a file called "flashall.bat". Change to the directory containing the file.</li>
<li>Connect all micro-USB ports and the barrel connector. At this point Windows did not recognize the Edison as a flash disk. This is part of what I was fixing.</li>
<li>Follow the steps in my question until the output on the console (also from my question) appears.</li>
<li>Run "flashall --recovery"</li>
<li>Run "flashall". When "Please plug and reboot the board" appears, disconnect the A (or middle) USB port and the barrel connector for the power. At this point everything is switched off. Then reconnect A and the barrel connector to reboot the board.</li>
<li>Wait about 5 minutes for the rest of the process to run automatically.</li>
</ol>
<p>At this point everything should work again.</p>
<p>You should see this on the command line in Windows:</p>
<pre>
C:\Users\_\Desktop\edison-image-ww25.5-15>flashall --recovery
Starting Recovery mode
Please plug and reboot the board
Flashing IFWI
!!! You should install xfstk tools, please visit http://xfstk.sourceforge.net/
C:\Users\_\Desktop\edison-image-ww25.5-15>flashall
Using U-boot target: edison-blankrndis
Now waiting for dfu device 8087:0a99
Please plug and reboot the board
Dfu device found
Flashing IFWI
Download [=========================] 100% 4194304 bytes
Download done.
Download [=========================] 100% 4194304 bytes
Download done.
Flashing U-Boot
Download [=========================] 100% 237568 bytes
Download done.
Flashing U-Boot Environment
Download [=========================] 100% 65536 bytes
Download done.
Flashing U-Boot Environment Backup
Download [=========================] 100% 65536 bytes
Download done.
Rebooting to apply partiton changes
Dfu device found
Flashing boot partition (kernel)
Download [=========================] 100% 6111232 bytes
Download done.
Flashing rootfs, (it can take up to 5 minutes... Please be patient)
Download [=========================] 100% 566330368 bytes
Download done.
Rebooting
U-boot & Kernel System Flash Success...
Your board needs to reboot to complete the flashing procedure, please do not unplug it for 2 minutes.
C:\Users\_\Desktop\edison-image-ww25.5-15>
</pre>
|
15985 | |c++|led|digital| | Arduino Pin won't go LOW | 2015-09-11T05:31:40.527 | <p>I have something strange going on with an output. When the following code is called the LED goes on, but it stays on, there is no blinking. If I comment out the set HIGH statement the LED never comes on (as expected). </p>
<pre><code>#define devicePin 10
void setup() {
pinMode(devicePin, OUTPUT);
}
void loop() {
digitalWrite(devicePin, HIGH);
delay(2000);
digitalWrite(devicePin, LOW);
}
</code></pre>
<p>Could I have damaged the board in some way?</p>
| <p>Yes, the pin is going low. I tested it for you:</p>
<p><a href="https://i.stack.imgur.com/qDZxx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/qDZxx.png" alt="Pin 10 going low"></a></p>
<p>It went low for 6 µs, once every 2 seconds. :)</p>
<hr>
<p>Overall, this is the effect:</p>
<p><a href="https://i.stack.imgur.com/3QuPS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3QuPS.png" alt="Pin 10 mainly high"></a></p>
<p>As you can see, high for most of the time.</p>
|
15988 | |arduino-ide| | Consulting and inserting a string into an array if it doesn't exist (Arduino IDE) 1 | 2015-09-11T06:01:46.790 | <p>Sorry that I repeat my question, I can't enter to my user...</p>
<p>In the project I'm doing, I connect an arduino mega with ethernet and Post some Strings to the server. The arduino mega has a receiver(315MHz). I have some arduinos nano connected with PIR sensors that sends a some int with transmitters (315MHz). What I want to do is a list in my arduino mega that stores the values sent by the arduinos nanos to use them to my server (using POST). my question is the following:</p>
<p>If I had an empty array, what I would like to do is</p>
<pre><code>listOfSensors[]={}
void funtion (String sensor){
if (sensor is inside listOfSensors){
//dont do anything
}
else {
add sensor to listOfSensors
}
</code></pre>
<p>I have been looking for hours, but I haven't found anything so far... Anyone has any idea? Thanks!!</p>
| <p>If you only need to add items of a fixed size to your sensor list (i.e. you don't need to delete items or sort them), you can use an uninitialized array large enough for the maximum number of items it will need to hold: </p>
<pre><code>#define MAXSENSORS 30 // max sensor count
#define SNAMELEN 12 // max sensor name length
struct sensorData {
char sname[SNAMELEN+1];
uint16_t svalue;
}; // defines data for 1 sensor
uint8_t sensorCount = 0;
struct sensorData listOfSensors[MAXSENSORS]={0}; // array of sensor data, initialized to 0, 0, ...
</code></pre>
<p>You'll also need an unsigned int (perhaps only a byte) to keep track of the count of items in the array, which you'll increment every time you add another sensor (up to the maximum number).</p>
<p>I think this is what you meant by "empty array". You would add your next sensor data at <code>listOfSensors[i]</code>, then increment i. Likewise, you would search for a sensor in the array from <code>listOfSensors[0]</code> to <code>listOfSensors[i-1]</code>. </p>
|
15991 | |virtualwire| | Convert the Serial.Println to string | 2015-09-11T08:12:29.793 | <p>I'm working with VirtualWire and I'm trying to get a string value out of the Serial.println in the loop. I've tried create a string and add the message[i] , but surprisingly message[i] becomes an int when added. Serial.println outputs the string correctly, but the string that I get from message[i] is just numbers...</p>
<pre><code>#include <VirtualWire.h>
byte message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
byte messageLength = VW_MAX_MESSAGE_LEN; // the size of the message
String sensorname;
void setup(){
Serial.begin(9600);
Serial.println("Device is ready");
// Initialize the IO and ISR
vw_setup(2000); // Bits per sec
vw_rx_start(); // Start the receiver
}
void loop(){
if (vw_get_message(message, &messageLength)){
Serial.print("Received: ");
for (int i = 0; i < messageLength; i++){
Serial.write(message[i]);
sensorname += message[i];
}
Serial.println();
Serial.pintln("Name of sensor: " + sensorname);
sensorname=""; //Reestart the string
}
}
</code></pre>
<p>I'm quite new with VirtualWire so I don't know if there is command to get the message and pass it directly to string...Any help will be appreciated!</p>
<p><strong>EDIT</strong>
I think I dind't express myself well. In my original question I didn't add the String sensor name</p>
<p>The Response I get in the Serial is the following:</p>
<pre><code>Device is ready
SensorA
Name of sensor: 8310111011511111465
</code></pre>
<p>My aim is to instead of having as sensorname=8310111011511111465, have sensorname=SensorA</p>
| <p>Those numbers are the numerical ASCII representation of the characters.</p>
<pre><code>83 = S
101 = e
110 = n
... etc ...
</code></pre>
<p>(Find the whole list here: <a href="http://www.asciitable.com/" rel="nofollow">http://www.asciitable.com/</a>)</p>
<p>The reason you are ending up with numbers is because of the <em>type</em> of variable you are receiving the data into - a <em>byte</em>.</p>
<p>A <em>byte</em> stores a number between 0 and 255. When you add that <em>byte</em> to a <em>String</em> the compiler assumes you want to append a number, since it is a numerical type that you are using.</p>
<p>If you instead tell it to use a <em>char</em> type then the compiler should realise "Ah, this is the numeric representation of a character - I will add the character instead".</p>
<p>You can either change the whole array type:</p>
<pre><code>char message[VW_MAX_MESSAGE_LEN]; // a buffer to store the incoming messages
</code></pre>
<p>Or <em>cast</em> the variable to be the right type when you append it:</p>
<pre><code> sensorname += (char)message[i];
</code></pre>
<p>Or better still, don't use the String class since it is really too heavyweight and prone to memory issues for use on a little microcontroller. Stick to C strings. They take a little more getting used to, but are so much more microcontroller friendly.</p>
|
16001 | |arduino-uno|gsm|string| | How does arduino fetch instruction string from sms and execute? | 2015-09-11T13:58:03.633 | <p>I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.</p>
<p>P.S. I am a total beginner at arduino coding so please help me out.</p>
| <p>Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.</p>
<p>Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.</p>
<p>The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).</p>
<p>Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!</p>
<p>"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.</p>
<p>Look up the function <code>sscanf()</code> [oops: not sprintf()] for one way to parse the incoming strings and collect their data.</p>
<p>Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
<br>Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:</p>
<pre><code>/*
* sscanf example - Uses sscanf to test and collect data from a
* a command string.
*/
#include <WProgram.h>
void test_sscanf(const char *sms);
// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
"motor,1,5",
"Hello World,3,2",
"motor 123 456",
"moto, 7, 13",
"motorized, 4, 11"
};
void setup() {
Serial.begin(9600);
delay(1000); // delay for user to launch a terminal (if you're quick)
// Test each SMS example in the SMS array
for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
test_sscanf(SMS[s]); // test one SMS string
}
}
void loop() {
; // nothing to do here
}
// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
int16_t assigned, values[2];
// Print the SMS and convert it.
Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);
// Display the results
Serial.print(assigned); Serial.println(" values assigned"); // How many values? A good command has 2.
if( assigned > 0 ){
for( uint8_t i = 0; i < assigned; ++i){
Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
Serial.println(values[i]);
}
}
}
</code></pre>
|
16004 | |arduino-uno|c++|led| | Simple Arduino Code Not Working | 2015-09-11T17:51:15.463 | <p>When I upload this code LED at pin 13 goes HIGH and that's it. My goal is to make it blink in the order specified in the array. What am I doing wrong?</p>
<pre><code>int Array[] = {1,1,1,0,1,0,0,0,1,0,1,0,1,1,0,0,1,0,1,0,1,1,0,0};
int Data = 13;
int i = 0;
void setup() {
pinMode(Data, OUTPUT);
}
void loop() {
int x = Array[i];
delay(200);
digitalWrite(Data, x);
i = i+1;
if (i==23) {
i=0;
}
}
</code></pre>
| <p>What you're doing wrong is living your life at a normal speed.</p>
<p>The LED will be blinking, but so fast you can't see it change.</p>
<p>Without adding some delays in there you will just see the LED light up.</p>
|
16005 | |c++|led|electronics| | Why doesn't the LED turn on in this circuit? | 2015-09-11T17:53:11.730 | <p>I'm experimenting with buttons and LEDs and I would like my code to change a LED's brightness once a button is pressed. I connect the LED to the PWD digital pin.</p>
<p>My circuit looks like this one:</p>
<p><a href="https://i.stack.imgur.com/Ptv4v.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Ptv4v.png" alt="enter image description here"></a></p>
<p>This is the code I'm using:</p>
<pre><code>int switchPin = 8;
int ledPin = 11;
boolean lastButton = LOW;
boolean currentButton = LOW;
int ledLevel = 0;
void setup() {
pinMode(switchPin, INPUT);
pinMode(ledPin, OUTPUT);
}
boolean debounce(boolean last) {
boolean current = digitalRead(switchPin);
if (last != current) {
delay(5);
current = digitalRead(switchPin);
}
return current;
}
void loop() {
currentButton = debounce(lastButton);
if (lastButton == LOW && currentButton == HIGH) {
ledLevel = ledLevel + 51;
}
lastButton = currentButton;
if (ledLevel > 255) ledLevel = 0;
analogWrite(ledPin, ledLevel);
}
</code></pre>
<p>Though, the LED never turns on, but the light on the Arduino is on. I made sure the leads of the LED were in the right spot. Why doesn't the LED turn on?</p>
| <p>Because you don't actually <em>have</em> a circuit? One side of the LED doesn't connect to anything.</p>
|
16009 | |c|interrupt|sleep| | Not waking up more than once? | 2015-09-11T18:06:25.010 | <p>I'm trying the following code on an Uno. I'm pulling the high side of a pull down 10K resistor to 5V, but it can only be woken once. Just once. Does anyone know why this might be the case?</p>
<p>It works fine if I use <code>LOW</code> for <code>attachInterrupt</code> along with a pull-up resistor though. Just not with <code>RISING</code> and a pull-down.</p>
<pre><code>#include <avr/sleep.h>
#include <avr/power.h>
int pin2 = 2;
void setup() {
Serial.begin(9600);
/* Setup the pin direction. */
pinMode(pin2, INPUT);
Serial.println("Initialisation complete.");
}
void pin2Interrupt(void)
{
/* This will bring us back from sleep. */
/* We detach the interrupt to stop it from
* continuously firing while the interrupt pin
* is high.
*/
detachInterrupt(digitalPinToInterrupt(pin2));
}
void enterSleep(void)
{
sleep_enable();
/* Setup pin2 as an interrupt and attach handler. */
attachInterrupt(digitalPinToInterrupt(pin2), pin2Interrupt, RISING);
delay(100);
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_mode();
/* The program will continue from here. */
/* First thing to do is disable sleep. */
sleep_disable();
}
int seconds=0;
void loop()
{
delay(1000);
seconds++;
Serial.print("Awake for ");
Serial.print(seconds, DEC);
Serial.println(" second");
if(seconds >= 3)
{
Serial.println("Entering sleep");
delay(200);
seconds = 0;
enterSleep();
}
}
</code></pre>
|
<p>Probably your switch is bouncing and giving two interrupts. The first wakens it, and the second is lying there waiting until you attach the interrupt again. Then it fires, detaches the interrupt, then you go to sleep, never to awaken. </p>
<p>Clear any pending interrupt <strong>before</strong> doing the attachInterrupt:</p>
<pre class="lang-C++ prettyprint-override"><code>EIFR = bit (INTF0); // clear flag for interrupt 0
</code></pre>
<p>See <a href="http://www.gammon.com.au/interrupts" rel="nofollow">Interrupts</a>.</p>
<p>It is also wise to have interrupts off while setting up for sleep.</p>
<hr>
<p>Example code:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <avr/sleep.h>
const byte LED = 13;
// interrupt service routine in sleep mode
void wake ()
{
sleep_disable (); // first thing after waking from sleep
} // end of wake
void sleepNow ()
{
set_sleep_mode (SLEEP_MODE_PWR_DOWN);
noInterrupts (); // make sure we don't get interrupted before we sleep
sleep_enable (); // enables the sleep bit in the mcucr register
EIFR = bit (INTF0); // clear flag for interrupt 0
attachInterrupt (0, wake, RISING); // wake up on rising edge
interrupts (); // interrupts allowed now, next instruction WILL be executed
sleep_cpu (); // here the device is put to sleep
detachInterrupt (0); // stop this interrupt until next time
} // end of sleepNow
void setup ()
{
pinMode (LED, OUTPUT);
} // end of setup
void loop ()
{
sleepNow ();
digitalWrite (LED, HIGH);
delay (1000);
digitalWrite (LED, LOW);
} // end of loop
</code></pre>
<p>Tested and works OK. </p>
<hr>
<p>Note: Since this is a rising interrupt you should have a <strong>pull-down</strong> resistor on the pin, and you trigger the interrupt by connecting the pin to +5 V.</p>
|
16012 | |arduino-uno|progmem| | Storing array in PROGMEM | 2015-09-11T20:01:38.617 | <p>I have an array of a lot of numbers (1 and 0) but i can't store them since arduino does not have enough space. How can i save an array of example 00110 in PROGMEM, then read from PROGMEM and set x to be equal lets say, third int in the array?</p>
| <p>Building on the excellent other answers by jwpat7 and
Ignacio Vazquez-Abrams, you could conceivably convert your bits into a table using Lua:</p>
<pre class="lang-lua prettyprint-override"><code>data = { 1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,
0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,
1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,
0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,
0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1 }
output = 0
bit = 0
for _, num in ipairs (data) do
assert (num == 0 or num == 1, "Number must be 0 or 1")
output = (output * 2) + num
bit = bit + 1
if bit >= 8 then
io.write (output .. ", ")
output = 0
bit = 0
end -- if
end --for
print ""
</code></pre>
<p>Output from above:</p>
<pre class="lang-none prettyprint-override"><code>197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
</code></pre>
<p>Now you can make a simple function to pull a particular bit out of PROGMEM:</p>
<pre class="lang-C++ prettyprint-override"><code>const byte myTable [] PROGMEM = {
197, 43, 32, 200, 47, 197, 30, 119, 153, 37, 180, 117, 48, 218, 214, 212, 170, 131,
};
bool getBit (const unsigned int which)
{
const unsigned int whichByte = which / 8;
const byte whichBit = which & 0x07;
return bitRead (pgm_read_byte (&myTable [whichByte]), 7 - whichBit);
} // end of getBit
void setup ()
{
Serial.begin (115200);
Serial.println ("Starting");
for (int i = 0; i < sizeof (myTable) * 8; i++)
{
Serial.print (int (getBit (i)));
Serial.print (", ");
}
Serial.println ();
} // end of setup
void loop ()
{
} // end of loop
</code></pre>
<p>Output from above:</p>
<pre class="lang-none prettyprint-override"><code>Starting
1,1,0,0,0,1,0,1,0,0,1,0,1,0,1,1,0,0,1,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,1,0,1,1,1,1,1,1,0,0,0,1,0,1,0,0,0,1,1,1,1,0,0,1,1,1,0,1,1,1,1,0,0,1,1,0,0,1,0,0,1,0,0,1,0,1,1,0,1,1,0,1,0,0,0,1,1,1,0,1,0,1,0,0,1,1,0,0,0,0,1,1,0,1,1,0,1,0,1,1,0,1,0,1,1,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,1,0,1,0,0,0,0,0,1,1,
</code></pre>
|
16019 | |programming|c++|library| | Can I automatically loop inside a library? | 2015-09-12T01:58:34.610 | <p>I want to write a little library;<br>
the unlibrarized functionality does:</p>
<p>checking in every loop-cycle some inputs,<br>
doing some calculations with it<br>
and finally setting a boolean to either true or false.</p>
<p><strong>How do I periodically check the inputs inside the library?</strong><br>
I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.</p>
<p><strong>Is there a way, to instantiate a class and start an periodically function by doing so?</strong> And if, how does this constant checking affect/coexist with my 'normal' loop()-function?</p>
| <blockquote>
<p>I know that I could add a function-call to the library in the loop()-function. But I would prefer to just check the boolean in the loop.</p>
</blockquote>
<p>What's the difference?</p>
<p>In the <code>loop</code> you can call something like:</p>
<pre><code>void loop ()
{
...
if (mylibrary.ready ())
{
// it's time to act!
}
...
}
</code></pre>
<p>You can make a function, that returns a boolean type, which tells you if the thing you need to do is ready. That function <em>does the checking</em> before returning true or false.</p>
<p>After all, you are planning to check the boolean periodically, presumably often enough to notice it changing, why not have that be the point of noticing whatever-it-is you need to notice?</p>
|
16024 | |power|arduino-pro-mini|sleep| | High power consumption during power down mode | 2015-09-12T08:04:19.603 | <p>I try to use power down mode to extend battery life, but no matter what sleep library I use, the power consumption never goes below 3.4-3.6 mA. I'm using a chinese pro mini board with VCC input (but using the RAW results the same).</p>
<p>avr/power sketch:</p>
<pre><code>#include <avr/power.h>
#include <avr/sleep.h>
void setup()
{
Serial.begin(9600);
byte i;
// Ensure no floating pins
for(i=0; i<20 ; i++)
{
pinMode(i, OUTPUT);
digitalWrite(i, LOW);
}
// Power-down board
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
sleep_enable();
// Disable ADC
ADCSRA &= ~(1 << ADEN);
// Power down functions
PRR = 0xFF;
// Enter sleep mode
sleep_mode();
}
void loop()
{
}
</code></pre>
<p>rocketscream/Low-Power sketch:</p>
<pre><code>#include <LowPower.h>
void setup() {
}
void loop() {
LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);
}
</code></pre>
| <p>I tried your first sketch on my "bare-bones" board.</p>
<p><a href="https://i.stack.imgur.com/OWnJk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/OWnJk.jpg" alt="Bare-bones board"></a></p>
<p>With the sketch exactly as written, it used 197 µA.</p>
<p>I wondered why it was that high, so I commented out this line:</p>
<pre><code> Serial.begin(9600);
</code></pre>
<p>That reduced consumption to 122 nA.</p>
<p>See <a href="http://www.gammon.com.au/power" rel="nofollow noreferrer">Power saving techniques for microprocessors</a>.</p>
<p>You need to get rid of any "power" LEDs, and disconnect any voltage regulators. If you want really low consumption you need to have minimal hardware.</p>
<p>Of course, if you <em>need</em> the voltage regulator, well so be it. But don't expect 100 nA consumption if you use it.</p>
|
16027 | |arduino-uno|c++|shields|relay|system-design| | Very easy Arduino code challenge for you brainiacs to solve | 2015-09-12T12:51:21.043 | <p>I've searched the forum for similar problems and still can't see my obvious issue. I'm working on a simple Halloween prop and I'm using an Arduino for the first time. I've tested each individual 'event' (i.e. fog machine, mp3, actuator, and LED strip) with a loop and all four have worked on continuous loop with no issue.</p>
<p>As soon as I combine them all together, the program runs successfully exactly one time. After that final 10 second delay, when I expect the program to start the loop again, it crashes. If it helps, right during the start of the next loop, the relay light turns on on the relay board for RELAY_1_A and sort of just flickers while the actuator hums. I usually shut it down quickly at this point. As soon as I turn the system back on, it successfully runs through another iteration until the loop hangs.</p>
<p>I'm happy to provide pictures or even a video of the issue if that helps. My guess is that you guys will spot my coding issue right away. Maybe some kind of memory overflow or something like that.</p>
<p>I know my code could be much more efficient but I'm just looking for the glaring problem that is keeping the loop from working.</p>
<pre><code>#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>
const int RELAY_1_A = 7; //the one with the issue
const int RELAY_1_B = 8;
SdFat sd;
SFEMP3Shield MP3player;
void setup() {
// initialize the digital pins as an output.
pinMode(10, OUTPUT); //Fog machine on Relay1 on 5V relay board
pinMode(3, OUTPUT); //LED strip off breadboard MOSFET
pinMode(RELAY_1_A, OUTPUT); //12V relay for actuator on Relay1 on 12V relay board
pinMode(RELAY_1_B, OUTPUT); //12V relay for actuator on Relay2 on 12V relay board
//start the shield
sd.begin(SD_SEL, SPI_FULL_SPEED);
MP3player.begin();
MP3player.setVolume(10, 10);
}
void loop() {
MP3player.playTrack(2); // Play MP3. Track 1 is coffin and track 2 is bird
delay(5000); // wait for 5 seconds
digitalWrite(10, LOW); // Turns ON fog machine
delay(3000);
digitalWrite(10, HIGH); // Turns OFF fog machine
digitalWrite(3, HIGH); // Turn the LED on (HIGH is the voltage level)
delay(5000); // wait for 5 seconds
retractActuator(); //Open coffin
delay (9000);
stopActuator(); //Close coffin
delay (9000);
extendActuator(); //Close coffin
delay(8000);
digitalWrite(RELAY_1_B, HIGH); //Turns off this relay during the wait period before next loop
digitalWrite(3, LOW); // Turn the LED off by making the voltage LOW
delay(10000); // wait for 20 seconds
}
void extendActuator() {
//Set one relay one and the other off
//this will move extend the actuator
digitalWrite(RELAY_1_A, HIGH);
digitalWrite(RELAY_1_B, LOW);
}
void retractActuator() {
//Set one relay off and the other on
//this will move retract the actuator
digitalWrite(RELAY_1_A, LOW);
digitalWrite(RELAY_1_B, HIGH);
}
void stopActuator() {
//Set both relays off
//this will stop the actuator in a braking
digitalWrite(RELAY_1_A, HIGH);
digitalWrite(RELAY_1_B, HIGH); }
</code></pre>
| <p>You are attempting to use IO pins that are already in use by the MP3 shield.</p>
<p>According to your subsequent research, only digital pins 0,1,5, and 10 are available for use.</p>
<p>You should shy away from using pins 0 and 1 since they are also connected to the computer through the USB interface and are used for uploading sketches. You will find that either you can't upload sketches with the relays connected to those pins, or the relays will "randomly" switch on and off while you're uploading a sketch.</p>
<p>Don't forget that the analog pins A0-A5 can also be used as digital pins, so you can quite happily drive your relays using any of those.</p>
|
16032 | |serial| | Can Arduino Uno's serial handle to foward push through 1-wire protocol? | 2015-09-12T16:36:19.190 | <p><strong>tl;dr</strong> on on digital ouput/input I would like to communicate with a 1-wire device, whose protocol requires precision to ~15 microseconds. My question is if Arduino Uno's serial communication can be as quick as to support to map the digital pin via serial->USB to my host computers app which should implement the 1-wire protocol?</p>
<p><strong>long version</strong>
The mode in which I thought to use my Arduino was, to attach it to a host computer and run the logic of what should be done on the host computer, having the Arduino only receive the data (for the pins) and return the state of the pins.</p>
<p>The challenge which prompts me to this question is that the Serial communication is not really that quick, compared to the timing requirement of some protocols (e.g. 1 wire) I wish to implement.<br>
For example: 1-wire-protocol's timing requirements (i.e. range of micorseconds) could easily be kept from code running on the Arduino Uno's Atmega328 directly, which at 16Mhz and assumed 2 cycles per command would allow somewhat a resolution of 2/16Mhz = 0,125 us.</p>
<p>If alternatively the data/instruction for the 1-wire protocol should be mapped via the serial interface to an application running on an PC attached to the Arduino I wonder if the time requirements of the 1-wire protocal can be reached?</p>
<p>It boils down to a question if the Serial communication can have a temporal granularity as small as the about 1 to 15 microseconds needed to implement the 1-wire protocol - not within arduino itself - but in the attached PC's application.</p>
| <p>It certainly is possible for an Arduino to do this. For example, source code for Atmel's implementations of <a href="https://en.wikipedia.org/wiki/1-Wire" rel="nofollow">1-Wire protocol</a> via bit-banging, via polling UART, and via interrupt-driven UART, is available at <a href="https://github.com/semicontinuity/embedded/tree/master/target/card-terminal/firmware/one-wire-thermometer" rel="nofollow">github.com</a>. </p>
<p>There is a 21-page PDF file, <a href="http://www.atmel.com/images/doc2579.pdf" rel="nofollow">doc2579.pdf</a>, available at Atmel. It documents how the different implementations work.</p>
<p>However, the notion of communicating faster than serial via the 1-Wire protocol seems like a mistaken notion. As I understand it, the serial implementations above use one serial character per 1-Wire bit, so necessarily are slower than serial.</p>
|
16034 | |bluetooth|usb| | Bluetooth Stream to USB | 2015-09-12T17:20:34.883 | <p>I want to make a device that will take a Bluetooth stream and play it on speakers via the USB port for speakers that do not have Bluetooth.</p>
<p>I think it may be possible by taking the stream and using an Arduino to convert the stream to a virtual file so that the speaker will see the USB as a mass storage and play the file. </p>
<p>I am not sure that is just an idea, any thoughts or solutions?</p>
| <p>If your target is a USB audio device - like a USB headset or USB speakers (NOT an MP3 player with USB interface) then you could connect it to something which can act as a USB host with USB audio device drivers. That means <em>not</em> an Arduino, but something much more powerful like a Raspberry Pi or BeagleBone Black for instance.</p>
<p>If your target is basically an MP3 player that allows you to connect a USB stick with songs on it then you're completely out of luck. There's this small thing called <em>time</em> that gets in your way. You can't stream data to something that expects the data to already be there. You can't seek in a file that doesn't exist until the moment you try to read from it. Also you have to act as if you were a USB memory stick, and that's not easy, and certainly not something an Arduino can do. Even things like the Pi would have a lot of difficulty in managing that since they are hosts, not devices, as far as USB is concerned.</p>
<p>The key word here is <em>stream</em>. Your target as to be able to receive a <em>stream</em> of data rather than request blocks of data from a file. USB audio <em>devices</em> can do that, but USB audio <em>hosts</em> cannot.</p>
|
16037 | |arduino-uno|c++|wifi|pins| | Printing arduino pin numbers to MySQL | 2015-09-12T18:24:47.850 | <p>I mistakenly posted this on stack overflow first. The community was kind enough to point me to this forum. I apologize for the double-post. </p>
<p>I've been working on an Arduino Uno r3 + WiFi Shield project for a few months now building up the complexity as I go. I've hit a wall. I started this project with exactly zero experience writing code of any kind and exactly zero experience working with boards. If you have any doubts as to whether or not I'll understand your response, please dumb it down!</p>
<p>I've made a simple arduino + wifi shield setup that can report a button push to a MySql database. All of the .php stuff on the backend works and the database is managed with phpmyadmin. I'm trying to add a second button but can't seem to make it work and need some help.</p>
<p>I have settled on a four-field database table as the output:</p>
<ul>
<li>1st column: the key. A sequential, unique identifier for each entry</li>
<li>2nd column: the pin number that the sensor is connected to </li>
<li>3rd column: the sensor value</li>
<li>4th column: the date and time</li>
</ul>
<p>Notice that I'm not using a dedicated column for each sensor. By using the sensor pin input, I want to simply print the sensor pin number in a column. This (a) saves space in the table and (b) allows the Arduino to use as many sensors as it has pins.</p>
<p>The idea is that each button press (even if two are pressed simultaneously) will get it's own line, sensor pin source, value, and timestamp. No values will be sent unless a button is pressed.</p>
<p>I haven't the foggiest idea of how to implement this! Help!</p>
<hr>
<p><strong>My question:</strong></p>
<p>How can I ask the sketch to retrieve the pin from which a signal originates and write it to the db as a number in the second column? The 13th line of code is what will write the pin number (I think). The "senseval=" needs to be a variable that reports the source pin.</p>
<p>I don't know how to set this up and google has led to nothing but dead ends. I'd like this thread to answer the questions I'm sure a few more people have/will have!</p>
<hr>
<p>My sketch is included below and the insert_php_doc below that. I'm using the Silinas/Benoit "Arduino /Post" example from github:</p>
<pre class="lang-C++ prettyprint-override"><code>#include <SPI.h>
#include <WiFi.h>
char ssid[] = "linksys";
int status = WL_IDLE_STATUS;
WiFiClient client;
IPAddress server(xxx,xxx,xxx,xxx);
int inPin_0 = A0; // choose the input pin (sensor #1)
int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON//
int sensorSense_0 = 0; //variable
int sensorSense_1 = 0; //variable //ADDED FOR SECOND BUTTON//
String SensorVal = "senseval=";// "yourdata="
String senseval;//yourdata //MUST KEEP sensval for PHP
void setup() {
Serial.begin(9600);
pinMode(inPin_0,INPUT);
pinMode(inPin_1,INPUT); //ADDED FOR SECOND BUTTON//
connectWifi();
}
void loop() {
sensorSense_0=analogRead(inPin_0);
if (sensorSense_0 == LOW){
postData();
delay(5000);
}
sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//
if (sensorSense_1 == LOW){ //ADDED FOR SECOND BUTTON//
postData(); //ADDED FOR SECOND BUTTON//
delay(5000); //ADDED FOR SECOND BUTTON//
}
void connectWifi() {
while ( status != WL_CONNECTED) {
Serial.print("Attempting to connect to SSID: ");
Serial.println(ssid);
status = WiFi.begin(ssid);
delay(7000);
}
}
}
void postData() {
senseval=SensorVal+String(inPin_0);
senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//
if (client.connect(server, 80)) {
Serial.println("connecting...");
client.println("POST /insert_mysql_doc.php? HTTP/1.1");
client.println("Host: www.<domain>.com");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.println("Content-Type: application/x-www-form-urlencoded;");
client.print("Content-Length: ");
client.println(senseval.length());//yourdata
client.println();
client.println(senseval);//yourdata
client.stop();
}
else {
Serial.println("Connection failed");
Serial.println("Disconnecting.");
client.stop();
connectWifi();
printWifiStatus();
}
}
</code></pre>
<hr>
<p>The insert PHP from <a href="https://github.com/ericbenwa/POST-Arduino-Data-Wireless" rel="nofollow">https://github.com/ericbenwa/POST-Arduino-Data-Wireless</a>:</p>
<pre class="lang-php prettyprint-override"><code><?php
foreach ($_REQUEST as $key => $value)
{
if ($key == "senseval") {
$senseval = $value;
}
}
// EDIT: Your mysql database account information
$username = "test_user";
$password = "test_password";
$database = "test_db_name_here";
$tablename = "test_table_name_here";
$localhost = "localhost";
// Check Connection to Database
if (mysql_connect($localhost, $username, $password))
{
@mysql_select_db($database) or die ("Unable to select database");
// Next two lines will write into your table 'test_table_name_here' with 'yourdata' value from the arduino and will timestamp that data using 'now()'
$query = "INSERT INTO $tablename VALUES ($senseval,now())";
$result = mysql_query($query);
} else {
echo('Unable to connect to database.');
}
?>
</code></pre>
| <pre><code>int inPin_0 = A0; // choose the input pin (sensor #1)
int inPin_1 = A1; // choose the input pin (sensor #2) //ADDED FOR SECOND BUTTON/
...
senseval=SensorVal+String(inPin_0);
senseval=SensorVal+String(inPin_1); //ADDED FOR SECOND BUTTON//
</code></pre>
<p>The above is wrong because you are sending the <strong>pin numbers</strong> and not the values read from those pins. You previously read them here:</p>
<pre><code> sensorSense_0=analogRead(inPin_0);
...
sensorSense_1=analogRead(inPin_1); //ADDED FOR SECOND BUTTON//
</code></pre>
<p>It is <code>sensorSense_0</code> and <code>sensorSense_1</code> that you should be sending.</p>
<p>Also, as Damiano Verzulli pointed out, your second assignment to <code>senseval</code> clobbers the first. You want something more like:</p>
<pre><code> senseval = SensorVal + String(analogRead(inPin_0)) + ", ";
senseval += SensorVal + String(analogRead(inPin_1));
</code></pre>
<p>Even that may not be perfect, I didn't read your PHP side.</p>
<hr>
<p>Looking at the PHP side now:</p>
<pre><code>$query = "INSERT INTO $tablename VALUES ($senseval,now())";
</code></pre>
<p>That isn't going to work too well for two values. I don't know your database schema, but that won't handle two values very well. A bit of tweaking and it might, or you could do two <code>INSERT</code> statements.</p>
|
16051 | |uploading| | How to rsync my node.js project to my intel edison board, through ssh? | 2015-09-13T08:18:04.650 | <p>I would love to get rid of Intel's heavy XDK software, and be able to quickly push the updates of my node.js code into my Intel Edison (arduino compatible) board.</p>
<p>I tried this: <code>rsync -avz ./ root@192.168.100.177:/node_app_slot/</code></p>
<p>But <code>rsync</code> is not installed on the board.</p>
<p>How would you do this?</p>
| <p>You have few options:</p>
<ol>
<li>use the Yocto sdk to compile rsync and then deploy it</li>
<li>switch to <a href="https://learn.sparkfun.com/tutorials/loading-debian-ubilinux-on-the-edison" rel="nofollow noreferrer">Debian</a> and then use the standard way to deploy rsync</li>
<li>use scp, like the OP wrote, using the <a href="https://unix.stackexchange.com/questions/105140/how-to-copy-only-new-files-using-scp-command">answer</a> from Rick</li>
</ol>
<p>If you are already looking for a more typical Unix way of doing things, option 2 might be the most efficient for you, in the long run.
I have not tried it, but AFAIK it should be possible to revert easily, since Edison uses dfu for system upgrades, so you should be able to go back to the stock SW, in case you do not like the Debian installation.</p>
|
16062 | |serial|arduino-mega|xbee|softwareserial| | Communicating Via Serial1 on Arduino Mega | 2015-09-13T17:30:08.507 | <p>Apologies if this a relatively simple question, but I am rather new to Arduino's and cannot seem to find any concise information on the topic.<br />
This is my XBee, mounted on a shield and placed onto a MEGA 2560. I want to leave Serial for USB debugging and use the Serial1 for XBee communication.
<a href="https://i.stack.imgur.com/UyKUE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UyKUE.jpg" alt="enter image description here" /></a></p>
<p>Just to confirm, the two XBee's do communicate if I use SoftwareSerial. This is the code that works using SoftwareSerial:</p>
<pre><code>#include <SoftwareSerial.h>
// XBee's DOUT (TX) is connected to pin 10 (Arduino's Software RX)
// XBee's DIN (RX) is connected to pin 11 (Arduino's Software TX)
SoftwareSerial serial1(10, 11); // RX, TX
boolean nextLine = false;
void setup()
{
Serial.begin(9600);
serial1.begin(9600);
}
void loop()
{
while(serial1.available()){ // there is data being sent from the xBee
char read = char(serial1.read());
if(read == 'A'){
//Where ~ is the EOT character
serial1.write("55.134~");
}
}
}
</code></pre>
<p>How do I communicate using Serial1?</p>
| <p>If you take a look at the headers on the Mega, you'll notice that one of them has labels of "RX1" and "TX1" through "RX3" and "TX3". You'll also notice that the XBee shield <em>does not</em> connect to that header, therefore you <em>cannot</em> use <code>Serial1</code> through <code>Serial3</code> with the shield. Either switch to a breakout board that you can connect manually or stick to software serial.</p>
|
16068 | |lcd|display|electronics|resistor|potentiometer| | 10k ohm Potentiometer vs 10k ohm Resistor on LCD Display | 2015-09-13T21:28:48.113 | <p>I'm trying to use a LCD Display with my Arduino, but I don't have a potentiometer and all of the guides I find always require one, usually a 10k ohm potentiometer.</p>
<p>The point is that I'm not very good at this stuff, but I understand that the potentiometer is actually a resistor that can vary, am I correct? In that case, if I use a simple 10k resistor I would have the same result as if I was using that potentiometer at the higher resistance (10k).</p>
<p>Would it be correct to use the resistor instead of the potentiometer? Then I would have to plug the positive on one side of the resistor and both the negative and output to the LCD on the other side of the resistor?</p>
| <p>you can use the digital pin to do this instead of resistance or potentiometer. I used a delay 500 which gave me good readable display. a value of 100 was to bright</p>
<pre><code>void setup() {
pinMode(13, OUTPUT);
}
void loop()
{
digitalWrite(13, HIGH);
delayMicroseconds(500);
/* 100 gives Approximately 10% duty cycle @ 1KHz with 500 i get a good value for screen text brightness*/
digitalWrite(13, LOW);
delayMicroseconds(1000 - 500);
/* now you can add your LCD code to print what ever you like.*/
}
</code></pre>
|
16069 | |serial|reset| | Hard-resetting an arduino | 2015-09-13T21:32:47.763 | <p>I need to hard reset (or seriously breathe life into) a stuck Arduino clone (Sunfounder UNO) which doesn't get recognized by Windows (error 43) after installing the wrong sketch. I am using the latest Arduino toolset and, before today, the setup was functional.</p>
<p>The problem is probably that I am writing to the serial in the <code>setup()</code> section like this:</p>
<pre class="lang-c prettyprint-override"><code>void setup() {
pinMode(a0, OUTPUT);
pinMode(a1, OUTPUT);
pinMode(a2, OUTPUT);
pinMode(b1, OUTPUT);
pinMode(m0, OUTPUT);
pinMode(m1, OUTPUT);
pinMode(m2, OUTPUT);
pinMode(OK, OUTPUT);
pinMode(KO, OUTPUT);
pinMode(carry, INPUT);
pinMode(result, INPUT);
delay(1000);
Serial.begin(9600);
Serial.write("Arduino Tester v. 0.1\n");
}
</code></pre>
<p>Arduino seems to be running the code. The problem is that Windows doesn't recognize it and doesn't set up a COM port for it.</p>
<p>So: i'd like to nuke it and restart from scratch.</p>
<p>How is this done?</p>
| <p>The word "clone" immediately rings alarm bells.</p>
<p>Firstly, for a "normal" Arduino (like an Uno, etc) the sketch cannot influence whether Windows detects the board or not. All that is handled by a completely separate chip.</p>
<p>A lot of the cheap clones these days are coming out of China with a really really cheap USB serial adapter chip. These barely work at the best of times. Looking at the pictures I have found of your clone (the manufacturer's site is considerably lacking in any information whatsoever) it doesn't look like it's one of those chips, but one never can tell.</p>
<p>If they have followed the reference designs for the Arduino then it will be an Atmel ATMega32U4 (IIRC) chip that deals with the interface to the computer. That has firmware of its own on it, and if that has become corrupted (very unlikely) or damaged (possible) then it could cause it to not be recognised. If that is the case the in the former instance (corrupted) you will need to replace the firmware on it. For that you will need either a hardware ICSP programmer or another Arduino. In the latter instance you're stuffed, since you would need to replace the chip.</p>
<p>As I say that is unlikely.</p>
<p>Instead your problem is most likely actually with either Windows or the USB cable. You may need to remove and reinstall the Arduino drivers, or try a difference USB cable. Also try your "Arduino" on another computer.</p>
|
16074 | |ethernet|gsm| | Ethernet to Cellular Modem Possible? | GSM + Ethernet + Arduino | 2015-09-13T23:43:54.003 | <p>Is it possible to combine an Arduino µC with a GSM shield and an ethernet shield such that a device connected via ethernet to the Arduino has internet access over the GSM network?</p>
<p>I have a system with an ethernet port to connect to the internet. It works fine if I plug it into my switch at home. However, I would like this system to have its own cellular internet connection.</p>
<p>This is what I have found so far:</p>
<ol>
<li><p>I'm basically trying to replicate the following:
<a href="https://nimbelink.com/e2clink-ethernet2cellular/#parts" rel="nofollow">https://nimbelink.com/e2clink-ethernet2cellular/#parts</a></p></li>
<li><p>If the following reddit post:
<a href="https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/" rel="nofollow">https://www.reddit.com/r/arduino/comments/3azxs6/create_gsm_cellular_ethernet_modem_with_arduino/</a>
is any indication, I would think the answer is "no" but I am hoping to confirm from the expertise available here.</p></li>
</ol>
| <p>No, it's not possible.</p>
<p>Chiefly because the normal Ethernet shield is not capable of routing. The Arduino never talks to the ethernet - it talks to the chip on the shield and tells it how to handle the ethernet connection - everything else is then done by the ethernet chip and the results passed back to the Arduino.</p>
<p>Similarly with GSM - you make requests to it and it goes off and does the work.</p>
<p>To link the two together you would need raw access to the incoming ethernet packets, and you would then have to perform NAT (Network Address Translation) and maintain internal state tables for current streams and such, and pass reformatted packets on to a GSM modem that could accept raw data like that.</p>
<p>Way outside the scope of a lowly Arduino.</p>
<p>Maybe possible with one of the higher end Arduino-ish systems like the Edison, Galileo or Yun (just) since they run Linux and have a real Ethernet port and a proper USB port to communicate with a proper celular modem.</p>
|
16083 | |c++|ethernet|arduino-galileo| | Client.connect galileo gen2 not working | 2015-09-14T17:35:51.030 | <p>I'm having a problem with the intel galileo gen2 ethernet. I am trying to get a webpage, but I can only connect to the ethernet, not the webpage.
I get this in the Serial monitor:
<a href="https://i.stack.imgur.com/ciBPt.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ciBPt.png" alt="Serial monitor output"></a></p>
<p>My code:</p>
<pre><code>/*
Web client
This sketch connects to a website (http://www.google.com)
using an Arduino Wiznet Ethernet shield.
Circuit:
* Ethernet shield attached to pins 10, 11, 12, 13
created 18 Dec 2009
by David A. Mellis
modified 9 Apr 2012
by Tom Igoe, based on work by Adrian McEwen
*/
#include <SPI.h>
#include <Ethernet.h>
// Enter a MAC address for your controller below.
// Newer Ethernet shields have a MAC address printed on a sticker on the shield
byte mac[] = { 0x98, 0x4f, 0xee, 0x01, 0x8d, 0xdf };
// if you don't want to use DNS (and reduce your sketch size)
// use the numeric IP instead of the name for the server:
IPAddress server(216, 58, 217, 206); // numeric IP for Google (no DNS)
//char server[] = "www.google.com"; // name address for Google (using DNS)
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 177);
IPAddress dns(192, 168, 1, 122);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 80 is default for HTTP):
EthernetClient client;
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
while (!Serial) {
// wait for serial port to connect. Needed for Leonardo only
}
delay(5000);
// start the Ethernet connection:
Ethernet.begin(mac, ip, dns, gateway, subnet);
Serial.println("connected to ethernet");
// give the Ethernet shield a second to initialize:
delay(1000);
Serial.println("connecting...");
// if you get a connection, report back via serial:
int ch = client.connect(server, 80);
if (ch) {
Serial.println("connected");
// Make a HTTP request:
client.println("GET /search?q=arduino HTTP/1.1");
client.println("Host: www.google.com");
client.println("Connection: close");
client.println();
}
else {
// kf you didn't get a connection to the server:
Serial.print("connection failed, error code ");
Serial.println(ch);
}
}
void loop()
{
// if there are incoming bytes available
// from the server, read them and print them:
if (client.available()) {
char c = client.read();
Serial.print(c);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("disconnecting.");
client.stop();
// do nothing forevermore:
while (true);
}
}
</code></pre>
<p>Any help is greatly appreciated.</p>
| <p>6 months after figuring out the answer, I found this question again. I solved this question by adding <code>system("ifup eth0")</code> which completely solved the problem.</p>
|
16084 | |arduino-uno|c++|timers| | Problem with Arduino code | 2015-09-14T18:58:08.953 | <p>Please help me with this code it's shows some error [but I can't be bothered to tell you what].</p>
<pre><code>#include <TimerOne.h>
/**
Analog Clock
Paul Cox Dec 2010
*/
#define PI 3.141592653589793e-06;
byte rows[8] = {9, 14, 8, 12, 1, 7, 2, 5};
byte cols[8] = {13, 3, 4, 10, 6, 11, 15, 16};
byte pins[16] = {5, 4, 3, 2, 14, 15, 16, 17, 13, 12, 11, 10, 9, 8, 7, 6};
byte screen[8] = {0, 0, 0, 0, 0, 0, 0, 0};
volatile byte screenRow = 0;
volatile byte screenCol = 0;
int iHour = 0;
int iMin = 0;
int iSec = 0;
void setup()
{
Timer1.initialize(100);
for (int i = 2; i <= 17; i++)
{
pinMode(i, OUTPUT);
}
Timer1.attachInterrupt(doubleBuffer);
Serial.begin(9600);
resetAnim();
}
void doubleBuffer()
{
digitalWrite(translatePin(rows[screenRow]), LOW);
digitalWrite(translatePin(cols[screenCol]), HIGH);
screenCol++;
if (screenCol >= 8)
{
screenCol = 0;
screenRow++;
if (screenRow >= 8)
{
screenRow = 0;
}
}
if((screen[screenRow] >> screenCol) & B1 == B1)
{
digitalWrite(translatePin(rows[screenRow]), HIGH);
digitalWrite(translatePin(cols[screenCol]), LOW);
}
else
{
digitalWrite(translatePin(rows[screenRow]), LOW);
digitalWrite(translatePin(cols[screenCol]), HIGH);
}
}
byte translatePin(byte original)
{
return pins[original - 1];
}
void allOFF()
{
for (int i = 0; i < 8; i++)
{
screen[i] = 0;
}
}
void on(byte row, byte column)
{
screen[column-1] |= (B1 << (row - 1));
}
void off(byte row, byte column)
{
screen[column-1] &= ~(B1 << (row - 1));
}
void resetAnim()
{
for (int i = 0; i < 8; i++)
{
screen[i] = B11111111;
delay(25);
}
for (int i = 0; i < 8; i++)
{
screen[i] = B00000000;
delay(25);
}
}
void loop()
{
drawClock();
iSec++;
if (iSec == 60)
{
iSec = 1;
iMin++;
if (iMin == 60)
{
iMin = 0;
iHour++;
if (iHour == 12)
{
iHour = 0;
}
}
}
delay(10);
}
void drawClock()
{
allOFF();
setHand(iHour,12,3);
setHand(iMin,60,4);
setHand(iSec,60,5);
}
// work out the pixel for a hand - val is out of a possible max val
// radius is distance from the centre
void setHand(int iVal, int iMax, int iRadius)
{
double dAngle = (iVal * 2 * PI) / iMax;
double dPosX = 4.5 + (iRadius * cos(dAngle));
double dPosY = 4.5 + (iRadius * sin(dAngle));
drawLine(5,5,constrain(round(dPosX),1,8),constrain(round(dPosY),1,8));
}
void drawLine(int x0, int y0, int x1, int y1)
{
int iTemp;
boolean bSteep = abs(y1 - y0) > abs(x1 - x0);
if (bSteep)
{
iTemp = x0; x0 = y0; y0 = iTemp; // swap x0,y0
iTemp = x1; x1 = y1; y1 = iTemp; // swap x1,y1
}
if (x0 > x1)
{
iTemp = x0; x0 = x1; x1 = iTemp; // swap x0,x1
iTemp = y1; y1 = y0; y0 = iTemp; // swap y0,y1
}
int deltax = x1 - x0;
int deltay = abs(y1 - y0);
int error = deltax / 2;
int ystep = ((y0 < y1) ? 1 : -1);
int y = y0;
int x = x0;
while(x <= x1)
{
if (bSteep)
{
on(y,x);
}
else
{
on(x,y);
}
error = error - deltay;
if (error < 0)
{
y = y + ystep;
error = error + deltax;
}
x++;
}
}
</code></pre>
| <p>It's amazing the difference one character can make:</p>
<ul>
<li>You must NEVER terminate a #define with a <code>;</code> unless you absolutely know that you need one when it is expanded.</li>
</ul>
<p>You have a macro defined:</p>
<pre><code>#define PI 3.141592653589793e-06;
</code></pre>
<p>That macro is then used here:</p>
<pre><code>double dAngle = (iVal * 2 * PI) / iMax;
</code></pre>
<p>Expand the macro PI and you get:</p>
<pre><code>double dAngle = (iVal * 2 * 3.141592653589793e-06;) / iMax;
</code></pre>
<p>Which obviously is a syntax error - you have a rogue <code>;</code> in there where you really don't want one.</p>
<p>Oh, and one other thing - you shouldn't define PI - the Arudino core already defines it for you to a greater accuracy than you are:</p>
<pre><code>arduino/Arduino.h:#define PI 3.1415926535897932384626433832795
</code></pre>
<p>... though you seem to be working in microPi's whatever those are...</p>
|
16086 | |arduino-mega| | Why are there 3 crystals on the Mega2560 schematic? | 2015-09-14T19:03:41.090 | <p>I am a software engineer who is new(er) to electronics, I only started a couple of months ago. I've built a bunch of custom circuits, then some arduino nodes that are around my apartment that communicate with a C# server. So I've at least got the breadboarding part down.</p>
<p>So now I am working on a controller board that connects to my home automation system and determines the color on the LED light strips I installed into my bookshelf. So I want to transfer from working with pre-built Arduinos to building my own full node, there are some things I think I'm missing. </p>
<p>I've noticed that there are duplicate parts on the schematic for the <a href="https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf" rel="nofollow noreferrer">Arduino Mega2560 schematic</a> (such as there being 2 voltage regulators - one is replacement if the other is not available). I couldn't find any such description however for why there are 3 crystals located on the board. I see 3 different circuits for crystals (all of which are 16MHz).</p>
<p>Specifically, I am referencing the following
<a href="https://i.stack.imgur.com/ylfe5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ylfe5.jpg" alt="Crystal 1"></a></p>
<p><a href="https://i.stack.imgur.com/3vI1B.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3vI1B.jpg" alt="Crystal 2"></a></p>
| <p>One of the crystals is for the ATMega8U2 chip which is being used for USB-Serial conversion.</p>
<p>The other two crystals are both for the ATMega2560. Why two? Basically they only populate one of the two, but they have two different footprints. One is for a surface mount resonator, the other for a through-hole crystal. </p>
<p>Having two footprints gives the option during assembly to go for the cheapest package at the time. It also means that the hobbyist can replaces the low accuracy resonator with a high accuracy crystal if their project requires. </p>
<hr>
<p>As a side note, if you look at Y1, you will notice it is not the symbol for a crystal, it is of a resonator.</p>
|
16089 | |serial| | How do I start a function with serial input? | 2015-09-14T19:44:44.960 | <p>I want to create a LED Sunrise/Sundown alarm clock. Therefore, I will use a Raspberry Pi that is sending commands over serial to a Teensy 3.1. Like: </p>
<ul>
<li>"30 Minute Sunrise starting with Color(255,140,0)"</li>
<li>"20 Minute Sundown with Color(255,140,0)"</li>
<li>"start something else with these 3 parameter.</li>
</ul>
<p>But I don't even get the basic serial part working. E.g. I tried this:</p>
<pre><code>void setup() {
Serial.begin(9600);
strip.begin();
strip.show(); // Initialize all pixels to 'off'
}
void loop() {
if (Serial.available() > 0) {
if (Serial.read() == 'A'){
int inte1 = Serial.parseInt();
int inte2 = Serial.parseInt();
int inte3 = Serial.parseInt();
int inte4 = Serial.parseInt();
int inte5 = Serial.parseInt();
if (Serial.read() == '\n') {
Serial.print(inte1);
Serial.print(inte2);
Serial.print(inte3);
Serial.print(inte4);
Serial.println(inte5);
}
}
}
}
</code></pre>
<p>I planned to do a <code>case</code> switch afterwards. <code>Inte1</code> should define sunrise/sundown, <code>Inte2</code> the minutes, 'Inte3-5' the rgb color.</p>
<p>However, when I enter "A 1 100 100 100" it is not printing anything at all. </p>
<p>What is the best way do get this working?</p>
<p>Thanks in advance!</p>
| <p>Okay, as Majenko and Nick Gammon have suggested. The <code>\n</code> had not arrived in the serial buffer. That way the if clause was not fulfilled and nothing was printed. This code has worked for me now:</p>
<pre><code>if (Serial.available() > 0) {
if (Serial.read() == 'A'){
char inte1 = Serial.read();
int inte2 = Serial.parseInt();
int inte3 = Serial.parseInt();
int inte4 = Serial.parseInt();
int inte5 = Serial.parseInt();
Serial.print(inte1);
Serial.print(inte2);
Serial.print(inte3);
Serial.print(inte4);
Serial.println(inte5);
}
}
</code></pre>
<p>Although i read quite a bit now, serial input is still a mystery to me.</p>
|
16093 | |signal-processing| | Looking for circuit diagram for evaluation of a pulsed signal | 2015-09-14T21:47:11.600 | <p>How can I evaluate a pulsed signal in Arduino? The signal comes from an car alarm system and is called (-) output 200 mA. Arduino and the car have the same GND. Can I attach the output through a resistor to PB0 (D8) or PD5 (D5)?
Alarm system is called Ampire. Probably the same as Viper. I just wanted to read these pulses, but I do not know exactly how I connect this output correctly with Arduino.
This is the description for this Output:</p>
<hr>
<p><strong>HN1/9 BROWN/WHITE – 200mA (-) Horn honk output: This wire supplies a 200mA (-) output that can be used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used to interface with the vehicle’s horn circuit</strong>. </p>
<hr>
| <p>I found a user manual at <a href="http://www.ampire.de/Security-Systems/Security-for-CAN-Bus-System/AUDI/AUDI-A3/from-model-year-2013/AMPIRE-Car-Alarm-System-for-High-Speed-CAN-Bus.htm?shop=ampire_en&SessionId=&a=article&ProdNr=CAN3903V&t=2899&c=16941&p=16941" rel="nofollow noreferrer">AMPIRE Car Alarm System for High-Speed CAN-Bus</a>.</p>
<blockquote>
<p><strong>N1/9 BROWN/WHITE – 200mA (-) Horn honk output:</strong> </p>
<p>This wire supplies a 200mA (-) output that can be
used to honk the vehicle’s horn. It provides a pulsed output when the security system is armed/disarmed
and in trigger sequence or in panic mode. In most vehicles with (-) horn circuits this wire can control the
vehicle’s horn without adding a relay. If the vehicle has a (+) horn circuit, an optional relay must be used
to interface with the vehicle’s horn circuit. </p>
<p><strong>IMPORTANT!</strong>
Never use this wire to drive anything but a relay or a low-current input! This transistorized output can only supply (-) 200mA and connecting directly to a solenoid, motor or other high current device will cause the module to fall</p>
</blockquote>
<p>Judging by that this output will sink up to 200 mA. You could conceivably set an Arduino pin to INPUT_PULLUP and let this output drive it low to indicate it is active.</p>
<p>Personally I think I would use an optocoupler, in case there were unexpected voltages on that pin. You would need a series resistor to limit current through the LED in the optocoupler, say 1 k would be about right if you were connecting it to the 12V car system.</p>
<pre><code>Vf = 1.2V (say)
Voltage over resistor = 12 - 1.2 = 10.8 volts
Current through LED = 10 mA
Limiting resistor = 10.8 / 0.01 = 1080 ohms
</code></pre>
<p>Now the output of the optocoupler can sink your Arduino pin, which you have configured as input pullup.</p>
<p>Write a test sketch to see what you are getting through it, but a multimeter should probably tell you, if it just flashes it slowly.</p>
<hr>
<p>Suggested schematic:</p>
<p><a href="https://i.stack.imgur.com/SiiN1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SiiN1.png" alt="Schematic for optocoupler"></a></p>
|
16101 | |gsm|arduino-duemilanove| | Problem in SIM900 GPRS connection | 2015-09-15T09:26:50.427 | <p>I make simple code to read web page by <a href="http://imall.itead.cc/gboard.html" rel="nofollow">ITEAD Gboard</a>. Here is my code:</p>
<pre><code> Serial.write("\nStarting..........\n");
mySerial.print("AT+CSQ");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----1-----\n");
mySerial.println("AT+CGATT=1");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----2-----\n");
mySerial.println("AT+CGATT?");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----3-----\n");
mySerial.print("AT+SAPBR=3,1,\"CONTYPE\",\"GPRS\"");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----4-----\n");
mySerial.print("AT+SAPBR=3,1,\"APN\",\"internet\"");
delay(2000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----5-----\n");
mySerial.print("AT+SAPBR=1,1");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----6-----\n");
mySerial.print("AT+HTTPINIT");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----7-----\n");
mySerial.print("AT+HTTPPARA=\"URL\",\"xx.xx.xx.xx/my/web/site\"");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----8-----\n");
mySerial.print("AT+HTTPDATA=100,1000");
delay(10000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\n-----9-----\n");
mySerial.println("AT+HTTPREAD");
delay(1000);
while(mySerial.available()!=0)
Serial.write(mySerial.read());
Serial.write("\nend.\n");
</code></pre>
<p>Which i get the following output:</p>
<pre><code>Starting..........
AT+CSQ
-----1-----
AT+CGATT=1
ERROR
-----2-----
AT+CGATT?
+CGATT: 1
OK
-----3-----
AT+SAPBR=3,1,"CONTYPE","GPRS"
-----4-----
AT+SAPBR=3,1,"APN","internet"
-----5-----
AT+SAPBR=1,1
-----6-----
AT+HTTPINIT
-----7-----
AT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"
-----8-----
AT+HTTPDATA=100,1000
-----9-----
AT+HTTPREAD
ERROR
end.
</code></pre>
<p>AT+HTTPREAD return error. What wrong with me?</p>
<p><strong>Note</strong></p>
<p>xx.xx.xx.xx/my/web/site is my web page. The error is still there for all web page.</p>
| <p>The problem (I believe) is that half way through your program you switched from using <code>println()</code> to using <code>print()</code>, thus the commands from that point on aren't being executed until right at the end where you switch back to <code>println()</code>, so the whole of the text you send from point 3 onwards is being run as one single command - which of course is in the wrong format:</p>
<blockquote>
<p>AT+SAPBR=3,1,"CONTYPE","GPRS"AT+SAPBR=3,1,"APN","internet"AT+SAPBR=1,1AT+HTTPINITAT+HTTPPARA="URL","xx.xx.xx.xx/my/web/site"AT+HTTPDATA=100,1000AT+HTTPREAD</p>
</blockquote>
|
16103 | |arduino-uno| | Arduino code (on board) runs really slow | 2015-09-15T10:39:49.807 | <p>Stumbled upon this weirdest behavior, from time to time, my Arduino (UNO) runs gode really slow.</p>
<p>Searching this issue didn't clarify anything, most people have problems with IDE itself. My issue is related to actual board.</p>
<p>Heres a sample of my flow:</p>
<ul>
<li>I compile & upload my sketch, all good</li>
<li>first initiation of program on the board seems to be "fast"</li>
<li>when I start to "animate" the neopixels it goes 3-4 times slower than it should</li>
<li>I'll touch the board, and animation goes fast again.</li>
</ul>
<p><a href="https://www.youtube.com/watch?v=B-7562YRjLU" rel="nofollow noreferrer">Here's a clip of that, at the end you'll see the "slowness"</a> </p>
<ul>
<li><p>Test environment:
<a href="https://i.stack.imgur.com/9HW7S.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/9HW7S.png" alt="enter image description here"></a></p></li>
<li><p>Live environment:
<a href="https://i.stack.imgur.com/bAezE.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bAezE.png" alt="enter image description here"></a></p></li>
</ul>
<p>The Touching part, is almost like if I "add" static electricity from my finger to the board, it wakes up and behaves normally.</p>
<p>For you who are curious about (non related) what animation I'm doing on neopixels, I'm turning on 15 pixels from 0 to 54. Like a "slide effect".
(I'm not using delay, only a delay(30) in the loop, rest of the delays are based on <code>millis()</code>)</p>
<p>Is there any general info / explanation that would explain this behavior, like in electronics, arduino boards specifically ?</p>
<p>EDIT: I should also add, when printing logs into serial monitor, that slowness also affects the outputs... they appear as "slow" as the pixels flow. When all works normally, I see pixels change and logs 50 times per second (roughly), but in this slow motion, I see pixels change and logs around 20 times per second. Taking out the <code>Serial</code> entirely from the code doesn't seem to have effect.</p>
<p>Code:</p>
<pre><code>#include <Adafruit_NeoPixel.h>
#include <avr/power.h>
#define LEFT_BLINK_IN 2
#define RIGHT_BLINK_IN 3
#define PIN 6
#define NUMPIXELS 54
Adafruit_NeoPixel leftLight = Adafruit_NeoPixel(NUMPIXELS, 6, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel rightLight = Adafruit_NeoPixel(NUMPIXELS, 10, NEO_GRB + NEO_KHZ800);
int leftBlinkCount = 0;
int rightBlinkCount = 0;
int PIXELTOSHOW = 20;
bool OEM_RIGHT_ON = false;
bool OEM_LEFT_ON = false;
int R_PIXEL = -1;
int L_PIXEL = -1;
int G_PIXEL = -1;
int D_PIXEL = -1;
char LAST_COMMAND;
bool DRL_ON = false;
int DRL_STARTPIXEL = 35;
uint32_t COLOR_YEL = rightLight.Color(240, 120, 0);
uint32_t COLOR_RED = rightLight.Color(255, 0, 0);
uint32_t COLOR_BLU = rightLight.Color(0, 0, 255);
uint32_t COLOR_NON = rightLight.Color(0, 0, 0);
uint32_t COLOR_WHI = rightLight.Color(255, 255, 255);
unsigned long rightPrevMillis = 0;
unsigned long leftPrevMillis = 0;
unsigned long generalPrevMillis = 0;
const long PIXEL_SWITCH_INTERVAL = 5;
int DRL_RESETER_LEFT = 0;
int DRL_RESETER_RIGHT = 0;
void welcome()
{
int totalPixels = (NUMPIXELS + PIXELTOSHOW);
while (G_PIXEL < totalPixels) {
unsigned long leftCurrentMillis = millis();
if (leftCurrentMillis - leftPrevMillis >= 12) {
leftLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
rightLight.setPixelColor(totalPixels - G_PIXEL, COLOR_WHI);
if (G_PIXEL >= 10) {
leftLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
rightLight.setPixelColor(totalPixels - G_PIXEL + PIXELTOSHOW , COLOR_NON);
}
leftLight.show();
rightLight.show();
G_PIXEL++;
leftPrevMillis = leftCurrentMillis;
}
}
G_PIXEL = 0;
while (G_PIXEL < totalPixels) {
unsigned long leftCurrentMillis = millis();
if (leftCurrentMillis - leftPrevMillis >= 12) {
leftLight.setPixelColor(G_PIXEL, COLOR_WHI);
rightLight.setPixelColor(G_PIXEL, COLOR_WHI);
if (G_PIXEL >= 10) {
leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
}
leftLight.show();
rightLight.show();
G_PIXEL++;
leftPrevMillis = leftCurrentMillis;
}
}
}
void blinkRight()
{
//slidePixels(rightBlinkCount, R_PIXEL, rightLight);
if (rightBlinkCount > 0 && R_PIXEL > -1)
{
//Serial.println("RIGHT "+String(rightBlinkCount));
LAST_COMMAND = ' ';
unsigned long rightCurrentMillis = millis();
if (rightCurrentMillis - rightPrevMillis >= PIXEL_SWITCH_INTERVAL) {
rightLight.setPixelColor(R_PIXEL, COLOR_YEL);
if (R_PIXEL >= PIXELTOSHOW)
{
rightLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
if (G_PIXEL > -1 && DRL_ON == false) {
leftLight.setPixelColor(R_PIXEL - PIXELTOSHOW, COLOR_NON);
}
}
leftLight.show();
rightLight.show();
R_PIXEL++;
rightPrevMillis = rightCurrentMillis;
}
if ( R_PIXEL >= (NUMPIXELS + PIXELTOSHOW)) {
rightBlinkCount--;
if ( rightBlinkCount > -1 ) {
R_PIXEL = DRL_RESETER_RIGHT = 0;
} else {
L_PIXEL = G_PIXEL = -1;
}
if(DRL_ON){
D_PIXEL=DRL_STARTPIXEL;
}
}
}
}
void blinkLeft() {
// slidePixels(leftBlinkCount, L_PIXEL, leftLight);
if (leftBlinkCount > 0 && L_PIXEL > -1)
{
//Serial.println("left "+String(rightBlinkCount));
LAST_COMMAND = ' ';
unsigned long leftCurrentMillis = millis();
if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
leftLight.setPixelColor(L_PIXEL, COLOR_YEL);
if (L_PIXEL >= PIXELTOSHOW)
{
Serial.print(" "+String(L_PIXEL));
leftLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);
if (G_PIXEL > -1 && DRL_ON == false) {
rightLight.setPixelColor(L_PIXEL - PIXELTOSHOW, COLOR_NON);
}
}
rightLight.show();
leftLight.show();
L_PIXEL++;
leftPrevMillis = leftCurrentMillis;
}
if ( L_PIXEL >= (NUMPIXELS + PIXELTOSHOW) ) {
leftBlinkCount--;
Serial.println("Count "+leftBlinkCount);
if ( leftBlinkCount > -1 ) {
L_PIXEL = DRL_RESETER_LEFT = 0;
} else {
L_PIXEL = G_PIXEL = -1;
}
if(DRL_ON){
D_PIXEL=DRL_STARTPIXEL;
}
}
}
}
/*void slidePixels(int &blinkCount, int &blinkPixel, Adafruit_NeoPixel &sideLight){
if (blinkCount > 0 && blinkPixel > -1)
{
LAST_COMMAND = ' ';
unsigned long leftCurrentMillis = millis();
if (leftCurrentMillis - leftPrevMillis >= PIXEL_SWITCH_INTERVAL) {
sideLight.setPixelColor(blinkPixel, COLOR_YEL);
if (blinkPixel >= PIXELTOSHOW)
{
if(G_PIXEL>-1){
rightLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
leftLight.setPixelColor(blinkPixel - PIXELTOSHOW, COLOR_NON);
}
}
rightLight.show();
leftLight.show();
blinkPixel++;
leftPrevMillis = leftCurrentMillis;
}
if ( blinkPixel >= (NUMPIXELS + PIXELTOSHOW) ) {
blinkCount--;
if ( blinkCount > -1 ) {
blinkPixel = 0;
} else {
blinkPixel = -1;
if(DRL_ON){
G_PIXEL = -1;
}
}
}
}
}*/
int switchRB = 0; // 0 = red, 1 = blue
void slideBlueRed() {
unsigned long currentMillis = millis();
if (currentMillis - generalPrevMillis >= 100) {
if (switchRB == 0) {
leftLight.setPixelColor(G_PIXEL, COLOR_RED);
rightLight.setPixelColor(G_PIXEL, COLOR_RED);
} else {
leftLight.setPixelColor(G_PIXEL, COLOR_BLU);
rightLight.setPixelColor(G_PIXEL, COLOR_BLU);
}
if (G_PIXEL >= 10) {
leftLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
rightLight.setPixelColor(G_PIXEL - PIXELTOSHOW, COLOR_NON);
}
leftLight.show();
rightLight.show();
G_PIXEL++;
generalPrevMillis = currentMillis;
}
}
void drlLight(){
unsigned long currentMillis = millis();
if (D_PIXEL < NUMPIXELS) {
leftLight.setPixelColor(NUMPIXELS-DRL_RESETER_LEFT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
rightLight.setPixelColor(NUMPIXELS-DRL_RESETER_RIGHT, DRL_ON == true ? COLOR_WHI : COLOR_NON);
rightLight.setBrightness(128);
leftLight.setBrightness(128);
rightLight.show();
leftLight.show();
D_PIXEL++;
//x //Serial.println(String(DRL_RESETER_LEFT) + " "+ String(NUMPIXELS - DRL_STARTPIXEL));
if(DRL_RESETER_LEFT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
DRL_RESETER_LEFT++;
}
if(DRL_RESETER_RIGHT+1 < (NUMPIXELS - DRL_STARTPIXEL)){
DRL_RESETER_RIGHT++;
}
generalPrevMillis = currentMillis;
}
}
void setup() {
Serial.begin(115200);
leftLight.begin();
rightLight.begin();
pinMode(LEFT_BLINK_IN, INPUT);
pinMode(RIGHT_BLINK_IN, INPUT);
delay(50);
welcome();
}
void loop() {
if (digitalRead(LEFT_BLINK_IN) == HIGH) {
if ( OEM_LEFT_ON == false ) {
OEM_LEFT_ON = true;
leftBlinkCount++;
//Serial.println("LEFT "+String(leftBlinkCount));
if (leftBlinkCount == 1) {
L_PIXEL = 0;
}
}
} else {
OEM_LEFT_ON = false;
}
if (digitalRead(RIGHT_BLINK_IN) == HIGH) {
if ( OEM_RIGHT_ON == false ) {
OEM_RIGHT_ON = true;
rightBlinkCount++;
if (rightBlinkCount == 1) {
R_PIXEL = 0;
}
}
} else {
OEM_RIGHT_ON = false;
}
if(DRL_ON && leftBlinkCount < 1 && rightBlinkCount < 1){
drlLight();
}
blinkRight();
blinkLeft();
if(rightBlinkCount < 1 || leftBlinkCount < 1){
delay(30);
switch (LAST_COMMAND) {
case 'q':
case '?': {
for ( int gp = 0; gp < NUMPIXELS + PIXELTOSHOW; gp++) {
leftLight.setPixelColor(gp, COLOR_NON);
rightLight.setPixelColor(gp, COLOR_NON);
}
leftLight.show();
rightLight.show();
G_PIXEL = -1;
break;
}
case 's': {
slideBlueRed();
//Serial.println("bluuu");
if (G_PIXEL >= NUMPIXELS ) {
G_PIXEL = -1;
switchRB = switchRB == 0 ? 1 : 0;
}
break;
}
case 'w': {
welcome();
if (G_PIXEL >= NUMPIXELS + PIXELTOSHOW) {
G_PIXEL = -1;
}
break;
}
case 'd': {
if(DRL_ON==false){
D_PIXEL = DRL_STARTPIXEL;
DRL_ON = true;
LAST_COMMAND = '-';
}else{
D_PIXEL = 0;
DRL_ON = false;
}
break;
}
}
if (Serial.available()) {
LAST_COMMAND = '-';
while (Serial.available()) {
char command = Serial.read();
G_PIXEL=-1;
LAST_COMMAND = command;
}
}
}
}
</code></pre>
| <p>Now, 3 years later, I found the actual source of your problem. I had a similar problem so I'm posting here for others to find this solution.</p>
<p>The problem is that the NeoPixel library disables ALL interrupts during the time it spends sending the pixel data. The millis() function is dependent on interrupts. It works by incrementing a counter once every millisecond, based on a interrupt, called from a hardware timer. If you disable all interrupts then the counter will not be incremented for the duration.</p>
<p>The NeoPixel library needs to disable them because NeoPixels need very accurate timing of the signals, and you'd suffer from visible intermittent glitches if not.</p>
<p>The millis() counter drops about 30 microseconds per a RGB pixel, or 40 microseconds for a RGBW pixel. You have 54 RGB pixels in your led strip. 54*0,030 = 1,62 ms. Which means that there's 1,62 milliseconds between each of your millis() updates. I.e. it updates too slow.</p>
<p>Your unstable button must've simply caused nonstop neopixel updates, due to some logic in your code.</p>
<p>There's no easy fix for this, but a few specialized alternative or companion libraries exist that use very device-specific peripherals to work around it. For example, you could use one of the hardware timers to measure the time spent sending NeoPixel data, and then manually go in and update the millis() counter accordingly when done. This requires hacking the NeoPixel library and reading the datasheets for your specific Arduino processor.</p>
|
16109 | |bluetooth|sound| | Would Arduino Nano be good for Bluetooth + Sound | 2015-09-15T17:27:18.277 | <p>So I've been browsing around for a whole looking for a good microcontroller that's super small. So far the smallest one I found was an Arduino Nano. But before I go buying it, there are some questions I have about it. </p>
<ol>
<li>Is Bluetooth compatible with it and if so where would I get the Bluetooth code?</li>
<li>Is there anything smaller than it that's Bluetooth compatible?</li>
<li>Would an Arduino Nano (Or the device in the question above) be able to play sounds?</li>
</ol>
| <p>There are <a href="https://www.adafruit.com/products/1588" rel="nofollow noreferrer">Bluetooth boards</a> and chips that you can connect to a Nano.</p>
<p>You can play sounds with a Nano. Crudely with PWM and a direct connection, for finely with an external digital-to-analog converter.</p>
<p>But if super-smallness is what you are after, there may be better options. </p>
<p>The <a href="http://www.makershed.com/products/lightblue-bean-bluetooth-4-0" rel="nofollow noreferrer">Blue Bean</a> is a complete BLE microcontroller on a single board that is smaller than a Nano+board.</p>
<p>If you want even smaller, you could get something like the new Cypress EZ-BLE module...</p>
<p><a href="https://i.stack.imgur.com/mlfYc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mlfYc.jpg" alt="enter image description here"></a>
<a href="http://www.cypress.com/products/ez-ble-module-bluetooth-smart" rel="nofollow noreferrer">http://www.cypress.com/products/ez-ble-module-bluetooth-smart</a></p>
<p>It is a complete programmable BLE system on a tiny module. It is hard to imagine anything smaller than that!</p>
|
16110 | |frequency|transistor| | Transistors to switch monitor inputs | 2015-09-15T19:21:27.510 | <p>I am using the following setup on my Arduino UNO to measure cpu fan RPMs:</p>
<p><a href="https://i.stack.imgur.com/pP1oM.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/pP1oM.png" alt="enter image description here"></a></p>
<p>The code is set to bring the trigger pin for each transistor high when it is checking that fan's RPM and FreqMeasure.h is then used to check the frequency of the signal on pin 8 which is then translated to RPM and sent to the LCD display.</p>
<p>I am experiencing reading issues and suspect that the signal is remaining on the measuring bus during the subsequent reads, however before revamping my code I simply wonder:</p>
<p>Is my circuit logic sturdy? I am just getting my feet back under me with microprocessors and have always found transistors to be a tricky subject, thanks in advance for your help!</p>
<p>If you'd like to see more info all can be found on <a href="https://github.com/msashlee/fanMon/" rel="nofollow noreferrer">GitHub.</a></p>
| <p>I have <a href="http://www.falstad.com/circuit/circuitjs.html?cct=$+1+0.000005+10.20027730826997+50+5+43%0AR+240+160+208+160+0+2+721+6+6+0+0.5%0Ag+288+176+288+208+0%0Af+240+160+288+160+0+1.5%0AR+432+80+432+48+0+0+40+5+0+0+0.5%0Ar+432+80+432+144+0+10000%0At+336+96+336+144+0+1+-4.999999997500001+-0.0000049995+100%0Aw+288+144+320+144+0%0Aw+352+144+432+144+0%0Aw+432+144+496+144+0%0Ar+336+96+160+96+0+10000%0Ar+336+240+160+240+0+10000%0AL+160+240+128+240+0+0+false+5+0%0Aw+352+288+432+288+0%0Aw+288+288+320+288+0%0At+336+240+336+288+0+1+-4.999999997500001+-0.0000049995+100%0Af+240+304+288+304+0+1.5%0Ag+288+320+288+352+0%0AR+240+304+208+304+0+2+382+6+6+0+0.5%0Aw+432+144+432+288+0%0AL+160+96+128+96+0+0+false+5+0%0Ap+496+240+496+144+0%0Ag+496+240+496+256+0%0Ao+20+64+0+558+5+0.00009765625+0+-1%0A" rel="nofollow">simulated your circuit</a> and it seems sound enough to me.</p>
<p>It is a little confusing having the transistors there though. I would prefer to convert the three open drain outputs to logic level outputs (each having its own pullup resistor) then use a digital 3:1 MUX (or discrete logic gates) to select the signal to sample.</p>
|
16114 | |arduino-uno|usb|arduino-mini| | USB mini type B port on Arduino Uno | 2015-09-15T20:43:40.773 | <p>I bought today an Arduino Uno R3, and I'm looking forward to make it an HID device. I have seen many projects using a serial USB type B port. As I want to build a little gamepad, I would like to use the smaller USB mini type B port to achieve similar results. Looking it up did not seem to bring significant results.</p>
<p>Am I missing anything? Do I have to use a serial port similar to the one used by Arduino or can I reproduce the project using the aforementioned port?</p>
| <p>As an alternative to Majenko's suggestion you can implement Virtual USB as described at <a href="http://www.practicalarduino.com/projects/virtual-usb-keyboard" rel="nofollow">Virtual USB Keyboard</a>. You just need:</p>
<ul>
<li>3 resistors</li>
<li>2 zener diodes</li>
<li>a bit of wire</li>
<li>a suitable USB socket</li>
</ul>
<p>The advantage is you haven't modified your Uno's USB chip (the ATMega16U2) so you can continue to upload sketches in the normal way.</p>
<p>The disadvantage is that the software USB may be more flaky than a hardware-implemented one. </p>
<p>Personally I don't like reprogramming my ATMega16U2 because I may as well have used one of the chips with a ATmega32U4 chip on it in the first place (like the Micro) which is designed for easy reprogramming.</p>
|
16122 | |arduino-uno|serial|c++| | How I can print several numbers via Serial with very few lines of code? | 2015-09-16T05:54:07.050 | <p>Could someone help me how to output the numbers from 1 to 10 via Serial, without having to write out each command by hand?</p>
<p>Below is my sketch - I need it concise instead of a long sketch:</p>
<pre><code>#include <Streaming.h
//setup
void setup() {
Serial. begin(9600);//The faster the better
}//Close the sertup
//main loop
void loop() {
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
delay(1000);
Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
delay(1000);
while(1){}//freeze the main loop
}
</code></pre>
| <p>Fixing the typos in your original code, so that it should probably read:</p>
<pre><code>#include <Streaming.h>
//setup
void setup() {
Serial.begin(9600); //The faster the better
} //Close the setup
//main loop
void loop() {
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(1) << endl;
delay(1000);
Serial<< _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(2) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(3) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(4) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(5) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(6) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(7) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(8) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(9) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(10) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(11) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(12) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(13) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(14) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(15) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(16) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(17) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(18) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(19) << endl;
delay(1000);
Serial << _BYTE(27)<< _BYTE(91)<< _BYTE(50)<< _BYTE(74);//CLR
Serial<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<<"\n"<< endl;
Serial<<"\t"<<"\t"<<"\t"<<"\t"<<"\t"<< _DEC(20) << endl;
delay(1000);
while(1){} //freeze the main loop
}
</code></pre>
<p>Then condensing the <em>cursor positioning</em> lines, gives:</p>
<pre><code>#include <Streaming.h>
//setup
void setup() {
Serial.begin(9600); //The faster the better
} //Close the setup
//main loop
void loop() {
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(1) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(2) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(3) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(4) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(5) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(6) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(7) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(8) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(9) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(10) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(11) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(12) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(13) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(14) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(15) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(16) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(17) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(18) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(19) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n" << endl;
Serial << "\t\t\t\t\t" << _DEC(20) << endl;
delay(1000);
while(1){} //freeze the main loop
}
</code></pre>
<p>Then joining the two <em>cursor positioning</em> lines, gives:</p>
<pre><code>#include <Streaming.h>
//setup
void setup() {
Serial.begin(9600); //The faster the better
} //Close the setup
//main loop
void loop() {
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(1) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(2) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(3) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(4) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(5) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(6) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(7) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(8) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(9) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(10) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(11) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(12) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(13) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(14) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(15) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(16) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(17) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(18) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(19) << endl;
delay(1000);
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(20) << endl;
delay(1000);
while(1){} //freeze the main loop
}
</code></pre>
<p>Then putting each repeated line in a <code>for</code> loop, and adding a <em>Maximum Count</em> <code>const</code> variable, gives:</p>
<pre><code>#include <Streaming.h>
const int MaxCount = 20;
//setup
void setup() {
Serial.begin(9600); //The faster the better
} //Close the setup
//main loop
void loop() {
for (int n = 1; n < 20; n++) {
Serial << _BYTE(27) << _BYTE(91) << _BYTE(50) << _BYTE(74); //CLR
Serial << "\n\n\n\n\n\n\n\n\n\n\t\t\t\t\t" << _DEC(n) << endl;
delay(1000);
}
while(1){} //freeze the main loop
}
</code></pre>
<p>However, <a href="https://arduino.stackexchange.com/questions/16122/how-i-can-make-serial-output-print-short#answer-16123">jwpat7's answer</a> is much better, and <a href="https://arduino.stackexchange.com/questions/16122/how-i-can-make-serial-output-print-short#answer-16124">Nick's answer</a> is the shortest.</p>
|
16133 | |arduino-uno| | Unexpected behaviour of blinking LED code | 2015-09-16T05:37:27.083 | <p>I'm new to Arduino so this may be a really silly doubt but I'm not finding an explanation for it anywhere online. I first uploaded this code (to blink 5 LEDs) on my Arduino Uno :</p>
<pre><code> void setup(){
pinMode(12, OUTPUT);
pinMode(11, OUTPUT);
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
}
void loop(){
digitalWrite(12, HIGH);
delay(1000);
digitalWrite(12, LOW);
delay(1000);
digitalWrite(11, HIGH);
delay(1000);
digitalWrite(11, LOW);
delay(1000);
digitalWrite(10, HIGH);
delay(1000);
digitalWrite(10, LOW);
delay(1000);
digitalWrite(9, HIGH);
delay(1000);
digitalWrite(9, LOW);
delay(1000);
digitalWrite(8, HIGH);
delay(1000);
digitalWrite(8, LOW);
delay(1000);
}
</code></pre>
<p>The 5 LEDs glowed brightly. But when I uploaded the following code (using an if statement to reduce the size of the previous one), the LEDs glowed dimly. </p>
<pre><code>int LEDpin = 13;
void setup(){
pinMode(LEDpin, OUTPUT);
}
void loop(){
digitalWrite(LEDpin, HIGH);
delay(1000);
digitalWrite(LEDpin,LOW);
delay(1000);
if(LEDpin >= 8){
LEDpin--;
} else {
LEDpin = 8;
}
}
</code></pre>
<p>Also, when I just typed the <code>if</code> statement without the <code>else</code> part, nothing happened after the LED at pin 8 had glowed on and off. Can someone please tell me why the LEDs glowed dimly in the second one and why nothing glowed after LED 8 when I skipped the <code>else</code> part?</p>
| <p>As Abhishek mentioned in his answer is correct, but the better way is to use for loops while dealing with many led's.</p>
<p>Let's say you have led's connected from pin 2 to 8.</p>
<pre><code>int pin = 2;
void setup()
{
for (Pin = 2; Pin < 8; Pin++)
{
pinMode(Pin, OUTPUT);
}
}
void loop()
{
for (int Pin = 2; Pin < 8; Pin++)
{
digitalWrite(Pin, HIGH);
delay(1000);
digitalWrite(Pin, LOW);
delay(1000);
}
}
</code></pre>
|
16139 | |programming|c++|sketch| | How do nested for loops work? | 2015-09-16T19:34:11.043 | <p>In the following code from an Arduino sketch will it run the first "for" statement before enacting the second "for" statement. Also how does it know go run the first stamens again? Will it continue to run till both statements are true? </p>
<pre><code>for(int r = 0; r < 8; r++){
for(int c = 0; c < 8; c++){
lc.setLed(0, r, c, HIGH);
}
}
</code></pre>
| <p>A <code>for</code> statement repeats everything between <code>{</code> and <code>}</code>, (or just the next line if there is no <code>{</code> and <code>}</code> a certain number of times. It's not as simple as you might at first think, but it makes more sense if you write it out as a <code>while</code> loop explicitly.</p>
<p>For instance, <code>for (a; b; c) { ... }</code> could be re-written as:</p>
<pre><code>a;
while (b) {
c;
}
</code></pre>
<p>So if you had: </p>
<pre><code>for (int i = 0; i < 100; i++) {
Serial.println(i);
}
</code></pre>
<p>it could be re-written as:</p>
<pre><code>int i = 0;
while (i < 100) {
Serial.println(i);
i++;
}
</code></pre>
<p>The two mean exactly the same thing. A <code>for</code> has the three elements - initializer, comparison and iterator. The initializer is run before the loop starts, the comparison is used to work out when the loop should finish, and the iterator is used to move through each iteration of the loop.</p>
<p>To re-write your specific example:</p>
<pre><code>for(int r = 0; r < 8; r++){
for(int c = 0; c < 8; c++){
lc.setLed(0, r, c, HIGH);
}
}
</code></pre>
<p>You would end up with:</p>
<pre><code>int r = 0;
while (r < 8) {
int c = 0;
while (c < 8) {
lc.setLed(0, r, c, HIGH);
c++;
}
r++;
}
</code></pre>
<p>Now, if we were to do away with the loops altogether and write it all out longhand, what would it look like? Well, let's start with the inner <code>c</code> loop. That loops from 0 to 7 (while less than 8), so replacing that loop with 8 discrete calls to the function replacing <code>c</code> each time would end up with:</p>
<pre><code>int r = 0;
while (r < 8) {
lc.setLed(0, r, 0, HIGH);
lc.setLed(0, r, 1, HIGH);
lc.setLed(0, r, 2, HIGH);
lc.setLed(0, r, 3, HIGH);
lc.setLed(0, r, 4, HIGH);
lc.setLed(0, r, 5, HIGH);
lc.setLed(0, r, 6, HIGH);
lc.setLed(0, r, 7, HIGH);
r++;
}
</code></pre>
<p>We could take it a step further and <em>unroll</em> the outer <code>r</code> loop. A subset of what you would end up with would be like this (note, I have skipped a lot of the middle ones):</p>
<pre><code>lc.setLed(0, 0, 0, HIGH);
lc.setLed(0, 0, 1, HIGH);
lc.setLed(0, 0, 2, HIGH);
lc.setLed(0, 0, 3, HIGH);
lc.setLed(0, 0, 4, HIGH);
lc.setLed(0, 0, 5, HIGH);
lc.setLed(0, 0, 6, HIGH);
lc.setLed(0, 0, 7, HIGH);
lc.setLed(0, 1, 0, HIGH);
lc.setLed(0, 1, 1, HIGH);
... skipped a lot ...
lc.setLed(0, 6, 6, HIGH);
lc.setLed(0, 6, 7, HIGH);
lc.setLed(0, 7, 0, HIGH);
lc.setLed(0, 7, 1, HIGH);
lc.setLed(0, 7, 2, HIGH);
lc.setLed(0, 7, 3, HIGH);
lc.setLed(0, 7, 4, HIGH);
lc.setLed(0, 7, 5, HIGH);
lc.setLed(0, 7, 6, HIGH);
lc.setLed(0, 7, 7, HIGH);
</code></pre>
<p>There would, of course, be 8 × 8 = 64 entries in there.</p>
<p><code>for</code> loops can be used in lots of other fun ways too. It's not just a simple "run this X number of times". For instance, you can loop through a C string until you reach the NULL character at the end of the string:</p>
<pre><code>for (char *p = str; *p != 0; p++) {
... do something with *p
}
</code></pre>
<p>You can iterate through the entries in a linked list:</p>
<pre><code>for (struct mylist *scan = myListHead; scan; scan = scan->next) {
... do something to scan->whatever ...
}
</code></pre>
<p>You can even embed functions in there:</p>
<pre><code>for (char c = 0; c != '\n'; c = Serial.read()) {
... Do something with character `c` until `c` is a line feed ...
}
</code></pre>
<p>As you can see <code>for</code> is an incredibly powerful and flexible tool that is often overlooked in favour of the more explicit <code>while</code>.</p>
|
16143 | |serial|c++| | serial communication between several arduinos to pc | 2015-09-17T00:11:13.363 | <p>Is possible the communication between several Arduinos to one serial port in the PC ?</p>
<p>If I have ARD_A, ARD_B,... ARD_Z running with some code like this</p>
<pre class="lang-C++ prettyprint-override"><code>void setup()
{
Serial.begin(9600);
}
void loop()
{
while (Serial.available() > 0)
{
String stringID = Serial.read()
int nFound = stringID.indexOf("@ARD_01");
// ---> Id is unique for each arduino
if ( nFound > 0 )
Serial.print("this is @ARD_01 responding sending some data");
}
}
</code></pre>
<p>And in the pc there is an exe sending a string:</p>
<pre class="lang-C++ prettyprint-override"><code>"@ARD_01 I want your data"
process the data
"@ARD_02 I want your data"
process the data
"@ARD_03 I want your data"
process the data
</code></pre>
| <p>Not directly, no. A PC's serial port - either a "real" one or a USB one, can only communicate with one device.</p>
<p>The Arduino, though, is a USB device, so you can just plug them all into a USB hub or a bunch of hubs - each one will get its own COM port. Managing all those COM ports can be kind of tricky though, especially when you have a lot of devices.</p>
<p>Another option, one that is more widely used when you want to communicate with a lot of <em>slave</em> devices from one <em>master</em> device is to use a <em>multidrop</em> network. RS-485 is the most popular of these. It allows you to connect many slave devices to one set of serial wires and the master sends instructions to a slave, and the slave may respond with data and information on request.</p>
<p>RS-485 requires special hardware to interface normal TTL level RS-232 (UART) ports to the bus.</p>
<p>You can read more about RS-485 here: <a href="https://en.wikipedia.org/wiki/RS-485" rel="nofollow">https://en.wikipedia.org/wiki/RS-485</a></p>
|
16145 | |nrf24l01+| | NRF24 Mixing with/without antenna | 2015-09-17T05:08:47.530 | <p>Is it possible to have the NRF24 module on an Arduino Mini transmitting to an NRF24 with SMA antenna on a Mega? In that case, would the antenna on the Mega help pickup the signal of the transmitting Arduino Mini?</p>
| <p>Yes, and yes.</p>
<p>A module without an antenna is exactly the same as a module with an antenna, it's just that the antenna is part of the PCB. Yes, the module with the antenna will have more sensitivity (able to receive fainter signals) as well as more transmitting power.</p>
<p>The same is true of the modules with the power amplifier. They again have even more sensitivity and transmitting power.</p>
<p>It is quite common to have a single powerful transceiver with power amplifier and antenna as a base station and then smaller modules as the remote slave devices. Especially if you couple the base station with a suitable parabolic or uni-directional high gain antenna to point directly at where the slave devices are.</p>
|
16153 | |interrupt|atmega328|timers|avr| | Atmega168 Watchdog timer | 2015-09-17T18:29:05.103 | <p>I'm trying to use the watchdog timer to prevent the atmel from being stuck in a loop.</p>
<p>Right now, I have the watchdog timer in System Reset Mode, with a 8sec timer. I reset the timer in every loop while the system is active. But when it goes to sleep, it cannot clear the timer and the whole system resets. Essentially, the system sleeps > System Reset every 8 sec > goes back to sleep.</p>
<p>While this works, I initialize a lot of other hardware with the atmel, and doing it every 8 second seems like a waste of resources. </p>
<p>I want to use the watchdog interrupt somehow only to wake the system up briefly and stop the full system reset. Only if it's truly stuck, it will do a full system reboot. But i'm not sure how the ISR will work or how to reset the timer or toggle.</p>
<p>Here a basic rundown of what I was thinking about.</p>
<pre><code>ISR(wdt_timer)
{
how to stop the full system reboot?
how to make the interrupt start again?
}
ISR(button_press)
{
gotoSleep=0;
}
void watchdog_init()
{
/* Reset the wdt. */
wdt_reset(); //from wdt.h
/* In order to change WDE or the prescaler, we need to
* set WDCE (This will allow updates for 4 clock cycles).
*/
WDTCSR |= (1<<WDCE) | (1<<WDE);
/* set new watchdog timeout prescaler value */
WDTCSR = 1<<WDP0 | 1<<WDP3; /* 8.0 seconds */
/* Enable the WD interrupt (note both interrupt and reset). */
WDTCSR |= (1<<WDIE) | (1<<WDE);
}
void main ()
{
watchdog_init();
//and initialize all the other hardware and power supply
while (true) //no need to step out of this loop
{
reset_watchdog();
//
//main program
//
if(go_to_sleep=1) //command received through serial
gotoSleep();
//wake up here
}
}
</code></pre>
| <p>Each time the watchdog interrupt triggers, WDIE is reset. You will need to set it again in the loop if you want to continue capturing the interrupt rather than resetting the system.</p>
<p>Also, consider using <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__watchdog.html" rel="nofollow"><code><avr/wdt.h></code></a> and <a href="http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html" rel="nofollow"><code><avr/sleep.h></code></a> to handle (most of) the watchdog and sleep functionality.</p>
<pre><code>EMPTY_INTERRUPT(WDT_vect);
void main ()
{
watchdog_init();
set_sleep_mode(SLEEP_MODE_STANDBY);
//and initialize all the other hardware and power supply
while (true) //no need to step out of this loop
{
wdt_reset()
//
//main program
//
if(go_to_sleep=1) //command received through serial
{
sleep_enable();
sleep_cpu();
sleep_disable();
WDTCSR |= _BV(WDIE);
}
}
}
</code></pre>
|
16154 | |arduino-uno|arduino-ide|ethernet|library| | Integrating two Arduino Ethernet libraries in one sketch | 2015-09-17T19:03:03.477 | <p>I am trying to integrate two different Arduino Ethernet libraries, EtherShield and UIPEthernet in one sketch.</p>
<p>EtherShield library is used to control LEDs via Android mobile application. While UIPEthernet is used to control the same LEDs via Web Server.</p>
<p>Both codes run perfectly when they're uploaded individually. But I need them to run in a single sketch. So I combined them in one sketch. That's where my problem is. They're not running smoothly anymore. My mobile app can only turn one LED off then the app will crash. Accessing my Arduino's web server gives me error as well (but before it is really, really working T.T)</p>
<p>Help me, please.
This is my code</p>
<pre><code>// ========== UIPEthernet library
#include <Dhcp.h>
#include <Dns.h>
#include <ethernet_comp.h>
#include <UIPClient.h>
#include <UIPEthernet.h>
#include <UIPServer.h>
#include <UIPUdp.h>
// ========== EtherShield library
#include "EtherShield.h"
#include "ETHER_28J60.h"
// ========== MOBILE
//static uint8_t mac[6] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
//static uint8_t ip[4] = {192, 168, 15, 97};
static uint16_t port = 80;
ETHER_28J60 e;
// ========== WEB
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 15, 97 };
byte gateway[] = { 192, 168, 15, 1 };
byte subnet[] = { 255, 255, 255, 0 };
String inString = String(35);
int i; // Used for looping
String Room;
int pin[] = { 0, 2, 3, 4, 5 }; // Lock pin num 0 in array is not used
int numOfRooms = 4; // Number of rooms
String value[] = { "OPEN", "OPEN", "OPEN", "OPEN", "OPEN" }; // Startup all rooms are closed
EthernetServer server(port);
String data;
void setup()
{
Serial.begin(9600);
// ========== MOBILE
e.setup(mac, ip, port);
// ========== WEB
Ethernet.begin(mac, ip, gateway, subnet);
server.begin();
// Set pin mode
for (int j = 1; j < (numOfRooms + 1); j++)
{
pinMode(pin[j], OUTPUT);
}
Serial.println("\n[ WEB + MOBILE ]\n");
Serial.println("Serial READY");
Serial.println("Ethernet READY");
Serial.println("Server READY\n");
}
void loop()
{
webModule();
mobileAppModule();
}
void mobileAppModule()
{
char* params;
if (params = e.serviceRequest())
{
//ROOM 311
if (strcmp(params, "?cmd=1") == 0)
{
digitalWrite(pin[1], HIGH);
Serial.println("ROOM311 is OPEN\n");
}
if (strcmp(params, "?cmd=2") == 0)
{
digitalWrite(pin[1], LOW);
Serial.println("ROOM311 is CLOSE\n");
}
//ROOM 312
if (strcmp(params, "?cmd=3") == 0)
{
digitalWrite(pin[2], HIGH);
Serial.println("ROOM312 is OPEN\n");
}
if (strcmp(params, "?cmd=4") == 0)
{
digitalWrite(pin[2], LOW);
Serial.println("ROOM312 is CLOSE\n");
}
//ROOM 313
if (strcmp(params, "?cmd=5") == 0)
{
digitalWrite(pin[3], HIGH);
Serial.println("ROOM313 is OPEN\n");
}
if (strcmp(params, "?cmd=6") == 0)
{
digitalWrite(pin[3], LOW);
Serial.println("ROOM313 is CLOSE\n");
}
//ROOM 314
if (strcmp(params, "?cmd=7") == 0)
{
digitalWrite(pin[4], HIGH);
Serial.println("ROOM314 is OPEN\n");
}
if (strcmp(params, "?cmd=8") == 0)
{
digitalWrite(pin[4], LOW);
Serial.println("ROOM314 is CLOSE\n");
}
//
if (strcmp(params, "?cmd=9") == 0)
{
digitalWrite(pin[1], LOW);
digitalWrite(pin[2], LOW);
digitalWrite(pin[3], LOW);
digitalWrite(pin[4], LOW);
Serial.println("All rooms are now CLOSED\n");
}
e.respond();
}
}
void webModule()
{
EthernetClient client = server.available();
if (client)
{
// An HTTP request ends with a blank line
boolean current_line_is_blank = true;
while (client.connected())
{
if (client.available())
{
char c = client.read();
// If users have gotten to the end of the line (received a newline
// character) and the line is blank, the HTTP request has ended,
// so users can send a reply
if (inString.length() < 35)
{
inString.concat(c);
}
if (c == '\n' && current_line_is_blank)
{
// Send a standard HTTP response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
client.println("<html>");
client.println("<head><title>CONTROL PANEL</title></head>");
client.println("<body style='padding: 0; margin: 0;' onunload='window.opener.document.getElementById('controlPanel').disabled = false;'>");
client.println("<div style='width: 100%; height: auto; background-color: #000000;'><center style='font-size: 18px; font-family: Impact; color: white;'>POLYTECHNIC UNIVERSITY OF THE PHILIPPINES<br />COLLEGE OF ENGINEERING<br />COMPUTER ENGINEERING DEPARTMENT<br /></center><center style='font-size: 30px; font-family: Impact; color: #FF9600;'>COMPUTER ENGINEERING LABORATORY</center></div>");
client.println("<div style='width: 100%; height: 10px; background-color: gray;'></div>");
client.println("<div style='width: 100%; height: 10px; background-color: #FF9600;'></div><br />");
client.println("<div style='width: 80%; height: auto; background-color: #FF9600; border-radius: 20px; margin: auto; padding: 5px;'>");
client.println("<div style='width: auto; height: auto; background-color: #FFFFFF; border-radius: 20px; margin: auto; padding: 5px;'><br /><center style='font-size: 30px; font-family: Impact;'>CONTROL PANEL</center><br /><hr /><br />");
client.println("<form method=get>");
for (i = 1; i < (numOfRooms + 1) ; i++)
{
Room = String("ROOM") + (i + 310);
if (inString.indexOf(Room + "=OPEN") > 0 || inString.indexOf("All=OPEN") > 0)
{
Serial.println("\n" + Room + " is OPEN");
digitalWrite(pin[i], HIGH);
value[i] = "CLOSE";
}
else if (inString.indexOf(Room + "=CLOSE") > 0 || inString.indexOf("All=CLOSE") > 0)
{
Serial.println("\n" + Room + " is CLOSE");
digitalWrite(pin[i], LOW);
value[i] = "OPEN";
}
client.println("<br /><center style='font-family: Impact;'>" + Room + "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' name=" + Room + " value=" + value[i] + " style='height: 50px; width:100px;' /><br /><br />");
}
client.println("<br /><br />All <input type='submit' name='All' value='OPEN' style='height: 50px; width:100px;' />&nbsp;&nbsp;&nbsp;&nbsp;<input type='submit' name='All' value='CLOSE' style='height: 50px; width:100px;' />");
client.println("</center></form>");
for (i = 1; i < (numOfRooms + 1); i++)
{
if (value[i] == "ON")
{
i = i + 310;
client.println("<br /><br /><p>Room " + String(i + 310) + " is OPEN</p>");
}
else if (value[i] == "OFF")
{
client.println("<p><p>Room " + String(i + 310) + " is CLOSE");
}
}
client.println("</div>");
client.println("</div>");
client.println("</body></html>");
break;
}
if (c == '\n')
{
// we're starting a new line
current_line_is_blank = true;
}
else if (c != '\r')
{
// we've gotten a character on the current line
current_line_is_blank = false;
}
}
}
// give the web browser time to receive the data
delay(1);
inString = "";
client.stop();
}
}
</code></pre>
<p>MOBILE means code for Arduino-Android
WEB means the code for Web Server</p>
| <p>You can't.</p>
<ol>
<li>The code has both libraries trying to run on the same port which is not allowed (in fact you couldn't even do that on a computer). You could try setting one to one port and the other to another port, but that might not work because...</li>
<li>These libraries most likely are both expecting to be the only code accessing the hardware and they will step over each other and cause problems. Sharing hardware between different pieces of code is an advanced programming topic not suited for beginners and would involve rewriting significant portions of these libraries.</li>
</ol>
<p>The best course of action is to either re-implement your app functionality to use the UIPEthernet Library, or re-implement the webpage using the EtherShield library. You should be able to do this because your app interface is supplying parameters (e.g the "?cmd=" part) and the webpage is not. You should be able to set it up so that if it has "?cmd=" in the request, it should perform the command, otherwise it should return the webpage.</p>
|
16161 | |arduino-uno| | Passing the input from one pin to another as output without polling? | 2015-09-18T02:30:47.743 | <p>I am trying to pass the input from one pin to another pin as output. Effectively I want to create a blind passthrough. The end goal is to connect two Arduinos and a series of test points together like the diagram below. I want Arduino B to shuffle which test points are connected to which pins on Arduino A on startup.</p>
<pre><code>+-----------+ +-----------+ +-------------+
| | | | | |
| Arduino A <-------> Arduino B <-----> Test Points |
| | | | | |
+-----------+ +-----------+ +-------------+
</code></pre>
<p>I figure one way to do this is to poll the input pins in the loop() and then change the output pins accordingly but I would prefer if the voltage changes just passed right through without it affecting timing.</p>
<p><strong>Update:</strong>
For some clarification:</p>
<ul>
<li>All signaling is digital</li>
<li>I'm looking to "route" around 10-12 test points to Arduino A ideally but 6 at a minimum</li>
</ul>
| <p>Because this is digital I would like to add a third option in addition to Ignacio's and Nick's great suggestions. Use a logic device such as an FPGA or CPLD. This will require some extra knowledge and set up to get it working, but it is well suited for the functionality you are looking for.</p>
|
16165 | |lcd| | Why does my LCD display random characters? | 2015-09-17T22:26:57.280 | <p>I've been struggling with my LCD for hours, and after solving more different issues than I can remember, I'm out of ideas for this one.</p>
<p>My LCD is showing random characters, see the picture below (the last character blinks, some characters change and over time there are slowly more and more characters). I'm starting to wonder if the LCD I chose has a driver compatible with the LiquidCrystal library, what do you think? If so what can I do to avoid buying another one?</p>
<p><a href="https://i.stack.imgur.com/DYED4.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DYED4.jpg" alt="enter image description here"></a></p>
<p>Here is the code:</p>
<pre class="lang-c prettyprint-override"><code>// include the library code:
#include <LiquidCrystal.h>
// initialize the library with the numbers of the interface pins
//RS EN D4 D5 D6 D7
LiquidCrystal lcd(2, 3, 4, 5, A2, A3);
//RW to GND, VSS to GND, VCC to 5V, V0 to wiper of 5V-to-GND 10k potentiometer
void setup() {
Serial.begin(9600);
Serial.println("Starting");
lcd.begin(16, 2);
}
void loop() {
lcd.setCursor(0, 1);
lcd.print(millis() / 1000);
Serial.println("Printing");
delay(1000);
}
</code></pre>
<p>I'm using this <a href="http://hobbycomponents.com/boards/140-arduino-compatible-5v-pro-mini-?search_query=pro%20mini&results=53" rel="nofollow noreferrer">Arduino</a> and this <a href="http://uk.farnell.com/midas/mc21605h6w-sptly/lcd-2x16-stn-led-b-l-blk-on-y/dp/2342641" rel="nofollow noreferrer">LCD</a>. Note that I'm using pins 10,11,12,13 for a SD (which works) and 6 7 8 for a MAX232 (which is disabled).</p>
<p>Any ideas?</p>
| <p>It could be because "millis()/1000" generates a "number", and not the "string" (or "char"). Try to add ",DEC" in your lcd.print(), something like "millis()/1000,DEC" to convert it to "decimal". Generally, it depends on the library, how they implement this function. </p>
<p>Good luck,</p>
<p>Mike</p>
|
16168 | |programming| | Arduino: Record value of the encoder only once at the instant the PS2 joystick reads 128 (when at rest) | 2015-09-18T03:39:12.387 | <p>I'm working on a project where I need my arduino to detect the value of encoder at the instant the reading of the joystick change to 128. When the joystick is at rest, the reading is 128 which also means, my robot will hold its position/brake. Values above or below 128 correspond to the motor moving forward or backward. </p>
<p>I actually want to record the encoder value exactly at the first instant my arduino reads 128, so that I can apply PID position control so that my robot can brake or hold its position against gravity. The first instant when the joystick reads 128, that is the encoder value that I'd like to set as the Setpoint.</p>
<p>Here's some explanations for implementing PID in Arduino.
<a href="http://playground.arduino.cc/Code/PIDLibraryConstructor" rel="nofollow">http://playground.arduino.cc/Code/PIDLibraryConstructor</a></p>
<p>For instance the joystick readings go from 140, 137, 131, [128], 128, 128, 133, 139, 131, [128], 128 and at the same time, the encoder gives out corresponding values. I need the encoder values at the Joystick value of 128 in the square bracket, [] in the example above.</p>
<p>If I use the code below, it will just run the statements in {} whenever it sees 128, which is not what I want. FYI, the motor sometimes tend to backdrive, and this gives different encoder value also at 128. What I only need is the first encoder value at the first reading of 128 whenever I encounter it.</p>
<pre><code>void loop()
{
int pwmSpeed;
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
Input = encoder0Pos;
if (Y_axis == 128)
{
Setpoint = encoder0Pos;
myPID.Compute();
analogWrite(pwm, Output);
}
else if (Y_axis > 128)
{
pwmSpeed = Y_axis;
digitalWrite(dir,HIGH); // set DIR pin HIGH or LOW
analogWrite(pwm, pwmSpeed); //analogWrite(pin, value)
}
else
{
pwmSpeed = abs(Y_axis-255);
digitalWrite(dir, LOW);
analogWrite(pwm, pwmSpeed);
}
}
</code></pre>
<p>Thanks.</p>
<p>//New edited code is shown below:</p>
<p>What do you think of the code? Did I do it correctly? I will test it once I get back to the lab.</p>
<p>If 128 is detected, encoder value is stored in Setpoint and then Pid.compute() is executed for as long as 128 is detected. For this duration, Pid.compute() will compute the error = Setpoint - Input and use Pid formula to calculate the Output that can be found in the analogWrite(pwm, Output). Motor will work to maintain its position at Setpoint. </p>
<p>However if other than 128 is encountered, it will just execute the 'else if' and 'else' statement to move the robot forward or backward.</p>
<pre><code>global g_detect128 = false;
void setup()
{
//any code here
}
void loop()
{
int pwmSpeed;
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
Input = encoder0Pos;
if (!g_detect128 && Y_axis == 128)
{
Setpoint = encoder0Pos;
g_detect128 = true;
}
if (Y_axis == 128)
{
myPID.Compute();
analogWrite(pwm, Output);
}
else if (Y_axis > 128)
{
pwmSpeed = Y_axis;
digitalWrite(dir,HIGH); // set DIR pin HIGH or LOW
analogWrite(pwm, pwmSpeed); //analogWrite(pin, value)
}
else
{
pwmSpeed = abs(Y_axis-255);
digitalWrite(dir, LOW);
analogWrite(pwm, pwmSpeed);
}
if(Y_axis != 128)
{
g_detect128 = false;
}
}
</code></pre>
| <p>If you only want to catch this event once - when it first hits 128, you just need a global variable to flag when you've seen it:</p>
<pre><code>boolean g_bSeen128 = false;
void setup()
{
// ... whatever
}
void loop()
{
// ... your existing code
// catch first time we see 128
if (!g_bSeen128 && Y_axis == 128)
{
// ... do whatever you need here. e.g.
Setpoint = encoder0Pos;
myPID.Compute();
analogWrite(pwm, Output);
// stop the event being caught next time
g_bSeen128 = true;
}
// from comments below - to just ignore consecutive 128's, add this:
if (Y_axis != 128) g_bSeen128 = false;
// ... your existing code
}
</code></pre>
<p>If you only want to do something if the input changes, no matter what it is, you can keep track of the last input:</p>
<pre><code>int g_nLastInput = -1;
void setup()
{
// ... whatever
}
void loop()
{
// get input
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
// if input has changed ...
if (Y_axis != g_nLastInput)
{
// ... save latest input
g_nLastInput = Y_axis;
// now process the change, e.g.
if (Y_axis == 128)
{
// ... do something special for 128
}
else
{
// ... do something else for other inputs
}
}
}
</code></pre>
<p>I'm not sure what you're trying to do with the PWM when you get inputs either side of 128, it seems to me that you might want to go in one direction if the input is less than 128 and go in the other direction if it's greater than 128. In either case, the magnitude of your PWM speed should just reflect how far you are from 128 in either direction. So subtracting 128 from your input will give a delta that is +/- 128 and we can scale its absolute value to 0..255 for the PWM setting.</p>
<p>If that's correct, an alternative way of coding your original logic might be like this:</p>
<pre><code>void loop()
{
// get input
int Y_axis = ps2.readButton(PS2_JOYSTICK_LEFT_Y_AXIS);
Input = encoder0Pos;
// if input has changed ...
if (Y_axis != g_nLastInput)
{
// ... save latest input
g_nLastInput = Y_axis;
// now process the change
int nDelta = Y_axis - 128;
if (nDelta == 0)
{
// i.e. Y_axis is 128
Setpoint = encoder0Pos;
myPID.Compute();
analogWrite(pwm, Output);
}
else
{
// choose direction
digitalWrite(dir, (nDelta > 0) ? HIGH : LOW);
// set PWM speed scaled to 0..255
analogWrite(pwm, abs(nDelta) * 2);
}
}
}
</code></pre>
|
16176 | |current|adc| | ACS712 inacurrate reading. Wild jumping | 2015-09-18T15:49:53.407 | <p>I'm trying to use my 30A ACS712 on my OSD (it has ATMEGA16L). </p>
<p>But it is very unstable, 0 amps goes from 450 to 445, but that isn't that bad, but when I put 10A of current through it jumps from 440 to 380. </p>
<p>I already searched on google and tried to add filter cap between acc and gnd, but it didn't help and acs712 and osd have different power supply than the load.</p>
<p>Any help is welcome.</p>
| <p>This is not a simple chip to use. These parts of the data sheet may help you understand what is happening. It is internally an analog device and needs clean power. I would highly recommend you download the Allegro data sheet, it has a lot of information that will help you. Below is a short section of the data sheet, The first paragraph should give you a hint that the output voltage will be about 2.5V with a 5V unipolar power supply.</p>
<p>"Quiescent output voltage (VIOUT(Q)). The output of the device
when the primary current is zero. For a unipolar supply voltage,
it nominally remains at VCC⁄ 2. Thus, VCC = 5 V translates into
VIOUT(Q) = 2.5 V. Variation in VIOUT(Q) can be attributed to the
resolution of the Allegro linear IC quiescent voltage trim and
thermal drift.</p>
<p>Electrical offset voltage (VOE). The deviation of the device output
from its ideal quiescent value of VCC / 2 due to nonmagnetic
causes. To convert this voltage to amperes, divide by the device
sensitivity, Sens.</p>
<p>Accuracy (ETOT). The accuracy represents the maximum deviation
of the actual output from its ideal value. This is also known
as the total output error. The accuracy is illustrated graphically in
the output voltage versus current chart at right."</p>
<p>I realize this does not answer your question but it does give you a good starting point to resolve your problem. Hopefully you or a buddy has some analog experience, that will help a lot. Oh Yes clean power supplies are imperative for this to work.</p>
|
16177 | |arduino-yun|sd-card| | Encoding an entire Byte for File Reading | 2015-09-18T17:39:21.900 | <p>I'm using an Arduino Yun to read from a data file, which will then populate a data structure. The <code>file.read()</code> function "<em>returns: The next byte (or character), or -1 if none is available.</em>" </p>
<p>This functionality is identical to the <code>SD.read()</code> function in the SD card library. </p>
<p>The data file will never have any value that exceeds 1 byte with all numbers in the range 0-255. If I print these numbers as a long string in the data file, each character is read as a byte. So I need to call <code>file.read()</code> 3 times to read in a single 0-255 value. And then do some additional processing to construct the final 8-bit value for storing. </p>
<p>I could reduce this to 2 calls by printing the Hex code in the data file, but this isn't much of an improvement. </p>
<p><strong>Is there a way to encode a full byte in a single character?</strong></p>
<p><strong>Effectively , is there a particular way I can format my data file so that I can read in an <code>8-bit unsigned</code> value in a single call to <code>file.read()</code>?</strong></p>
| <p>There's two parts to what you want to do, writing the file in the right form, and reading that format file.</p>
<p>The format of file is known as <em>raw binary</em>. Every byte in the file can store a separate value between 0 and 255, or between -128 and 127, dependin on how you interpret the data. At the end of the day, every byte in a file is just a collection of 8 bits yielding 2^8 = 256 combinations. What those combinations actually mean is more of a human thing than a machine thing.</p>
<p>We, as humans, have decided upon three main representations of those bytes: <em>unsigned</em> numbers from 0 to 255, <em>signed</em> numbers from -128 to 127 (lookup two's complement) and finally ASCII characters.</p>
<p>ASCII characters are more of a lookup table placed over one of the other two representations. Some systems use unsigned bytes and some signed bytes for the basis of that lookup tabe. </p>
<p>Writing text into the file results in looking up the corresponding byte values for each character in that text and placing those values in the file. When you read the file the reverse is done - the byte values are read and you look them up in the ASCII table to find the corresponding letters.</p>
<p>To store just numbers between 0 and 255 it is far more efficient to bypass that ASCII table and store the values directly as bytes. How you do that is entirely dependent on what language you are writing your software in. Since you haven't mentioned what that language is I can't advise you on that front' only give some examples in languages I know.</p>
<p>Such as in C you would store your data in an array of <em>unsigned char</em> or <em>uint8_t</em>. You then use the <code>write()</code> function to write raw data to the file.</p>
<p>In Perl you might use the <code>pack()</code> function to store your values as bytes in a string then write that string to a file.</p>
<p>When reading the data you are presented with a raw value. That may be given to you as a signed or an unsigned value depending on the underlying system. I don't know what the yun is off hand. Converting from whatever is handed to you by thr <code>file.read()</code> function to what you expect it to be though is a very simple matter, and is called <em>casting</em>.</p>
<pre><code>int in = file.read();
uint8_t bval = (uint8_t)in;
</code></pre>
<p>The bit in brackets is the <em>cast</em> which converts the value in the integer <em>in</em> into a uint8_t (Unsigned INTeger 8-bit Type) which corresponds to whatever you wrote as an unsigned char or uint8_t at the other end.</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.