text:
Writing MIDI Notes More Quickly to a Shift Register with Arduino
I'm working on an Arduino code which will interpret a given MIDI note message and output the corresponding note number to a string of LEDs as a binary integer. I have adapted it from existing code found on the site Notes & Volts which features a similar circuit designed to trigger an LED every time a key is pressed.
My circuit takes this further by telling the user exactly which note is being pressed. The note value byte is information is passed to a 74HC595 shift register which displays the note as a binary via a line of LEDs.
In a loose sense the code I have adapted "works". When a key is pressed a series of LEDs light up corresponding to the MIDI note designated to that key. The issue is that this only happens sporadically. Many times a key press won’t be followed by any LEDs but other times it will. Even quick, successive presses tend to result in only a handful of "read" notes.
Why does this happen? To my intuition it would seem that the Arduino is "missing" notes, that is, spending so many clock cycles writing bits to the shift register that it falls out of sync with incoming bytes from the keyboard. Notes & Volts describes almost this exact situation in one of their instructional videos (relevant part at around 6:57). The author cautions against including too many time consuming processes in the code but doesn't mention how many is too many. I can only assume that a ShiftOut command takes a good deal longer than a digitalWrite and that this explains why the example code works but my adaptation does not. Given this information, how long exactly does ShiftOut take and what could be done to speed up my program?
#include <MIDI.h>
MIDI_CREATE_DEFAULT_INSTANCE();

int latchPin = 8;
int clockPin = 12;
int dataPin = 11;  //The pins I am using

void note_On(byte channel, byte pitch, byte velocity) {  //Runs when note is pressed

  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, pitch);
  digitalWrite(latchPin, HIGH);  //Write 'pitch' to 74HC595. Standard fare
}

void note_Off(byte channel, byte pitch, byte velocity){ //Writes '0' when note is off (all LEDs off)
  digitalWrite(latchPin, LOW);
  shiftOut(dataPin, clockPin, MSBFIRST, 0x00);
  digitalWrite(latchPin, HIGH);
}
void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  MIDI.begin(MIDI_CHANNEL_OMNI);
  MIDI.setHandleNoteOn(note_On);
  MIDI.setHandleNoteOff(note_Off);
}

  void loop() {
  MIDI.read();  //This function which must be re-run in quick succession
}

UPDATE
@CL @Nick I wrote a code comparing the execution time difference between shiftOut and digitalWrite. While I am not perfectly confident in all of the numbers (1K digitalWrites takes a full 44mS??) one result did not surprise me - shiftOut is slower. By my numbers it is 3.75 times slower. That said, I welcome critiques on my methodology and I will address them as soon as I can. In the meantime I will make a point to research Arduino SPI and welcome any other alternatives to shiftOut.
int latchPin = 8;       //Declaration of serial register pins
int clockPin = 12;
int dataPin = 11;

int led = 13;          //On-board LED

void setup() {
  pinMode(latchPin, OUTPUT);
  pinMode(clockPin, OUTPUT);
  pinMode(dataPin, OUTPUT);

  Serial.begin(9600);

  pinMode(led, OUTPUT);

}

void loop() {

  unsigned long startTime = millis();    //Writes to SR 1K times.
  for(int i = 0; i < 1000; i++){       //Prints difference between
    digitalWrite(latchPin, LOW);       //start and end times.
    shiftOut(dataPin, clockPin, MSBFIRST, 0xFF);
    digitalWrite(latchPin, HIGH);
  }

  Serial.print("\nsO:");
  Serial.print(millis() - startTime);

  delay(1000);

  startTime = millis();
  for(int i = 0; i < 8000; i++){    //Performs digitalWrite 8K times
    digitalWrite(led, HIGH);
  }

  Serial.print("\t\tdW:");          //
  Serial.print(millis() - startTime);

  delay(1000);
}

UPDATE
While working on a similar issue I discovered that a dramatic change to my code seems to perfectly clear up the issue. I'd still like to know why this particular example does not, however, so I'll keep poking around until I get somewhere.

Is your MIDI input circuit the same as in the link? (I.e., does it omit the decoupling capacitor?) If you're using a 6N138, can you try with a faster optocoupler, like the H11L1 or 6N137?

Can't you measure how fast shiftOut executes? (Execute it ten thousand times, and run millis() before and afterwards.)

I'll try your and other people's suggestions today but I'll chime in now just to say that I am already using an H11L1 so I think I have isolated the issue to the code itself. The input circuit I copied directly from the datasheet with the addition of a 220 Ohm resistor and a protection diode at the MIDI input. I got nice sharp pulses on the oscilloscope.

I still don't think that shiftOut is the issue, even if it is slower. My code did serial prints which are a lot slower again. Try the code I linked in my answer. The hardware should be the same, except move the MIDI input to pin D2 - leaving D0 and D1 for communicating with the Serial Monitor. You haven't answered my question about how you wired the LEDs. If you don't have a series resistor you may be overloading the 74HC595 output pins. Also the 74HC595 should have a decoupling capacitor.

Just to clarify, using SPI is a good idea. I don't argue with that. But I don't think it will fix this issue.

shiftOut is slow, yes.  It is basically "bit banging" a synchronous serial interface, which is a bit daft really when the Arduino has a hardware synchronous serial interface built in that can operate at much higher speeds.
That built in synchronous serial interface is called SPI.  I suggest you switch to SPI instead of shiftOut.
Also you should check what codes the MIDI keyboard is actually sending out.  I had a similar experience to you recently, but as far as I can tell it's down to the keyboard, not my software.  I built a system which reads in MIDI NoteOn codes through a serial port and plays a sample of a bass guitar at the right pitch.  The system worked perfectly when wired to the computer through a USB MIDI adapter, but as soon as I connected it to a keyboard (I don't have one, so I only had the one chance to test it recently with a real keyboard) it would only react to a key pressed after a long delay.  Almost as if the keyboard only sends a NoteOn if there is nothing happening for a while, and sends something else at other times.  I need to examine the keyboard's output data in more detail to see exactly what is being sent and why.
You might like to manually examine the MIDI codes being sent by the keyboard to be sure that it is actually sending a NoteOn when you think it should be and not something else (it'd be very interesting to see the results of your experiments too).

The keyboard problem sounds as if your code did not support running status.

@CL quite possibly, since I have never heard of that, and none of the references I read while writing it mentioned it. Do you have a link?

MIDI Specification: Running Status

That's interesting stuff. No, my code doesn't implement that and it explains perfectly why it failed on the keyboard. I wonder if the same is true for the MIDI class used by the OP?

The OP's problem sounds more random.

I can't believe it is the shiftOut that is the issue. There is more going on here than meets the eye. I wrote a MIDI decoder a while back. That reads from MIDI and outputs to serial. That would be a lot slower than doing one shiftOut. It runs perfectly, not just with you sitting there tapping notes, but with the synth generating its inbuilt music. See video of it in action.
Either the library is doing something weird, or your 74HC595 is wired strangely. Do you have current-limiting resistors for each LED? Please show your wiring.
Also add a Serial print to display when your note_On and note_Off are called, and with what values. In my test I was able to connect MIDI up to Software Serial (pins D2 and D3 in my case) which was fine for receiving MIDI.


text:
Standalone Atmega 2560 ISP program
First I need to say, I'm a complete electrics newbie, so I need your help.
I have got a standalone Atmega 2560, which I want to program. I connected MISO, MOSI, SCK, RESET, 5V and GND to an Arduino Uno.
In addition a 16MHZ oscillator is connected to XTAL1 and XTAL2 plus I pull all VINs of the Atmega with a 100nF to GND. Plus I connected a separate VIN and GND to the 2560.
I programmed the Arduino Uno as an "Arduino as ISP". Afterwards I connected the 2560 as mentioned above, changed the board to "Mega 2560" and tried to upload a sketch through the Arduino and I get the error message:
avrdude: stk500v2_getsync(): timeout communicating with programmer
Is there something I missed?
Cheers
jb

Did you connect nRESET to the nRESET of the Uno?

Yes, the Pin10 of the Uno is connected to RESET of the 2560 as decribed here: https://www.arduino.cc/en/Tutorial/ArduinoISP

A 16Mhz crystal needs some caps to. Also if the ATMega2560 is brand new, the fuses don't have the correct value yet. Most notably, it's set to run at 1Mhz. You have to run avrdude at a lower speed (-B10) to program the new fuses

What do you mean by "caps"? I have got an resistor of 1MOhm between both pins of the crystal.Yes the Atmega2560 is fresh out of the box. What fuses do I need to set?

I see, I don't have capacitors at the crystal (like the arduino mega 2560 R3 reference design). Could that be the cause it, doesn't work? @Gerben

Your error message indicates that the problem is between the computer and the Arduino-as-ISP sketch, not anything to do with the connections between that board and the target chip.

@jblaze the Arduino Mega uses a 3-pin oscilator, that has the capacitors build in. If you have the same part, than disregard what I said. If it's a 2 pin crystal you need to add (load) capacitors.

I have got a two pin crystal without capacitors. So I need to add two caps with 22pF each?

I double checked my crystal. It has capacitors built in (CSTCE16M0V53-R0).

I have a sketch that programs bootloaders. A side-effect of that sketch is it fixes up the "divide clock by 8" fuse.
It looks like the wiring will be the same, but cross-check on that page (scroll down to the part about programming the Mega2560).
Once a bootloader is installed you could use it, if you get an FTDI cable, or simply go back to using the ArduinoISP now that the fuse is fixed.

Thanks @Nick I was able to burn the bootloader to my 2560 with "Atmega_Board_Programmer":
Erasing chip .
Writing bootloader .
...
Written.
Verifying.
No errors found.
Writing fuses.
LFuse = 0xFF
HFuse = 0xD8
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x89
Done.
Signature = 0x1E 0x98 0x01
Processor=ATmega2560
Flash memory size = 262144 bytes.
LFuse = 0xFF
HFuse = 0xD8
EFuse = 0xFD
Lock byte = 0xEF
Clock calibration = 0x89
Bootloader address = 0x3E000
Bootloader length = 7474 bytes.
Look good so far, but still I got "timeout" when uploading my own sketch. Did I miss something?

So far, so good. The chip is alive. :) Please describe your wiring for uploading your own sketch. I'm not totally sure that ArduinoISP supports the Mega2560 - it may do. Alternatives are cheap ISP programmers from eBay and other suppliers (like Adafruit or Sparkfun), get an FTDI cable and use that for serial programming using the bootloader, or use my sketch "Hex uploader" that uploads from an SD card. You need an SD card adapter for that, but they are around $15.

