text:
Simple compiler design help: Variable length arrays in Arduino?
I'm trying to write a simple compiler in the Arduino language that I am making up for my lab.  The compiler will have to be able to turn a string like this:
"do command_one 3 times"

into a data structure that represents this:
<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:
"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.
These examples show all of the functionality that I would want from the compiler.
I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in Arduino need to be initialized with a length, this could be a problem.
I am not fluent in Arduino so I am hoping that an Arduino whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.
You will also notice that I posted the same question in the C++ stackexchange.  I am trying to write the same code for an Arduino and in C++.  I know that Arduino code is based on C++, if the answer is the same in Arduino as it is in C++ that would be very helpful.

Arduino has full c++ language support, but does not have the standard library, so if your c++ answer is "use std::vector" you will need to find or write a separate vector implementation. Outside of implementation, the answers should be the same.

That's the only answer I've gotten so far.  If that continues to be the only answer then I'll have to find something else for the Arduino

Do you want to run your compiler on the Arduino ? That seems a bit odd.

Yes I do.  I want to be able to insert an SD card with the code and I want the arduino to compile it.

Posting the same question on multiple sites is not permitted.  Arduino is C++, but beware you have fairly extreme memory limitations.  Ordinarily one would want to do any compiling on the device where the text is being provided, and put only the distilled result into the limited resources of the traditional Arduino board.

Do you want the arduino to run the code afterward? You can't edit code memory while running on an AVR. What you may want instead is to write a very simple interpreter for some language you write to the SD card.

If you want to compile and run code from Arduino to Arduono, then the answer is simple: you can't. What you can potentially do however is parse a command line and get a series of lower-level instructions (a kind of bytecode like in Java) and then interpret them. But that's quite complex work, though.

I'm curious now: does Arduino support dynamic memory allocation with pointers like in standard C++?

@jfpoilpret, I don’t think the answer is that clear cut: First, every Arduino boot loader can and does modify program memory. Second, a compiler could compile to byte code in RAM, instead of machine code.

@AnnonomusPenguin yes it does, but because RAM is so scarce, the use of dynamic allocation is extremely rare. I think there might be only a single malloc in all Arduino libraries: https://github.com/arduino/Arduino/blob/3a8ad75bcef5932cfc81c4746a87ddbdbd7e6402/libraries/SD/File.cpp

@microtherion only code in the bootloader are can write code to the rest of the Flash (I think there are some ugly tricks to work around that but it is NOT advised, event by Atmel I believe). Regarding intermediate bytecode writing to SRAM, actually this is exactly what I was saying!

@microtherion, there are more locations in Arduino libraries that use dynamic allocation, the first that comes to my mind is String, which is why I avoid using String like the plague.

@jfpoilpret sorry about the byte code thing. Should not post when fatigued. I believe you're right about the bootloader restriction, but who says a compiler can't live (at least in part) in the bootloader section. Besides, OP was talking about Arduino Due, to which rather different rules may apply.

You may have more luck investigating standard C ways of dealing with this issue, instead of the common C++ methods.
Although it is typically not advised, you can use malloc and free on the Arduino. This allows you to dynamically use memory. I would provide a more detailed code example than below but when using dynamic memory it can be hard to troubleshoot what is going on without the use of a library to simplify the process. I would strongly advise doing a little study and understanding both dynamic memory management, and the repercussions of doing so on the Arduino platform. A solid foundation in this will pay off tenfold in time saved when debugging.
Note that you should check each time that you call malloc that it is successful
These resources might help:

Dynamic Arrays
Check Malloc Succeded
Malloc and Free on Arduino Discussion
Is it a bad idea?

Simple Example:
// Make a pointer to your array
someType *A;

// The size of your array, may be changed programmatically.
int arraySize = 5;

// Reserve memory for your array.
A = malloc(arraySize * sizeof(someType));

// Use Array
A[0] = someData;

// Release A's memory when complete.
free(A);

The Arduino IDE features nearly full C++ language support (at least for C++03 features).
library support is limited, but any standard component you need, you should be able to get an open source implementation that compiles.
That said, you have 2K of RAM to work with on an Arduino, so the kind of C++ code you would write for a general purpose computer just won’t get you very far.
I could be wrong, but I very much doubt there are full Python implementations for Arduino.

Edit: Thanks to Mr. Penguin for pointing out that we’re dealing with an Arduino Due, not an Uno (I had overlooked the OP’s tag). 96K of memory is actually a decent amount to play with, so grab a library implementation like this one and use the C++ techniques you wish to use.

You have 96 KB of RAM on the Due if I remember right, 2K is on the Uno. That still doesn't make it better...

You probably also have hardware capability to execute-from-ram.  It really changes the whole story.

You question isn't totally clear to me, so this is just a pile of advice:

I think that you might be looking for a run() type of command, where you can run any function in code. However, since C++ is a compiled language, this is not possible. You can only do this in scripting languages.
Besides that, you want a variable length array? I haven't been able to confirm that this works with Arduino, but I know in standard C++ it is called dynamic memory allocation and you can do this with a pointer.
As for the string to store your data, where you're heading is wrong if you care about efficiency. I'd go with an array of integers (unsigned int myData[2] = {1, 290};) since you can store a lot more data in two bytes than you could typing out the function names.

For the "multiple run" function of your language, a simple for loop might work better to save space:
for(int x = 5; x <3; x++) {
  //Code here
}

Another thing you might want to do is store this "code" on a SD card encoded in two characters to yield a number like this:
byte valOne = SD.read();
byte valTwo = SD.read();
int outputVal = (valOne << 8) + valTwo;

This would solve the whole variable array crisis in the first place.
End of unorganized thoughts...

For a while, "New" wasn't implemented, but it is now. "malloc" and "free" and the like have always been available on arduino for dynamic memory management. I don't use it often because with such a small amount of RAM I'm always worried about memory fragmentation, but I have used it.

@Brett nice to know! The OP is using a Due, so RAM should be sufficient for most cases.


text:
How do you wire a ssr relay to a arduino nano
I am trying to wire a fss1-102z 5v ssr relay to my arduino nano but i cant get it to work here is my circuit. It stays stuck on and i cant get it to turn off.

Bluetooth control code
char val;         // variable to receive data from the serial port
int ledpin = 2;  // LED connected to pin 2 (on-board LED)

void setup()
{
  pinMode(ledpin = 2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin = 3, OUTPUT); // pin 3 (on-board LED) as OUTPUT

    Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
    ;
  }
  val = Serial.read();         // read it and store it in 'val'

  if( val == 'a' )               // if 'a' was received led 2 is switched off
  {
    digitalWrite(ledpin = 2, HIGH);    // turn Off pin 2
  }

  if( val == 'A' )               // if 'A' was received led 2 on
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
  }

  if( val == 'b' )               // if 'b' was received led 3 is switched off
  {
    digitalWrite(ledpin = 3, HIGH);    // turn Off pin 3
  }

  if( val == 'B' )               // if 'B' was received led 3 on
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
  } //else (ledpin = 3, LOW)        //set led pin 3 to low state

  if( val == 'C' )               // if 'C' was received led 2 on for 1 second
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'D' )               // if 'D' was received led 3 on for 1 second
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin, HIGH);      // turn Off pin 3
  }

  if( val == 'E' )               // if 'E' was received led 2 on for 5 seconds
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'F' )               // if 'F' was received led 3 on for 5 seconds
  {
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin, HIGH);       // turn Off pin 3
  }

  if( val == 'G' )               // if 'G' was received turn led pin 2 on for 500ms then switch off and turn on pin 3 for 500 mili seconds then off
  {
    digitalWrite(ledpin = 2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin, HIGH);      // turn Off pin 2
  }

  if( val == 'h' )               // if 'h' was received switch off all pins
  {
    digitalWrite(ledpin = 13, LOW);    // turn Off pin 13
    digitalWrite(ledpin = 2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin = 3, HIGH);      // turn Off pin 3
}

  if( val == 'H' )               // if 'H' was received switch pin 2 on and off 1000 times

  for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin = 2, HIGH);  // turn ON pin 2
   delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin = 2, LOW);  // turn Off pin 2
   delay (1000); //wait 1000 mili seconds

  }

}

According to its datasheet, the FSS1-102Z doesn't work with DC-voltage. Also the minimal voltage required is 50VAC. Here is the excerpt from the datasheet:

@jfpoilpret So when i hook it up to a 240v 80w pump it will work fine?

Yes, 240V AC will work with this SSR (just be careful). 80 Watts is around 0.4A, so well below the maximum 2A rating.

@jfpoilpret Should i put a diode on the input to stop current back-flow or is that only needed with coil relays?

It's Photo Isolated, so a diode isn't needed. Though I find it kind of strange that there is a coiled-relay, inside a solid state relay. Solid state generally means there are no moving parts. Most SSRs use triacs, I think.

so i can just wire it like in the image but to a 240v load?

Yes, the FSS1 has an input impedance of 470 Ohm, which will limit the current to 15mA max (well below the 40mA limit of the arduino). So you can just wire it directly to ground and a digital pin.

Is it really 5v relay?
Need your code.
Check your output is really 5v.

You do a lot of mistakes:
Int ledPin2=2;
Int ledPin3=3;
...
pinMode(ledPin2,OUTPUT);
pinMode(ledPin3,OUTPUT);
...
digitalWrite(ledPin2,HIGH);

I am on way now. I will edit and my answer when get back. Now correct your code
EDIT
You should improve your code... I edited it with switch cases. Also edit your comments because they are wrong!!! In the end there is Serial.printout states of pins. If you want uncomment them.
Here is the edited code:
char val;         // variable to receive data from the serial port
int ledpin2 = 2, ledpin3 = 3, ledpin13 = 13;  // LED connected to pin 2 (on-board LED)
bool status = true;

void setup()
{
  pinMode(ledpin2, OUTPUT); // pin 2 (on-board LED) as OUTPUT
  pinMode(ledpin3, OUTPUT); // pin 3 (on-board LED) as OUTPUT
  pinMode(ledpin13, OUTPUT);
  Serial.begin(9600);       // start serial communication at 115200bps

}

void loop()

