text:
How to add data without pre-defining variables?
I am currently working on a RFID card reader. I need the reader to send the ID to a storage space.
What I am trying to achieve is a person swipes their card, enters their name on the serial monitor, and then have that data stored in a pair. The thing is that I do not know how many people will have cards. After that, I could call a person's name and it would show "Hello w, your ID number is xxx xxx xxx xxx xxx.
So I know there are no such things as "dynamic" variables. And I think I would need to pre-define a TON of arrays if I wanted to use them. So I am kinda at a stopping point. Is there no way to generate a new variable name and store data to that variable?
Also, I work with PLCs so I thought that indirect addressing might work, but I am unfamiliar on how to even do that in C++, only in ladder logic or if it would even work. Or how I would be able to call out an ID by name with that approach.

This would be an array of structs, plus storage space for all the names.

Array of structs? Could you please explain? I'm still only intermediate at programming.

Use the EEPROM. This allows data to remain intact and unchanged even when power is disconnected.
As you say you're new to programming, and because I wrote a similar program just last week as an experiment for something bigger, I'll talk you through some of it. However, I'm not going to give you the whole code to copy-and-paste, I'm only going to give you information on dealing with EEPROM and structures. C-aficionados may grumble at some bits, and Arduinites at others - sic vita est. This is something of a crash-course so it's not gospel, but it should be more than enough to guide you. You may already know some or most of it; it's included nonetheless for completeness, for those who don't.

For those who don't know
In C, data relevant to an object can be stored in a structure, or struct. You can put all sorts of different types of data in a struct, like so:
struct personalProfile {
    char    firstName[8];
    char    lastName[8];
    uint    cardID;           // 'uint' is an unsigned int...
    bool    accessAllowed;
};

You can then use that structure to create a 'personal profile' for however many people you want:
// within your main program:

struct personalProfile Person1;
struct personalProfile Person2;

// Now you can directly access individual aspects as so:

Person1.firstName = "John";
Person1.lastName = "Brown";
Person1.accessAllowed = TRUE;

Person2.firstName = "Dodgy";
Person2.lastName = "Dave";
Person2.accessAllowed = NOT_A_HOPE_IN_HELL;

You can use the members of a structure in exactly the same way you'd use that member type if it wasn't part of a structure. Nice and easy.
The best way to store multiple instances of a particular variable type is in an array:
struct personalProfile listOfPeople[5];

You now have an array of five (blank) structs, which can be accessed by listOfPeople[n].firstName = Potato;, where 'n' is between 0 and the number-of-entries-minus-one. So far so potato.
An array is pretty basic. It's present in all sorts of programming languages because it's inherently essential to almost any program, but the trouble is that it's static. Using the code above, once the array has been created with five structs in it you can't add or remove any. One solution is to create a massive array, and set all the values in each struct to zero, or some other 'empty' identifier, so you're always going to have enough entries (up to a point). However, that's lazy, time inefficient (you've got to set aaaaalll the individual elements to your 'empty' signifier), resource inefficient (look at all that unused space!), and the data only lasts while the program is running. As soon as you cut the power to the Arduino, the information is lost.
Next comes containers. These are part of the Standard Template Library (STL) in C++. They're great for creating and managing dynamic-length arrays. There are different types for different purposes (see the link), but they don't exist in C (at least as far as this post is concerned) and they're not available as part of the Arduino IDE without installing a bunch of libraries or some other intervention. Therefore you've got to make your own version. It's actually pretty easy...

EEPROM basics
The EEPROM library that comes with Arduino is of course essential for this. It doesn't have many functions, and the ones that exist are fantastically easy to understand. EEPROM, for those who don't know, is non-volatile memory. That means that when you store data it stays there forever, even if you remove the power. The only way to get rid of the data is to write over it. The downside of EEPROM is that it has limited amount of times it can be written to - 100,000 times per bit typically so you don't need to start keeping count, it just means you shouldn't be using it as regular program memory. Reading data from EEPROM isn't limited in the same manner.
Using the function EEPROM.put(address, data) you can put ANY data type - an int, char or - you guessed it - a struct into the EEPROM, starting at the byte specified by address. Of course there has to be enough space so you can't put an int, which takes up more than 1-byte of space, into the last address without the function failing. (Or can you? I haven't tried it yet because I'd never do it in practice.)
So you've created your structure, and made sure that all it's members are a fixed size. That means the structure has a fixed size. If you know that size, you can start putting them into the EEPROM.
// within main program

struct personalProfile Person1;
struct personalProfile Person2;

// fill in the details for Person 1...
// fill in the details for Person 2...

// ...then put Person1 in the EEPROM at address 0.
EEPROM.put(0, Person1);

// Done. Now put in Person2. But where?
// You need to make sure you put them AFTER Person1.

int AddressJump = sizeof(personalProfile);

// AddressJump now equals how many bytes are need to store one person.

EEPROM.put(AddressJump, Person2);

Simple as that.
If you create a Person3, you're going to need to put them sizeof(personalProfile) bytes AFTER Person2, i.e. EEPROM.put(AddressJump*2, Person3);. So, you add PersonN to address AddressJump * (N-1).
Retrieving data is the same principle, except you use EEPROM.get():
// provided you've used the above snippet somewhere to actually
// populate the EEPROM with something!

struct personalProfile personA;

EEPROM.get(0, personA);

Serial.print("Person A is called:");
Serial.println(personA.firstName);

Again, you're going to need sizeof(personalProfile) to read the second, third, or Nth person. If you 'send EEPROM.get() to the wrong address it will still populate the personalProfile instance with data, it will just be gobbledygook. Once you start putting people in the EEPROM you're going to need to keep track of things otherwise you'll end up lost. You need to manage the list to make sure you don't put one person on top of another (you could get in trouble for that) and you don't want to get someone that isn't there.

List management
This is where I leave you, for now. When you have digested the information above, and you want to continue, I'll carry on.
Your first task is to determine what sort of array you want. Inevitably it's going to be a Linked List. This is an array of structs, where each struct element in the list contains the memory address of the following element, thus the list is linked. You need to consider:

How the array will be linked (if at all);
Whether or not the array is space-critical (does it have to be as small as possible);
Where the array is going to start;
How you're going to keep track of how many people are in the array.

@TL140 I await your response, good luck!

WOW! a lot of info here. Love it. I have dealt with class/objects in JS and Python, but never knew about Structs in C. The only thing that I am fairly concern about is would I have to create each object by hand? because that is what I am trying to get around. I understand the storing part of them and pushing them to the EEPROM, and indexing them to reference, but it is more on the creation part that I am getting hung up on. Such as sally scanning her RFID card, enter her name, the objects are then automatically created under that class, and stored after that. So far, it's looking like...

I will have to use arrays with just the raw data and indexing. which I do not mind. But thank you for the tutorial on Structs, and the references. Also, Why can the EEPROM only be used 10k times?

@TL140 As part of your 'list management' you write a function for adding new entries. When it begins you create a new structure struct personalProfile NewEntry then fill in the details how you like, i.e. the name fields are typed in by Sally herself and the card details are automatically entered from the RFID reader. Call EEPROM.put() which copies the data from NewEntry, byte for byte, into the EEPROM. When your add-new-entries function finishes, NewEntry falls out of scope (it gets forgotten about, rather then strictly deleted), but the version in the EEPROM remains forever.

And as to why EEPROM has limited write-cycles: Google it! It's related to the way that data is stored so that its integrity remains once you remove power to it. As with everything, it's a trade-off between features.

Awesome! I think im catching on little by little. Still foggy on structs but they are a new concept for a new language so I'll just need to practice. I'll probably use a big array to simulate the EEPROM since I dont want to ruin my board's. I'm guessing I should also store a pointer in the EEPROM to reference my list? or is there a way i can read my EEPROM and see just how much space is already stored in it, then use that? Because, wouldn't updating that counter every time a card was read ruin my EEPROM pretty fast?

Wait a second: do you realise how much 100,000 is? Unless you're really trying you'll never reach that high! And don't forget it's write cycles; reading it is unlimited. To further convince you that it's OK, the EEPROM.put() function calls a sub-function called EEPROM.update(), which is a magic function that only writes a value to an address if the existing value is different. If your loop() function contains only one line: EEPROM.put(0, "Relax, TL140");, you could run your Arduino forever, and restart it to your hearts content, and the EEPROM would only ever be written to once.

I'll come back to my answer later (it's 2am) and start on some list-management explanations, with reduced EEPROM-write dependencies. Your board will be safe, I promise!

I see! I was under the misconception that it wrote a new value to it each time, so that if I accidentally coded an infinite for loop (I may be an intermediate level programmer, but I know way better than this! just using the worse case scenario.), 100,000 cycles that the code runs would burn out the EEPROM in minutes. Now I know that it doesn't work that way. I appreciate all your help! Thank you a ton!

@TL140: As you've chosen an answer (which wasn't mine!) I shalln't continue with my answer. If you need further assistance, perhaps start a new question with your specific problem.

@TL140 Now I feel somewhat guilty, I didn't mean to demand my answer be chosen. I recommend you search for information on the Arduino library EEPROMex. It's an extension for the standard EEPROM library and I think it will explain all manner of aspects of correctly and efficiently utilising the EEPROM. I've only just found it, and it looks pretty ace.

Both of the answers are very good and you have helped me a lot more. I tossed up between which one to pick and honestly yours is the better pick because most of my questions have been answered.I mainly voted his because it has one upvote and im too low rep to upvote yours. Still new to SE so im not sure how it works in its entirety.

The "key" is creating a means to access a table of IDs that you can search through for a given name or a given ID number. There are various ways of doing this and if you are unclear on these that can be discussed in due course. But, to start, I'll assume that making and searching some form of table or array is not a problem for you.
You obviously MUST have enough storage space for the maximum number of simultaneous IDS that you wish to store at any time. Call this "IDCount".
You can allocate IDCount ID storage locations by whatever means suits you.
In unused locations you store a dummy or null ID number.
eg ID 000 000 000 000 000 is probably invalid so can be used as an 'empty' indicator.
To add a new ID  either search through your table of IDs for an empty location and store the new ID there. To find a given ID match you search the table for the ID and , if it exists, retrieve the matching name.

"Improvements":
To reduce access times when the potential entries are large you can store all entries "at the bottom" and have a pointer to the 1st free location. New entries are added "at the end". If an entry is removed, all entries above it are moved down by one. eg   if entry N is removed:
for (entry >= N and entry < end_pointer)
...move entry N + 1 into location N
...and step N by 1.
Another method is to use a "linked list" where each entry has a pointer to the next entry in the list. New entries take an address from the empty_locations list and add their address to the used_locations list. Removed entries do the opposite. This can be fast and effective but also mind blowing for beginners and, when it goes wrong it can go VERY wrong. Best avoided initially.
The simple "search for 1st empty entry" method will usually work very well.