Yes I think so. My wires are: MISO-MISO, SCK-SCK, MOSI-MOSI, 5V, GND, and Pin10 Uno to Reset in Mega. // Tthe fuses should be OK with your sketch "Atmega_Board_Programmer"? I have this crystal (3 leg) with a 1MOhm resistor between both legs connected to XTAL1 and XTAL2: CSTCE16M0V53-R0. The middle leg is connected to GND. // Thanks for the hint with the programmer. I will search for one.

I was able to write my sketch to the Atmega2560 with a USBasp. But somehow the program does not work. Simple example: I have a small LED connected to Pin D2 (thats PE4 on Atmega2560). But when I do "digitalWrite(2, HIGH);" it is not working (it has been initialized before with "pinMode(2, OUTPUT);"). Anything I need to change in my sketch? Or do I need to change fuses?

I think you should start a new question now. You can upload sketches so this particular one is dealt with. As to why it doesn't "work" please make a post describing your setup, post the sketch, show your wiring, etc.

source: Stack Exchange

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

sort: votes


text:
Read from the SD card - ACMD41 times out
I'm trying to read from the SD card using an Arduino Pro Mini (3.3 V), Pololu micro-SD reader (the 3.3V one) over a SPI protocol.
I've tried both the SD library from Arduino SDK, and the Adafruit one.
Connections:

Arduino pin 10 -> CS,
pin 11 -> DI
pin 12 -> DO
pin 13 -> SCLK.

I've also connected VCC and GND of course.
This call (from the DumpFile example) fails:

// I've tried SD.begin(), SD.begin(10) as well.
if (!SD.begin(10, 11, 12, 13)) {
  // I can see this print statement in serial monitor.
  Serial.println("Card failed, or not present");
  return;
}

I've also tried manually setting pin 10 to OUTPUT, as well as to set it to HIGH.
Now, with the Adafruit SD library, I investigated this issue a bit more. It seems, that SD.begin() invokes the card.init(SPI_HALF_SPEED, csPin, mosi, miso, sck) (of the Sd2Card class).
I added print statements and discovered this exact piece fails:
while ((status_ = cardAcmd(ACMD41, arg)) != R1_READY_STATE) {
    if (((uint16_t)millis() - t0) > SD_INIT_TIMEOUT) {
     // This is being printed.
     // status_ is 1
     Serial.println("init err here!");
     Serial.println(status_);
     error(SD_CARD_ERROR_ACMD41);
      goto fail;
    }
}

I've prepared a card (2GB one) - it's FAT16 formatted, and contains one partition. On this partition there's a single file ony, named "a.txt".

EDIT: After trying another SD card, I got some progress. Now, the following call fails:
volume.init(card) // in SD.cpp

After digging in, I discovered that this invokes the cacheRawBlock(volumeStartBlock, CACHE_FOR_READ), which invokes sdCard_->readBlock(blockNumber, cacheBuffer_.data) and then Sd2Card::readData(block, offset, count, dst).
In readData(), the following fails:
if (!inBlock_ || block != block_ || offset < offset_) {
    block_ = block;
    // use address if not SDHC card
    if (type()!= SD_CARD_TYPE_SDHC) block <<= 9;
    if (cardCommand(CMD17, block)) {
      // ****************************
      // FAIL IS HERE - cardCommand(CMD17, block) fails.
      // ****************************
      error(SD_CARD_ERROR_CMD17);
      Serial.println("SD_CARD_ERROR_CMD17");
      goto fail;
    }
    if (!waitStartBlock()) {
      goto fail;
    }
    offset_ = 0;
    inBlock_ = 1;
}

What the issue can possibly be?

Have you tried a different SD card?

if (!SD.begin(10, 11, 12, 13)) { - that does not compile. expects 1 argument, 4 provided. Please post the entire sketch you tried, which compiles, but does not successfully open the card. Also try another card, you must have another SD card lying around. Internally some of them work better than others, connected to the Arduino.

The SD.begin(10,11,12,13) works with Adafruit SD library. Anyway. I just tried it with a different SD card (FAT-32 this time, 4GB) and I got some progress! Now it fails on volume.init(card) call. I'll update the question in a second.

Sounds like you were using a cheap (Chinese, eBay) card that doesn't support the SPI protocol.  Works fine on a PC with SDIO but not an Arduino on SPI.

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


text:
Reading a photoresistor
I have a wire with a 0-5v current. I want to detect if the current is there or not (HIGH/LOW.)
I'm using an optocoupler to avoid putting too much current into my micro, as it is only a 3.3V micro. I'm nervous about powering this on as one of my other micros stopped working although it's not clear if it could have been the circuit?

I could not find my optocoupler in fritzing. This is it:
http://www.amazon.com/gp/product/B00CGXK1RG?psc=1&redirect=true&ref_=oh_aui_detailpage_o07_s00
This is my plan.

The microcontroller is a spark/particle core 3.3v. It the yellow wire connects to the analog pin A6. The screw terminals connect to the wire with the 5v current that I'm trying to detect.
I based my circuit on this:

But I don't know if it will do the same thing.

What's the optocoupler for again?

The micro is at 3.3v but the signal I'm trying to detect passively is at 5v

I thought you were trying to read a photoresistor.

Not in the TLP621. That model uses a phototransistor.

Thanks my diagram is incorrect here is the relevant datasheet: http://en.f-alpha.net/electronics/optoelectronics/optocoupler/get-started/different-optocoupler/

Do you want to detect a current or a voltage? Why not just use a voltage divider to detect if the voltage is there?

White LED needs about 3V to operate. Here it eats all your breakfast. Short LED, short R4,. Make R2 say 1K. Connect A6 input to R2 to  opto junction. connection.

Based on the revised information given above I present a different answer. Use the opto-coupler as shown here:
Your kettle LED will be in series with the optocoupler (note the polarity, not reversed like in your question).
If the LED is on the transistor in the PC817 will conduct and the Arduino pin will be LOW. If the LED is off the transistor will not conduct and the Arduino pin will be HIGH.

Note: The Arduino pin will be the reverse of the kettle LED.
I'm leaving the other answer there because I think it is a reasonable answer to the question of "detect a voltage".

This works! Thanks for the help. I learned a good deal from both of these answers.

Wouldn't this be simpler?

Note: amended answer increases R1 to 10 k.
The 10 k resistor limits current to 0.17 mA. The 3.3 V zener diode clamps the input voltage to 3.3 V (I measured 2.3 V on mine so that is well within spec). The other end of the zener diode goes to the Arduino ground pin.
I originally had R1 as 1 k however if you had a high voltage input (like 20 V) it didn't quite clamp the pin to 3.3 V (more like 3.8 V). This is a bit high for an input pin, so I tried 10 k instead.
This gives:

For an input voltage of 5 V -> 2.3 V on the Arduino input
For an input voltage of 10 V -> 2.6 V on the Arduino input
For an input voltage of 20 V -> 2.9 V on the Arduino input
For an input voltage of 30 V -> 3.1 V on the Arduino input

This is all within spec for the Arduino.
Now the question is, will 2.3 V on the input pin register as HIGH? The answer is "yes" because high is considered to be 0.6 * VCC.
3.3 * 0.6 = 1.98

Thus any voltage of 1.98 or above is considered HIGH, and it will successfully read 2.3 V as high.

What is the zener diode connected to? If there is a voltage spike what happens?

It's connected to ground (the triangle part).  I tested with higher input voltages, and increased R1 to 10 k (from 1 k in my original answer). That clamped input voltages as high as 30 V to a safe level.

this won't work. it triggers the device to turn on and off. I can't ground the 5v signal except using the ground line associated with it. I tried a voyage divider which is a similar concept and that didn't work.

I'm really unclear about this. How does connecting it via a 10 k resistor "ground the 5 V signal"? Can you describe your set-up more completely? Are you saying the ground from your device, and the ground from the Arduino, need to be separate? What is this device exactly? In your question, your images seems to show an LED (is this the device?) wired backwards in polarity to the opto-coupler you are using.

The device is a kettle. it has a 5v board with the on off buttons and temp display. I have successfully emulated the momentary button presses the turn the kettle on and off with a relay via Internet. but I need to know if it worked. I also need to know if the kettle is in an on state due to a manual button press. these cables are two of five cables that form the the input output for the 5v board. every time my micro reads it triggers the kettle to turn on or  off.

Are you using opto-couplers for the other things (operating the button)? Or are you sharing a common ground?

everything else is separate. the buttons are triggered through a relay shield. it seems any change to the kettle's 5v line can make it change states. I just want to passively read.

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


text:
Does restarting Yún configuration mess up Arduino or its SD card?
I noticed something odd recently - a Yún, that was working previously, wouldn't connect.
After logging in to the web setup, setting the access point and password (which hadn't changed), and save & restart, it connected. Unfortunately, it still doesn't work, and after ssh into it, I find I cannot ls /mnt/sd/ or sda1. It just sits there, requiring Ctrl+C, and gives no output.
Did I reset the Arduino or Linux somehow by setting up access point again, or could my SD card be broken after months of heavy logging?

It sounds like your SD card has likely failed. Try connecting it to a computer with an SD card reader. If it works at all, back it up immediately if you have files you wish to keep. Then try reading and writing files on it. Also if you have a spare SD card, try to use that in the Yun after setting it up appropriately. That should help narrow down the cause to either the Yun or the SD card.

It could also simply be SD card corruption. This can easily happen if a file is being written to and the Yun looses power, or can happen from being force reset while in a stuck state.

Good guess, actually it looks like the ls command hangs when  there are >11000 files in the root of the card - after removing them and trying again it works.


text:
Using an Arduino as an LED controller for an arcade stick
I'm attempting what seemed to be a rather simple problem at first glance, but due to my limited knowledge of Arduino workings I need some help. I'm trying to use button outputs from a PS360+ arcade controller. Each of the button terminals output +5V, and is meant to be connected through a button to the grounds on the PS360+.
  What I want to do is have an Arduino somewhere in between the button output and ground on the PS360+, to control and animate LEDs. What I've done so far is connect the VCC of the PS360+ to the Arduino's VIN and the ground of the Arduino to the PS360+'s button ground, which powers the Arduino. I then have a button output from the PS360+ going into the button, and the button's ground is connected to an Arduino pin. That Arduino pin's mode is set to INPUT. I then have another pin with an LED which is set to the value of the input pin.
  For some reason, the Arduino seems to get random input from the button(Though it does seem to react somewhat to buttons presses), and the PS360+ does not recognize the button press. Setting the input pin to pullup mode has even less result, and never reads low.
Anybody got any ideas? Here's my current circuit diagram. 1P is a +5V output. I think that it's an internal pull-up pin like the Arduino's, but I am not certain.
And my current code:
int buttonlisten = 22;
int led = 53;
int val = 0;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(buttonlisten, INPUT);
}

void loop() {
  val = digitalRead(buttonlisten);
  digitalWrite(led, val);
}

Thanks!

Are the two grounds on the board connected internally?

Yes, All grounds on the PS360+ board are connected internally.

You should connect the vcc of the PS360 directly to 5v on the arduino. Not to Vin. Vin will make the voltage go through the voltage regulator first. Supplying a 5v regulator with 5v will result in a voltage lower than 5 volt. Putting 5volt on a input pin while the atmega runs at a lower voltage could damage the chip.

Oh, scary. I will definitely do that. Thanks for the advice.

I think the idea of putting the arduino between the button and ground is the problem here — 1P appears to be the input for the controller button, and you can't expect to take an 'input' from the button on both pins at once.
Try connecting one lead of the button back to its ground, and the other to 1P (as it would be originally I assume). Then solder/connect another lead from the button's non-grounded pin to an arduino pin designated as INPUT_PULLUP.
This way you have two pulled-up input pins connected to the same button pin, which are both pulled low (since Arduino & PS360+ share GND) when the button is pressed.

Perfect! This works quite well, and does not seem to interrupt any inputs on either board. Thanks a lot!


text:
Embedded-c, schedule a function?
Simple question, of course if you do this
FunctionA();
Delay(1000);
FunctionB();
FunctionC();

it will call A, then wait a second, then call B, then call C.
How does one do this? ...
FunctionA();
.. Invoke FunctionX one second from now ..
FunctionB();
FunctionC();

So, I want it to do A, then without stopping continue to B and then C.  Later (one second later) it will do X.
Of course, in c# you'd just use a coroutine, in Android you'd use a Handler or whatever.
Surely there's a command along the lines of .. invoke in .. 2000 .. method.
Really sorry for the basic question, experts, I am damned if I can find this anywhere. Thanks!

Surely there's a command along the lines of .. invoke in .. 2000 .. method.

Not "a command" but you can make up something like that easily enough. Example:
// Function scheduler demo
// Author: Nick Gammon
// Date: 11 July 2015

typedef void (*GeneralFunction) (); // function pointer type

GeneralFunction wantedFunction = NULL;  // function to call
unsigned long functionTimerStarted;     // when the timer started
unsigned long delayPeriod;              // how long to wait (ms)

void functionA ()
  {
  Serial.println ("Function A");
  }  // end of functionA

void functionB ()
  {
  Serial.println ("Function B");
  }  // end of functionB

void functionC ()
  {
  Serial.println ("Function C");
  }  // end of functionC

void functionX ()
  {
  Serial.println ("Function X");
  }  // end of functionX

void scheduleFunction (GeneralFunction f, unsigned long when);  // prototype
void scheduleFunction (GeneralFunction f, unsigned long when)
  {
  wantedFunction = f;
  functionTimerStarted = millis ();
  delayPeriod = when;
  }  // end of scheduleFunction

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();

  functionA ();  // call this now
  scheduleFunction (functionX, 2000);  // call this later
  functionB ();  // call this now
  functionC ();  // call this now

  }  // end of setup