{
  if( Serial.available() )       // if data is available to read
  {
  val = Serial.read();         // read it and store it in 'val'
  switch (val){
    case 'a':
    digitalWrite(ledpin2, HIGH);    // turn ON pin 2
    status = true;
    break;

    case 'A':
    digitalWrite(ledpin2, LOW);
    status = true;
    break;

    case 'b':
    digitalWrite(ledpin3, HIGH);
    status = true;
    break;

    case 'B':
    digitalWrite(ledpin3, LOW);
    status = true;
    break;

    case 'C':
    digitalWrite(ledpin2, LOW);  // turn OFF pin 2
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin2, HIGH);      // turn ON pin 2
    status = true;
    break;

    case 'D':
    digitalWrite(ledpin3, LOW);  // turn OFF pin 3
    delay(1000);                     // wait 1 second
    digitalWrite(ledpin3, HIGH);      // turn ON pin 3
    status = true;
    break;

    case 'E':
    digitalWrite(ledpin2, LOW);       // turn OFF pin 2
    delay(5000);                      // wait 500 milli seconds
    digitalWrite(ledpin2, HIGH);      // turn ON pin 2
    status = true;
    break;

    case 'F':
    digitalWrite(ledpin3, LOW);  // turn ON pin 3
    delay(5000);                     // wait 500 milli seconds
    digitalWrite(ledpin3, HIGH);       // turn Off pin 3
    status = true;
    break;

    case 'G':
    digitalWrite(ledpin2, LOW);  // turn ON pin 2
    delay(500);                     // wait 500mili second
    digitalWrite(ledpin2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin3, LOW);  // turn ON pin 2
    delay(500);                     // wait 500 mili second
    digitalWrite(ledpin3, HIGH);      // turn Off pin 2
    status = true;
    break;

    case 'h':
    digitalWrite(ledpin13, LOW);    // turn Off pin 13
    digitalWrite(ledpin2, HIGH);      // turn Off pin 2
    digitalWrite(ledpin3, HIGH);      // turn Off pin 3
    status = true;
    break;

    case 'H':
    for(int i = 0; i < 1000; i++)
  {
    digitalWrite(ledpin2, HIGH);  // turn ON pin 2
    delay (1000); //wait 1000 mili seconds
    digitalWrite(ledpin2, LOW);  // turn Off pin 2
    delay (1000); //wait 1000 mili seconds
  }
  status = true;
    break;
  }
  }

  /* Print out state of pin */
  /*
  if (status) {
   Serial.print("ledpin2 = ");
   Serial.print(bitRead(PORTD,2));
   Serial.print(" ,ledpin3 = ");
   Serial.print(bitRead(PORTD,3));
   Serial.print(" ,ledpin13 = ");
   Serial.println(bitRead(PORTD,7));
   status = false;
  }*/
}

source: Stack Exchange

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

sort: votes