So breaking it down, I basically have to create an array, give it a definite storage value, use a for loop to fill everything with a null value, and then fill in accordingly using a checker to see if the data is != said null value? Seems fairly simple. Now what about the pairs of data? Should I nest the array? how would I go about using a lookup in a multi dimensional array?

@TL140 You can use a two dimensional array or if it suits use two arrays of the same size (number of entries)) but one dimensioned for names and the other for IDs as required. Whatever position you read or write from in the ID array, you can read and write from "blindly" in the name array as they are 2 parts of the same entry.


text:
Arduino Uno R3 L(yellow) led stays on and error on upload
So I recently got an Arduino Uno R3. Installed the IDE and drivers under Windows 8.1 and everything seemed to work fine and received the 'Done uploading' message when goofing around with the Blink example(was in a hurry that day).
Next day when I connected the Uno, I noticed the L(yellow) led keeps staying on and I get the following error when trying to upload:
System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/cy/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]

I tried on both Windows and Ubuntu and am really excited about learning things with Arduino. Thanks in advance for your help!

Have you got it working at all using Ubuntu, or was the goofing just in Windows? Each time you reboot your PC (at least for me) I have to select the correct COM port in the IDE from Tools -> Port. I think the same goes for my Linux setup (debian based), but I use that for a slightly different programming process, and I've never received an upload error using linux so I don't know what they look like. Could you add the error you get from Windows too? The current error message suggests that the IDE can't find your board.

The goofing around was only in Windows. I plugged the board now and I got "USB Device not recognised".

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Problem uploading program to Atmega 328 microcontroller
I recently bought a Atmel Atmega 328 P-PU microcontroller.I tried uploading a program to it by using the circuitry given in the link.I am using a RS 232 breakout board.Here is the link http://www.arduino.cc/en/Main/Standalone .I am not able to upload programs to it.It says problem uploading to board or avrdude attempt 1 out of 10 failed.What can I do about it?

the uploader is a usb to uart bridge

Did you install the bootloader first?

Additionally, if you wired ATmega pins directly to RS232 levels without level translation, your chip may be damaged.   You can buy a replacement with a bootloader preinstalled at a small premium, or use another Arduino or a programmer or even some other development board to load the bootloader into a good chip.

It is a pre bootloaded chip

You never described the problem.

Which RS232 breakout board are you using and how have your connected it between your PC and the Atmega chip?

The problem has been solved by pressing the reset button at the right time.I must have added a 100nf capacitor there.(between DTR and reset)

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Problems when communicating with SD card using ethernet shield
I am using the "SD read/write" code from the Arduino IDE examples to test an ethernet shield (clone). The problem is that although a file is created no data is stored in it.
When running the serial monitor will only show the first characters of the Serial.print() sentences, e.g when doing Serial.print("Initializing SD card...") the serial monitors displays Ini or In and nothing else.
Also the IDE shows the following error message: (some words in spanish)
Error dentro de Serial.serialEvent()
java.io.IOException: Error de entrada/salida in nativeavailable
at gnu.io.RXTXPort.nativeavailable(Native Method)
at gnu.io.RXTXPort$SerialInputStream.available(RXTXPort.java:1598)
at processing.app.Serial.serialEvent(Serial.java:258)
at gnu.io.RXTXPort.sendEvent(RXTXPort.java:774)
at gnu.io.RXTXPort.eventLoop(Native Method)
at gnu.io.RXTXPort$MonitorThread.run(RXTXPort.java:1644)

I have tried with 2 different SD cards, including a brand new one, and 2 different Arduino Uno (a clone and an original one). The OS is Ubuntu 13.10.
My guess is that it has something to do with the myFile.println() sentences, when they are commented the serial monitor works fine.
Any help is much appreciated since I couldn't find the problem anywhere else so far!


text:
Storing and parsing data with Arduino
I use Ethernet Shield and Arduino to GET data from the server in JSON format. Request looks like this:
client.println("GET http://ramp.local/api/actions?");

The response I get is:
[{"action_id":1,"action_type":"up","action_status":"new","ramp_id":31,"user_id":17},
{"action_id":2,"action_type":"down","action_status":"new","ramp_id":32,"user_id":20},
{"action_id":3,"action_type":"up","action_status":"completed","ramp_id":32,"user_id":17},
{"action_id":4,"action_type":"up","action_status":"failed","ramp_id":31,"user_id":17}]

How to collect a data in a string variable and parse it to get action_status?

Ideally, you would use a proper recursive JSON parser, like the one
suggested in prakharsingh95's answer. However, if code speed and size
are critical considerations, and if the format of the response is
narrowly constrained, then you can build a fast special-purpose parser.
Here is a simple example. It assumes the response has been stored in the
response char array:
static const char key[] = "\"action_status\"";
const char *p, *q;
char action_status[16];

for (p = response; ; p = q) {
    p = strstr(p, key);    // find key
    if (!p) break;         // not found
    p = strchr(p, ':');    // find ':' between key and value
    p = strchr(p, '"');    // find opening quotes for the value
    q = strchr(p+1, '"');  // find closing quotes

    // Report finding.
    strncpy(action_status, p+1, q-p-1);
    action_status[q-p-1] = '\0';
    Serial.print("Found action status: ");
    Serial.println(action_status);
}

Of course, in production code you would check that every strchr call
returns a non-NULL pointer. And you would check that the status you
found fits in your buffer.
Edit about the pros and cons of this method:
Compared to a proper JSON parser, this approach will give you smaller
and faster code, the drawback is it being more fragile. For example,
this will not detect a corrupted JSON, and it will return garbage if the
action_status happens to be a number instead of a string, or is a
string with embedded double quotes, or if the string "action_status"
appears as a value of some other field... A full JSON parser should
correctly handle all these cases.
On a non-embedded computer, a proper JSON parser would probably be the
only appropriate answer. On a constrained microcontroller environment,
you sometimes have to make trade-offs. In this particular instance, the
“best” answer depends on how much you weight speed and size vs.
robustness against unexpected input.

I would recommend a JSON parsing library. Checkout https://github.com/bblanchon/ArduinoJson
var response = [] ; // get response here
int response_length = 4; //Put length of the response array here
StaticJsonBuffer<200> jsonBuffer;

String action_ids[] = new String[response_length];
String action_types[] = new String[response_length];
String action_statuses[] = new String[response_length];
String ramp_ids[] = new String[response_length];
String user_ids[] = new String[response_length];

for (int i=0; i < response_length ; i++) {
    JsonObject& data = jsonBuffer.parseObject(response[i]);
    // Note the '&' above

    action_ids[i] = data["action_id"];
    action_types[i] = data["action_type"];
    action_statuses[i] = data["action_status"];
    ramp_ids[i] = data["ramp_id"];
    user_ids[i] = data["user_id"];
}

Of course, you only need to extract those fields that you need.

Welcome to Arduino SE! Please do not abuse the edit functionality of our site by superfluous edits and rollbacks. To prevent misuse of the edit functionality here, I've locked this answer for a week; after this time, you will be able to edit your answer again. Thanks for your cooperation and feel free to reply with any questions.

Try this on for size.
This is an arduino based, open source, JSON processor.