void loop ()
  {
  // see if time to call the delayed function
  if (wantedFunction && millis () - functionTimerStarted >= delayPeriod)
    {
    wantedFunction ();
    wantedFunction = NULL;  // don't call it again
    }  // end of if time up

  // do other wanted stuff here

  }  // end of loop

This uses:

A function pointer to remember which function to call in the future.
A global variable to remember when you wanted this timing interval to start.
A global variable to remember how long to wait.

In setup() I called a function to save this information for future use:
  scheduleFunction (functionX, 2000);  // call this later

Then in loop() we see if the time is up, and then call the function.
This example just calls functions with no arguments, things will get more complex if you want to call a function with an argument. It would even be possible to remember the argument, but it may be unnecessarily complicated to explain how to do that, since your example did not ask for it.
You could also even schedule multiple functions, but again, showing all that adds to the complexity of the explanation.
For more information about function pointers, see Function pointers / function callbacks / function variables.

Hi Nick. Thanks for that detailed code sample!  Thanks for letting me know there is indeed no "schedule" or "invoke" like function .. interesting. It's interesting you really have to "roll your own" just using the main run loop. Of course, this is a "one shot" solution, if you send another scheduleFunction it will walk over the previous one right!  I'm wondering is there a trivial way to say start a new thread or some such? perhaps that would allow for a more flexible solution.  Again it's priceless info there is NO schedule or invoke -like command, thanks!!!!

There is no pre-emptive multi-tasking because the (AVR) hardware does not support it. The Unix-based boards probably do. The best you can manage is co-operative multi-tasking, where you give other functions a chance to run at some suitable point. If you wanted to have multiple functions scheduled you would have to expand what I wrote a bit, for example to have an array of outstanding functions. However you may want to design your project with a different paradigm, people have done quite complex projects without scheduling functions to run in the future.

@JoeBlow: No, there is no trivial way to start a new thread. You would need to install some sort of scheduler, which you don't have in the standard Arduino environment. You can take a look to the ArduinoThread library though. It is not threads, it's rather a generalization of Nick Gammon's approach.

Hi Nick ... fascinating.  Brilliant, thanks.  Hi Edgar, that's awesome - again thanks for the definitive information.  You guys are the best.  Yes I will just write my own threadesque, blocker, etc.  Thanks!!!!!

@NickGammon: Preemptive multitasking is possible on the AVR. See Atomthreads for example. I never tried, and it's likely to be expensive in RAM, as you need a per-thread call stack.

Hmmm, OK. That appears to use a timer to "pre-empt" whatever-it-is that is executing. No doubt that can work after a fashion, but of course you need the timer interrupt, which you may not want to give up, and you have to, of course, have interrupts enabled. Joe: You are probably best off designing differently. For example, in my code I tested in the main loop if it was time to call a scheduled function. You could, of course, simply have flags for things that need doing (eg. turn the tank pump off) and check directly.

The other thing is that RAM is generally one of the most precious things on these processors, as many problems I have seen with crashes are when people use up all their RAM. So maintaining multiple call-stacks is going to make that problem somewhat worse.


text:
How to program for two Arduinos with different code but share one same .h?
I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder.
So I put 'share.h' and main.ino in one folder, and the ino is like:
#include "share.h"
#define TX
#ifdef TX
void setup(){...something for Tx...}
void loop(){...}
#else
void setup(){...something for Rx...}
void loop(){...}
#endif

The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the #define line, and upload. Then I have to change port to 42(the Rx one), comment the #define line and upload. So inconvenient!
So do you have any good ideas? Much appreciation!


text:
Converting float to String
How can I convert a float value into a String object without implementing any library?
I'd like to avoid using char array.

Why would you want to "avoid" a char array?  Surely the String is the one to avoid?

Why is char better than string?

Because Strings use dynamic allocation which is bad on a microcontroller with only 2K or RAM. With char you usually use static allocation and just allocate what you need. Strings are evil - a crutch for people who can't be bothered to do it properly.

I've been trying to convert integers, floats, dates and strings and String looked to be the easiest. So how can I convert all that in a char?

The conversion is the same, but the storage medium is all that is different.

So I will need a for loop to print the array?

No.  A "char array" is the native "string" format in C.  The String object is an Arduino specific wrapper around it that adds extra bloat.

What function can I use to convert from a Float? sprintf() works only for Ints

A "String object" is (implemented by) a library, so by definition, your question cannot be answered. dtostrf() will do the conversion for you.

@NickGammon, I deleted my comment.

If you want to do it manually, rather than using the standard tools (dtostrf() for example) then you need to think mathematically.
A floating point number is made up of two distinct parts - the integer part and the decimal part.
For instance the number 123.4567 is made up of the integer part 123 and the decimal part 4567.  Chopping off the integer portion is simple to do, and if that happens to be just one digit then you can simply add that as the first digit of your output.  In this case, though, it isn't.
So what to do?  Simple: keep dividing the number by 10 until it is just one digit.  But be sure to count the number of times you divide by 10.  So the example above would end up as 1.234567 with a divide count of 2.  This is the same as the scientific representation, 1.234567×10².
So now you have it divided you can chop off the integer (just cast it to an int), add that integer part to your string, then remove it from the source number.  So you end up with "1" and 0.234567 and a count of 2.
Now multiply by 10 and subtract one from your count, so you get 2.34567 and a count of 1.  Grab the integer portion and add it to your string, then remove it from your number.
Keep repeating until your count is 0, at which point you have now done all the integer portion - so you can now add a "." to your string.
You now just keep repeating the same process again and again until the absolute value of the count equals the number of decimal places you want to print.
For negative numbers you should start by placing a "-" in your string, then taking the absolute value of the number (the number as a positive).
Or you just use the standard library function dtostrf().