text:
Adjust resistance of a circuit
I need to emulate a component that measures an input mechanically and varies resistance from 0 to infinity (a more detailed set of specs list it at 20-1,000ohms, though I'll have to actually check its true values myself once I have physical access to it).
My aim is to replace this troublesome mechanical component with a current (read as available and serviceable) component, and convert the signal from the new component into an emulated signal (varying resistance) from the old component.
I am not certain as to the resolution required (how big the steps can be), though it may be able to handle 50ohm 'leaps', just judging by the range of mechanical movement and my past experience with replacing similar mechanical systems with ready-made kits for conversions.  I'd like to smooth the curve a whole lot more than 50ohm leaps though.
I have barely an idea where to begin on this.  I thought maybe a resistor ladder and a set of transistors triggered by the arduino to connect into the different points in the line, though I suspect there has to be a better way to achieve a much better result (and I don't think I have enough outputs for that anyway).
Is there a digital component that can vary its resistance using a PWM signal or maybe an analog signal from an arduino?
FYI, I greatly appreciate your input.
EDIT
The controller provides a constant voltage to the component, and the controller then looks at the ground (the voltage over a static resistor) I presume. It is an actual load.
I may be able to provide a variable voltage to the controller on its ground pin, though I have never seen that done on them before. I think that may be the trick, though the controller may(??) dislike it? I can try that.. The next best thing (only 2nd because it requires more components) would be the digital pot.
Anyone ever forged a return signal on a circuit thats supposed to supply its own constant voltage to a resistor type sensor?

The idea of using a servo to move a potentiometer came up, and that doesn't work because it cannot keep up (its too slow).

How is the resistance being used? is it an actual load?

Does your system really need a variable resistor, or is the variable resistor only used to generate a variable voltage. If the latter, you could just use a digital DAC.

What about a digital potentiometer
Digital Pot
Many types available, generally controlled via a serial interface e.g SPI

A JFET can act as a voltage-controlled resistor. It will need additional components if you require precision (a shunt resistor and a couple of op amps come to mind), but it should do. JFETs are rarer than they used to be, but still should be available for a few decades.

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


text:
I can't scroll Arduino IDE's example & scketch lists down
I have Arduino IDE 1.0.5 in win7 x64. I have so many library units. A pity that I can't scroll down to my other options. Is it Arduino.exe's problem or something else? How can I add triangle to scroll down and scroll up to see whole Sketchbook and Examples list? Thanks.

Try using 1.5.+. It has scroll arrows to allow larger lists of menus, bigger than the screen.
I find that most, if not all, sketches work equally well, if not better.
Up to 1.5.6r2 uses the same version of compiler as 1.0.+'s. 1.5.7 and newer uses a new compiler, that is more sctrict. All stock libraries work. And well written 3rd parties work. I personally use 1.5 and test backwards to 1.0.
There is a fork of 1.0 called ERW that has the scrolling. But 8t is becoming obsolete.

I downloaded this: http://forum.arduino.cc/index.php?topic=118440.435 And your answer is also good to me. Thanks.

You can get to the examples in Explorer. Just go to My Documents\ Arduino\ libraries\ <library-name>\ examples.
This one made me chuckle. Thank you for sharing.

Yes I know this way but I need two triangle to down the list. Thank you for your answer but I didn't want this.


text:
Hub RFID Arduino + WIFI
I will start an Arduino project and its main requirement is that some RFID readers (at most 6 readers) be connected and controled by the arduino board.
I do not have a strong background in eletronics, and therefore I do not have any idea in how to start it. Is it possible to connect more than one RFID reader to an Arduino board? If it is possible, which reader is the best for this porpouse?
Another requirement of this project is the need to send the data collected by each RFID reader to a PC server through WIFI. For this what is better to use, an Arduino UNO with a WIFI shield or an Arduino YUN? What is better and why?
Thanks!!!

Which RFID reader will you use? Depending on model a different amount of pins are used (from 1 to 3 at least). So if you choose a reader that only requires 1 pin you might be able to connect all 6 to one arduino. Another question is how far apart these should be? If very far it might not be feasable anyways, and easier to use multiple arduinis... As you say that each reader should send its data over wifi. Then instead of putting cables for each RFID to a central Arduino, just put down Ethernet cable and use a standard Ethernet module and multiple arduinis to send the data to a PC.

I have not decided yet which RFID reader I will use. Can you sugest anyone? The idea is build a smart table that can recognize tagged objets over it, thus I think that the distance is not more than 1 meter between each reader and the Arduino. If required more than one Arduino the project is not be feasible. WIFI is a primary requirement, the client do not want data cables from table to a PC, all data collected by the RFID reader must be sent through WIFI.

Ok, then it wouldnt be a problem to connect multiple rfid readers to one arduino I guess, if the library allows this. I cannot recommend any reader, as I have just bought a simple one from ebay, but havent tried it yet, so I really cant comment on functionality either. I'll have to get back to you when I have tried this out...


text:
What does the line "while (! Serial);" do in an Arduino program?
I'm new to Arduino, and I am trying a couple of tutorials. What does this line do in a program?
while (! Serial);

On boards with an FT232 chip or other USB->Serial bridge chip (Uno, Mega, etc) it does absolutely nothing.
On boards with a direct USB connection, such as the Leonardo or the Yùn it waits for an active serial connection to be established by the PC (i.e., for the serial port to be opened by a piece of software).
When you open the serial port of a board like the Uno or Mega the whole board usually resets*, so opening the serial port allows you to see the first bits of the serial data.  On the Leonardo etc it doesn't reset when you open the serial, so any serial output during the setup() function would be missed.  Adding that line makes the board pause until you open the serial port, so you get to see that initial bit of data.
*) Unless you specifically write some software that doesn't assert DTR when you open the port

Strictly "When you open the serial port of a board like the Uno or Mega the whole board resets," is not correct. The Arduino's IDE does that by default. However, simply opening the serial port from the USB host PC does not reset the ATmega. I've written code that opens a serial connection over USB from the host, and it doesn't reset the ATmega.

Actually, it is both OS and driver dependant, not just down to the software that does the port opening.

The arduino resets when it gets the DTR signal. It is transmitted by default whenever I open a connection from anywhere, not just arduino's IDE.

In some OSses it's possible to open the serial without asserting DTR. In others it's possible to configure a port to not assert DTR when opened, but only after it's been opened once. By default, as mentioned, the IDE always explicitly asserts DTR.

I believe it is possible to open an FTDI SUB/Serial without asserting DTR on Windows, OS X, and Linux, because I've done it. It is optional. So please update the answer, either say that when the IDE opens the serial port the board is reset, or that opening the serial monitor resets it, or that opening the serial port usually resets the board. I don't mind which is chosen. However the current answer is not accurate.

@BrettM - which OS?

On Linux you have to open the port first in order to set the port to not assert DTR. That first opening will always reset the board regardless.

Note that if that line is in your sketch, you are using a 32u4 or M0 or similar chip with built-in USB support, and you are trying to run without being connected to a host via USB, your sketch will hang forever waiting for Serial to be ready. This is a common problem: "Sketch runs when connected to PC, but not when unconnected".


text:
Cannot send two arguments from a WebClient
I am using the Arduino WifiWebClient to insert records into a RoR (Ruby on Rails) app. It works but it only inserts one field regardless of the number of arguments I send.
For example, if I test with Curl
curl -d "sale[itemId]=1234&sale[machineId]=4567"  http://myapp.herokuapp.com/sales

It will create a Sale record and populate both fields itemId and machineId. Everything OK.
But when I send the following instruction from the Arduino, it will only populate the first field:
(I am only including the POST method to simplifly the code, the rest of the code is similar to http://arduino.cc/en/Reference/WiFiClient)
void sendPOST() //client function to send/receive POST request data.
{
if (client.connect(URL,PORT)) {  //starts client connection, checks for connection
Serial.println("connected");

Serial.println("POST /sales HTTP/1.1"); //download text
Serial.println("From: Arduino1");
Serial.println("Host: evening-sierra-3769.herokuapp.com");
Serial.println("User-Agent: HTTPTool/1.1");
Serial.println("Connection: close");
Serial.println("Cache-Control : no-cache");
Serial.println("Pragma: no-cache");
Serial.println("Expires: -1");
Serial.println("Content-Type: application/x-www-form-urlencoded");
Serial.print("Content-Length: ");
Serial.println(31);
Serial.println();
Serial.println("sale[machineId]=\"09876543211234\"");
Serial.println("sale[itemId]=\"09876543211234\"");
Serial.println();

client.println("POST /sales HTTP/1.1"); //download text
client.println("From: Arduino1");
client.println("Host: evening-sierra-3769.herokuapp.com");  // Will be needed if apache is configured for VHOSTS
client.println("User-Agent: HTTPTool/1.1");
client.println("Connection: close");
client.println("Cache-Control : no-cache");
client.println("Pragma: no-cache");
client.println("Expires: -1");
client.println("Content-Type: application/x-www-form-urlencoded");
client.print("Content-Length: ");
client.println(31);
client.println();
client.println("sale[machineId]=09876543211234\r\n");
client.println("sale[itemId]=09876543211234\r\n");
client.println();

Serial.println("ARDUINO: HTTP message sent");
delay(3000);
if(client.available())
{
  Serial.println("ARDUINO: HTTP message received");
  Serial.println("ARDUINO: printing received headers and script response...\n");

  while(client.available())
  {
    char c = client.read();
    Serial.print(c);
  }
}
else
{
  Serial.println("ARDUINO: no response received / no response received in time");
}

client.stop();
}

31 is not the right content-length for the whole content you try to post. It only includes the first line.

Solved!
Changed the following lines:
client.println("Content-Type: multipart/form-data");
client.print("Content-Length: ");
client.println(63);
client.println();
client.println("sale[itemId]=123456789012341234&sale[machineId]=123456789012341234\r\n");
client.println();


text:
tone() and PWM limits
I'm developing an active sonar using Costas arrays and Golomb rulers. I need the Arduino to switch between frequencies very quickly to shorten the length of the ping, both to improve processing and to lessen speed of sound limitations. I also need to know the exact times each frequency will be released from the Arduino so the real time computer can ignore those frequencies.
I'm able to generate the melodies I want using the tone() command, but I couldn't find the time required to change frequencies or the standard deviation of that time. I'm also not sure what the minimum length of PWM is.
So I want to know, what is:

The switching time for changing PWM frequencies
The standard deviation of that switching time
The minimum length PWM pulse that can be generated
The standard deviation of the length of that minimum PWM pulse.

And how might I achieve those minimums?

1,2; You could be able to change the frequency in something like 4 instructions, but tone has quite a bit of overhead. But it should still be pretty fast. Though you could write your own optimize code, setting the prescaler and OCRx registers. 3; Highest frequency is something like half of 16Mhz, so 8Mhz. Maybe even higher using PLL.

The number of instructions does not equal the switcing time... well, maybe if they're assembly instructions, but even then, the hardware has to react to the cpu. And highest frequency doesn't necessarily equal the minimum length PWM, that would be the period; if I can stop generating PWM after less than one wavelength, then the PWM's length is smaller than the wavelength, and same if I have to wait more than one wavelength to stop it.

In PWM, Phase Correct mode you can update the OCRA and OCRB values while it is running. It will buffer those values and only update them and the end on the "cycle". That way no "half-tone" is ever generated. Since you are talking about tone generation I was assuming 50% duty cycle. Or did you mean duty cycle when you said minimum length PWM?

Yeah, 50% duty cycle is correct. So the minimum length of PWM is almost exactly its period?

If you pre-calculate the values you need, and arm an interrupt to change on the next edge, then for anything up to a few hundred KHz you should be able to load the new values into the registers before that count is reached, yielding the fastest frequency change theoretically possible with a rectangular waveform.  It's been a while since I looked at the details, but you may need to pre-load the total count register during the the cycle preceding the one in which you want to change it.  For better results, one would think you would want a sinusoidal synthesizer.


text:
IRremote library and Moteino
Does somebody know if the IRremote library is compatible with Moteino boards?
If not, do you know a cheap solution to build a IR-remote controllable via wireless?

Yes, the moteino is just an UNO clone using the same ATMega328P microcontroller.

You need two spare digital pins to use the IR-library. These pins can be set to whatever you like. Pins D3 to D7 are free on the Moteino so the library will be OK to use if you connect the IR LED and receiver to two of those pins.

Your Arduino do not need to be wireless to be able to control it wirelessly.
If you have a wireless network at home (which most people do), there is usally some ethernet RJ45 ports as well.
So instead you use a very cheap ENC28J60 to connect your arduino to the network. You can then access your Arduino wirelessly through your home router. As long as it is connected to your local network its should work.
As for connecting the IR sender and reciever, you need as said before, one digital pin for recieving IR-signals and one digital pin for sending. Which should be no problem even when adding the ENC28J60. It should also work very well with the Moteino if you choose to go that way.


text:
How to sense snow and ice?
We are building an outdoor snow melting system for the pavement. It would be nice if it could turn on itself only when it is needed: if there is snow, ice in the surface or the pavement is wet and the temperature is below the freezing point. Is there a good way to detect if the surface of something is snowy, icy or wet?

If the pavement is black, you could detect snow by infrared reflectivity. You might detect wet by resistivity. That leaves ice. Reflectivity might work there, too, at a different threshold. You'd need to experiment.
Another possibility might be a short-range sonar. If the measured distance changes, something is there. Ice would probably read as nearer. You'd probably need to average a number of measurements to increase the measurement resolution; you care about very thin ice coatings. Snow might well read as no return - but again, experiment.
A combination of the reflectivity and sonar might be the most reliable.

I may experiment with a simple photocell used to turn lights on or off, and a light source for night time.  Mount the photocell so that its lens is upwards towards the sky, at night you'd need a light source shining on the photocell, I'm thinking a very low wattage led light to reduce power consumption, or even another photocell or astronomical time clock to turn the light source on or off, depending on how complex you'd want to make it.  When the photocell can no longer detect light you know it is covered.  You'd have to experiment with the opaqueness of the snow, and how much coverage would block out the light.  Seems like a cheap, easy, pretty much "out of the box" solution for snow anyway.

cheap video camera with snow detection software. See this article for a start

Please summarize the linked content because if it goes down your answer will loose its value.

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


text:
Importance of resistor
I'm new to Arduino and also new to electronics. I'm following the tutorial here. I'm not understanding the importance of the resistor in this schematic diagram. Can someone please help me on this?

Maybe the author meant removing the resistor, not replacing it with a wire?

That resistor, where positioned, is called a pull-down resistor, and if replaced by a straight wire, that circuit would short out when the switch was closed.
The purpose of this is that when a digital input pin is not connected, it floats, and if the switch were open that pin could see upwards of 2v floating value from external and internal noise. With Digital circuitry, any value in this float range can be invalid and return invalid results.
A pull down resistor will generally have a very high ohmic value >5kohm, as to allow as little current pass as possible. Here, you are shorting the pin to ground through the resistor so it will not have a LOW value when the switch is open, instead of possibly invalid.
When the switch is closed, you will have 5v passing through switch into the pin, to be read as a HIGH value, also sending 5v across a 10k or so resistor to ground, consuming only .5mA of current.
It you want to see what I mean by a floating value, debug the output of any analog pin with a wire going nowhere, and watch as the value changes. Try touching the wire, now add a pull down to ground, or try pulling it up to 5v and observe the behavior.
Happy Arduinoing!

Without the resistor, closing the switch would connect the positive supply directly to the negative supply. This would cause the voltage across all digital components in the circuit to drop close to 0V, crashing the whole thing.

so,it's what we call short circuit if i'm not wrong?

It would cause a short circuit across the power supply, yes.

In the above circuit there are several other resistances that are being ignored for simplicity and because most of them are extremely tiny. However, one of the resistances is significant, and that it the internal resistance of the power supply.
Without the resistor shown in the schematic, the internal resistance of the battery becomes the most significant resistance in the circuit and the voltage measure at D2 would remain near zero when the switch is closed and very near zero when the switch is opened.
If the resistor shown were several thousand ohms or greater, the voltage at D2 would measure close to 5 volts when the switch is closed and zero when the switch is open (however D2 will be subject to picking up any nearby static electricity or strong electromagnetic fields when the switch is open).
To prevent D2 from being subject to spurious noise, resistors are often used between signal points and ground to dampen any such undesired noise. To better imagine how this works, imagine a 100 megohm resistor connected to D2 with the other end hanging out into the air. The unconnected end of the large resistor is acting like an antenna picking up any possible noise in the vicinity. Because the resistor shown in the diagram is so much smaller then the imaginary resistor, the noise will seem to be shorted out to ground in comparison.
In a very real sense, this schematic is telling you to add in a known resistor to ground or suffer from the effects of all the resistors not show; some being very very high resistance and some being nearly non-existent.

Why the down vote... +1 to rectify

Ohnose! That was supposed to be an up... And now it is locked in. Make a quick edit and I can up it ;D

Vote fixed. (and more letters)

Check out the internal pull-up resistor (disconnected by default) for Arduino as well. Save yourself wiring up an extra resistor.
pinMode(5, INPUT_PULLUP); // Enable internal pull-up resistor on pin 5

From SparkFun: Pull-up Resistors


text:
PROGMEM: do I have to copy data from flash to RAM for reading?
I have got some difficulties understanding the memory management.
Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory. I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture. I want to make use from that to make my UI menu on a LCD possible.
But I'm bewildered by those instructions to just read and print data from program memory:
strcpy_P(buffer, (char*)pgm_read_word(&(string_table[i]))); // Necessary casts and dereferencing, just copy.
    Serial.println( buffer );

Why on earth do I have to copy the damn content to RAM before accessing it? And if this is true, what happens to all the code then? Is it also loaded to RAM before execution? How is the code (32kiB) handled then with only 2kiB RAM? Where are those little goblins carrying floppy disks?
And even more interesting: What happens to literal constants like in this expression:
a = 5*(10+7)

are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

A global variable is loaded into memory, and is never released from it. The code above only copies the data to memory when needed, and releases it when done. Also note that the code above only reads one byte from the string_table array. That array might be 20KB, and would never fit in memory (even temporarily). You can however load just one index using the above method.

@Gerben: This is a real drawback on global variables, I did not take this into account yet. I get some headache now. And the code snippet was just an example from the documentation. I refrained to program sth. myself before having clarification about the concepts. But I've got some insight now. Thanks!

I found the documentation somewhat confusing when I first read it. Try looking at some real life examples too (like e.g. a library).

AVR is a modified Harvard architecture family, so code is stored in flash only, whereas data exists primarily in RAM when being manipulated.
With that in mind, let's address your questions.

Why on earth do I have to copy the damn content to RAM before accessing it?

You don't need to per se, but by default code assumes that data is in RAM unless the code is modified to specifically look in flash for it (such as with strcpy_P()).

And if this is true, what happens to all the code then? Is it also loaded to RAM before execution?

Nope. Harvard architecture. See the Wikipedia page for the full details.

How is the code (32kiB) handled then with only 2kiB RAM?

The preamble generated by the compiler copies the data that should be modifiable/modified into SRAM before running the actual program.

Where are those little goblins carrying floppy disks?

Dunno. But if you happen to see them then there's nothing I can do to help.

... are 5, 10 and 7 really copied to RAM before loading them into registers?

Nah. The compiler evaluates the expression at compile time. Whatever else happens depends on the lines of code around it.

Ok, I did not know AVR was harvard. But I'm familiar with that concept. The goblins aside, I think I know when to use those copy functions now. I have to restrict use of PROGMEM to data which is rarely used to save CPU cycles.

Or modify your code to use it directly from flash.

But how would this code look like? let's say I have several arrays of uint8_t representing strings I want to put onto a LCD display via SPI. const uint8_t test1[5]= { 0x54, 0x65, 0x73, 0x74, 0x31 }; const uint8_t bla[9]= { 0x62, 0x6c, 0x61, 0x62, 0x6c, 0x61, 0x62, 0x6c, 0x62 }; const uint8_t Menu[4]= { 0x3d, 0x65, 0x6e, 0x75}; how do I bring this data to flash and later on into the SPI.transfer() function, which takes one uint8_t per call.

http://www.nongnu.org/avr-libc/user-manual/pgmspace.html

This is how Print::print prints from program memory in the Arduino library:
size_t Print::print(const __FlashStringHelper *ifsh)
{
  const char PROGMEM *p = (const char PROGMEM *)ifsh;
  size_t n = 0;
  while (1) {
    unsigned char c = pgm_read_byte(p++);
    if (c == 0) break;
    n += write(c);
  }
  return n;
}

__FlashStringHelper* is an empty class that allows for overloaded functions like print to differentiate a pointer to program memory from one to normal memory, as both are seen as const char* by the compiler (see https://stackoverflow.com/questions/16597437/arduino-f-what-does-it-actually-do)
So you could overload the print function for your LCD display so that it takes a __FlashStringHelper* argument, lets call it LCD::print, and then use lcd.print(F("this is a string in progmem"));' to call it.F()` is a macro that ensures the string is in program memory.
To predefine the string  (to be compatible with built-in Arduino print) I have used:
const char firmware_version_s[] PROGMEM = {"1.0.2"};
__FlashStringHelper* firmware_version = (__FlashStringHelper*) firmware_version_s;
...
Serial.println(firmware_version);

I think an alternative would be something like
size_t LCD::print_from_flash(const char *pgms)
{
  const char PROGMEM *p = (const char PROGMEM *) pgms;
  size_t n = 0;
  while (1) {
    unsigned char c = pgm_read_byte(p++);
    if (c == 0) break;
    n += write(c);
  }
  return n;
}

which would avoid the __FlashStringHelper cast.

Arduino documentation says, it is possible to keep constants like strings or whatever I don't want to change during runtime in program memory.

All constants are initially in program memory. Where else would they be when the power is off?

I think of it as embedded somewhere in the code segment, which must be fairly possible inside a von-Neumann-architecture.

It's actually Harvard architecture.

Why on earth do I have to copy the damn content to RAM before accessing it?

You don't. In fact there is a hardware instruction (LPM - Load Program Memory) which moves data directly from program memory into a register.
I have an example of this technique in Arduino Uno output to VGA monitor. In that code there is a bitmapped font stored in program memory. It is read from that on-the-fly and copied to the output like this:
  // blit pixel data to screen
  while (i--)
    UDR0 = pgm_read_byte (linePtr + (* messagePtr++));

A disassembly of those lines shows (in part):
  f1a:  e4 91           lpm r30, Z+
  f1c:  e0 93 c6 00     sts 0x00C6, r30

You can see that a byte of program memory was copied into R30, and then immediately stored into the USART register UDR0. No RAM involved.

However there is a complexity. For normal strings the compiler expects to find data in RAM not PROGMEM. They are different address spaces, and therefore 0x200 in RAM is something different from 0x200 in PROGMEM. Thus the compiler goes to the trouble of copying constants (like strings) into RAM at program startup, so it doesn't have to worry about knowing the difference later on.

How is the code (32kiB) handled then with only 2kiB RAM?

Good question. You won't get away with having more than 2 KB of constant strings, because there won't be room to copy them all.
That's why people who are writing things like menus and other wordy stuff, take extra steps to give the strings the PROGMEM attribute, which disables them being copied into RAM.

But I'm bewildered by those instructions to just read and print data from program memory:

If you add the PROGMEM attribute you have to take steps to let the compiler know that these strings are in a different address space. Making a complete (temporary) copy is one way. Or just print directly from PROGMEM, a byte at a time. An example of that is:
// Print a string from Program Memory directly to save RAM
void printProgStr (const char * str)
{
  char c;
  if (!str)
    return;
  while ((c = pgm_read_byte(str++)))
    Serial.print (c);
} // end of printProgStr

If you pass this function a pointer to a string in PROGMEM, it does the "special read" (pgm_read_byte) to pull the data from PROGMEM rather than RAM, and the prints it. Note that this takes one additional clock cycle, per byte.

And even more interesting: What happens to literal constants like in this expression a = 5*(10+7) are 5, 10 and 7 really copied to RAM before loading them into registers? I just can't believe that.

No, because they don't have to be. That would compile into a "load literal into register" instruction. That instruction is already in PROGMEM, so the literal is now dealt with. No need to copy it to RAM and then read it back.

I have a lengthy description of these things on the page Putting constant data into program memory (PROGMEM). That has example code for setting up strings, and arrays of strings, reasonably easily.
It also mentions the F() macro which is an easy way of simply printing from PROGMEM:
Serial.println (F("Hello, world"));

A bit of preprocessor complexity lets that compile into a helper function which pulls the bytes in the string from PROGMEM a byte at a time. No intermediate use of RAM is required.
It is easy enough to use that technique for things other than Serial (eg. your LCD) by deriving the LCD printing from the Print class.
As an example, in one of the LCD libraries I wrote, I did exactly that:
class I2C_graphical_LCD_display : public Print
{
...
    size_t write(uint8_t c);
};

The key point here is to derive from Print, and override the "write" function. Now your overridden function does whatever it needs to output a character. Since it is derived from Print you can now use the F() macro. eg.
lcd.println (F("Hello, world"));


text:
Cheap arduino wi-fi TRIGGER
I am looking for cheap way to have very basic wireless communication between an Arduino and a iphone.
I don't need to send complex data, it would be sufficient to "trigger" the arduino: let's say it is reading a certain pin voltage and waiting for it to be up in order to do stuff, my goal is to trigger this pin up by any (wireless and iphone friendly) mean.
I have figured out two solutions: wi-fi shield, cheap RF transceiver. The problem with the latter is that it is not trivial to communicate with a RF transceiver from an iphone. I should add another arduino controlling an RF transceiver on the iphone side and commanding this arduino with an usb.
The wi-fi shield on the other hand is too expensive. Even small routers such as the wr703n (30 euro more or less) is too expensive in my opinion. I just want to send a "bit" of information, so I don't want to spend more than 10 euro.
The third option would be to hack some cheap wi-fi controlled tool, such a lamp or plug: do you know any?
Do you have any other idea?
Thanks!

Does the triggering involve user interaction, eg. pushing a button on the iphone. Or should it be done completely automatic when the phone comes "near" the Arduino?

Button on the iphone

If you are going to need human interaction (button) Then I suggest you get a wifi router with a few ethernet ports in it (if you dont have one already... most homes have one nowadays). And then you connect the arduino via ethernet (ethershield (quite cheap) or ENC28J60 (very cheap) or etherten or other). That way you can connect to your arduino from your iphone.

WiFi you either need a WiFi router or for either the iPhone or Arduino to create a network.
RF transceiver you need external circuitry.
The common way to do this at the moment is using Bluetooth Low Energy. Using a Bluetooth Low Energy (BLE) shield you can directly connect the Arduino to a modern iPhone or Android phone (supporting Bluetooth 4.0).
Check out redbearlabs, who have a range of shields and BLE-enabled Arduino clones. There are example sketches and iOS apps on the net. I have made a BLE controlled RGB light using the redbearlabs BlendMicro and example OSX application.


text:
Error: 'SofwareSerial' does not name a type
I have trouble compiling this sketch. The error I get is

'SoftwareSerial' does not name a type

Any ideas how could I fix it?
#include SoftwareSerial.h

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Ready!");

  // set the data rate for the SoftwareSerial port

  // for HC-05 use 38400 when poerwing with KEY/STATE set to HIGH on power on
  mySerial.begin(9600);
}

void loop() // run over and over
{
  if (mySerial.available())
    Serial.write(mySerial.read());
  if (Serial.available())
    mySerial.write(Serial.read());
}

After doing this, I find that SoftwareSerial has a problem in it. Simply by coding #include "SoftwareSerial.h" and not even doing this: //SoftwareSerial Serial(RX, TX); Without SoftwareSerial, I have no idea where to get the output. It does not seem to want to send it to the Serial monitor. That's because there is no Port to select. So I am still stuck. I still get this error: C:\Users\mikey\Documents\Arduino\libraries\attiny_software_serial-master/SoftwareSerial.h:70:17: error: redeclaration of C++ built-in type 'bool' [-fpermissive] typedef uint8_t bool;

Add to @geometrikal.
or
#include <SoftwareSerial.h>

You forgot the quotation marks, try
#include "SoftwareSerial.h"

#include "SoftwareSerial.h" worked instead of

#include <SoftwareSerial.h>
ie " " not <>


text:
Simple compiler design help: Variable length arrays?
I'm trying to write a simple compiler in C++ for a language that I am making up for my lab.  The compiler will have to be able to turn a string like this:
"do command_one 3 times"

into a data structure that represents this:
<command_one>, <command_one>, <command_one>

it should also be able to turn something more complicated like this:
"do do c_one do c_two 2 times 2 times c_thr 2 times"

into a data structure that represents this:
<c_one> <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr> <c_one>
                <c_two> <c_two> <c_one> <c_two> <c_two> <c_thr>

Another function will then read the commands out one by one.
These examples show all of the functionality that I would want from the compiler.
I'm having design issues for the compiler that I want to create.  Initially, I just wanted to do some string manipulation and turn the input string into an array of integers representing commands.  However, since the compiler will be outputting an arbitrarily large number of commands, and since arrays in C++ need to be initialized with a length, this could be a problem.
I am not fluent in C++ so I am hoping that a C++ whiz can show me a quick solution.  I have already come up with the suggested solution on my own in Python, however, my solution in Python has to do with the ability to change the length of lists on the fly.
EDIT: I am also intending to use this code for an Arduino, which supports C++ code but not the standard libraries.  I found the vector solution to work in my C++ code, but it will not work in the Arduino interface.  Is there a way to do the compiling WITHOUT using vectors?

Use std::vector?

look into C++ vectors.

Compilers are difficult. Not knowing the language you are writing the compiler in sounds crazy.

It is, both were asking different questions originally (answers for C++ and answers in Arduino) but as I got an answer in C++ the mods moved the C++ question to the Arduino forums

To clarify, I did need answers for both C++ and Arduino since I needed the compiler on both systems.

In C++ there is a std library container called vector you can use to create variable length arrays. You can use it like this:
#include <vector>
// ...
std::vector<int> commands;
// ...
// parse string and generate commands, add your commands with push_back
commands.push_back(new_command);
// and you can access elements in the array like normal
commands[0];
// and also see how many elements are in the array
commands.size();

I also want to mention the std stack, which I think would be a helpful class for managing the states of your nested loops. Each time your interpreter enters a new loop for example, push to the top of the stack how many times to run, and each iteration count down till 0 and pop (just as an example).
Edit:
Because you can't use vectors C++ also supplies the new and delete keywords to dynamically allocate and delete memory. However as arduino has really low memory I don't recommend trying to implement an expansible array on this.
This post here mentions that program memory and global memory is shared on 2K: new operator on arduino
You may just want to go with a reasonably sized static array on arduino considering the memory limitations. I would suggest using a pool or the new + delete stuff but any implementation you add to deal with memory management will take away space you need for your interpreter and its instructions.
Also I don't know what data type you've chosen to represent your instructions but char is probably best  on the embedded implementation if your instruction set is small as it only occupies one byte each.

My instructions can simply be represented by numbers.  Ex: 1 can mean cmd_one and 2 can mean cmd_two, etc...

After Edit:
Since you cant use vectors ...
... or use variable length arrays, if the compiler you are using it, supports it.
... the other viable solution is to get your own list or vector library, either from an existing open source library or implementing your own.
Cheers.


text:
Help connecting an Arduino and an electronic speed controller
We have this controller that we are planning to use with this motor. How do we plug it to the Arduino to make it work?
This is a totally new subject for our school team, since we are mostly programmers, so your help will be really appreciated.

You'll have to do a little more work than that.  We help people with design problem not assembly issues.

The operational connection will be trivial; what may be more challenging is if the controller is supposed to be programmed by moving transmitter sticks in a particular sequence.  You might need to have an alternate sketch which controls the PWM signal with a potentiometer to emulate that.

HobbyKing, which sells Arduinos and is a great source for motors and controllers, has an instructable on this at http://www.instructables.com/id/ESC-Programming-on-Arduino-Hobbyking-ESC/
I found another on the OpenROV site, at http://community.openrov.com/forum/topics/how-do-i-activate-electric-speed-controller-with-arduino
Did you actually try googling "arduino electronic speed control" before coming here?

Link-only answers are discouraged. Please add some detail to your post that can help answer the question. You can quote text from the links.

As the controller and motor are from the same vendor, they can help you with specific questions.
That motor controller is designed to emulate a servo motor. So it takes a servo-motor signal:
Ground
Power
PPM signal
The Arduino servo library will drive the PPM signal. Power and ground for the controller need to come from a separate power supply. The Arduino can't power it.


text:
Using timers on an Arduino Mega 2560
I'm an amateur and I wish to use timers in my project. I'm using an Arduino Mega 2560 with a touch-sensitive screen with six  DS18B20 temperature sensors and a DS1307 RTC (real time clock). I would like to query my sensors every 1 or 2 minutes to refresh the screen for temperature acquisition. I do not how to program timers to schedule the readings and which timers to use?

You can use the function millis(), that returns the number of milliseconds since the Arduino board began running the current program (unsigned long). This number will overflow (go back to zero), after approximately 50 days.
The code below uses the millis() function, a command that returns the number of milliseconds since the Arduino board started running its current program, to blink an LED.
/* Blink without Delay

 Turns on and off a light emitting diode(LED) connected to a digital
 pin, without using the delay() function.  This means that other code
 can run at the same time without being interrupted by the LED code.

 The circuit:
 * LED attached from pin 13 to ground.
 * Note: on most Arduinos, there is already an LED on the board
 that's attached to pin 13, so no hardware is needed for this example.

 created 2005
 by David A. Mellis
 modified 8 Feb 2010
 by Paul Stoffregen

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
 */

// constants won't change. Used here to
// set pin numbers:
const int ledPin =  13;      // the number of the LED pin

// Variables will change:
int ledState = LOW;             // ledState used to set the LED
long previousMillis = 0;        // will store last time LED was updated

// the follow variables is a long because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long interval = 1000;           // interval at which to blink (milliseconds)

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the
  // difference between the current time and last time you blinked
  // the LED is bigger than the interval at which you want to
  // blink the LED.
  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    // set the LED with the ledState of the variable:
    digitalWrite(ledPin, ledState);
  }
}

Source: http://arduino.cc/en/Tutorial/BlinkWithoutDelay

This solution is the way to go. Timers aren't really useful in this case. Also don't worry about the 50 day overflow. Since you are calculating the time difference, this will never become a problem (unless you want to check the temperature every 60days or so).

You can use the watchdog timer for that. Below is part of the code that I use to make temperature readings every 8 seconds using the watchdog timer. It compiles on Arduino IDE 1.0.5 for Arduino Uno R3 board, but be warned that I didn't run it as it is below (so it's untested). You can change variables COUNTER_TRIGGER and WATCHDOG_PARAM to adjust its timing it to your liking. Note also that I'm using ATmega328P, so map it accordingly to your MCU.
#include <avr/sleep.h>
#include <avr/power.h>