text:
How do I know how many memory that Arduino is use after my code is running for a few time
When I upload my program to Arduino it says the memory that the program is used. But what if I use a bad management of dynamic memory, or any object is created several times in use a lot of memory and the Arduino memory overload.
How do I know the current size of memory that Arduino is use?
I am thinking about to create a function in Arduino that return me this information if I send it a request command, but also I don't know how do I inspect the Arduino memory.
Note: I am using the Board: Arduino Mega 2560.
I read the question and the answer for Measure SRAN usage
In the question @fuenfundachtzig ask:
Can I determine how much SRAM I have left in the live system?
In my question I am asking about how do I know or monitoring my program memmory. Ok the Measure SRAN usage answer give me the tips or tools to develop my idea, but the question is not the same.
I am tryin to know in an specific time what is the size of my memmory.
example...
void setup() { //doing some configuration };

void loop() {  // invoke some functions and evil function  };

// in other place a evil function

void evil(){
MyClass * instance = new MyClass();
//play with the instance and it class create other instances....
//and a dynamic memmory is used but not deleted.
}

I am trying to know if it happens and how do I detect with Arduino? I am not talking about how much memmory do I left in the live system.

memory used = total memory − free memory.

You should not just say your question is different, you should explain how it is different. Be specific about what you are asking for. At this point, it still looks like a duplicate.

Basically it looks like you want to figure out if you have a memory leak. Since the objects get allocated continuously you will end up having less and less free memory.
You can use the functions presented in the sister question answered very nicely by Edgar (more specifically the complex one that calculates all the memory going through the allocation chain).
You can check the returned value every so often (few seconds/minutes depending on your needs) and if the free memory value drops continuously then you have a memory leak somewhere. This will not tell you where the leak is of course. Also this should work well while debugging the code, but would probably not be a good idea to leave it in "production" code.

I will try with the function that Edgar post, thank you for the answer and comments.


text:
Shortening large chunks of code
Some of the code that I have is unbearably long and drives me insane. I don't know if there were simpler ways to doing what I am doing.
long turn1;
long turn2;
long turn3;
long turn4;
long turn5;
long turn6;
long turn7;
long turn8;
long turn9;
long turn10;
long turn11;
long turn12;
long turn13;
long turn14;
long turn15;

#################
  turn1 = random(sizeof(turns) / sizeof(char*));
  turn2 = random(sizeof(turns) / sizeof(char*));
  turn3 = random(sizeof(turns) / sizeof(char*));
  turn4 = random(sizeof(turns) / sizeof(char*));
  turn5 = random(sizeof(turns) / sizeof(char*));
  turn6 = random(sizeof(turns) / sizeof(char*));
  turn7 = random(sizeof(turns) / sizeof(char*));
  turn8 = random(sizeof(turns) / sizeof(char*));
  turn9 = random(sizeof(turns) / sizeof(char*));
  turn10 = random(sizeof(turns) / sizeof(char*));
  turn11 = random(sizeof(turns) / sizeof(char*));
  turn12 = random(sizeof(turns) / sizeof(char*));
  turn13 = random(sizeof(turns) / sizeof(char*));
  turn14 = random(sizeof(turns) / sizeof(char*));
  turn15 = random(sizeof(turns) / sizeof(char*));

#

if (turn1 == turn2 or turn2 == turn3 or turn3 == turn4 or turn4 == turn5 or turn6 == turn7 or turn7 == turn8 or turn8 == turn9 or turn9 == turn10 or turn10 == turn11 or turn11 == turn12 or turn12 == turn13 or turn13 == turn14 or turn14 == turn15) {

#

lcd.print(turns[turn1]);
lcd.print(turns[turn2]);
lcd.print(turns[turn3]);
lcd.print(turns[turn4]);
lcd.print(turns[turn5]);
lcd.setCursor(0, 2);
lcd.print(turns[turn6]);
lcd.print(turns[turn7]);
lcd.print(turns[turn8]);
lcd.print(turns[turn9]);
lcd.print(turns[turn10]);
lcd.setCursor(0, 3);
lcd.print(turns[turn11]);
lcd.print(turns[turn12]);
lcd.print(turns[turn13]);
lcd.print(turns[turn14]);
lcd.print(turns[turn15]);

You mean like using an array and loops?

Yes you can, and the solution is very simple. It's in two parts, and they make up part of the absolute fundamental building blocks not just in C, but in almost any programming language.
You can read good information on arrays here, and 'for loops' here (it's about half way down the page). Without wishing to offend, it seems like you are missing some really basic concepts and I recommend starting at the beginning of the tutorial series that the two aforementioned links are part of.
I'll just cover the basics. If you don't understand anything, refer to the tutorials. If you still don't understand then please comment, but make sure you can convince us that you've really given it a good go. We're here to help as long as you're here to learn.
To declare an array of N variables, all of which are the same type, you use:
<type> <name_of_variable> [<number_of_elements>];

or:

long turns[15];

Now you have an array of 15 longs. Ta da!
You now have to set the values of each turn. As your values are all the same (if you ignore the fact that random() ultimately leaves you with different values) you can use a for loop:
for (int x=0; x<15; x++)
{
    turns[x] = random(sizeof(turns) / sizeof(char*));
}

I won't explain how a for loop works; I gave you a link to the tutorial to save me writing it all out myself.
That covers shrinking of part 1 and 2. Part 3 requires a little more thought. That said, as you didn't complete your if statement, I don't actually know what you plan to do if any two adjacent turn elements are the same. I shall assume that you would 're-randomise' one of the duplicates. For this you can again use a for loop, starting at the beginning and running to N-1 th element, where N is the total number of elements:
for (int x=0; x<14; x++)
{
    if (turns[x] == turns[x+1])
    {
        turns[x+1] = random(sizeof(turns) / sizeof(char*));
    }
}

You need make sure that turns[x+1] is not outside of the array, which is why the for loop runs for one iteration less than there are elements.
The fourth shrinkable part is just a matter of swtiching multiple print statements into single for loops:
for (int x=0; x<NUMBER_OF_PRINTS_IN_1st_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,2);
for (int x=WHERE_YOU_LEFT_OFF; x<NUMBER_OF_PRINTS_IN_2nd_BUNCH; x++)
    lcd.print(turns[x]);
lcd.setcursor(0,3);
for (int x=WHERE_YOU_LEFT_OFF_AGAIN; x<NUMBER_OF_REMAINING_PRINTS; x++)
    lcd.print(turns[x]);

All done.

Is it my imagination or are you off-by-one, @chaaarlie2? Your array is of length 15, so is 0-14; in the first for loop code, you say int x=0; x<16; x++ - surely that will go around from 0 to 15, not 0 to 14? Same applies to the second for loop (reduced by 1 to skip the last value).

Alternative to the fourth part: do one loop to do all of them, then if (x==4) lcd.setcursor(0,2); if (x==9) lcd.setcursor(0,3);

@AMADANON it's obviously my imagination, not yours. I wrote the whole answer with reference to 16 values, then when I noticed the OP didn't have "long turn0;" at the start, went back and only remembered to change the first two references. Answer updated, thanks for spotting.

Thanks for the help. Also, for the third shrinkable, good assumption, that's actually what I am doing. On another note, is there a way to fix if two of them match? The turn values are stated as this: {"L2 ", "R2 ", "F2 ", "U2 ", "D2 ", "B2 " , "L' ", "R' ", "F' ", "U' ", "D' ", "B' ", "L ", "R ", "U ", "F ", "D ", "B "} , is there a way I could prevent something like L2 L or L2 L'?

Also, turns[] was already declared in char *turns[], so i end up getting conflicting declaration 'long int turns [15]' Heres the chunk: char *turns[] = {"L2 ", "R2 ", "F2 ", "U2 ", "D2 ", "B2 " , "L' ", "R' ", "F' ", "U' ", "D' ", "B' ", "L ", "R ", "U ", "F ", "D ", "B "}; long turns[15];

I assume char *turns[] = {"L2 ", "R2 " ... }; is your list of possible values, and long turns[15] holds an array of 15 random values from your that list? I'm afraid you've got yourself in a muddle again. You can't have two variables with the same name, even if they're different types; you're attempting to declare two things called turns. No! Perhaps have char *turnChoices[] instead - always consider naming your variables in a way that tells a stranger what the variable means. This is definitely a good idea if you're new to programming, because it's easy to forget what does what!

Next up I have to complain about how you're doing what it looks like you're trying to do: 1. Make a list of possible turn 'commands'; 2. Make a list of N random choices from that list of possible commands. Nothing wrong with that idea, it's perfectly sensible, but you're going about it the wrong way. Really wrong! I understand that you're new to C, we all were once, so I definitely don't want to put you off when I keep referring you to tutorials; read the section on enumeration - it's exaclty what you need.


text:
Bluetooth shield with ardudroid RGB LED
Here is their code:
/*
 PROJECT: ArduDroid
 PROGRAMMER: Hazim Bitar (techbitar at gmail dot com)
 DATE: Oct 31, 2013
 FILE: ardudroid.ino
 LICENSE: Public domain
*/

#define START_CMD_CHAR '*'
#define END_CMD_CHAR '#'
#define DIV_CMD_CHAR '|'
#define CMD_DIGITALWRITE 10
#define CMD_ANALOGWRITE 11
#define CMD_TEXT 12
#define CMD_READ_ARDUDROID 13
#define MAX_COMMAND 20  // max command number code. used for error checking.
#define MIN_COMMAND 10  // minimum command number code. used for error checking.
#define IN_STRING_LENGHT 40
#define MAX_ANALOGWRITE 255
#define PIN_HIGH 3
#define PIN_LOW 2

String inText;

void setup() {
  Serial.begin(9600);
  Serial.println("ArduDroid 0.12 Alpha by TechBitar (2013)");
  Serial.flush();
}

void loop()
{
  Serial.flush();
  int ard_command = 0;
  int pin_num = 0;
  int pin_value = 0;

  char get_char = ' ';  //read serial

  // wait for incoming data
  if (Serial.available() < 1) return; // if serial empty, return to loop().

  // parse incoming command start flag
  get_char = Serial.read();
  if (get_char != START_CMD_CHAR) return; // if no command start flag, return to loop().

  // parse incoming command type
  ard_command = Serial.parseInt(); // read the command

  // parse incoming pin# and value
  pin_num = Serial.parseInt(); // read the pin
  pin_value = Serial.parseInt();  // read the value

  // 1) GET TEXT COMMAND FROM ARDUDROID
  if (ard_command == CMD_TEXT){
    inText =""; //clears variable for new input
    while (Serial.available())  {
      char c = Serial.read();  //gets one byte from serial buffer
      delay(5);
      if (c == END_CMD_CHAR) { // if we the complete string has been read
        // add your code here
        break;
      }
      else {
        if (c !=  DIV_CMD_CHAR) {
          inText += c;
          delay(5);
        }
      }
    }
  }

  // 2) GET digitalWrite DATA FROM ARDUDROID
  if (ard_command == CMD_DIGITALWRITE){
    if (pin_value == PIN_LOW) pin_value = LOW;
    else if (pin_value == PIN_HIGH) pin_value = HIGH;
    else return; // error in pin value. return.
    set_digitalwrite( pin_num,  pin_value);  // Uncomment this function if you wish to use
    return;  // return from start of loop()
  }

  // 3) GET analogWrite DATA FROM ARDUDROID
  if (ard_command == CMD_ANALOGWRITE) {
    analogWrite(  pin_num, pin_value );
    // add your code here
    return;  // Done. return to loop();
  }

  // 4) SEND DATA TO ARDUDROID
  if (ard_command == CMD_READ_ARDUDROID) {
    // char send_to_android[] = "Place your text here." ;
    // Serial.println(send_to_android);   // Example: Sending text
    Serial.print(" Analog 0 = ");
    Serial.println(analogRead(A0));  // Example: Read and send Analog pin value to Arduino
    return;  // Done. return to loop();
  }
}

// 2a) select the requested pin# for DigitalWrite action
void set_digitalwrite(int pin_num, int pin_value)
{
  switch (pin_num) {
  case 13:
    pinMode(13, OUTPUT);
    digitalWrite(13, pin_value);
    // add your code here
    break;
  case 12:
    pinMode(12, OUTPUT);
    digitalWrite(12, pin_value);
    // add your code here
    break;
  case 11:
    pinMode(11, OUTPUT);
    digitalWrite(11, pin_value);
    // add your code here
    break;
  case 10:
    pinMode(10, OUTPUT);
    digitalWrite(10, pin_value);
    // add your code here
    break;
  case 9:
    pinMode(9, OUTPUT);
    digitalWrite(9, pin_value);
    // add your code here
    break;
  case 8:
    pinMode(8, OUTPUT);
    digitalWrite(8, pin_value);
    // add your code here
    break;
  case 7:
    pinMode(7, OUTPUT);
    digitalWrite(7, pin_value);
    // add your code here
    break;
  case 6:
    pinMode(6, OUTPUT);
    digitalWrite(6, pin_value);
    // add your code here
    break;
  case 5:
    pinMode(5, OUTPUT);
    digitalWrite(5, pin_value);
    // add your code here
    break;
  case 4:
    pinMode(4, OUTPUT);
    digitalWrite(4, pin_value);
    // add your code here
    break;
  case 3:
    pinMode(3, OUTPUT);
    digitalWrite(3, pin_value);
    // add your code here
    break;
  case 2:
    pinMode(2, OUTPUT);
    digitalWrite(2, pin_value);
    // add your code here
    break;
    // default:
    // if nothing else matches, do the default
    // default is optional
  }
}

And a photo of my circuit:

Is anyone able to tell me why when the ardudroid app and bluetooth shield are linked successfully, my LED won't respond to the commands on the app?

Please take a look at the formatting help: http://arduino.stackexchange.com/editing-help


text:
Cannot open ov7670 output file
I have taken a data file using arduino and ov7670 camera module. In this project I used the famous code https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno . But after taking the datafile ov7670NoRam.hex, I can't open it. I spent 3 hours to search how to open, but failed.
Could anyone please let me know how to have a look the image in .hex? or would it be possible to take image data from ov7670 directly to jpg?
I tried to convert the hex file to bin using hex2bin, but when I opened the bin, only errors occurred.
The following is the content of the ov7670NoRam.hex
:100000000C9436000C944B000C944B000C944B0059
:100010000C944B000C944B000C944B000C944B0034
:100020000C944B000C944B000C944B000C944B0024
:100030000C944B000C944B000C944B000C944B0014
:100040000C944B000C944B000C944B000C944B0004
:100050000C944B000C944B000C944B000C944B00F4
:100060000C944B000C944B005244590011241FBEB9
:10007000CFEFD8E0DEBFCDBF12E0A0E0B1E0EAE70D
:10008000F2E002C005900D92A235B107D9F70E94A7
:10009000AF000C943B010C9400008093BB0084E8FB
:1000A0008093BC008091BC0087FFFCCF8091B90099
:1000B000887F90E070E08617970709F408950E9402
:1000C000A00084EA8093BC008091BC0087FFFCCF35
:1000D0008091B900887F883009F408950E94A000BB
:1000E000CF93DF93D82FC62F0E94610068E182E48E
:1000F0000E944D0068E28D2F0E944D0068E28C2F17
:100100000E944D0084E98093BC008FE99FE0019735
:10011000F1F700C00000DF91CF910895CF93DF93F6
:10012000EC0103C00E9470002296FE01849131967A
:1001300064918F3FB9F76F3FA9F7DF91CF91089591
:10014000259A90E285B1892785B92FEF31EE84E0B9
:10015000215030408040E1F700C00000F3CFF89418
:10016000239A8091B6008F798093B60083E48093C0
:10017000B00089E08093B1001092B30087B1807F16
:1001800087B98AB183708AB92FEF8BE792E9215042
:1001900080409040E1F700C000008091B9008C7F62
:1001A0008093B90088E48093B8001092C50081E084
:1001B0008093C4008091C00082608093C00088E179
:1001C0008093C10086E08093C20060E882E10E94D3
:1001D00070002FEF81EE94E0215080409040E1F7D5
:1001E00000C0000080E091E00E948E0060E285E1A6
:1001F0000E94700060E08CE00E9470008AE392E050
:100200000E948E0088E492E00E948E0069E181E104
:100210000E947000E8E6F0E094918091C00085FFB4
:10022000FCCF9093C6008091C00085FFFCCF319633
:1002300084918111F1CF4B9BFECF4B99FECF40EEC5
:1002400051E08FE792E04A99FECF36B129B1207F85
:100250003F70232B2093C6004A9BFECF9C01215068
:100260003109892B11F0C901EECF415051094115D7
:0A027000510539F7CFCFF894FFCF06
:10027A0012803A0412001713180132B619021A7AB8
:10028A00030A0C003E00703A7135721173F0A20134
:10029A0015027A207B107C1E7D357E5A7F69807616
:1002AA0081808288838F849685A386AF87C488D706
:1002BA0089E813C0000010000D401418A505AB070B
:1002CA002495253326E39F78A068A103A6D8A7D84A
:1002DA00A8F0A990AA9413C5300031000E610F4B03
:1002EA0016021E07210222912907330B350B371DEF
:1002FA003871392A3C784D404E20690074108D4F70
:10030A008E008F009000910096009A00B084B10C84
:10031A00B20EB382B80A430A44F045344658472815
:10032A00483A59885A885B445C675D495E0E6C0A94
:10033A006D556E116F9E6A400140026013C74F806F
:10034A00508051005222535E5480589E41083F000B
:10035A00750576E14C0077013D484B09C960564066
:10036A0034113B12A48296009730982099309A84CF
:10037A009B299C039D4C9E3F78047901C8F0790F14
:10038A00C8007910C87E790AC880790BC801790C2F
:10039A00C80F790DC8207909C8807902C8C07903C5
:1003AA00C8407905C8307926FFFF32F617131801BD
:1003BA0019021A7A030AFFFF12013D08413D76E14C
:0203CA00FFFF33
:00000001FF

What is it you hope to achieve by "opening" the hex file or "converting it to binary"?
A hex file is a compiled sketch. It is intended to be installed into the Arduino Uno using avrdude.

...you mean that it is not an image data? Oh.... I misunderstood. Because it was generated after the 'make write flash' I thought that it is the image. Thank you a lot for informing it.

But could you please let me know how I can get an image...? I know it is a stupid question, but I have no idea how to take it now.

It looks like you open the serial port on your computer, and the image data arrives.  From my initial glance at the code it looks like you get the marker "RDY" between frames.

If I type 'make write flash', then does the image arrive? Or is it just installation and the should I do something to run the code?

I am the author of the code and needless to say I am very confused right now on what you are trying to do. You run make writeflash in order to do what the target names implies write the hex file to microcontroller's internal flash memory. After that is done the code will run and you will use my frame grabber https://github.com/ComputerNerd/simpleFrameGrabber to capture an image.

Thank you for your answer. I misunderstood what the hex file is. But now I can't capture any image too. After running your simpleframegrabber I only see a black screen, even my oscilloscope shows that the ports D0~D7 are giving output signal. I set baud rate of the camera to be 9600 and then changed baud rate of the simpleframegrabber to be 9600 too. However it doesn't work. Even I tried opening IDE and then checked serial monitor which shows nothing. Could you please let me know what the problem would be?


text:
Cleaning up code? Removing repetition?
I am using Adafruit motor shield, I am running multiple DC motors for different amounts of time, but to start at the same time - I have researched that to do this I have to monitor the elapsed time of each motor in the loop instead of using the delay to avoid blocking if I want them to run at the same time.
Eventually, There will be around 10 DC motors running off this, however it seems very sloppy to me to have 10 repeat entries of very similar code.
Is there a way to create a class or something for the following code so I am not repeating it all as although it works it seems like the way I am currently doing it is bad practice(?) and could be done more eloquently! Forgive me if this is a strange question as I am new to arduino.
In this example there are only 2 motors, however when it gets to around 10, there will be a lot of code just for this bit!
Any suggestions are welcome.
Thanks in advance.
Example code:
#include <Wire.h>
#include <Adafruit_MotorShield.h>

boolean runMotor1 = false;
boolean Motor1Running = false;
unsigned long Motor1StartMillis;
unsigned long Motor1RunTime = 5000;

boolean runMotor2 = false;
boolean Motor2Running = false;
unsigned long Motor2StartMillis;
unsigned long Motor2RunTime = 10000;

//etc etc etc up to 10 Motors

Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *MotorMotor1 = AFMS.getMotor(1);
Adafruit_DCMotor *MotorMotor2 = AFMS.getMotor(2);

void setup()
{
  Serial.begin(9600);
  AFMS.begin();
  runMotor1 = true;  // set condition to true for testing
  runMotor2 = true;
}
void loop()
{
/// Motor1 START
  if (runMotor1 == true) {
     Serial.println("Run Motor 1!");
     runMotor1 = false;
    MotorMotor1->setSpeed(255);
    MotorMotor1->run(FORWARD);
    Motor1StartMillis = millis();
    Motor1Running = true;
  }

  if( Motor1Running && (millis()-Motor1StartMillis > Motor1RunTime) )
  {
    Serial.println("Motor1 Time Elapsed!");
    MotorMotor1->setSpeed(0);
    MotorMotor1->run(RELEASE);
    runMotor1 = false;
    Motor1Running = false;
  }

  /// Motor 2
    if (runMotor2 == true) {
     Serial.println("Run Motor 2!");
     runMotor2 = false;
    MotorMotor2->setSpeed(255);
    MotorMotor2->run(FORWARD);
    Motor2StartMillis = millis();
    Motor2Running = true;
  }

  if( Motor2Running && (millis()-Motor2StartMillis > Motor2RunTime) )
  {
    Serial.println("Motor2 Time Elapsed!");
    MotorMotor2->setSpeed(0);
    MotorMotor2->run(RELEASE);
    runMotor2 = false;
    Motor2Running = false;
  }

}

Thanks for reading, and thank you for any input you may have.
Steve

It's not in the least bit bad practice: that's what classes are for! And it's exactly how the vast majority of all Arduino add-ons, your Adafruit motor shield included, are represented in software.

Yes, I meant, The way I am doing it is bad practice, and should I be using a class or something. Let me change it to clarify :)

Aha! If you can hold on for a few hours I can give you a fuller answer - you might benefit from extending the Adafruit class rather than reinventing the wheel.

You are perfectly right, a class would help simplify your code. Here is
a tentative class that should work for what you are doing:
class Motor
{
public:
    Motor(const char *_name, Adafruit_DCMotor *_motor,
          unsigned long _runTime)
    : name(_name), startNow(false), running(false),
      runTime(_runTime), motor(_motor) { }
    void start() { startNow = true; }
    void update();
private:
    const char *name;
    boolean startNow;
    boolean running;
    unsigned long startTime;
    unsigned long runTime;
    Adafruit_DCMotor *motor;
};

Most of this is almost copy-paste from your actual code, except for your
runMotorX variables that I renamed startNow, which seemed more
appropriate.
Beware that the name of the motor is copied as a pointer. Thus you
should better call the constructor with a literal string (like
"the name") as a first parameter. Otherwise it would be more
appropriate to allocate memory and copy the characters themselves, but I
like to avoid dynamic memory allocation on an Arduino if I can.
Now, all the code that you have in loop() for each motor would be the
Motor's update() method:
void Motor::update()
{
    if (startNow) {
        Serial.print("Run ");
        Serial.print(name);
        Serial.println('!');
        startNow = false;
        motor->setSpeed(255);
        motor->run(FORWARD);
        startTime = millis();
        running = true;
    }

    if (running && (millis()-startTime > runTime))
    {
        Serial.print(name);
        Serial.println(" Time Elapsed!");
        motor->setSpeed(0);
        motor->run(RELEASE);
        running = false;
    }
}

With this class, your code would now look like:
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor m1("Motor 1", AFMS.getMotor(1),  5000);
Motor m2("Motor 2", AFMS.getMotor(2), 10000);
//etc etc etc up to 10 Motors

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    m1.start();
    m2.start();
}

void loop()
{
    m1.update();
    m2.update();
}

Of course, when you get to 10 motors, this would still be annoying
repetition. You can simplify further by putting the motors in an array
and looping through it:
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Motor motors[] = {
    Motor("Motor 1", AFMS.getMotor(1),  5000),
    Motor("Motor 2", AFMS.getMotor(2), 10000)
    //etc etc etc up to 10 Motors
};
#define NUM_MOTORS (sizeof motors / sizeof motors[0])

void setup()
{
    Serial.begin(9600);
    AFMS.begin();
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].start();
}

void loop()
{
    for (unsigned int i = 0; i < NUM_MOTORS; i++)
        motors[i].update();
}

Excellent, thanks a lot, this is easy enough to understand and is exactly what I was looking for. Thanks for going the extra mile with the loop example too!


text:
Power source for Arduino uno, sparkfun usb shield and adafruit motor shield
I'm having trouble powering my boards altogether. Right now, I'm using 8x AA batteries to power everything. Running my arduino with one shield runs fine, but not with both shields stacked on top of my arduino. I've even tried powering it with an extra 4x AA batteries on my motor shield, but it still won't run. The way it's stacked is; arduino uno board, usb host shield then motor shield.

We don't know how your batteries are connected, or what power requirements your devices all have.

I have a 8xAA battery holder that's connected to the arduino uno via the 2.1mm plug and on my motor shield I have 2 DC motors and 2 servo motors that all require 6v. If that is what you mean by power requirements(?) If you mean power requirements for boards, I know that with the uno, it is suggested I use between 9v-12v, so I just went by the 12V.  @IgnacioVazquez-Abrams

Sounds odd. Do the lights on the boards turn on? Are the sparkfun and adafruit shields pin compatible? Sometimes shields by different companies use the same pins for transmitting data.

I can power a Mega, motor shield and a wifi shield connected to 2 motors, a servo and a variety of sensors using 4-5 AA batteries, so 8 should be more than adequate for your needs.

Yes, the lights on all boards are turned on. I've tried again with all boards stacked on top of each other and realised that the USB host shield works when I disconnect 2 servos from the motor shield. However, the DC motors from the motor shield still does not work. I'll look into the pins now. But if they do use the same pins for transmitting data, is there a solution for that? Thanks @bladepanthera

If that is the case, you might have to get clever with some rewiring of pins. I had to do that for my adafruit wifi shield as it uses the same pins as my arduino motor shield. Cross that bridge if it comes to it, though!

Can I ask, how did you find out that they used the same pins? @bladepanthera

Documentation for the boards. They usually clearly describe which pins are being used.

IF your motors are powered VIA the Arduino board "there will be problems". The motors should receive power directly from the battery on their own voltage input line. If the power goes via the SArduino board you have a good chance of noise problems AND if the Arduino voltage regiulator is used you will exceed its ratings for all except the tiniest of motors. As ever a circuit diagram is essentially mandatory. Words are often very ambiguous in situations like this. Your actual question gives no clues at all and your comments cannot be interpreted with certainty.

I've already tried powering the motor shield with it's own power source using 4xAA battery holder, while at the same time powering the arduino with 8xAA battery holder. But the motors still won't move when it's stacked on top of the usb host shield and arduino board. @RussellMcMahon

(1) Circuit diagram !!!!!!!!!!!!!!!!!! please (2) When you say "still won't move" the meaning is potentially broad. ... when you do what? When what is connected how. Saying shields stacked on top of each other is about information free - that's what shields do. | You say "USB host shield" Which one? Web reference? Maker?  What happens i it is absent, if you know? If you don't know, why not? | What happens if you power the motor boaard stand alone and the assert the motor activating pins with a jumperto +5V or whatever is required ? If you have not done it you should do so and report back. ||

You say the motors do not move but, why should they? Have you chcked at the shield input that the signal that is meant to make them move is appearing at thje pin that you think it should ? This can be done with a meter oran LED and a resistor. etc. | At the moment from our viewpoint you are supplying semi random pieces of information with their relatrionshiop not obvious and gaaaps. You need to supply a coherent consistent complete picture if you want to maximise use of the available hive mind.

Did you check about pin compatibility? And what code are you using to run the motors? The standard example?

AA batteries are fine for small hobby motors - the issue is that you shouldn't be running the motors off the same regulator as the logic circuitry.  Ideally you would not run the motors off a regulator at all, but rather choose some suitable for the voltage of the pack itself.  You may however need to obtain a lower dropout regulator for the Arduino, or reduce it's operating voltage to 3.3v - the stock 5v regulator may start to drop out if the battery pack voltage dips below 7.something volts under load of the motors.

Its a very bad idea to power everything from the same battery source. Most motors, especially ESP, generate large current spikes, rather than draw a small current throught. AA batteries are not designed for this.
You can get away with using AA batteries for micro-controllers, shields. However, keep motors on a sweater power supply. There are batteries for specific motor types, and these will typically have a high current rating. Of course, without a circuit diagram, I cannot go into details. I'll update my answer when you do.

It's not "a very bad idea" it merely requires some care - and a lower dropout regulator than stock wouldn't be a bad idea.  What is a problem is trying to run the motors off the logic regulator.


text:
Call a class method from inside the same class
If i have file cSpeedOfSound.h:
#ifndef cSpeedOfSound_h
#define cSpeedOfSound_h
#include "Arduino.h"
#include "math.h"
class cSpeedOfSound{
    public:
        cSpeedOfSound(float *i,float *C);
    private:
        float *C;
        float *a;
        float *i;
    };
#endif

and file cSpeedOfSound.cpp:
#include "cSpeedOfSound.h"
cSpeedOfSound::cSpeedOfSound(float *i,float *C){
    //some code...
    *C =roundto(*C,2);}
float cSpeedOfSound::roundto(float x,float dp){
return (round(x*pow(10., dp)) / pow(10., dp));}

where i want to run function roundto inside class, but it doesnt seems to work. So what im making wrong and how to do it properly?
Ps: Im begginer to arduino (want it to learn robotics + C language) and know python (learnd for about 1+ year), so pls do not hate me if i made crucial mistakes.

In this case you could simply write roundto() as a plain function. Declare it as static to make it visible only from inside cSpeedOfSound.cpp. That's the C way of encapsulation.

You need to include roundto() in your class declaration, e.g. something like this:
class cSpeedOfSound {
public:
    cSpeedOfSound(float *i,float *C);

private:
    float roundto(float x, float dp);

    float *C;
    float *a;
    float *i;
};

In C++, class structures are fixed. You can define the body of a function almost anywhere, but all member functions/data must be specified in the original declaration.

As a side note, it's worth pointing out that you have a naming conflict in your code. You have member variables called i and C, and you have totally separate function parameters called i and C. The compiler won't complain about this (the function parameters will simply mask the member variables), but it may not do what you expect.


text:
What is the difference between file.print() and file.write()
From here I think I understand the difference between Serial.write and Serial.print, but is it the same when writing to a file in a SD card for example. Does it mean that File.write saves bytes in the file instead of text?

The File class inherits from the Stream class, which in turn inherits from the Print class.
The Serial class inherits from the Stream class, which in turn inherits from the Print class.
print() and write() are defined by the Print class.
So yes, File.print() and Serial.print() are the same, as are File.write() and Serial.Write().


text:
How to effectively modify a library to be able to function with Mozzi Library?
I have sketch that runs almost exactly as I would want it to. Now I am trying to add sound to it using the Mozzi Library instead of just using the tone function. This way I can avoid having to put a memory card slot and a memory card with the Arduino, considering Mozzi produces some good sound. The problem is that Mozzi takes over the timers and a lot of other things. The analogread and the delaymicroseconds have been replaced by Mozzi functions mozzi analog read and mozziMicros etc. I rewrote my sketch adding mozzi relted stuff, but it stops functioning like it should, but it does compile. SO I am assuming I would need to change the Library to replace original functions with mozzi functions like mozzianalogread. On doing this, several errors about arguments and declaration for these functions pop up. Is editing the other library a necessary step? If yes, then what should be things to look out for to prevent such errors.

Without knowing what Mozzi is (an Australian mosquito?), I'd say that your problem is that you need to include the Mozzi library in this "other" library so it knows what these mozzi* functions are.

http://sensorium.github.io/Mozzi/examples/#08.Samples
I did do that and added all the commands and the header to the QTouchADC library.


text:
What is the most memory-friendly way to declare integer literals?
I'm having SRAM overflow problems with my 8bit atmega328p in my Arduino Uno, which has 2KB of SRAM, so I'm defining all my for loops with bytes as counters instead of ints. As in:
for(byte i=0;i<16;i++) buf[i]=(char)ap1[i];

Would it make any difference if I declared the integer literal 16 as a constant?
const byte BUFSIZE=16;

Or using the preprocessor:
#define BUFSIZE 16

There's also the macro PROGMEM which stores variables in flash memory, which I've decided to use for all my constants, but is it not the point of const to do this? as well as aiding the compiler in warning you if you screwed up changing the variable.
const byte BUFSIZE PROGMEM=16;

AFAIK, using const would save BUFSIZE in the flash memory, but how about using the preprocessor? Using the preprocesor would be the exact the same as using the literal 16, as far as i'm concerned.
This fear arose from the fact that string literals are saved in Flash and then transferred to SRAM, wasting twice the space, which you can solve using the arduino macro F("thisisastring"), which stores them in flash memory, and I don't want to waste 2 bytes of SRAM in every for loop I use

The compiler should optimise out any constants into the most compact form possible. Take a look at the assembly code if you're curious.

Do you have a lot of global variables? Try to move everything into smaller functions using local variables except things that absolutely must be persistent. The compiler does a very good job of optimising constants out of SRAM so they are unlikely to be your problem.

Well, it's easy to just try and see... Let's try the following program:
#ifdef USE_CONST
const byte BUFSIZE = 16;
#else
#  define BUFSIZE 16
#endif

char buf[BUFSIZE], ap1[BUFSIZE];

int main(void)
{
    for (byte i = 0; i < BUFSIZE; i++)
        buf[i] = ap1[i];
    return 0;
}

I compiled this for an Uno both with and without #define USE_CONST,
and it doesn't make any difference! avr-size reports the same sizes for
both versions, and the generated assemblies are identical: the optimizer
transformed the loop into something like
byte *Z = ap1;
byte *X = buf;
do {
    *X++ = *Z++;
} while (Z != ap1 + 16);

where X and Z are two of the CPU's pointer registers, and ap1 + 16 is
an immediate constant, i.e. part of the instruction itself, c.f. the
AVR addressing modes.
It is worth noting that, in C++,
const implies internal linkage.
Thus a const global variable is very much like a preprocessor constant.
This is unlike C, where you would need to qualify the variable as
static const in order to get the same behavior. Otherwise the compiler
would need to allocate storage to BUFSIZE, just in case it is
referenced as extern from another source file, even though it can
replace occurrences of BUFSIZE in the same file with its immediate
value.
On the other hand, the Arduino IDE compiles your code with
-ffunction-sections -fdata-sections
and links it with
--gc-sections,
which means the linker will eventually get rid of the unused reserved
storage.

I'm not familiar with the Atmel megaAVR microcontrollers or Arduino.  But generally speaking, your memory optimization ideas are misguided.
For example, it's likely that the compiler implements local loop variables within a register so that they don't consume any RAM at all.
And the integer literal constants, such as 16 from your example, also likely don't consume any RAM.  The compiler likely incorporates these constants into the code.
Whenever you optimize something it's best to go after the big fish first.  You're focusing on the tiniest fish.  To find the big fish, look at the *.map file produced by the linker.  The map file should show how much RAM and Flash memory is used by your program.  The RAM sections might be labeled "bss" and "data" in the map file.  Hopefully the map file will also detail how much RAM is used by each compilation unit.  Find the compilation units that are using the most RAM and focus on them.  Maybe there are large buffers or arrays defined in those compilation units that can be reduced in size or redesigned.
The map file is also where you could check to see if your optimizations have made any difference.  For example, try some of the optimization you described and see whether the map file changes significantly.

Yes, defining "const byte bufsize" would make a difference - it'll use one additional byte of SRAM. All variables are stored in RAM unless they're annotated as being PROGMEM.
A #define gets translated into its value by the preprocessor, and so looks the same to the compiler.
Your constant '16' isn't taking up any SRAM in the first place; look elsewhere (at actual variables) if you need to optimise.
String literals are treated the same way as arrays of any numeric type: they're copied to SRAM on startup because the code has to be able to dereference the pointer (which is what myarray[x] does) and find the location in RAM. Single numeric constants do not have this issue - they're value types - and so don't get copied into RAM.

It's actually slightly worse. The const byte is first stored in flash by the compiler/linker, and then during the preamble it's copied to SRAM. So you're taking twice the hit needlessly.

Did the test: you are actually taking zero times the hit, not twice.

At higher optimization levels of course (for a given definition of "higher").


text:
Feedback Request: HID USB to Bluetooth Relay
Bluetooth Relay Project:

Develop a USB to bluetooth adapter for my mechanical keyboard. Using a USB host shield, have an Arduino Pro Mini read keyboard usb commands and repeat them over bluetooth.

I have minimal experience with Arduino and circuitry, from my perspective this project seems pretty straight forward plug and play of the hardware components.
I plan to use the following hardware:
Hardware:

Arduino

Arduino Pro Mini 328 - 3.3V/8MHz
Sparkfun Products: 11114

Bluetooth HID module

BlueSMiRF HID
Sparkfun Product: 10938 ($25)

USB Host Shield

USB Host Shield for Arduino Pro Mini
circuitsathome ($20)

Power Source

USB Phone power block
Output: 5v 1000mA

Total Cost: $55
I will be connecting the USB module by following the write up here and will be connecting the USBHost shield by following this guide and this guide
Does anyone have any comments/suggestions/concerns/words of wisdom before I start to order stuff?


text:
Sketch stops working after ~40 minutes. Overflow?
I have this simple sketch I use on Arduino Micro:
int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
unsigned long prevMicros = 0;        // will store last time LED was updated  +
unsigned long interval =  7000000;           // lunghezza della pausa in secondi
unsigned long intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
 pinMode(fan, OUTPUT);
 pinMode(led, OUTPUT);
 prevMicros = micros();
}