text:
Arduino webserver: faster alternative to "indexof" for parsing GET requests?
I have a webserver successfully running on an Arduino Mega, but I'm trying to make sure it's parsing the GET requests in the fastest way possible. This is what the relevant code for the GET requests looks like:
String readString;
EthernetClient client = server.available();
if (client) {
  while (client.connected()) {
    if (client.available()) {
      char c = client.read();

    if (readString.length() < 20) {
      readString += c;
    }
    ...
    ...
      if (readString.indexOf("?a1o") >0){
        mySwitch.send(a1o, 24);
      }
      if (readString.indexOf("?a1c") >0){
        mySwitch.send(a1c, 24);
      }

The sketch checks for 40 possible GET variables. I'm running it as a local webserver with the address: http://192.168.0.180.
-Is there a command faster than "indexOf" that I could be using?
-I saw some information suggesting that sometimes "parseInt" can be faster. Is there any way for me to make that work even though my local base URL is already full of integers? I would be willing to convert the commands into integers (like "11" instead of "a1o") if there was a way to use parseInt or another faster command with it.
Thanks!

Can you post an example of the sort of input you are processing? Is it, perhaps: http://192.168.0.180?a1o or http://192.168.0.180?a1c, or might you have multiple of them on the GET line?

Maybe state what these 40 GET variables are. Is there a pattern? Eg. a1o, a1c, a2o, a2c, a3o, a3c ... ?

yes, that's exactly how it looks: 192.168.0.180?a1o

There's a pattern, but it doesn't have to be that way. Currently it goes: a1o, a1c, a2o, a2c, etc until a5o, a5c. Then it starts: b1o, b1c, etc. ('o' stands for 'open' and 'c' stands for 'close', it's opening and closing different wireless outlets). I would have no problem though renaming them all, like just giving them all numbers or a clear pattern, if there was a way to make it parse faster.

Extract the query string once, and store it in a variable. Next test whether this variable is 'a1o' or 'a1c', etc. Using switch-case would be faster than a whole list of if statements.

Thanks Gerben! I will try using Gammon's code below, but with the addition of using your advice about the switch-case.

I know it is very old post but can you please show how to parse POST method with your code?
It should be very useful for beginners like me :-)
Thank you so much!
PPT

Well, for fast parsing I wouldn't use String for a start. I've written an example (below) which does away with the String class, and also demonstrates parsing the line once.
#include <SPI.h>
#include <Ethernet.h>

// Enter a MAC address and IP address for your controller below.
byte mac[] = {  0xB3, 0x8D, 0x72, 0x1D, 0xCE, 0x91 };

// Our IP address
IPAddress ip(10,0,0,241);

// Initialize the Ethernet server library
// with the IP address and port you want to use
// (port 80 is default for HTTP):
EthernetServer server(80);

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

  // start the Ethernet connection and the server:
  Ethernet.begin(mac, ip);
  server.begin();
  Serial.print(F("Server is at "));
  Serial.println(Ethernet.localIP());
  }  // end of setup

// how much serial data we expect before a newline
const unsigned int MAX_INPUT = 100;
// the maximum length of paramters we accept
const int MAX_PARAM = 10;

// Example GET line: GET /?foo=bar HTTP/1.1
void processGet (const char * data)
  {
  // find where the parameters start
  const char * paramsPos = strchr (data, '?');
  if (paramsPos == NULL)
    return;  // no parameters
  // find the trailing space
  const char * spacePos = strchr (paramsPos, ' ');
  if (spacePos == NULL)
    return;  // no space found
  // work out how long the parameters are
  int paramLength = spacePos - paramsPos - 1;
  // see if too long
  if (paramLength >= MAX_PARAM)
    return;  // too long for us
  // copy parameters into a buffer
  char param [MAX_PARAM];
  memcpy (param, paramsPos + 1, paramLength);  // skip the "?"
  param [paramLength] = 0;  // null terminator

  // do things depending on argument (GET parameters)

  if (strcmp (param, "foo") == 0)
    Serial.println (F("Activating foo"));
  else if (strcmp (param, "bar") == 0)
    Serial.println (F("Activating bar"));

  }  // end of processGet

// here to process incoming serial data after a terminator received
void processData (const char * data)
  {
  Serial.println (data);
  if (strlen (data) < 4)
    return;

  if (memcmp (data, "GET ", 4) == 0)
    processGet (&data [4]);
  }  // end of processData

bool processIncomingByte (const byte inByte)
  {
  static char input_line [MAX_INPUT];
  static unsigned int input_pos = 0;
  switch (inByte)
    {
    case '\n':   // end of text
      input_line [input_pos] = 0;  // terminating null byte
      if (input_pos == 0)
        return true;   // got blank line
      // terminator reached! process input_line here ...
      processData (input_line);
      // reset buffer for next time
      input_pos = 0;
      break;

    case '\r':   // discard carriage return
      break;

    default:
      // keep adding if not full ... allow for terminating null byte
      if (input_pos < (MAX_INPUT - 1))
        input_line [input_pos++] = inByte;
      break;
    }  // end of switch
  return false;    // don't have a blank line yet
  } // end of processIncomingByte

void loop()
  {
  // listen for incoming clients
  EthernetClient client = server.available();
  if (client)
    {
    Serial.println(F("Client connected"));
    // an http request ends with a blank line
    boolean done = false;
    while (client.connected() && !done)
      {
      while (client.available () > 0 && !done)
        done = processIncomingByte (client.read ());
      }  // end of while client connected

    // send a standard http response header
    client.println(F("HTTP/1.1 200 OK"));
    client.println(F("Content-Type: text/html"));
    client.println(F("Connection: close"));  // close after completion of the response
    client.println();   // end of HTTP header
    client.println(F("<!DOCTYPE HTML>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("<title>Test page</title>"));
    client.println(F(""));
    client.println(F(""));
    client.println(F("
My web page
"));
    client.println(F("
Requested actions performed"));
    client.println(F(""));
    client.println(F(""));

    // give the web browser time to receive the data
    delay(10);
    // close the connection:
    client.stop();
    Serial.println(F("Client disconnected"));
  }  // end of got a new client
}  // end of loop

The incoming lines from the client are captured in a static buffer. This eliminates issues with memory fragmentation (caused by using String).
processIncomingByte is called for each byte from the client. Once an entire line is assembled it calls processData. If that finds a "GET " line it calls processGet. That looks for the parameters on the GET line. The GET line looks like this:
GET /?bar HTTP/1.1

So we need to get between the "?" and the next space, to get the parameter ("bar" in this case). This can be accomplished by finding their positions with strchr.
Finally (as a simple example) I tested with strcmp for a direct match on various words. You could probably make that more efficient but I doubt it would matter much.

I just implemented these changes, and it's noticeably a TON faster!!!!! I'm so happy with this! Thanks a lot for the help!

I converted all my GET parameters into integers so that I could use a switch-case. I converted "param" into an integer like this:   param2 = atoi(param); and then I did "switch(param2);". Can you please tell me if this is a bad way of doing things? Thanks.

That's fine, it will give you a slight speed increase. If you liked my answer please "accept" it by clicking the tick mark next to it. This lets other users know that the answer was helpful. Thanks!

Thanks! JSYK how much faster your code was: beforehand it took 2-3 seconds after clicking the web link before the wireless switches would get activated. Now it only takes 200-300 ms. This is very useful to me.


text:
Number of elements in an array char
What kind of function can I use to know how many elements are in an array char?
sizeof() gives the number of 'spaces' available so it doesn't work for me.

Can you give an example please? eg. char foo [100] = "bar"; - is that what you mean? You want the answer: 3?

yes that's right

You want strlen.
char foo [100] = "bar";
Serial.println (strlen (foo));   // --> prints 3

If the answer worked for you please click the "accept" button (it looks like a tick). That way other people will know that the solution worked.

I had to wait a couple of minutes to do that

Note that this will only work if the data in your char[] contains an ascii string, and is properly null-terminated. Furthermore, if you have a long string in the char[], and you overwrite it with a shorter string without adding the null-termination, you will get the size of the older string.

Quite right. My answer was for the question as presented. The things you mention should be taken into account for null-terminated C strings.

I know you have your answer from @NickGammon, but I'd just like to add a bit more in-depth information about how all this works.
sizeof() is not a function in the normal sense of the word.  It is an operator which gives you the number of bytes of memory allocated to whatever you pass to it.  If you pass it an array then it returns the number of bytes that array has available to it.  If you pass it a pointer to an array then it returns the size of that pointer, not the size of the array.  If you pass it an integer variable it returns the number of bytes used by that integer variable (2 on an 8-bit system like AVR, 4 on a 32-bit system like the Due).
So some examples:
char array[50] = "hello";
// sizeof(array) = 50.
char *array_p = array;
// sizeof(array_p) = 2 or 4 depending on architecture.
char single = 'a';
// sizeof(single) = 1.
char string[] = "hello";
// sizeof(string) = 6 (5 letters plus \0) - it allocates the memory at compile time to fit the string

Now strlen().  How exactly does that differ from sizeof()?  Simply put, strlen() counts the number of characters in a character array up until it reaches the character \0 which is the "NULL" terminating character of a C string.  Let's take the examples before but use strlen instead:
char array[50] = "hello";
// strlen(array) = 5.
char *array_p = array;
// strlen(array_p) = 5.
char single = 'a';
// strlen(single) = ERROR!  strlen() doesn't operate on single characters.
char string[] = "hello";
// strlen(string) = 5.

You notice it always returns the number of characters in the string up to, but not including, the trailing \0 character.
In its simplest form the strlen() function might look like this:
int strlen(const char *data) {
    int c = 0;
    const char *p = data;
    while (*p) {
        c++;
        p++;
    }
    return c;
}

Basically it starts at the first character in the string (*p = data), examines if it's a \0 or not (while (*p)), increments the count of characters (c++) and moves on to the next character in the string (p++).
If you want to iterate through your string in your program you could call strlen() first to get the number of characters in the string then use that value in a loop.  That is a bit wasteful, since strlen() first iterates through the string, so you end up iterating through it twice.  It is far more efficient to learn how best to step through each character in the string until you find the terminating character, such as how the strlen() function uses the pointer to move through memory.  You can also see just how vital it is that you ensure the \0 character exists at the end of the string, otherwise how will functions like strlen() know when to stop?  They can't know how long the string is (sizeof() will return the size of the pointer it is passed, not the size of the array), so they have to have some kind of manual marker, and the convention in C is to use \0.
Note that Arduino's print() functions actually do it very inefficiently.  If you do something like:
char message[] = "Hello";
Serial.println(message);

It will actually do quite a lot of work it doesn't really need to.  Taken step by step it:

calls println(message)
which calls write(message)
which gets the string length with strlen(message)
and calls write(message, length)
which then loops from 0 to length-1 sending each character of message to write() in turn.
finally prints the \r\n for the new-line.

So it actually ends nested around 4 functions deep, and iterates the entire string twice. A classic example of how to waste processing time.  By iterating through the string once looking for the \0 character in the write(message) function (step 2) it would operate at least twice as fast.  Good old Arduino...

Re “In its simplest form the strlen() function might look like this”, in a shorter (perhaps simpler?) form it  could look like:  int strlen(const char *data) {     const char *p = data;     while (*p++);     return p-data-1; }

@jwpat7 I said "simplest", not "shortest and most compact".  That form, while smaller and more efficient, is much much harder for the OP (who is obviously not a programmer) to understand.

Agreed :)  Also easier to make mistakes in.  And if the \0 is the last accessible byte in a segment, the *p++ will fault. But int strlen(const char *data) { const char *p = data; while (*p) ++p; return p-data; } avoids that problem.

Actually, *p++ won't fault even if the \0 is the last accessible byte in a segment; the *p part will access the last byte; the ++ part will set p to an invalid address; but as that  invalid address doesn't get referenced, on a typical machine no fault occurs.

It is a compile-time macro ... It's not a macro, it's an operator (like "+" and "-" are operators). They are lower-level than macros which are things done at pre-processor time. See sizeof operator. Also Operators in C++

Indeed it is. Three years ago I thought differently.

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


text:
How to program for two Arduinos with different code but share one same .h?
I am now programming for two Arduinos. One is used as Tx and the other is Rx. Of course they are programmed by different codes, but they share some same .h files I programmed(let's say 'share.h'), which are not libraries and shouldn't be put in Arduino's 'library' folder.
So I put 'share.h' and main.ino in one folder, and the ino is like:
#include "share.h"
#define TX
#ifdef TX
void setup(){...something for Tx...}
void loop(){...}
#else
void setup(){...something for Rx...}
void loop(){...}
#endif

The shortage is that every time I want to update my code to the two unos, I have to: first change the board port to 40(the Tx uno) in ide, add the #define line, and upload. Then I have to change port to 42(the Rx one), comment the #define line and upload. So inconvenient!
So do you have any good ideas? Much appreciation!

So, you want a common file, but you don't want to put it in a common file location?

Are you on a real operating system, or are you using Windows?

@Majenko Sorry but can't quite follow you. What's a real operating system? I'm using windows 7.

Then you're not using a real operating system and I can't suggest a way to do it in the Arduino IDE.  If you were using a real operating system like Linux or OS X then you could create a symbolic link so that the share.h file was shared between two locations.  Instead you can't because windows doesn't provide that most basic of facilities.

@Ignacio Vazquez-Abrams Er you can say it is, and there may be other ways.

Something easier than writing or removing two backslashes? Uhm... How can you determine what is the device you want the program to be compiled? Since I suppose that the hardware is the same, the only easier solution I can figure out is to make two different programs and then open them in two different Arduino IDE windows. This way you won't even need to switch port...

@frarugi87 but then how to share the share.h? This is the main problem.

Modify your hardware to produce a HIGH on a digital input, then have your program decide whether it's TX or RX based on that input.  Then it is always the same code, plus a resistor.

Thanks to everybody, now I get a better solution. It is changing the build path to our working directory, and then we can use relative path!
Here are the deatiled steps:

Click IDE's File-Preferences and find where it storages preferences.txt. Mine is at C:\Users\Administrator\AppData\Roaming\Arduino15\preferences.txt
In the txt file add this line: build.path=D:\MyProject\ArduinoBuild. This means let Arduino put the temp files in this directory, such as the .h waiting to compile.
Because the .h Arduino automatically generated from our .ino is in ArduinoBuild directory, you can now use #include "./../Share/SomeShare.h" in order to include the D:\MyProject\Share\SomeShare.h

Here is the same question asked in another stackexchange board: Here

If your answer worked, select it as the correct answer.

@lan M It says i can only do it tomorrow.

I confronted this exact issue a little while back when writing some sketches that hard shared information. In particular github.com/nickgammon/arduino_sketches
Whilst another IDE may help, I wanted to make my sketches usable by people with the default IDE.
There are a few (annoying) issues here:

You can't use relative folders as suggested in another answer, because the IDE copies your current sketch folder to a temporary folder and compiles from there. It won't copy other nearby folders that happen to be mentioned in .h files.
You can make soft links (in Linux anyway) as suggested, however that makes it hard to do Git control on them. My first attempt had the link (only) appear in GitHub, which meant that the links didn't compile, once you downloaded them (via the .zip file option in GitHub).
I switched to hard links, but then had another issue. If you edit a file in the IDE, and save it, evidently this becomes a new file, and so the files in other folders, which are now hard-linked, have the older version and not the newer version.

The best solution I could come up with (and I am open to suggestions) was to have a "master" sketch - which has the "real" files you want to include. The other folders have links to them. However if you change the master folder you have to recreate the hard links. I wrote a shell script to do that, but it is still an ugly solution. However since it is a manual process anyway, under Windows you could simply make a copy of the files, when you change the master one.
The other (simpler) alternative would be to make a library, and then simply change the files in that library. That gives you better Git management. The only thing is that you have to edit the library, and then go and test the sketch. It's not that bad.

And I found that after I added the h as library, no matter how I change the content of the h, the first version is always used in ide.

That shouldn't happen unless the IDE doesn't expect the library to change in-between compiles. If that is the case, even the library idea has flaws.

Since it is unavailable to use ./../share.h, I think I may use absolute path. I can define the absolute path of the lib in a .h, and anyone else using my program only need to change this.

Yes, presuming they have the exact same folder setup as you do. Better not put your name for the home folder, for example. Better hope that they have the sketchbook folder in the same place you have. There are a lot of things that can go wrong there.

Thanks. And I find another way. See it in my own answer. :)

@NickGammon Your first point there about relative paths is making a wrong assumption. It's not because the IDE copies the files.  You assume that a relative path is only from the "build" location, but it isn't. It's taken from each of the given include paths (-I...) in turn until it's found.  The build location happens to be one of those paths, as are a myriad of others (including all the library paths and system include locations). If the IDE included the sketch folder in the list of includes then you could use relative paths even with it copying files to the build area.  By the way, it ...

... doesn't "copy" files at all, but it has all the files open in the IDE and when you compile it saves those files out to the build folder from the IDE, not copy them from the sketch folder.  That's why the IDE doesn't have to save your work when you compile.

I classify "saving the files" into a temporary folder as copying them. I agree that you can compile a file you haven't saved, but surely, that is a copy in the build folder. It is a copy of the file you have open in the IDE.

Anyway, I tried the idea out of using the ../whatever/foo.h idea and it didn't work, so my assumption wasn't exactly wrong.

Ok, first of all you have to answer this question:

How can I tell the compiler what program it should compile?

The first (and easiest) solution is to have the preprocessor to this job. It's just a matter of writing two /...
Personally, instead of wrapping everything in an ifdef, I would have done something like
#include "share.h"
#define TX
#ifdef TX
#define setup_tx() setup()
#define loop_tx() loop()
#else
#define setup_rx() setup()
#define loop_rx() loop()
#endif

void setup_tx(){...}
void loop_tx(){...}

void setup_rx(){...}
void loop_rx(){...}

This way I could put the two different setup/loop pairs in two different files (e.g. tx.ino and rx.ino). Moreover the ifdef block can be moved in an h file.
NOTE: I'm not sure wheter the function redefinition works well, because I never tried it. If it doesn't work you can try doing the opposite (i.e. #define setup() setup_tx() and so on) or, in the end, make single-line functions (i.e. void setup(){setup_tx();} and so on).
Another solution can be applied if the processors are different. For instance if you have an Arduino UNO as transmitter and an Arduino Mega 2560 as a receiver, you could write:
#ifdef __AVR_ATmega2560__
- receiver functions
#else
- transmitter functions
#endif

But this would require you to switch processor along with the port.
The third solution is to place the shared h file in an include directory. You can do this by using a common include dir:

The include path includes the sketch's directory, the target directory (/hardware/core//) and the avr include directory (/hardware/tools/avr/avr/include/), as well as any library directories (in /hardware/libraries/) which contain a header file which is included by the main sketch file.

(See here)
You can also pass the -Idir option to avr-gcc to include also dir in the include dirs list, but this requires you to change the boards.txt file.
The last solution I can think at is to compile both programs, load the same files on both arduinos and then choose at runtime what is the correct program to use by assinging a pin to the "choice of program" function.
For instance you assing pin 8 to this function. On the TX board you connect pin 8 to VCC, while on the RX board you connect it to GND. Then the program is:
#include "share.h"

// Loop function callback (to speed things up)
typedef void (*loopfunction)();
loopfunction currentloop;

const int RXTX_PIN = 8;

void setup()
{
    pinMode(RXTX_PIN,INPUT);
    if (digitalRead(RXTX_PIN))
    {
        setup_tx();
        currentloop = loop_tx;
    }
    else
    {
        setup_rx();
        currentloop = loop_rx;
    }
}

void loop()
{
    currentloop();
}

void setup_tx(){...}
void loop_tx(){...}

void setup_rx(){...}
void loop_rx(){...}

IMHO the best solution is the first one, i.e. the define one. But... You should choose the best for your particular problem.
Bye

Thanks. But I find another way. See it in my own answer. :) On account of your hard work by commenting such a long answer, I choose your answer as the "accepted answer".

Because you're using Windows there is no easy way of doing what you want to do.
If you were on Linux or OS X you would be able to create a symbolic link so that your shared file can exist in more than one location:
$ ln -s /path/to/real/share.h share.h

On Windows there is then just two options that I can think of:

Turn your shared file into a library.  I don't know why you are so adverse to this, since it is by far the simplest option.  Just create a folder "MyProjectShared" in your libraries folder, then name you shared header "MyProjectShared.h" within that folder.  Then #include <MyProjectShared.h>.  Of course, choose a sensible name not MyProjectShared.
Change to a different IDE that will allow you to add include locations.  One example is my UECIDE which allows you to add the line:
#pragma parameter board.flags=-IC:/Path/To/Other/Includes

to the top of your sketch, which adds another location to find header files while compiling.
Another thought has just occurred to me.  If the two sketches are side by side in a folder (say Arduino/Sketch1 and Arduino/Sketch2) then you may be able to use a relative path.
In Sketch2, do:
#include "../Sketch1/share.h"

Thx. I don't use library because I use git for my code. If there are a lot of folders dispersing in my computer, it is hard to track them in git(maybe there is a way to approach it?). And I found that after I added the h as library, no matter how I change the content of the h, the first version is always used in ide... I will try the idea tomorrow.

@Turtle I have just had another thought - take a look at my edit.

I remembered that Arduino ide doesn't support sub folder. Anyway I will have a try tomorrow.

@Turtle It doesn't need to - two separate sketches, as long as they are in the same place, you should be able to use a relative path.

My esthetic preference would be to put share.h in .. instead of in Sketch1, so the include looks like #include "../share.h"

@jwpat7 Or put it in ../shared so it's #include "../shared/share.h"

@Majenko, yes, that looks like a good alternative

"then you may be able to use a relative path" - surely that doesn't work? The IDE copies files into a temporary folder. It won't copy files from another folder in the way you have it.

@nickgammon it's been so long since I used the Arduino IDE I can't remember if it includes the sketch folder in the list of include paths or not. UECIDE certainly does.

Even if it did, the build path is not the sketch path. For example /tmp/build4769560075719248978.tmp/sketch_jul09a.cpp. So if it went up one level you would go to /tmp/shared/share.h which is a directory and file which won't exist.

Sorry but your last opinion doesn't work. But I find another way based on your opinion. See it in my own answer. :)

@NickGammon Except that's not how C includes work.  The given path is tried relative to each of the given include paths (-I...) until it is found.  "." is normally an implicit include path, though many people choose to add -I. to their compilation command anyway.  If the Aduino IDE includes the path to the sketch folder in its include paths (which evidently it doesn't) then it would find ../share/share.h relative to that path.   See this paste of a test I just performed: http://pastebin.com/hrz4EyVs

You can feed the compiler a command-line switch, -D<define_name>, so for your TX you could have a project that has -DTX and for the RX -DRX.
Then you can share the code between the two projects and you don't need to change the code when you're compiling.

But how to do this in arduino ide?

You could also use:

in transmitter.ino
#define TX 1
#include "share.h"

in receiver.ino
#define RX 1
#include "share.h"


text:
SD Library writing char in a file
I'm trying to write into a file using this code from the example of the library:
String dataString = "";
int sensor = 0;
dataString += String(sensor);
dataString += ",";
sensor +=1;

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataString);
  dataFile.close();
}

I have a char array that I want to write in the file, but it works only with String objects apparently. What can I do?

Try using dataFile.write(arrayName);
https://www.arduino.cc/en/Reference/FileWrite

You can write char arrays? What makes you think you can't? Example:
char dataBuffer [80];
strcpy (dataBuffer, "Hello, world");

File dataFile = SD.open("datalog.txt", FILE_WRITE);
if (dataFile) {
  dataFile.println(dataBuffer);
  dataFile.close();
}

Do C++ strings still need the '\0' char at the end?

Depends on the type of string you are talking about. The strings manipulated by the standard library (eg. strcpy, strcmp, strcat) expect strings to have a 0x00 byte at the end.


text:
How to test Arduino board?
A little history: I have two Arduino Uno and I couldn't program them by IDE, I got these errors:
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00

So I googled it for a while and I suspect of missing bootloader on atmega micro on the board, as I don't have AVR programmer I programmed both Arduinos with Raspberry Pi and Arduino IDE tool through ICSP pins.
It (burning bootloader) runs perfectly on both Arduino. One of them got fixed and got back to normal, but the other one gave me same error, so I changed their Atmega micro, but same result. Second Arduino (bad one) can't transfer program to AVR even with other one (good one) AVR so both AVRs on the boards are good.
The program (blink LED) run even on the bad Arduino and pin 13 blink.
My questions are:
How could I test the suspected Arduino board? Is the second Atmel micro near usb female port need bootloader too?

Update 1: I follow this tutorial but my Arduino couldn't go to DFU
  mod by shorting the pins. When I connect those pins led pin 13 not blink and lsusb command show Arduino not Atmel.
Update 2 : I went through this question and this
  troubleshoot to upload bootloader to Atmel USB device but my
  second Arduino (bad one) didn't respond and gave me this error :

Atmega chip detector.
Written by Nick Gammon.
Version 1.17
Compiled on Jul 13 2015 at 11:14:35 with Arduino IDE 105.
Attempting to enter ICSP programming mode......................................................
Failed to enter programming mode. Double-check wiring!
Programming mode off.

Is it possible my Atmega16U2 chip is burned?
Update 3 : I do reach the point that I am pretty sure Atmega16U2 is
  dead and it isn't responding to its ICSP pins and it blocks any USB to AVR connection. I check the wiring and I
  test it on good Arduino and its sequence are correct and it works on good one. Now what can I
  do, as Atmega16U2 is not rechangeable, should I throw bad Arduino away?

See http://arduino.stackexchange.com/questions/13292/have-i-bricked-my-arduino-uno and see if that helps.

Do you have anything connected to the serial? (Pins 0 and 1)

@TheDoctor No sir, all pins are free.

This answer is for your 3dr Update - should you throw it away?
I'd say no, if you are comfortable with using the Raspberry PI as programmer, as you already did.
You will not be able to use the USB-based programming, nor you will be able to emulate USB peripherals, but that's it.
Everything else will (or should) work normally, so why would you throw it away? :-)
I also suggest you grab the stronger magnifying lens you can find and have a look at the soldering of all the components. Especially those connected to the Atmega16U and the chip itself. Maybe it's not broken, but there is some short caused by conductive debris or by some excess of soldering material. If that's the case, it might be easy to remove it.

The problem is i can only upload bootloader with rasberry pi but i can't upload sketch into it. I don't know why ?

I don't know either (although it might have to do with the bootloader interfering with further uploads), but I see 2 options, at roughly the same price: either throw away the arduino and buy a new one (3-4 euros on ebay) or buy an USBASP (about 4-5 euros on ebay). The USBASP should be able to program the main AVR, as long as it is alive. And it might be useful if you do - on another board - something which requires reprogramming the Atmega16U, so you can simplify the upload process.

Btw, the USBASP would also enable you to save a bit on future purchases of arduinos: with the USBASP you can program also the mini-pro flavor of arduino, which is basically the same micro on a much smaller PCB, without USB connector. Price < 2 euros.

does the built-in arduino LED light up?? If yes try connecting your arduino in another uno usb port or try pressing the reset button on your arduino uno.

The power LED light and i test it with other cable and i even used reset button trick, non of them works.


text:
Programming Arduino for Mindflex
I am learning brain wave programming from Tinkernut tutorial.
#include <IRremote.h>
#include <IRremoteInt.h>
#include <Brain.h>
IRsend irsend;
Brain brain(Serial);
const int ledPin = 3;
long interval = 500;
long previousMillis = 0;
int ledState = LOW;
int medValue;

void setup() {
  // Set up the LED pin.
  pinMode(ledPin, OUTPUT);
  // Start the hardware serial.
  Serial.begin(9600);
}

void loop() {
  // Expect packets about once per second.
  if (brain.update()) {
    Serial.println(brain.readCSV());
    // Attention runs from 0 to 100.
    medValue = brain.readMeditation();
  }

  // Make sure we have a signal.
  if(brain.readSignalQuality() == 0) {
    // Send a signal to the LED.
    if (medValue < 50) {
    irsend.sendNEC(0x10EFA05F, 32);
    delay(40);
    }
  }
}

The above code by tinkernut controls a single button of a tv remote only if the meditation value drops below 50.
My question is,
How to program arduino to control all the buttons of a tv remote ?

Get more probes. Or move up to a real neural control tool.

@IgnacioVazquez-Abrams can you please mention a real neural control tool ?

If I used more probes for different buttons then fluctuating meditation values could go out of control and tv goes crazy. Please correct me if I'm wrong

Instead of having more input sensors you could do some pattern matching? (Think morse code, but tbh I don't know much about these "mind control" sensor thingies, seems kind of limited to me)


text:
Separate ATmega 2560 - turn on a single LED - troubleshooting
I have got my own PCB with "some stuff" on it and first I want to make it run a simple "turn on LED".
My setup:

Atmega 2560
LED connected to PE4 (D2 in Arduino language) => PE4 - LED - 1K resistor - 5V
ceramic resonator (CSTCE16M0V53-R0 16MHZ) connected to XTAL1 + XTAL2 with 1MOhm resistor in between
all VINs are pulled to GND with capacitors

Upload is working through ICSP (MISO, MOSI, SCK, RESET, 5V, GND) with an USBasp
Here is my Arduino sketch, which I upload through the Arduino software:
void setup() {
  pinMode(2, OUTPUT);
}

void loop() {
  digitalWrite(2, LOW);
}

I checked the fuses on the Atmega as well:
avrdude: safemode: lfuse reads as FF
avrdude: safemode: hfuse reads as D8
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (H:FD, E:D8, L:FF)

avrdude uploads successfully: (output truncated!)
avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions
Reading | ################################################## | 100% 0.01s
avrdude: Device signature = 0x1e9801
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: writing flash (1518 bytes):
Writing | ################################################## | 100% 5.47s
avrdude: 1518 bytes of flash written
avrdude: reading on-chip flash data:
Reading | ################################################## | 100% 3.45s
avrdude: verifying ...
avrdude: 1518 bytes of flash verified

avrdude done.  Thank you.

Problem: the LED doesn't work. It is OFF all the time.
Any ideas why it is not working?

You have forgotten to mention what the problem even is.

You're right. I edited my post. The LED isnt blinking.

Have you tested the voltage at the pin?

When you say it doesn't blink, can you clarify: Is it on all the time, or off all the time?

it is off all the time. @NickGammon
// which pin do you mean

At the pin that's supposed to be blinking.

Try pin D52 (the SCK pin) since we know that works or you wouldn't have been able to upload the sketch in the first place.

Everything on the PCB is already hard wired and I cannot change. I can try to pull a temporary cable from D52 to the LED. I will give it a try // I will also test the LED itself (just apply 5V) and I will measure the voltage when I remove blinking and just turn the LED on. Will come back later!

Well, you should have access to the SCK pin, because you use that to program the thing. It's what you plug the ICSP cable into.

I updated the original question: I need to pull the output pin to LOW to make the LED work ( PE4 - LED - 1K resistor - 5V). When I put a cable between PE4 and GND the LED works. I have no LED attached to SCK but I can attach one to the ICSP header where I have connection to the SCK pin. Good idea! @NickGammon

You haven't mentioned any capacitors - any of the required decoupling capacitors on the power pins, the critical capacitors on the crystal, etc.  Also you haven't mentioned what your reset circuitry is like - are you pulling the RESET pin HIGH through a resistor?  Show your full circuit

I mentioned the capacitors of the power pins in my original question. They are all conected to GND with a 100nF cap. The crystal has got internal caps and RESET is pulled to HIGH with a 10K resistor. @Majenko

@jblaze That's not a crystal, that's a ceramic resonator - a very different beast.

@Majenko OK sorry, you are right. This comes straight from the Arduino2560 reference design.

@Majenko I added the relevant circuits to the original question

@jblaze Do you have an oscilloscope?  Can you see if the resonator is oscillating at 16MHz?  (Tip: set the probe to 10x)

@Majenko sorry I don't have an oscilloscope

@jblaze Then you really should see about acquiring one - even a dirt cheap ancient analog one from eBay that you can get for next to nothing.  They are an essential piece of equipment for circuit diagnostics.

@Majenko Thanks for the hint. When there is a problem with the crystal/ceramic resonator, would I have been able to program the Atmega?

@jblaze Quite probably yes - I can't remember the details on the Atmel chips, but either it uses the incoming SCK as the system clock, or it switches to the internal 1MHz RC clock, I forget which - it allows you to set the fuses regardless of what the rest of the circuit is doing.

I need to pull the output pin to LOW to make the LED work - I see. But it doesn't blink? It won't with your altered sketch.

@NickGammon I only want it to turn on for the first shot.

I'm losing track of your problem. The way you wired it, as far as I can tell, you expect it to turn on if you digitalWrite LOW to it. You initially said it didn't blink, and then you said I need to pull the output pin to LOW to make the LED work - so working as expected. What are you expecting exactly?

You are saying that the LED lights if you write LOW to it.

I need to pull the output pin to LOW to make the LED work

That's exactly what you expect.

Since the other end of the LED is wired to +5 V, then you need to drive the pin low to have a voltage difference over the LED, and for it to light.

I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

Yes, I suggest you do that.
Look at Engbedded Atmel AVR® Fuse Calculator to see what to set them to. I suggest the internal 8 MHz oscillator.

Yes, I have to pull it LOW but nothing happens.

Well it shouldn't take long to change the sketch to refer to pin 52 (SCK), upload that, jumper your LED to the SCK pin, and test.

Unfortunatly this doesn't work :-(

Please measure the pin with a multimeter. Upload your earlier "blink" sketch. See whether or not the pin changes voltage.

The pin set to LOW and measured against GND, the resistance is infinite. When I set the pin to high the voltage swings between 5-8mV.

Can you post a photo of you measuring that pin? I can't believe that you can upload new code, but the SCK pin is incapable of behaving like a normal pin.

Here it is: measure1 and measure2 - I disconnected SCK and 5V and measured between both pins

Normally voltages are measured with reference to GND. So what I expect you to do is run the sketch, and while the board is powered measure between the SCK pin and the GND plane.

OK, let me describe in detail: first I set SCK to HIGH and measured against GND: 5-8mV. Afterwards set SCK to LOW and measured against 5V: 0V.

I double checked the Atmega and it is a ATmega2560V, which is rated for 8Mhz. Any chance to fix this with the existing PCB? Change the Fuses to use the internal clock?

See amended answer.

OK thanks. Are these appropriate fuses to go for? "-U lfuse:w:0xc2:m -U hfuse:w:0x99:m -U efuse:w:0xff:m"

it is working!! Thanks to all participants!


text:
Arduino Mega PWM pins stop working for LEDs once servo is attached?
I can get LEDs to fade properly using PWM on pins 44-46 on the Mega2560 when I don't have a servo attached, but once I "attach" the servo in the code, then PWM pins 44-46 don't work for PWM. They can still work with digitalWrite, but not with analogWrite.
This is the code:
#include <Servo.h>
Servo myservo;
int led = 46;

void setup()  {
  myservo.attach(3);
  pinMode(led, OUTPUT);
  analogWrite(led, 60);
}

void loop()  {}

If I comment out the "myservo.attach(3);" line, then PWM works for the LED pin. Otherwise the LED stays off. Why would PWM on pins 44-46 stop working once the servo is attached?

Wanted to add: I just tested it on an earlier PWM pin (12), and the PWM worked fine even when the servo was attached. It seems that only 44-46 are having problems.

Looks like the mega has some clever servo handling features. Servo control always uses a timer of some sort and can conflict with the pwm timer. The first 12 servos knock out pins 44,45,46 ...

For Arduino Mega it is a bit more difficult. The timer needed depends on the number of servos. Each timer can handle 12 servos. For the first 12 servos timer 5 will be used (losing PWM on Pin 44,45,46). For 24 Servos timer 5 and 1 will be used (losing PWM on Pin 11,12,44,45,46).. For 36 servos timer 5, 1 and 3 will be used (losing PWM on Pin 2,3,5,11,12,44,45,46).. For 48 servos all 16bit timers 5,1,3 and 4 will be used (losing all PWM pins).

Wow, great find!! Thanks so much for the help! I already had switched to using pins 11-13 for the PWM, but I was still interested in learning the answer.


text:
How does one design for the power on transient conditions?
Following on from the question Reset an Arduino UNO by an command (software) and the excellent answer provided by mpflaga, the comment addressing option (1) suggests that there are design considerations for connecting an output pin to the RESET pin.

Option 1. or a variant can be a clean enough way to do this as long as
  power on transient conditions are designed for.
  - Russell McMahon

or more ominuously

From everything I've read, the first option is not recommended. - sachleen

Could someone tell me exactly what those considerations are? Is it that it is not as simple as connecting the two with a jumper cable - is additional circuitry (i.e. an RC timer) required, or is there a software solution?
I find the latter option unlikely as the device is rebooting, so unless the software fix is to ignore hardware interrupts (since a RESET is simply that, and the state of the output pins is unlikely to be known, or stable at reboot) for a few mS after reboot, I presume that a hardware fix is required.

An external driver, such as a simple monostable circuit (555 timer, if a little inelegant) could be constructed to pull the reset pin low for the right amount of time when triggered by the uC. However, you are far better off with Nick Gammon's software-only solution.

Atmel specifically recommend against driving /RESET low from an output pin, because the first thing that the reset process does is set all pins to high impedance, thus cancelling the reset pulse before the recommended reset pulse length has elapsed.
The recommended use of the watchdog timer does not suffer from these limitations. It is designed to reset the board (or there would be no purpose to having it) and it does a proper reset (unlike jumping to address 0x0000).

Reference
Atmel knowledge base - Software Reset

If you want to perform a software reset of your AVR you should use the internal Watchdog. Simply enable it and let it time out. When the Watchdog triggers it resets the program counter back to 0, clears all the registers and performs all the other tasks. This operation gives the same result as pulling the RESET line low.
You should not try to:

Use another pin of the AVR to pull the external RESET line. The pins of the AVR are tristated halfway through the minimum reset time, this releases the RESET line and hence nothing happens.
Jump to program location 0. Jumping to program location 0 does not clear all the registers and hence you do not have a "clean" reset.

Their suggested code to reset the processor:
#include <avr/io.h>
#include <avr/wdt.h>

#define Reset_AVR() wdt_enable(WDTO_30MS); while(1) {}

int main(void)
{
Reset_AVR();
}


text:
Read an analog signal without changing it? Or should I start over?

Hi! I'm still working on my kettle project. I want to obtain the kettle temp from the existing thermometer. I'm able to do this, but much like trying to look at an electron my circuits all reduce the voltage going to the kettle control board. This means the kettle's microcontroller (SN8P2722  SONiX) acts as if the kettle is cooler than it really is.

I don't think there is an easy way to program this microcontroller (if there is I'd love to know) -- I suspect the bad temp data will lead to overheating and hot water all over my kitchen.

Is there any way to passively obtain the voltage? I've been looking into the way that voltmeters work. Is this the right idea? is there a breakout board for this?
I really wanted to have the existing buttons still work as they always have. I've done this with power. I can press it remotely or on the kettle and I can tell of the kettle is on or off both on the control panel and remotely.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp.
Maybe I should try to replace the entire control board? What would be easier? I'm something of a beginner.

Please post the schematic for the voltage-measuring (temperature measuring) part of your system. The input impedance of the analogRead should be pretty high.

I'm the last person to question somebody who's making a tea-related project, but are you ultimately attempting to control your kettle over WiFi? Do you really need to be able to turn your kettle on from your computer or phone so that it's just boiling as you walk into the kitchen and thus eliminate all that unnecessary hanging around while OH MY WORD THIS IDEA IS GENIUS.

This means the kettle's microcontroller acts as if the kettle is cooler than it really is. So what? Just "press" the button again to turn it off when you determine empirically that you have reached the right temperature.

I can press all the other buttons remotely but I can't tell if it's working without knowing the kettle temp. Why wouldn't it work? You have pressed the button, you detected the "on" LED lit up. What could go wrong now?

Where are you attaching the wire going into the analog pin on the arduino? There might be some amplification/buffering going on on the board. Try tracing where the signal goes, and then connect the wire to the trace that's going strait into the microcontroller. Also, do you have any idea what kind of sensor they use for temperature measurement?

The goal is to have hot water waiting for me when I wake up or get home to save time. The other goal is just to learn how the kettle works and learn about micros.
" So what? Just "press" the button again to turn it off" This is the kind of kettle that heats water and keeps it at a set temperature for an hour. Many teas need water that is hot but not boiling. Monitoring the kettle manually defeats the purpose and would mean my project is worse than the kettle I started with.

I will see if I can figure out the "voltage-measuring (temperature measuring) part of the system" I'm unclear if you want to know about the sensor, or if you want more information on the 5v board and display?
"Where are you attaching the wire going into the analog pin on the arduino?" I'm tapping the output to the 5v board coming from the HV board (2nd to last image)
"Also, do you have any idea what kind of sensor they use for temperature measurement?" No, it's built into the kettle base. I'll see if I can find out though. I do have and extra kettle that I can rip apart.

A JFET op amp such as the TL071 has an input impedance in the hundreds of gigaohms or higher. Using one to buffer the voltage should allow you to sample it without much interference to the existing circuit.

so the goal is to make this: https://en.wikipedia.org/wiki/Precision_rectifier

Why do you need to rectify the signal?

"Total Supply Voltage (Min) (+5V=5, +/-5V=10)" the voltage is 0-5v.  This is less than the min? I can look for one with a different set of specs.

I just need to read about this more. I'm really confused.

A circuit diagram would help muchly. However: the analog voltages are most likely DC. If they are within Arduino ADC range then reading most such would affect them minimally. If a buffer is needed then a circuit as simple as in Fig 3 in Ignacio's buffere reference should be good enoug in may cases - but a TL071 may not be the best choice, depending on voltage to be measured and available supply voltages. | Using a voltmeter (DMM) will allow you to measure voltage and advise us how it varies with temperature. ...

... BUT it would be very useful if you can provide even a partial hand drwawn cct of what you are measuring. If you do not know you are wandering around in the dark and expecting us to discern what is in the darkness by remote control. (We may be able to hazard a good guess but your help will help.
| What is range of voltage to be measured? AC or (presumably) DC. . How is it produced (temperature measurement technology). | This should be "quite easy" once a little light is shone.

The range is 0-5v. But I need to reduce it to 0-3v or my chip will fry.


text:
Arduino code cannot continute process
Two days ago, my code is working fine on the arduino board. But yesterday, and today I tried so many time to upload the arduino code, which contains 1000 lines of code. It was successfully uploaded the code into arduino. But it only upload half code into arduino when I saw the serial monitor results (I use serial println(); test where the code is located. ) I am so confusing, why the code is working fine two days ago. but later, only half code being used. Please help.
Here is the memory I left when I uploaded it.
Sketch uses 48,314 bytes (19%) of program storage space. Maximum is 253,952 bytes.
Global variables use 2,603 bytes (31%) of dynamic memory, leaving 5,589 bytes for local variables. Maximum is 8,192 bytes.
Here is the code it stuck :
   Get Parameters
//
//  This function reads the information from the SD card for a given monitoring
//  site.
//

//
int getParameters(){
  String lowerLimit, upperLimit;

   char buffer[36];
  char newChar;
  int index, index1, index2, index3, line, theLength, numSensors;
  myFile.setTimeout(2000);
  line = 0;
  while (myFile.available()) {
    index = 0;
    do{
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    }
    while(newChar != 10);
    buffer[index] = 0;
    theLines[line] = buffer;
    Serial.print(theLines[line]);
    //here the result is something like this
    //theLines[0] , class 111
    //theLines[1] , 192.168.1.10
    //theLines[2] , Mac Address

    line += 1;
  }

//so it is working fine above the code. But here is the problem stuck.
//the code cannot go through the rest of the code below. Nothing happened!!!
  for (int line = 0; line < 10; line++){
    Serial.print(theLines[line]);

  }

Please edit question and say how much program memory is in use, how much RAM is being used, and perhaps provide a diff between current code and the code that worked a few days ago

I have posted it.

A portion of your code is shown below.
  myFile.setTimeout(2000);
  ....
  while (myFile.available()) {
    index = 0;
    do {
      newChar = myFile.read();
      buffer[index] = newChar;
      index += 1;
    } while(newChar != 10);
   ....
  }

Apparently your code is accepting and printing several lines of option setting text and then hangs up in the code extract shown above.
Suppose, for example, one extra character appears after the supposedly-last linefeed character.  Your while (myFile.available()) loop will run again.  It will store the extra character, then try to read another character.  If another character isn't available, newChar = myFile.read(); will return a -1 that your code will store.  That will happen repeatedly,  clobbering RAM.
To see if this is what's happening, you could change while(newChar != 10); to (eg) while(newChar != 10 && index<36);.  If the code then stops hanging up, look into where the extra character is coming from.

I think this may well be correct, however also, how big is this array theLines? How many lines are in the file you are reading? Possibly you have exceeded the size of the array. Or possibly you have run out of RAM.

In addition change while(newChar != 10) to while(newChar != 10 && myFile.available()) to allow for running out of file data.


text:
Implementing DES or AES Encryption with DateTime Synchronization on Uno
We are trying to implement AES or DES encryption using an Arduino Uno.
We have a keypad module attached that will be used to input integers. A String should be generated based on the entered data and encrypted using AES or DES.
We have tried several online libraries with no success due to the constraints put on the "plain text" size.
An example pseudo-code for the above:
string key = "This is a key";
string plain = "This is the keypad input" + keypadInput + "and some other random stuff"; <- This should have any size.

var cipher = AES.encode(plain, key);
print(cipher);

var decoded = AES.decode(cipher, key);
print(decoded);

Could someone please point to the right direction on how to do this?

Can you explain what was wrong with the libraries you looked at? I don't think AES or DES is simple enough to just paste in an answer.

We have tried several online libraries with no success - what online libraries? Your question is very short on detail.

It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

So what you need then is to figure out how to pad and then break a message into the 16 byte chucks specified by AES reversably.

How is this doable? Given the character restriction... Can you provide a sample so that I can look into it more? Thanks @BrettAM

Its really simple. Just encrypt the first 16 bytes, then the next 16 bytes and so on. If you are left with, say, 5 bytes, append 11 bytes of zeros and encrypt that. Decryption is the same but instead of appending zeros, you cut off trailing zeros.

Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

We thought about this by the way and figured out that the other party can decrypt whatever is encrypted from the arduino given that it knows the key provided above. However, will this be a problem to the other party trying to decrypt? Given that the output of the encryption will vary based on keypadInput...?

We have no experience with the byte[] objects and whatnot.

Might be time to do a few tutorials. You won't get far programming if you don't learn how to use arrays.
The string class is part of the STL (Standard Template Library) which does not come pre-installed on the Arduino (however you can download it if you want to).
The Standard Template Library (STL) for AVR with C++ streams

Briefly, however you could do something like this:
char key [20] = "This is a key";
char keypadInput [16];  // whatever they entered

char plain[80];

strcpy (plain, "This is the keypad input");
strcat (plain, keypadInput);
strcat (plain, "and some other random stuff");

The example code doesn't have any size checking. You would want to make sure that you don't put more than 79 characters into "plain" (to allow for the terminating 0x00 character). For example, look up strncat.

Can you please elaborate on how DES or AES as described in the question can be implemented?

Have you done much research? Have you Googled Arduino AES encryption like I just did? I got this as the first hit:
Topic: new AES library - Arduino Forum

I've written an AES (Advanced Encryption Standard) library for Arduino.  It supports 128, 192 and 256 bit key sizes.  Code space overhead is about 4KB I think, each instance requires 240 bytes RAM for subkeys.  Fairly tightly coded and checked against official test vectors for ECB mode.  Also CBC mode supported.

It seems that if value of plain is larger than 16 characters the library will encrypt the first 16 characters only... Is this an Arduino Uno limitation?

I don't want to seem unhelpful, but you really should do some research before asking these questions. From Wikipedia - Advanced Encryption Standard (AES):

AES is a variant of Rijndael which has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.

A "fixed block size of 128 bits" means you encrypt 128 bits at a time, that is, 128/8 = 16 bytes.
So no, it is not an Arduino Uno limitation, it is the way AES works.

Also see Wikipedia - DES.

In the case of DES, the block size is 64 bits.

So DES does 8 bytes at a time.

What you can do with a password is to hash it, for example: Secure Hash Algorithm or MD5 (amongst others). These algorithms take a variable length string and return a fixed "hash". In the case of MD5 the output is a 128-bit field.
You could then encrypt that 128-bit hash, if you want to keep it a secret.

Would encrypting the 16 bytes and then append the next 16 bytes and so on result to the same output as if the whole plain text was encrypted in the first place in one go?

The suggestion by @BrettAM was, if you want to encrypt more than 16 bytes, do them 16 bytes at a time, padding if necessary the final block.
eg.
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000
      encrypt        encrypt          encrypt
LLLLLLLLLLLLLLLL MMMMMMMMMMMMMMMM NNNNNNNNNNNNNNNN
      decrypt        decrypt          decrypt
AAAAAAAAAAAAAAAA BBBBBBBBBBBBBBBB CCCCCCCCCC000000

In this example the final block was padded with zeros. Now the receiving end decrypts in 16-byte blocks.

Can you please elaborate on how DES or AES as described in the question can be implemented? Or the proper way to do so? Thanks

So i should md5 the string and then apply AES on it?

That was my suggestion, yes.

Hashes are better if the idea is to make this a password system. What do you really hope to get by encrypting the hash though? The password still produces the same, unique, 128-bit string each time, its just a bit different now.

I agree with @BrettAM however the original question specifically asked about We are trying to implement AES or DES encryption using an Arduino Uno. Without knowing more details about this project it is hard to give a definitive answer. A straight hash might fall victim to a dictionary attack, whereas if it was encrypted, and if the key was not known, that might protect it.

I suppose that would be different, but I think salting is the more traditional solution. Either way someone holding the hashed password wouldn't be able to produce a hash collision without a little bitstring stored on the chip.

The purpose of this is that the key stored on the chip is known by another private party and it is the only one who can decode it. Would storing the key on the chip be reversible in any way?

I think you should start a new question, like "can an encryption key stored on a Uno be discovered?" - this is really a new topic.