#define WDTCR_REG WDTCSR
#define SERIAL_DEBUG

int COUNTER_TRIGGER = 1; // 1 * 8 sec = 8 seconds
int WATCHDOG_PARAM = 9; // 9 = 8 sec
// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec

volatile long watchdog_counter = 0;
int counter_trigger = COUNTER_TRIGGER;

const byte TEMP_PIN = A5;

void setup() {
  #ifdef SERIAL_DEBUG
  Serial.begin(9600);
  #endif

  pinMode(TEMP_PIN, INPUT);

  //Power down various bits of hardware to lower power usage
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  sleep_enable();

  // ADCSRA &= ~(1<<ADEN); //Disable ADC
  ACSR = (1<<ACD); //Disable the analog comparator
  DIDR0 = 0x3F; //Disable digital input buffers on all ADC0-ADC5 pins

  sei();
  setup_watchdog(WATCHDOG_PARAM);
}

void loop() {
  #ifdef SERIAL_DEBUG
  Serial.print("Sleeping...");
  Serial.flush();
  delay(20);
  #endif

  sleep_mode();

  #ifdef SERIAL_DEBUG
  Serial.println("awake");
  #endif
  // Zzzz...

  #ifdef SERIAL_DEBUG
  Serial.print("watchdog_counter = ");
  Serial.println(watchdog_counter);
  Serial.print("counter_trigger = ");
  Serial.println(counter_trigger);
  #endif

  if (watchdog_counter >= counter_trigger) {
    watchdog_counter = 0;
    doSomething();
  }
}