void loop() {
  unsigned long currMicros = micros();

  // manage overflow? BOH
   if (ledState == HIGH && (((unsigned long)(currMicros  - prevMicros)) >= intervalON)){
     prevMicros = currMicros;
      ledState = LOW;
    }
    else if (ledState == LOW && (((unsigned long)(currMicros - prevMicros)) >= interval)){
      ledState = HIGH;//riparte
      prevMicros = currMicros;
    }

    digitalWrite(led, ledState);
    digitalWrite(fan, ledState);
}

I could use millis() instead of micro(), but I decided to keep this to shorten the overflow rate (should be 72 minutes). I shall go back to millis() once my issue is fixed.
The sketch works as expected, turning on the LED for a second every 7, but the sketch hangs after 40 minutes. Can you tell me why, and how to manage overflow properly? Why is it hanging after 40 and not 72 minutes? Thanks

Shouln't it be (((unsigned long)(currMicros  - prevMicros)) >= intervalON) instead of (((long)(currMicros  - prevMicros)) >= intervalON), since the timing value from micros() is unsigned?

To confirm: if the problem really is (long) vs (unsigned long) time interval comparison, then the observed behavior should be LED stops blinking after at t=40 minutes, but then starts blinking again at t=70 minutes when then micros() overflows back to 0. Definitely a good idea to test/verify with micros() first.