void doSomething() {
  // do your thing here
}

// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms, 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
void setup_watchdog(int ii) {
  byte bb;
  int ww;
  if (ii > 9 ) ii=9;
  bb=ii & 7;
  if (ii > 7) bb|= (1<<5);
  bb|= (1<<WDCE);
  ww=bb;

  MCUSR &= ~(1<<WDRF);
  // start timed sequence
  WDTCR_REG |= (1<<WDCE) | (1<<WDE);
  // set new watchdog timeout value
  WDTCR_REG = bb;
  WDTCR_REG |= _BV(WDIE);
}

// executed when watchdog timer expires
ISR(WDT_vect) {
  watchdog_counter++; // increment volatile
}

I don't remember where I got it. I'll add proper attribution when I find out who provided the code... soon.
I hope this helps.

Thank you for sharing your knowledge. I am going to make tries.


text:
Controlling ESC with Arduino
I want to control these motors: hexTronik DT750 Brushless Outrunner 750kv with this battery: Turnigy 2200mAh 3S 25C Lipo Pack and these ESCs: TURNIGY Plush 18amp Speed Controller.
I am new to this field of driving brush-less motors. Can someone tell me if I need anything else? Will this set-up work without anything getting destroyed?

This looks like shopping advice, which is off-topic for ee.se. See the [help] for advice. "Can someone tell me if I need anything else?" What do you actually want to do? The motor specification (spec) describes the max current 18A for a specific propeller, but only repeats the same value for its maximum current, which seems an odd coincidence. The ESC has a maximum continuous current of 18A, with a burst of 22A, but the specification doesn't say the burst duration. So it looks okay for some uses, but might not be for others.