I think your observations deserve a voted answer :)

40 minutes is approximately 2^31 microseconds, so it seems an overflow of some kind. Also it is good practice to use type definition like uint32_t instead of unsigned long for readability and cross platform portability.

I think the problem is in the prevMicros being pushed up all the way and never being reset when the currMicros rolls over to 0. Better to use a delta for currMicros in this case rather than an absolute number. You'll have to detect and correct for micros() roll over though.

What about using unsigned long long?

Your code looks rollover-safe to me, as does the current implementation of micros(). This should work just fine across the micros() rollover. What version of Arduino are you using?

BTW, you have too many casts and parentheses: if (ledState == HIGH && currMicros - prevMicros >= intervalON) is the same, but easier to read.

Here is how you can speed up your tests: globally declare extern unsigned long timer0_overflow_count; then, in setup(), set this global variable to 0x001f0000. This way the high bit of micros() will toggle in ≈ 67 seconds. Set it to 0x003f0000 and micros() will roll back to zero, again in ≈ 67 seconds.

I just tested the program on an Uno, using the technique mentioned above to trigger a prompt rollover, and with a Serail.println(micros()); for debugging. It works exactly as expected: it does not hang. The question asked is “Why does the program hang?”. Since it does not really make sense, shouldn't the question be closed?