I 've been working on an autonomous arduino quadcopter for about 7 months now and I have a few tips for you.
1) your setup seems fine as long as your motors aren't going to draw more amps than your ESC can supply, but It is always a good idea to buy ESCs with a higher "max amps" than your motors draws. I would choose 25 amp max ESCs or higher.
2) In order to control the motors via PWM, I use the Servo library because you get a resolution from 700-2000 as opposed to "analogWrite" which gives a default resolution of 0-255.
3) your ESC probably has a minimum pulse width value before it will start. I would recommend writing a program that gives you the ability to plug in values from 700-2000, and use the program to slowlly find that arming pulse width value. Mine is 1110 for reference.
If you have anymore questions, I will glady answer them.
May I ask, what is your project?

Thanks for the feedback. I too am working on a quad. I essentially started this project to learn as much as I can about electronics, since I have just gotten into the hobby.

Nice, I have been learning a lot about quads and electronics. Message me with a question when you have one. I had a successful test flight 2 weeks ago so I can help you up to that point. I'm now on altitude hold.

@Trexter you are awesome. So glad to see a community member be so helpful, it's what makes these SE sites great. I didn't see any blog information on your profile. Do you have any examples of your autonomous arduino work you can show off?


text:
Maxbotixs LV-EZ4 analog read question
I am using an external 5 volt power supply to power my Sonar, and I am using a Teensy 3.1
to read in analog signal  from the sonar. my question is since the teensy is only 3.3v tolerant with analog in, is it safe to use with the maxbotix sonar?

That is not safe. Maximum voltage on the analog pins is 3.3v, according to the datasheet. But why don't you power it from 3.3v? Minimal voltage for that unit is 2.5v. And it uses only 2mA.

Yes, I just did. I assumed that it would be drawing too many mA but I was completely wrong.

Converted Gerben's comment to an answer

That is not safe. Maximum voltage on the analog pins is 3.3v, according to the datasheet. But why don't you power it from 3.3v? Minimal voltage for that unit is 2.5v. And it uses only 2mA.


text:
ATMega328P not running sketch in standalone (works in Uno R3 Board though)
I bought an ATMega328P-PU and burned OptiBoot onto it using a second Arduino Uno R3 with great success.
I then put the microcontroller back on the (empty) Uno R3 (DIP) Board for programming, connected USB and uploaded the blink sketch successfully.
Now to the weird stuff:
Blink works on the Arduino Board itself, but if I pull it out and stick it into my breadboard, the program seems to not start. Here are some facts:

happens with or without external crystal 16.000 (Pin 9-10)
happens with or without the 22pF capacitors from crystal to GND (9-GND, 10-GND)
happens with Fuses set to internal OSC or to external clock (Uno default)
happens with or without the ADC VCC (Pin 20) and REFERENCE (Pin 21) Pins @ 5V
happens on 5V and on 3V3
happens with or without external Pullup on RESET Pin (1)
Most of the output Pins sit at 0.8 V

Could you post a diagram of your circuit (the one on breadboard). Particularly useful would be power supply and its regulation. Also, do you use a decoupling capacitor, between 5V and GND, near the MCU?

I supplied either 5.1 V from my computer, or 5 V by using an LM7805 (without any capacitors, yet). I also use a 100 nF ceramic capacitor at the nearest point of the MCU between VCC and GND.

I would expect if you connect a scope to your +5 it is oscillating like crazy.  ALWAYS put the recommended capacitors as close as possible to the regulator (check manufacturer's data sheet they are not all the same). It is amazing how many designs I have seen with problems caused for this very reason and the variety of abnormalities displayed. Finding this problem without a scope is extremely hard so simply add them they are not expensive and the regulator will operate cooler.

I found the solution by accident.
While I used my multimeter to measure the voltages between GND and the Pins (for the last fact), I noticed the program running at weird speeds. I. e. the LED started blinking.
What did I measure?
Actually I was just measuring one of the crystal pins (Pin 9 or 10). The sketch went running for a few seconds and very different speeds and then stopped.
This small change in voltage gave the ATMega the clock signal it needs to step through the program.
Maybe I need less capacitance of the two capacitors as mentioned in the comments. I will update the answer with more information later on.
The perfect solution
As pointed out in the comments, I really chose the wrong capacitors. It worked without, but we want the stability so use a bright light and a magnifying glass if you are unsure. Really, do it.

This is not an answer to your question! You should rather edit your question to include the content of your answer, and then delete your answer.

@jfpoilpret - untrue, this is an answer as it solves the problem.  It may not satisfy all curiosity though.

Seems like you might have a resonator not designed for external caps rather than a crystal.  Or the substantial parasitic capacitance of your breadboard may add up to too much with the caps (ideal value takes layout into consideration!) Another possibility is misinterpreting capacitor value markings - they could be bigger than believed.

@Chris-Stratton You're right, actually I misread the answer and did not see upfront that it worked without the 22pF caps, I needed to read it a second time to see it as a solution! Maybe editing it would make that appear better?

Dear Sir @ChrisStratton. You were absolutely right. I just checked the printed numbers on the two capacitors under the magnifying glass. They are not 22pF, they are 220nF (Code 224). The 4 was on the side of the capacitor... Pure human failure. Thank you for the tip, I would not have checked it else.


text:
Car dome light fading with arduino nano
So I'm working on my car and now I've got my sights on the electrical system. I've installed a keyless entry system and a pulse timer for the dome light. Now, I'd like to give the dome light the fade effect all the modern cars have. After looking around, it seems an Arduino would be the most reliable.
I currently own an board similar to the Arduino Nano, specifically the SainSmart Nano. So I've determined that I'd power the board with a constant 12V, use pin 7 as input, and use pin 9 as output.
My code:
int domeLightIn = 7;
int domeLightOut = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(domeLightOut, OUTPUT);
  pinMode(domeLightIn, INPUT);
  digitalRead(domeLightIn);

}

void loop() {
  // Case 1: State of Door: Open/Closed
  // Case 2: State of Switch: On/Off
  // Case 3: State of KES: Active/Inactive

  //Case 1: If door is closed and led is off, brightness remains 0;
  //Case 2: If switch is off and led is off, brightness remains 0;
  //Case 3: If KES is inactive and led is off, brightness remains 0;
  if (digitalRead(domeLightIn) == LOW && brightness != 255){
    brightness = 0;
  }

  //Case 1: If door is open and led is off, brightness will fade in;
  //Case 2: If switch is on and led is off, brightness will fade in;
  //Case 3: If KES is active and led is off, brightness will fade in;
  if (digitalRead(domeLightIn) == HIGH && brightness != 255) {
    for (brightness = 0; brightness < 255; brightness = brightness + fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay(35);
    }
  }

  //Case 1: If door is closed and led is on, brightness will fade out;
  //Case 2: If switch is off and led is on, brightness will fade out;
  //Case 3: If KES is inactive and led is on, brightness will fade out;
  if (digitalRead(domeLightIn) == LOW && brightness == 255) {
    for (brightness = 255; brightness > 0; brightness = brightness - fadeAmount) {
      analogWrite(domeLightOut, brightness);
      delay (35);
    }
  }
}

I am unsure whether I am using digitalRead() correctly along with wiring the input. So, am I doing this right? or perhaps there is a better way?

Any particular reason why you don't want to use a capacitor and resistor instead?

Flexibility. I didn't mention this, but I'm also installing footwell lights, perhaps even more accessories. Eventually I'll try different things with it. I'd like to give each a fade effect, but if I can't do it with the arduino, then I'll fall back to capacitors and resistors.

Did you've added a PULLUP resistor on the input?