When comparing time intervals, use unsigned long instead of long.
if ( ... (((unsigned long)(currMicros - prevMicros)) >= intervalON) )

The time counter overflows at some point -- micros() overflows after 70 minutes, milis() overflows after nearly a month -- but these are unsigned values.
When an unsigned value is interpreted as a signed value -- (long) instead of (unsigned long) -- then half of the values are interpreted as negative numbers. So after 40 minutes, the micros() value looks like a negative number, and the (curr-prev) >= interval comparison returns false. After 70 minutes, the micros() overflows back to 0, and the signed comparisons work as expected.
The solution is to use unsigned long for all delta-time comparisons.
This is easier to see if you consider a smaller, 3-bit number: there are 8 values for a 3-bit number. If the 3-bit number is unsigned, then the values are 0, 1, 2, 3, 4, 5, 6, 7. But if the 3-bit number is signed, then those same binary code numbers are interpreted as 0, 1, 2, 3, -4, -3, -2, -1. Same principle for int and long values, just a larger range of values.
EDIT:
Based on your comment below, I did some testing on my own hardware (Sparkfun "red board" Arduino UNO R3 clone), and added some code to help make it more testable. Some highlights:

Added a diagnostic LED on Arduino pin 9, to indicate when the timer overflow has happened (i.e. new time is less than previous time).
Added a mask to force the timer overflow to happen sooner, so I don't have to wait an hour to verify whether the code had any effect.
Calculated timeSinceLastChange and applied mask, to handle overflow.
Added TIMER_DATATYPE based on jippie's comment

The complete code:
//--- based on comment from jippie about using C++ standard width integer types
// #define TIMER_DATATYPE unsigned long
#define TIMER_DATATYPE uint32_t

//--- MarkU: diagnostic LED to indicate that timer overflow happened.
// Comment out this line for normal operation.
#define DIAGNOSTIC_LED_TIME_OVERFLOW 9
//---

//--- MarkU: diagnostic: force timer overflow to happen sooner.
// This must be significantly longer than the intervals being measured.
// Must be a binary all-1's bitmask.
// 0x3FFFFFF overflow after approximately 1 minute
// 0xFFFFFFF overflow after approximately 5 minutes
// 0xFFFFFFFF overflow after approximately 70 minutes
#define DIAGNOSTIC_TIMER_OVERFLOW_MASK 0x3FFFFFF
//---

int fan = 3;
int led = 13;
int ledState = HIGH;         //all'inizio gira
//unsigned long time;
TIMER_DATATYPE prevMicros = 0;        // will store last time LED was updated  +
TIMER_DATATYPE interval =  7000000;           // lunghezza della pausa in secondi
TIMER_DATATYPE intervalON =  1000000;           // lunghezza del ON in secondi

void setup() {
  pinMode(fan, OUTPUT);
  pinMode(led, OUTPUT);

  //--- MarkU: diagnostic LED indicate that timer overflow happened
#if DIAGNOSTIC_LED_TIME_OVERFLOW
  pinMode(DIAGNOSTIC_LED_TIME_OVERFLOW, OUTPUT);
  digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, LOW);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
  //---

  prevMicros = micros();
}

void loop() {
  TIMER_DATATYPE currMicros = micros();

  //--- MarkU: diagnostic: force timer overflow to happen sooner
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
  currMicros = (TIMER_DATATYPE)(currMicros & ((TIMER_DATATYPE)DIAGNOSTIC_TIMER_OVERFLOW_MASK));
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK

  //--- MarkU: consolidate time delta calculation
  TIMER_DATATYPE timeSinceLastChange;
  if (currMicros < prevMicros) {
    //--- MarkU: handle timer overflow
#if DIAGNOSTIC_LED_TIME_OVERFLOW
    digitalWrite(DIAGNOSTIC_LED_TIME_OVERFLOW, HIGH);
#endif // DIAGNOSTIC_LED_TIME_OVERFLOW
#if DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & DIAGNOSTIC_TIMER_OVERFLOW_MASK;
#else // DIAGNOSTIC_TIMER_OVERFLOW_MASK
    timeSinceLastChange = (currMicros - prevMicros) & 0xFFFFFFFF;
#endif // DIAGNOSTIC_TIMER_OVERFLOW_MASK
  } else {
    timeSinceLastChange = currMicros - prevMicros;
  }
  //---

  // manage overflow? BOH
  if (ledState == HIGH && (timeSinceLastChange >= intervalON)) {
    prevMicros = currMicros;
    ledState = LOW;
  }
  else if (ledState == LOW && (timeSinceLastChange >= interval)) {
    ledState = HIGH;//riparte
    prevMicros = currMicros;
  }

  digitalWrite(led, ledState);
  digitalWrite(fan, ledState);
}

I'm sorry it's still not working, I updated the code above

I'm testing your edited code. Anyway, I'm beginning to suspect the problem isn't overflow, since it's not re-starting ever. Your code is working as expected though, switching the DIAGNOSTIC_LED_TIME_OVERFLOW to ON after specified time. Let's wait to see if it hangs again... Thank you for your time!

nothing to do, it blocked after 2 hours, this time with ledState set to HIGH permanently. I don't think it's a circuit problem , but should I try  removing the load on fan?

Yes, I tested the above code driving an LED, not a fan. Perhaps the real problem is some kind of power disruption when turning the fan on or off -- maybe it's acting like an inductive load? Relays and motors are a bit tricky to drive. What circuit are you using to drive the fan, or is the fan just directly connected to an Arduino digital pin? And what kind of fan is it exactly (make/model number)?

the fan is a small 3V motor absorbing up to 0,5A. I'm driving it using a 2N3904 connected to Vin and a potentiometer 0-9k ohm from digital pin to transistor's base. Input voltage to Arduino Micro is 5V regulated

the motor is similar to pkz3916, with a small propeller on it