You're not using digitalWrite properly. You should do:
if (digitalRead(domeLightIn) == LOW && brightness != 255){

Just a sidequestion. What is pin7 connected to? If it's a 12v signal, you'd have to convert it down to 5v somehow.
Also, the 12v in the car can be up-to 14v, and can have some huge spikes. Not sure if the sainsmart's regulator can handle those spikes. It might die prematurely. It's also just wasting 60% (generating heat!), turning 12v to 5v. I would suggest adding one of those cheap car-phone-chargers.

Thanks. And Pin 7 is supposed to be the input signal wire. Messed that up in my code. And I was thinking more along the lines of wiring up a voltage divider to change the input voltage to somewhere between 7V and 12V

A voltage divider means wasting power twice.

If I want to power the board, wasting power is inevitable. My car's accessory wire isn't always on. The only wires that I believe are constantly hot are the 12V constants, dash and headlights, and dome light.

A voltage divider will work. It would only wast a few milli amps, if you use high enough resistors, so not an issue. Not sure what you meant by "between 7V and 12V". Maximum input voltage is 5.5V. So try to get a voltage between 3v (minimal) and 5v, when providing a signal voltage between 12v and 14v.

Ah my bad. The 7V to 12V was meant for the wire powering the board.

You should consider bringing the voltage down to 5v thats very important, when a car is running as stated above the voltage will increase because the battery is no longer running the electronics, the alternator powers everything and charges the battery.
Instead of trying to control this strait from the Arduino, use a transistor such as the TIP 120 darlington in order to control the existing light or you can put in a new one if you want.  This gives you the ability to add more powerful lights or add more lights to the circuit, which the Arduino would not be able to power via pwm.


text:
GSM shield SIM card troubles
So I'm trying to use the GSM shield to communicate with my smart phone. The SIM card that came with the shield only works with other devices on that network, and it's an obscure latin network that I don't have so I cant use that one, and I bought another t-mobile SIM card activation kit, but I can't figure out how to activate it without having an actual T-mobile number. Somebody please help me! Either help me figure out a way to get the T-mobile SIM card to work or tell me what other SIM to use! If you used the GSM shield with a different SIM card, could you give me a link to where you bought it? Thanks!

How do you propose to use the GSM shield to communicate with your smart phone? SMS?

Yeah, I was going to use SMS.


text:
Why does an Arduino MEGA 2560 have different PORTS
I'm currently looking at my Arduino MEGA 2560 board and was just wondering why there are different ports to it e.g. ANALOG IN, DIGITAL, Communication? in fact I've only seen this in some microcontrollers. Not many microcontrollers have ports dedicated to certain things. Is anyone able to give me an answer as to why there is different ports to the microcontroller? is it making it easier for the chip to handle etc. A detailed but not too detailed answer would be great!

"Not many microcontrollers have ports dedicated to certain things." [citation needed]

I remember using an Attiny chip, not sure of the exact model, which basically just had ports A,B,C,D and didn't have any labels such as PORT A = Write PORT B = Communication etc. Basically from my experience, what I think is i've seen is that Not many microcontrollers seem to have dedicated ports to them

Most ATtiny MCUs do have peripherals fixed to specific pins. The ATtinyX41 have reassignable pins for OC, but they're also fairly new.

Why is it that they have specific pins for them? what's the reason behind it? could you please give me an explanation

Probably because it means less logic which means less upfront development cost which means lower cost to the system integrator.

That confused me a lot. Maybe dumb it down a bit?

Actually, most of the ATmega2560 pins have two or more functions. The ATTiny crams a lot of functions into one pin because it has a low pin count and to make it versatile, and therefore marketable.

Most microcontrollers have a lot of pins with various functions, but extremely complex patterns of what is and isn't supported on each pin, often appearing to derive from internal details known only to the designers.  In short, you look at the data sheet with care, but don't (productively) wonder why.  A great way to shoot yourself in the foot (if you neglect to check) is to design a PCB connecting a signal to a "general purpose" pin which happens to uniquely not support the one special mode you actually need it for...

Thats because Arduino has configured the Mega to do so. In microcontrollers you need to select what use will each pin have based on the availability. To make user interface easy arduino has done this based on what is commonly used by everyone. Even then some functions are still not disabled.
For example 50,51,52,53 are SPI pins on mega which use Pin change interrupt for working. Thus it not necessary we use them for SPI we can also use them for Pin change interrupt.
Similar is the case for pins 10,11,12,13. These PWM pins can also be used for Pin change interrupt but other PWM pins cannot.

This is not correct! On most atmega, attiny, some pins can serve a specific purpose (eg usart, spi, i2c, analog input) and although you can use them for digital input or output, you cannot chose other pins for these specific purposes. Hence, this is not "Arduino that configured the mega".

Well if you can look at the data sheet of atmega 2560 used on the mega you can see a lot of functions for a single pin. and also There are some pins having pin change interrupts on them but they do not work on the mega board.
I have seen working of ARM cortex-M4 microcontroller, many functions exist on each pin and you need to have a board configuration file programmed to enable disable some the pins of registers and ultimately the functions. A similar version exists at the ATmega controllers if you can see the proper programming in CVAVR.


text:
How to eliminate noise from PWM controlled 12V fan at low speed
I am trying to build a simple fan controller (single fan). So far I have successfully created a circuit which powers the fan with an external 12v DC adapter and added a transistor (NPN) to switch it on and off. The transistor is connected to a PWM port on the Arduino.
When putting HIGH on the port the fan works perfectly at high speed, but when I want to lower the speed (say analogWrite(fanPin, 150)) it starts to make a humming noise. I believe this is caused by the use of PWM.
What is the best way to control the speed of the fan without (too much) noise?
ps. The fan is a Cooler Master 3-wire PC fan. Transistor is a P2N2222A.
Update: Here is the schema I am using:

Martynas pointed out that I should include the circuit, I will do that later today when I get home from work.

Try using pins 5 or 6, as those pwm pins are running at twice the frequency of the other pwm pins.

When I try your suggestion the noise changes but isn't gone.

I had the same problem with a 5V fan.  Something simple worked for me: To decrease the PWM frequency.  You probably want to do this using pin 9 or 10 (for the Uno) as changing the frequencies of other PWM pins messes up the delay and millis functions.  Details on how to do it and a very convenient function are provided in http://playground.arduino.cc/Code/PwmFrequency.  In my case, using the lowest frequency possible (31250/1024 = 31Hz), I completely eliminated the hum for higher speeds and significantly reduced it for lower speeds.  And by the way, I used the PWM pin to drive a MOSFET since the current of my fan was 140 mA, much higher than the 20 mA Arduino pins can safely provide.

I'd be interested in why this works. Is this sound due to some mechanical side effect of the motor or something more interesting like the hum produced by a transformer which (I believe) isn't mechanical.

Try using pin 3 (or 11) and lower the prescaler of timer 2 using the following code in your setup;
//move from /64 prescaler to /32 prescaler
TCCR2B |= _BV(CS20);//set bit (remove this line for a /8 prescaler)
TCCR2B |= _BV(CS21);//set bit
TCCR2B &= ~_BV(CS22);//clear bit

Halving the prescaler will double the frequency.

When I try this I get a noise with a higher frequency.

The goal is to use a frequency high enough to not be audable by the human ear. Have you tried removing the line with CS20?

Yes, I tried that too, but I still hear an annoying noise.

It might help to use a capacitor to smooth your PWM signal.
See http://ww1.microchip.com/downloads/en/AppNotes/00771b.pdf

That document describes adding a capacitor to reduce slew rate while using an NPN transistor. Is there any way to slow the slew rate while using a MOSFET?

There will be no real difference between using a capacitor to smooth the output from an NPN transistor and filtering the output of a MOSFET. From the point of view of the load, an NPN transistor (driven fully on or off) is a switch with a series resistor on it, where a MOSFET has very low resistance. The extra resistance of the NPN transistor would slow the charge rate for the capacitor a little, but you can pretty much ignore the difference.

A capacitor is a crude low-pass filter. It starts to charge up during the ON cycle of the transistor, and starts to discharge when the transistor is off. Since it never fully charges or discharges, it evens out the peaks and valleys of the PWM signal to a rough average of the voltage that is fed to it. (Without a load, the capacitor will charge up to almost the full supply voltage since it during the ON cycle but doesn't really discharge.)

coment add circuit to know what you have done
Does your circuit looks similar like:
Do you use resistor for transistor? Diode for fan?

I suspect that you do not have diode.
The purpose of the diode is to allow current that is flowing in the motor coil to continue to flow in the same direction when the transistor turns off. When the transistor turns off, the voltage at the transistor collector will rise as it was flowing out of the motor. From Vce(SAT) it will rise above the power supply voltage and stop only when the transistor breaks down (or when it starts to ring with parasitic capacitance). By putting a diode from the transistor collector to the +12V rail, you prevent the voltage across the transistor from exceeding 12V and and allow the motor current to continue to flow.

If you need to ask the original poster questions, please do so by commenting on the question itself. An answer isn't the right place to do that.

@PeterR.Bloomfield i understand everything. Sorry for that, but i added an answer too. I would comment if not 44 rep. pts...

I added my schema. It's indeed very similar to yours. Only I had to connect the grounds to get it working.

There is also the possibility adding a capacitor bypassing the transistor. But you have to be careful, if the capacity is to big you could damage your transistor.

SAS is correct - lowering the PWM to 31Hz works great. Tested using a 12v fan.  Before lowering the PWM, the sound from the fan was a loud "WHEEEEEeeeeeeeee" sound at any speed other than full speed.  Low speed made the sound worse.
After lowering the PWM frequency, the noise is inaudible at higher speeds.  At lower speeds you might hear a light "clicking" noise.  The sound reminds me of the faint "clicking" noise you hear as the valves on a car engine open and close.

I can also confirm that SAS answer ist correct. I tested it with a 5V DC fan. I hear a very high noise at lower speed, but you have to listen closely, and a very fast clicking noise at higher speeds.
All in all i would say lowering the PWM to the suggested 31Hz did it for me but it is not a perfect solution.

I get that this post is 4 year old, but I successfully removed all fan noise with simple electrolytic cap and one ceramic on output, after adding caps you need to bias RPM. You can still get some relay low squeak coming from mosfet but only on low RPM

25kHz power PWM solved this problem for my 3-pin fan. Diode had no effect on noise, it fixes another problem (EMI).

Do you talk about 4-pin fans?

@SimSon no, I did 25kHz to power line. 3.3V GPIO from MCU is connected to darlington transistor. Didn't check by scope, likely there are all kinds of basic electrical problems, so not proposing any particular circuit. But the general idea to go high frequency seems an obviously right choice for me.


text:
Detecting grass, pavement, gravel
I think about building my own robotic mower, therefore I would like to detect if the surface the mower in moving on is grass, pavement, gravel ... etc.
Which sensors would be the best choice in order to achieve this?
The benefits:

no parimeter wire to bury
possible lawn edge detection (here most mowers fail to do a good job)

I have found this DIY mower page (where they apparently already implemented a grass sensor). Grass sensor. Other useful info can also be found (mixed in english and german).
They are measuring the capacity of the underground in about 2cm (1inch) height.
On gravel or other hard material this is near 0 (as the sensor is in the air). On grass the value is higher.
Haven't though of this solution, should be the way to go.

You could try to use a force sensitive sensor to detect when grass blades touch it.

I like this "bumper" idea, as it can serve two purposes. Tiny force means grass (good). Big force means object (bad). No force (no grass).

Yes and no ... you are mowing the grass and changing the surface the mower is detecting. But it might be a good indication for the mower to know if he already mowed this region ... as a complementary sensor not a bad idea at all.

You may need to use a combination of sensors. I can't think of any single sensor that can reliably detect the different surfaces.
An IR sensor could detect the difference between grass (cooler) and pavement/gravel (warmer).
An ultrasonic ranging sensor could detect the difference in heights between the grass and pavement/gravel.
A photoelectric sensor could detect the difference in reflectivity between the grass and gravel/pavement.
A visual camera could be used with image processing to detect color differences, although this may be too processing intensive for an Arduino.
A final possibility would be measuring the resistance to movement of the wheels. The robot will travel easier over the hard surface of pavement/gravel.
I would think that a combination of the above sensors would provide the most reliability and accuracy. However, it will still likely be limited to one location without recalibration. The weather will even cause a change in some of the sensors (photoelectric for example on a sunny vs. cloudy day).

Definitely a sensor combination is the solution ... a camera detecting the greenish colour plus IR ... pattern detection is out of scope.

A combination of colour sensors as the predominant one and proximity sensors as the secondary one should work fine. Around $10 so definitely worth trying out. Also, the code should be relatively easy.
Here are links as samples. I hope this helps :)
$6 colorvsensor
$4 Proximity  sensor


text:
Cant's code against Yun Wireless Section
Just got my Yun today.  Successfully connected to my home wireless, installed YunSysUpgrade_v1.5.1,
and divied up my Micro SD card for Linino and Windows file system with YunDiskSpaceExpander,
and got files serving on the native file server from the SD card.
But I can't seem to touch the wireless section from a sketch.
I'm running a mod of the example ScanNetworks sketch - here's the relevant part:
void loop() {
  delay(1000);
  String fv = WiFi.firmwareVersion();
  Serial.println("Version: ");
  Serial.println( fv );
  Serial.println("Status: ");
  Serial.println( WiFi.status() );
  // scan for existing networks:
  Serial.println("Scanning available networks...");
  listNetworks();
}

Here is the ouptut: no version and a status of 255 (which I cannot find documentation on....)

Version:
Status:
  255
  Scanning available networks...
  ** Scan Networks **
  number of available networks:0

I looked at installing wifi_dnld.elf, but could not find jumper 3 on my Yun, so assumed it was for the 'true shield'.
What am I doing wrong, or do I need to return this to amazon?

WiFi library won't work with the Yun: it's meant to work only with the WiFi shield.
On the Yun, everything but the pins is connected to the linux cpu. For the microcontroller to use all the devices available to linux, including wifi, you need to use the Bridge library. Try running example WifiStatus (Examples -> Bridge -> WifiStatus)
A drop in replacement (almost) of both Ethernet and WiFi libraries is the YunClient/YunServer pair, part of the Bridge library. Check out the docs at http://arduino.cc/en/Reference/YunBridgeLibrary.


text:
Can arduino create a file in its memory?
I am an arduino enthusiast and i am new to it.just wanted to know weather the micro processor itself could create a file in its memory while its is running. I know that it is possible to read a write from a file in c++ but is it possible to do so in an arduino (while it's running).

Can you explain what you're trying to achieve? Are you just looking for a way to store long-term data on the Arduino, or do you want another device to be able to read the file as well?

You can connect a SD-card, and communicate to it via SPI.

I am trying to save the output from a sensor as a text file temporarily which I can later tansfer to a PC

You can save it in a buffer in RAM, and if you maintain power and avoid reset then list it out on the debug serial interface and capture it on the PC side.  Or if it is bigger or you want it to last longer, you can use an SD card as already described.  An on-board SPI flash would be cheaper, but requires you to build the functionality for dumping the data over the serial and capturing it.

To answer the original question: Basically, yes, you can write libraries to implement a file system using the memories of an embedded microcontroller.
However, if it's feasible highly depends on the controller architecture and its peripherals.
Some of them (e.g. the one on Arduino Due) allow Flash reprogramming while an application is running from Flash.
Others require to have the application running in a special boot block or even in RAM when accessing the Flash for writing (this should be the case on an Arduino Uno)
And others don't allow Flash accesses from application at all.
Anyway:
The use of this for your purpose is very little, because the interface to the PC would also have to support the file system (for example, you could implement a FTP server and use an Ethernet connection...).
Therefore, the SD card approach is surely a very good suggestion.


text:
How do voltage and resistance work for two 5v servos when using an external 12v power supply?
I have a 12v/1.5 amp barrel plug power supply on my Arduino Uno. I have two servos that say they are rated for 4.8v to 6v, but no amps are specified. When my circuit is configured as it is in this image, it appears to work fine. (In my test sketch, I'm constantly and simultaneously rotating them from 0 - 180 degrees and then in reverse.)
But I don't understand why it works. I assumed the 5v pin can only supply 5v of total power to the whole configuration. Is it instead supplying a regulated 5v at as needed between both servos from a total pool of 12v (presumably up to 10v at once)? Do I need voltage regulation? Shouldn't I have to know the amps for the servo(s) and use some sort of resistance?
Thanks for any information and advice you can share on learning about the concepts underlying a situation like this.

Update: I ultimately modified my approach based on the feedback received here by wiring a separate 5v/2a power supply to the breadboard for the two servos, and wiring the rest of the circuit appropriately (using a common ground, etc.).

Do not do this.  Although the "total voltage" type of concern you raise is based in misunderstanding, there are real problems.  A servo encountering mechanical load can easily draw more power than the arduino's regulator can supply, causing brown out and misoperation (or if you are lucky, merely reset) of your program.  Even when not causing brown out, servos are notorious for putting "grunge" noise onto power supplies.  Give your servos their own regulator, preferably a switching one.

Ugh. I've got a lot to learn! Thanks for mentioning this. You mean something like this (two: one for each servo)? https://www.sparkfun.com/products/107

Because the supplies of both servos are connected in parallel, they both see the same voltage. Hence there is no "pool", both are being supplied the same 5V.
There is a regulator on the Arduino which reduces the 12V input down to 5V. It does so by burning off the other [7V times however much current is being used] as heat. Since you are supplying it with 1.5A, the most it can supply is in turn 1.5A.

Hmm, I understand less about this than I realized! I don't get how you can send 5v of electricity to two devices that both need 5v at the same time and they are able to work simultaneously. And I reckon I get that 1.5A is technically available to the servos, but I don't understand why I don't have to find out if the servos need a lower amount of current and put in resistance down to that amount, if necessary. (Or put another way, did I just get lucky that they can handle receiving 1.5A?)

"Volts" isn't a quantity, it's a characteristic of the electricity itself. It's the amount of energy imparted to each unit of charge. As for the current, most devices will only draw what they require regardless of how much is being supplied. The exception to this is P-N semiconductor junctions, since they absorb energy as charge flows across them ("reduce the voltage") and are generally not affected by current beyond consumption of power.

Addition to Ignacio. Explanation from real life.
Gregir, look at your home devices like TV, micro wave, fridge and so on. They all need 220-230 V AC and you can plug all them to one socket. As Ignacio said voltage doesn't plus. The current does plus, for ex. you have 2 servos connected in parralel, both 5V, no load current 0.1A. So to run them with no load you will have to supply 5V and 0.1+0.1=0.2A.
I tried to explain at very basic level ;)

Ah, of course! That makes good sense. I am still a little confused about the servos and their amperage. How do you get the 0.1A? (I can't seem to find it anywhere on the data sheets for the servos or on the manufacturer's site.)

Gregir that's for example :) Different motors consumes different amount of current. Bigger motor = more power = more current. First mini servo in google search http://www.rctoys.com/pdf/hitec-servos/HIT-HS55.pdf .You can google information about servos like this interesting pdf http://www.bpesolutions.com/bpemanuals/Servo.Info.pdf

Ah, OK. I see so few examples of people using resistors with servos so far, and hadn't found much info on my particular servos. Easily confused at this stage. Thanks for setting me straight.

Be careful though as a servo that stalls due to load will easily draw up to 1A so if they both stall you might draw more than can be supplied.


text:
Hiduino as a Serial-USB midi coverter
I have an Arduino Mega2560 configured to Hiduino, which makes the Arduino a driverless class-compliant MIDI interface.
I am currently converting RS232 serial I/O data to midi data using the 'hairless midi-serial' software running in the background. I am hoping that I can utilize this Hiduino interfacing to send and receive this data in the same fashion, just through the Arduino instead.
I am lead to believe this would require the MIDI library to be used to program the 2560 to understand the serial bytes coming from the controller and converting to the appropriate midi bytes into my program, and vice versa.  I am just getting into programming. Could someone could give an example of how a program could be written to send and receive this data through the Arduino?

If all things were right, you could send MIDI data from your Hiduino (Serial.write commands) and the inner-hacked chip will do the rest of the job. What's the code you've uploaded? Did you try it with real MIDI ports?

I've jumped in quite deep these last few weeks, I am sending serial data out to the computer, and back from the computer to my controller successfully. There is a bug however, that i can only confirm occurs with Pro Tools. Once Pro Tools is open, i cannot connect Hiduino i/o to any other application besides Pro Tools without a memory error occuring.


text:
Arduino Uno suddenly not recognized in Windows 8.1 (code 43)
I had my Arduino Uno connected to an external 12 V supply for 2-3 hours as I was working on other parts of my project. Suddenly the voltage from pin 9 which I was monitoring in the oscillator dropped down to 0 approximately.
I went on removing the external supply. The board was very very hot. I then connected the USB to my laptop and I got an error 43 (Windows did not allow the device to connect because it was reporting problems). I can't load any program of course. The 5 V pin works but it outputs a voltage lower than usual (at about 3.9 V). When I connect the external supply the 5 V pin outputs full voltage.
Any idea? Any fix?

Have you tried rebooting your laptop?

yes of course...and reseting arduino as well...

What is pin 9 of the oscillator?

pin 9 is from arduino

Is this a knock-off Arduino or Genuine Arduino?

I changed the cable and it works :)

Something is shorted out.
When you connect via USB, the USB port cannot supply enough current because of the short. The output drops to 3.9V and the USB port on your computer reports an error, probably due to over current.
When you connect the external power supply, it has enough power to supply the short. The output remains at 5V.
You can think of power supplies as having a very small internal resistance (R_p), and the board as being a resistive load (R_b). This forms a voltage divider, but because R_b >> R_p the voltage seen by the board is basically the same as that of the power supply. With a short, R_b is often < R_p, and thus the voltage seen by the board is much lower than the power supply voltage.
The fix will depend on which component is getting hot. Plug in the external power supply and check which one it is. Note: The component will get hot enough to burn your finger after a few seconds. One way is to check one component at a time, disconnecting the power between each check. Start with the big ICs.
If either the Atmega328P or the smaller ATmega8u2 (?) are hot, they will have to be replaced.
Finally, boards don't short out by themselves. Something is wrong with your circuit or you may have placed the board down on some conductive surface. If you post you circuit we might be able to spot the problem.

I've been dealing with the same issue, and have resolved it in a manner similar to random approach described above.
Drivers will get corrupted as we all know. But if you want to get past that Code 43 error, you need to have the arduino unplugged from the USB when reinstalling. Otherwise windows will bind the USB.inf generic driver to the device, which prevents the install of the CH341SER driver.
So unplug USB, delete the unknown device via Device mgr, run the CH341SER, *then plug in the USB cable. So I think that random approach worked not because the 9v reset was done unplugged, but because that was first chance (unplugged) that the CH341SER driver had to install without resources bound to generic USB.inf driver.