text:
How to int variables with similar names without tons of code?
I'm using int with 14 LEDs to specify pins, but I don't want to use int 14 times, like this:
int led1 = 2;
int led2 = 3;
int led3 = 4;
int led4 = 5;
int led5 = 6;
int led6 = 7;
int led7 = 8;
int led8 = 9;
int led9 = 10;
int led10 = 11;
int led11 = 12;
int led12 = 13;
int led13 = 45;
int led14 = 46;

is there any way to not do this?
Also, to define them as output, is there any way to avoid using pinMode(***, OUTPUT) 14 times as well?

The word you are looking for is array.
An array is like a list of values all of the same type.  For instance, your LED pins could be specified as:
int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

You can then access the LEDs by number.  Note that arrays start counting from zero not from one, so you would have:
leds[0]
leds[1]
leds[2]
... etc to ...
leds[12]
leds[13]

It's great for using them in an array:
for (int i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

If the values are never going to change, as in this case since they are pin numbers, the array should be declared const so it doesn't take up any of your precious RAM:
const int leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

Also you should get into the habit of tailoring the data types to the expected values.  If the values are never going to exceed 255 then you should use "byte" not "int", or better still the C standard "uint8_t".
const uint8_t leds[14] = { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 45, 46 };

for (uint8_t i = 0; i < 14; i++) {
    pinMode(leds[i], OUTPUT);
}

An int takes two bytes, so using int when you can get away with uint8_t means you're wasting half the memory.


text:
Where is documentation on Arduino's Internal Interrupts?
First time arduino programmer here...however I have programmed the TI MSP430 in the past...
I am trying to figure out how to configure internal Interrupt Vectors on this Arduino Uno.
In the Arduino IDE, I am skeptical about writing lines of code like
ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

Because it doesn't appear to matter what I type inside ISR(), for instance I can write
    ISR(GibERisH) {
    }
And it still compiles and uploads to the arduino. What?! Also how could Arduino IDE know what the heck TIMER1_CAPT_vect is without having the library?
I found a list of interrupt vector names here: http://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html
But I can not find documentation ANYWHERE ELSE on what to call these interrupt vectors.
Should I abandon the Arduino IDE and go with the Atmel Studio 6.2 (There is a juicy looking arduino plug-in...)? I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

EDIT: I realized my problem was I was looking for documentation for the atmega16U2 (that does something else on the board), not the atmega328P.

The vector names are all defined within the header files for the main chip in the compiler.  The IDE doesn't need to know anything about that kind of thing - that's all up to the compiler.
Look for the files "lib/avr/include/avr/io*.h within the compiler in your chosen IDE.  In there are all the chips and all their definitions.
For instance, the ATMega328P definition (iom328p.h) has this list:
#define INT0_vect         _VECTOR(1)   /* External Interrupt Request 0 */
#define INT1_vect         _VECTOR(2)   /* External Interrupt Request 1 */
#define PCINT0_vect       _VECTOR(3)   /* Pin Change Interrupt Request 0 */
#define PCINT1_vect       _VECTOR(4)   /* Pin Change Interrupt Request 0 */
#define PCINT2_vect       _VECTOR(5)   /* Pin Change Interrupt Request 1 */
#define WDT_vect          _VECTOR(6)   /* Watchdog Time-out Interrupt */
#define TIMER2_COMPA_vect _VECTOR(7)   /* Timer/Counter2 Compare Match A */
#define TIMER2_COMPB_vect _VECTOR(8)   /* Timer/Counter2 Compare Match A */
#define TIMER2_OVF_vect   _VECTOR(9)   /* Timer/Counter2 Overflow */
#define TIMER1_CAPT_vect  _VECTOR(10)  /* Timer/Counter1 Capture Event */
#define TIMER1_COMPA_vect _VECTOR(11)  /* Timer/Counter1 Compare Match A */
#define TIMER1_COMPB_vect _VECTOR(12)  /* Timer/Counter1 Compare Match B */
#define TIMER1_OVF_vect   _VECTOR(13)  /* Timer/Counter1 Overflow */
#define TIMER0_COMPA_vect _VECTOR(14)  /* TimerCounter0 Compare Match A */
#define TIMER0_COMPB_vect _VECTOR(15)  /* TimerCounter0 Compare Match B */
#define TIMER0_OVF_vect   _VECTOR(16)  /* Timer/Couner0 Overflow */
#define SPI_STC_vect      _VECTOR(17)  /* SPI Serial Transfer Complete */
#define USART_RX_vect     _VECTOR(18)  /* USART Rx Complete */
#define USART_UDRE_vect   _VECTOR(19)  /* USART, Data Register Empty */
#define USART_TX_vect     _VECTOR(20)  /* USART Tx Complete */
#define ADC_vect          _VECTOR(21)  /* ADC Conversion Complete */
#define EE_READY_vect     _VECTOR(22)  /* EEPROM Ready */
#define ANALOG_COMP_vect  _VECTOR(23)  /* Analog Comparator */
#define TWI_vect          _VECTOR(24)  /* Two-wire Serial Interface */
#define SPM_READY_vect    _VECTOR(25)  /* Store Program Memory Read */

Further, _ISR() is just a macro.  It creates a suitable function prototype for your function, and if that happens to include a valid vector then it becomes an ISR.
#  define ISR(vector, ...)            \
    extern "C" void vector (void) __attribute__ ((signal,__INTR_ATTRS)) __VA_ARGS__; \
    void vector (void)

That is defined in "avr/interrupt.h" in the compiler's include files.  With your gibberish you'd end up with:
extern "C" void GibERisH (void) __attribute__ ((signal,__INTR_ATTRS));
void GibERisH (void) {
    // something here
}

With a real vector you'd get the more meaningful:
extern "C" void _VECTOR(7) (void) __attribute__ ((signal,__INTR_ATTRS));
void _VECTOR(7) (void) {
    // something here
}

Of course, _VECTOR() itself is a macro:
lib/avr/include/avr/sfr_defs.h:#define _VECTOR(N) __vector_ ## N
So that further expands out to:
extern "C" void __vector_7 (void) __attribute__ ((signal,__INTR_ATTRS));
void __vector_7 (void) {
    // something here
}

And magically, that new function name of __vector_7 is directly referenced from the standard vector handling code in the startup library crt of the AVR compiler.

Thank Majenko. Also the documentation actually does have the names of the interrupts, but looking at the header makes it crystal clear. Thanks for answering.

ISR(TIMER1_CAPT_vect) {
    Serial.Print("Entered Capture Vector");
}

Rule #1. Don't do serial prints inside an ISR. Doing that will likely hang the sketch.

Because it doesn't appear to matter what I type inside ISR(), for instance I can write ISR(GibERisH) { }

Yes you can do that. It just degrades into some function that is never called. The way it is organized with all the defines, any non-valid ISR name effectively creates a non-ISR function, which is therefore ignored. Even getting the capitalization wrong can cause this.

I need advanced control of the guts of this processor, and there is zero documentation about how to do this anywhere on the internet.

There is a considerable amount of detail on my site: http://www.gammon.com.au/interrupts


text:
Do I need 3 full-size arduinos to control this LED setup?
I'm sourcing the parts now for an LED persistence of vision setup on a bicycle.  Two wheels with anywhere between 16-32 LED's per wheel, as well as 24 LED's mounted on the frame of the bike itself
Since the Arduinos have to be mounted into the wheels to drive the POV displays - do I need a total of 3 arduinos?
Driven by 2x [Nano 3.0 Atmel Atmega328P Mini-USB Board][1] + an Arduino Uno from the frame?
So far I think I'll pick up 2 x [433Mhz RF Transmitter Module + Receiver Module Link Kit][2] for wireless control, [Reed Switch Magnetic Detection Sensor Module][3] for calculating velocity from a small magnet mounted somewhere on one of the forks. 4 x [WS2811 RGB 8-LED Light Strip Module][4] as the POV LED's, or maybe some of the [DotStar Digital LED][5]
and miscellaneously perhaps are some of these required/ useful? maybe instead of the 4x8 I could go 4x [SSC Seoul P4][6], or from [SparkFun][7],  following pieces of [this guide][8]

DIY AT89S52 Microcontroller Development Board Set
[KT0026 Electronic Parts Pack][9]
[Square Prototyping Plate][10]
[ZnDiy-BRY Z-069 MB102 Breadboard + Power Supply Module][11]

My main concern is refresh rates....getting everything controlled...and making sure I have enough I/O. Any help would be greatly appreciated.  (URL's available on request :P)

NeoPixels are not great for POV stuff because they have inherent jitter of about 2ms regardless of your frame rate and how many pixels you are driving. This can make your edges look ragged at sufficient speeds. You can read more about the source of the jitter here... http://wp.josh.com/2014/06/09/neopixels-revealed-warping-time-and-space-to-actually-see-inter-pixel-jitter/

Maybe look at NeoPixels Revealed: How to (not need to) generate precisely timed signals. The author there controlled 1000 Neopixels with a Duemilanove with fairly simple code. These were WS2812 not WS2811 but perhaps the code could be adapted to suit. Judging by the datasheets they are fairly similar.
Since he got 30 fps with 1000 pixels, your requirement of around 100 pixels would seem fairly straightforward.

Those WS2811 strips are a good idea. You can control them all from pins on the same port which will make the control a little more complex but multiply the refresh rate, or you can chain all of them off a single pin if you find the refresh rate high enough that way.

Controlling two LED strips in parallel would not be easy. The Adafruit NeoPixel library uses inline assembly to get the timings right. There are quite a few nops in the 400 kHz bitstream / 16 MHz CPU case, so it is certainly doable, but you will have to write it in assembly and count the CPU cycles.

That's what util/delay.h is for.

Not really helpful: if you want to keep a logic level for some specified time, you have to delay for that time minus the time needed to execute the other instructions in your loop. So you still need to count the cycles in the assembly code. We are talking sub-µs timing tolerances.

There are only three transitions needed per cycle. The hard part is putting all the bits together for the second transition, and even then that has a fixed cost which would be far less than the 50us reset period. So complex, but not anywhere near impossible.

You can drive up to 8 strings at the same time from 8 different IO pins on an arduiono. Yuo do need to get all the outgoing bytes (each byte has the bit outgoing pattern for all out outputs) ready beforehand, but you can do that outside the timing-critical loop.

You wouldn't necessarily need full Arduinos - you could prototype them on Arduinos, then move them to just Atmel chips on your own board (e.g. stripboard). To do this, you would need your own resonator, power supply, and programming. Resonators are cheap and easy, you would probably want to set up your own power supply anyway (3 AA batteries is a perfect power supply for the Atmel), and you can program using a USBISP or similar, right from inside the Arduino IDE.
As for speed, I see a bicycle wheel is on the order of 26 inches/660mm diameter. This makes the perimeter about 6 foot 9 inches/2 meters (sounds like a lot, doesn't it?). Google tells me that a sprint on a bike by a fit person is about 40km/h, or 11 meters/second, making 5.5 revs/second of the wheel - about 180 milliseconds/revolution. This means that if you want 1 degree accuracy, you're going to have to change ALL the (changing) leds at about 2khz. The Arduino can run at up to 20mhz, giving you 10,000 instructions to change the leds. Plenty of time.
If you have strips, you should check the specs on the strips to see how fast you can change them. Remember that you probably have to update ALL of them, and you want most of the time to be spent between updates; while you are updating, it may show unwanted lights on/off.

500 µs (2 kHz) is not “plenty of time”. You have 384 bits to push (2 strips/wheel × 8 LEDs/strip × 24 bits/LED) at 400 kb/s (as per the WS2811 spec), and then you send a 50 µs pulse to latch the data. That's 1010 µs per refresh, of which only 50 (the latch pulse) are available for other computations. Using WS2812 (800 kb/s) would probably help. And no, you do not get unwanted lights during the update.

Also take into account the 400hz refresh rate of the WS2812.


text:
IDE to program Arduino Uno especially internal interrupt vectors
I am trying to program this Arduino Uno's Timer1 module to use its Input Capture pin to record the times of edges and store / transmit them during the Input Capture Interupt Service Routine, but I cannot find documentation on how to program the guts of this Arduino Uno?
What IDE do people use to do advanced things with their Arduinos? I am trying to use Atmel Studio 6 after I gave up using the Arduino IDE and now I'm trying to use Visual Micro plug-in for visual studio.
Suggestions?

You can do all you need to do in the Arduino IDE.  It doesn't "block" you from doing any low-level operations.  Any other IDE will also allow you to do what you want.
All the information you need to manipulate the "guts" of the Arduino is the datasheet for the main chip - the ATMega328P on the Uno.
http://www.atmel.com/images/atmel-8271-8-bit-avr-microcontroller-atmega48a-48pa-88a-88pa-168a-168pa-328-328p_datasheet.pdf

Ah yes. For some reason I thought my chip was an Atmega16U2, which doesn't have interrupt vector names for its interrupts in its documentation. The documentation for the 328P actually has everything. Thank you for making me realize my mistake.


text:
Why are LED's receiving different voltages connected to Arduino
I have four LED's all connected the exact same way to four pins via four 150OHM resistors. (ignore the sensors, they are doing nothing currently) The code is very simple in the loop:
  digitalWrite(blue1, HIGH);
  digitalWrite(green1, HIGH);

  digitalWrite(blue2, HIGH);
  digitalWrite(green2, HIGH);

Here's a photo of the setup, notice how the LED's all light up differently. They are receiving the following voltages from left to right (2.48, 1.72, 3.02, 2.15):

Why is this happening and how do I get them all to light up the same?

Note that, apart from the pinMode issue, blue and green LEDs are likely to have very different forward voltages and quite possibly also different brightness, so balancing their light output is going to be nontrivial anyway.

After trying another Arduino I realized the problem. I did not use pinMode in the setup for all of the pins. Darn.

Good point, I've been bitten by this mistake once and it took me quite some time to find out what mistake I had done.

Yep.  By writing to a digital pin that hasn't been specifically set to an output you are actually controlling the internal pullup resistor of the input pin.  That allows a small amount of current through, but not much (so a dim glow), and the actual resistor value varies wildly from pin to pin (they don't need to be accurate for pullups), so you get different (dim) brightnesses.


text:
Arduino EEPROMex library problem
I am trying to write a float value to the EEPROM on an Arduino MEGA2560. According to some research I should use Arduino EEPROMex library. I added the library to Arduino, but I get the message "EEPROM was not declared in this scope". How can I solve this problem or have you got any suggestions to do this?

Show us code...

It sounds like you've used the word EEPROM somewhere in your code without a function after it. As the first comment asks: CODE PLZ.


text:
Serial.println Sensor Value and text in one line
How do I put the sensor value and text on the one line in the serial monitor.
I just want Pot Value 30 to show in the serial console. What am I doing wrong?
Serial.println("POT value ")(sensorValue);

You just do two Serial prints:
Serial.print("POT value ");
Serial.println(sensorValue);

The .print prints without moving to a new line, the .println moves to a new line.
If you want to be more fancy and don't mind the processing and memory overhead, you can use snprintf to format the string:
char temp[15];
snprintf(temp, 15, "POT value %4d", sensorValue);
Serial.println(temp);

You can read more about sprintf and formatting here:

http://www.cplusplus.com/reference/cstdio/snprintf/ (function parameters)
http://www.cplusplus.com/reference/cstdio/printf/ (formatting options)

Note that there is no floating point support in the standard library for the Arduino - so you can't use %f etc.

Thanks Mate perfect, i have only just started on this. Thanks for your help it worked!


text:
Arduino Ethernet Shield 2 stuck on EthernetServer::begin()
I am currently trying to get the Ethernet Shield working on my Mega. I was trying to run the Webserver example but the program seems to stuck at one point, so I tried to start from scratch.
This is my test code:
#include <Ethernet.h>
#include <SPI.h>

byte mac[] = {
  0x90, 0xA2, 0xDA, 0x0F, 0xF6, 0x3D
};
byte subnet[] = { 255,0,0,0 };
byte gateway[] = { 2,0,0,1 };
IPAddress ip(2, 0, 0, 1);

EthernetServer server(80);

void setup() {
  Serial.begin(9600);
  Ethernet.begin(mac, ip, gateway, subnet);
  Serial.println("Ethernet started");
  server.begin();
  Serial.println("Server started");
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("Loop");
}

The output I get from the serial console is:
Etrted
Ethernet started

So I think the program gets stuck inside the EthernetServer::begin() function.
I am aware that there are earlier versions of ethernet shields which are not compatible to the mega, but the vendor of my shield says it is.
Also I don't understand, why it outputs the first line.
Thanks for your hints!

Ok, I had to make some hardware changes to fit the pin layout. Now the code works but the interface does not get the desired IP adress. Instead of putting out the right IP, the serial console only prints 255.255.255.255 or 0.0.0.0 randomly.
Any hints on that?

I now know that 0.0.0.0 occurs when pin 53 (SS, actual pin 10 on ethernet shield) is set to LOW and 255.255.255.255 occurs when pin 53 is set to HIGH (disable ethernet). In all cases, pin 4 (SD_CS) is set to HIGH to disable the SD card reader.

Just to get this answered (see comments): It was a weird "bug" in my case. After days of research I found people with the same issue and in their cases it helped to cut all of the pin headers but the ICSP header by 2mm so the ICSP header had better contact. I tried it on my shield and it worked.

You must use these libraries:
#include <Ethernet.h>  -->  #include <Ethernet2.h>
#include <EthernetUdp.h>  -->  #include <EthernetUdp2.h>

More info at this link Arduino Ethernet Shield2

// fill in your Domain Name Server address here:
IPAddress myDns(192,168,1,1);

// initialize the library instance:
EthernetClient client;

char server[] = "www.arduino.cc";

unsigned long lastConnectionTime = 0;
// last time you connected to the server, in milliseconds
boolean lastConnected = false;
// state of the connection last time through the main loop
const unsigned long postingInterval = 14*1000;
// delay between updates, in milliseconds

void setup() {
  pinMode (pin, OUTPUT);
  digitalWrite (pin, LOW);

  // start serial port:
  Serial.begin(9600);
  // give the ethernet module time to boot up:
  delay(1000);
  // start the Ethernet connection using a fixed IP address and DNS server:
  Ethernet.begin(mac, ip, myDns);
  // print the Ethernet board/shield's IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
}

void loop() {
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  if (client.available()) {
    Serial.println ("1"); delay(500);
    char c = client.read();
    Serial.print(c);
    } else {Serial.println ("11");delay (500);}
  // if there's no net connection, but there was one last time
  // through the loop, then stop the client:
  if (!client.connected() && lastConnected) {
    Serial.println(2); delay(500);
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
  } else {Serial.println ("22");delay (500);}

  // if you're not connected, and ten seconds have passed since
  // your last connection, then connect again and send data:
  if(!client.connected() && (millis() - lastConnectionTime > postingInterval)) {
    Serial.println(3); delay(500);
    httpRequest();
    Serial.println ("4");delay (100);
  } else {Serial.println ("33");delay (500);}
  // store the state of the connection for next time through
  // the loop:
  lastConnected = client.connected();
  Serial.println ("end loop");
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // if there's a successful connection:
  Serial.println ("httpRequest"); delay(500);
  if (client.connect(server, 80)) {
     Serial.println ("H1"); delay(500);
    Serial.println("connecting...");
    // send the HTTP PUT request:
    client.println("GET /latest.txt HTTP/1.1");
    client.println("Host: www.arduino.cc");
    client.println("User-Agent: arduino-ethernet");
    client.println("Connection: close");
    client.println();

    // note the time that the connection was made:
    lastConnectionTime = millis();
  } else {
    Serial.println ("H11"); delay(500);
    // if you couldn't make a connection:
    Serial.println("connection failed");
    Serial.println("disconnecting.");
    client.stop();
  }
}

I inserted debug lines.  all I get are the faileure "if" comments.  after 15 seconds, I get debug #3 and then "HTTP Request" then nothing but crickets....

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Adafruit motor shield 1 and Arduino Pro Mini
Can any one tell me how to connect Adafruit motor shield v 1.0 with Arduino Pro Mini 5v 8 Mhz. Motor shield uses which pins as I want to replace my Arduino UNO to Pro Mini and need re-wiring. Tried it using jumper cables but did not work. Please help...

Product page here
Manual here
Larger version of schematic here
Schematic:

Providing links to ALL relevant gear would help. If it did not work "stand alone" with jumpers (eg NO Arduino) then you do not understand the shield pinouts.


text:
control Arduino board using Android sensors and wifi?
i am thinking about building a Quadcopter that can be controlled with a computer via Wifi . but the problem is that with a lack of components and limited resources , i have been thinking of using my available components ( Arduino uno + smart phone + quadcopter frame with 4 brush-less motors and 4 speed control )
so i am asking you guys if it is possible to read smartphone sensor values using Arduino usb and control the quadcopter using smartphone wifi ??

Is it possible?  Yes, it's certainly possible.  You can read the sensor values from within an Android program. It's possible to get Android to communicate with the Arduino through the USB.  The Arduino can be programmed to respond to what it gets through the serial.
Is it easy? Well, that depends on how good you are at Android programming.
One good place to start might be the ArduinoFirmata-Android project.  Don't worry about programming the Arduino, just install Firmata on it.  Then it's all down to how you program the Android device.  The Arduino just becomes a peripheral to your phone.

it looks a little bit complicated , in addition i dont have so much knowledge about android programming !!! is there any other more simpler method ?

Yes there is. It's called "buying the right components".

Thank you for your help @Majenko . I think i have to start learning android  programming .