text:
Unable to get my created library to work - while it compiles
I am experimenting with creating my own Arduino libraries. Unfortunately, while the program compiles, the end result does not work.
For purposes of experimentation, I have broken down the library in two parts. One that will handle blinking by controlling the LED_BUILDIN pin and one that will talk to the serial input.
Thus two .h and two .cpp files. Plus there is another file for the configuration that handles preprocessor directives that the library reads.
This is the code:
FILE 1
//header_config.h
#ifndef MY_CONFIGURATION
#define MY_CONFIGURATION

#include <Arduino.h>

#define SERIAL_DEBUG
#define LED_BLINK

#include <led_functions.h>
#include <serial_functions.h>

void my_setup()
{
  my_setup_led();
}

void my_loop()
{
    led_blinker();
    serial_transmit("Hello");
}

#endif

FILE 2
//led_functions.h
#ifndef MY_LED_LIBRARY
#define MY_LED_LIBRARY

  #include <Arduino.h>
  #include "header_config.h"
  #include "serial_functions.h"

  extern void led_blinker();
  extern void my_setup_led();

#endif

FILE 3
//led_functions.cpp
void led_blinker()
{
  #ifdef LED_BLINK
  digitalWrite(LED_BUILTIN, HIGH);
  serial_transmit("LED ON");
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
  serial_transmit("LED OFF");
  delay(1000);
  #endif
}

void my_setup_led()
{
#ifdef LED_BLINK
pinMode(LED_BUILTIN, OUTPUT);
#endif
}

FILE 4
//serial_functions.h
#ifndef MY_SERIAL_LIBRARY
#define MY_SERIAL_LIBRARY

  #include <Arduino.h>
  #include "header_config.h"

  #ifdef SERIAL_DEBUG
  #include <SoftwareSerial.h>
  #define rxPin 2
  #define txPin 3
  SoftwareSerial mySerial(rxPin, txPin);
  #endif

  extern void serial_transmit(char*);

#endif

FILE 5
//serial_functions.cpp
void serial_transmit(char *str)
{
  #ifdef SERIAL_DEBUG
  //mySerial.begin(9600);
  //mySerial.println(str);
  //mySerial.end();
  Serial.begin(9600);
  Serial.println(str);
  Serial.end();
  #endif
}

Please note that while the serial code creates a SoftwareSerial object (in serial_functions.h), I do not use that (in serial_functions.cpp) and instead I make use of hardware Serial. The reason is debugging, so that I can see communication on the PC. I left the SoftwareSerial object inside, because that is what I ultimately want.
Finally, outside the library, in it's separate folder, is the .ino file that makes use of this library.
#include <header_config.h>
#include <led_functions.h>
#include <serial_functions.h>

void setup()
{
  my_setup();
}

void loop()
{
  my_loop();
}

As I said, the program compiles fine, but it does not work in the real world. Neither the blinking, nor the serial communication.

Your cpp files don't include the header_config.h file, so they don't have SERIAL_DEBUG and LED_BLINK defined.
The content of included file replaces the include directive so if you now include header_config.h into both cpp, there will be 3 functions named my_setup() and 3 functions named my_loop() and the linker will complain. So you can't put functions definitions into an include file. And for the same reason you can't have variable definitions in .h file so the SoftwareSerial instance will cause problems too if used.

"Your cpp files don't include the header_config.h file, so they don't have SERIAL_DEBUG and LED_BLINK defined." Why is this necessary, since both header files are included in header_config.h? And the final .ino file calls header_config.h. Also, since the header files use the extern keyword for the function definitions, then shouldn't that work?

@user1584421 the cpp files don't include any .h sothey don't include the header_config.h  over the  other .h files

And what do you suggest i do about the SoftwareSerial object? Should it go to the cpp file instead?

@user1584421 you use it only in serial_functions.cpp so yes

I managed to get it working! Thank you! However, it is still unclear to me why I have to include, <header_config.h> in the .cpp files. Like you said, the content of the files replace the include directive. So if in header_config.h I include the .cpp files and then in the .cpp files, in include back the header_config.h file, isn't it like the header_config.h file includes itself back?

@user1584421 the header files are not compiled. The #include line is replaced by the preprocessor with the content of the included file so  the content of the includes file becomes part of the preprocessed cpp file and then it is compiled


text:
tone() corrupts the PWM on a different pin
I have to use PWM to control some lights. I do this successfully with:
analogWrite(11, 127);
for a 50% PWM pulse on pin 11.
Now, i also have to have tone() support on my code. When I do:
tone(10, melodyArray[thisNote], noteDuration);
I invoke the tone() function on pin 10.
When I do so, then PWM pulse is corrupted. Since I do not have an oscilloscope, I cannot exactly understand what happens.
But from the effects on the lights, I can speculate that the PWM pin (pin 11) is always HIGH or always LOW.
It is obvious that the PWM pin and the tone() pin are different.
Why does this happen? Perhaps the tone() uses some timers that interfere with the PWM?
When I comment out the tone() line, the PWM works as intended.
Is there a solution to this? Can I use the tone() function and still have PWM support (on another pin)?

To quote from the Arduino documentation of tone():

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

So yes, you should use a different pin than 3 or 11 for analogWrite(). This is because tone() will configure the hardware Timer2 for outputting these timed signals via hardware. PWM on these pins is also tied to Timer2. When both functions are trying to configure Timer2 in a different way, there will be conflicts.
Note: The documentation talks about "boards other than the Mega", which was true when there weren't other Arduino boards than the old Uno/Nano/Mini (based on the Atmega328p). Nowadays there are so much boards, which all can be programmed with the Arduino framework, that this sentence is a real stretch. Instead I would say "on boards based on the Atmega328p". Depending on your used board your mileage may very. Check the microcontrollers datasheet for the hardware Timers it has and their connected pins.

"on boards other than Mega". looks like it was written long time ago when every Arduino had a classic ATmega MCU

@Juraj Yes, very much. Though Uno/Nano is still used widely. I will add a sentence to comment on that

Thank you so much! Embarrassingly, I spent months being stuck on this...

source: Stack Exchange

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

sort: votes


text:
Purpose of LED indicator
I am using an arduino mega clone called the Funduino.
I am developing a python based, tkinter application that will receive the serial data that arduino sends.
However, i am witnessing some behavior that i cannot explain and i am trying to debug. I won't say anything more, because this is an arduino forum, not a python forum.
But, in the arduino, there are some leds. One of them is power, which is constantly ON, when the arduino is powered.
There is another led that is named 'L'. When i open a serial connection this is lighted up and it stays ON.
However sometimes, when i send a string to the arduino, in order to trigger some data exchange, this button is switched off.
So what does this 'L' led is, and what it means when it is turned off?

"L" is the user LED that is connected to pin 13. It's controlled by your software installed in the Arduino, whatever that might be.

@Majenko -- if unconfigured, the LED pin is tristate, and could be controlled by signals external to the Arduino.

If you do not configure the pins, they are initialized as pinMode(xx,INPUT) which is a floating high impedance state.  Per the Arduino Uno R3 schematic, that pin is on PB5/SCK/13 which is run through the op-amp (top center in the schematic) to drive the LED. Per the Arduino Mega schematic, that pin is on PB7/OC0A/OC1C/13 which isn't run through the op amp.  I left mine unconfigured on a Mega clone and measured a 1.5V on 13 and had the LED on.  On an Uno clone, the light was on while unconfigured, and I measured 0.9v (but my DMM seemed to draw down the voltage).
If the pin is left floating in an unknown state, it could drive the LED into an unknown state.

You can control it's state with:
pinMode(LED_BUILTIN,OUTPUT);  // LED is forced off (0.01V)
digitalWrite(LED_BUILTIN,1);  // force LED on (4.97)

or
pinMode(LED_BUILTIN,INPUT_PULLUP); // On, but with the internal pullup resistor, not logic gates.  Pin 13 can be shorted to ground.

or set it back to the default tri-state:
pinMode(LED_BUILTIN,INPUT); // Tri-state, undefined.
// You could control the LED from an external signal on the pin.

Measure the voltage at pin 13 and see what you get.
Personally, I purpose it as a status indicator light.  E.g.  https://github.com/drf5n/foxyPulseInduction_Discrimination/blob/discrimination/StatusCodeLED/StatusCodeLED.ino
Because of the tri-state/op-amp LED driver on "L", you can use the light as as a logic probe--you could leave it unconfigured and jumper it to other inputs or outputs for troubleshooting and diagnostics.  If you have a project monitoring one important input, rather than putting it on a different input pin and explicitly echoing it to the LED like digitalWrite(LED_BUILTIN,digitalRead(sensorPin)); you could hook it to pin 13 to visually see the input status and just digitalRead(sensorPin).
====
Note that there are two revisions of the Arduino Mega schematic.

https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf -- A top search hit
https://content.arduino.cc/assets/MEGA2560_Rev3e_sch.pdf from https://store-usa.arduino.cc/products/arduino-mega-2560-rev3

After testing this behavior, I noticed that the my Mega clone did not match the Arduino Mega schematic at https://www.arduino.cc/en/uploads/Main/arduino-mega2560-schematic.pdf . Tracing it out, it does use the op-amp like the Uno. (Pin 1&2 of the opamp attach to the "L" LED through the third resistor in the resistor array next to the LED.)

This buildin LED is connected to an IO pin of the microcontroller on the Mega (most commonly pin 13, but might be different depending on the board). So the meaning depends on what the code on the Mega does with it.
When the board is reset (which happens on opening of serial connection), first the bootloader will run. It gives you a short blink on the buildin LED. After the bootloader finishes, your own code is in charge. Whatever you do in your code with pin 13 will be reflected on the LED. Here the meaning depends on you.

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


text:
Conditional assignment of array
I have some really long global variable arrays filled with data.
There is a single function that processes the data. The function works on only one array everytime. This arrays value changes every iteration and gets the value from the global variable arrays.
Since i declare lots of global variable arrays, in order to pass them to the array_to_be_processed_by_the function, the memory is filled up really quickly.
What is the best way to conditionally give values to the array?
For example, there could be a counter in the program, and if the counter is a particular value, the array would be initialized with certain data. Of course, i would also have to call the function, and i would have to keep track of the counter and increase it and zero it at the beginning of the loop, to start from the beginning.
In this approach, only one variable would always be initialized.
PSEUDOCODE:
int looper = 0;

void loop()
{
  switch(looper)
  {
     case 0:
        my_array[] = {DATA HERE};
        exec_func(myarray);
        looper++;
        continue;
     case 1:
         ......
     case 'last_case':
         ...
         looper = 0;
         break;
  }
}

However, i am not sure if this approach is the correct one.
Especially for a microcontroller.
One obvious issue, is that the array values are not necessarily the same size.
Therefore, the base array should be destroyed at each case?
If this is good approach, should new/delete be used on an arduino?
What is the best approach to conditionally initialize an array, so that i don't get out of memory

Are your base arrays constant? If yes, you could put them in flash/program memory instead of RAM. As I've understood you would copy the data into an extra arasy anyway to work on the data there

In the example pseudocode, my_array[] defined in case 1 would be automatically destroyed at the end of case 1. Incidentally,  if you define variables within a case, the case block should be enclosed in brackets { } or you get compiler warnings.

In order to answer your question, we need to know how you define the exec_func(myarray)? What is the data type of my_array[]? Does the function take in a my_array[] or does it take in a pointer to the array?  Whether the my_array[] only be used within the case 0 or does it uses somewhere else? Meanwhile I'd suggest you read Learn C++. BTW, the new/delete is used for dynamic allocated memory using command like malloc(), it does not applicable to static array creation.

Would you mind to [edit] your question and provide a minimal, reproducible, and complete example, please? It should show your use case, even if it is not optimized as you like.

@chrisl Yes they are constant. I am learning about PROGMEM right now! Thank you for the tip!

@hcheung My arrays are type int with many values. The functions receive the pointers directly, not a pointer to them. Which is the same thing actually, since the name of an array is a pointer to the first element. In my theoretical implementation (it was for solving the full memory problem), it would be used only in the case 0 situation.

@thebusybee It really isn't anything special. Just long int arrays with lots of data. Then they get assigned to a working array, that is passed to a function for processing. Add many long global vars and you quickly get out of memory. Nothing fancy. If you want though, i can still provide code, if you are interested.

Sure. For example, we need to know whether these arrays contain constant values. Or whether the called function changes elements of the arrays. And so on. Make sure that any important aspect is covered for a good answer. Only good questions receive good answers, that's the GIGO principle.

Let's consider this:
case 0:
    my_array[] = {DATA HERE};
    exec_func(myarray);

This is not quite valid C++, but let's pretend you get the syntax right
to make it work. The problem is: doing this will not help you save
memory. Where do you think the compiler is going to store {DATA HERE}?
In memory, right. It will be stored as an anonymous array. Then the
initialization of my_array will make a second copy of the data in
memory, this time in a named array.
You can avoid this second copy by naming your arrays of constants, and
passing the correct one to your function:
// At global scope:
const int my_array_0[] = {...};
const int my_array_1[] = {...};

// Within the switch/case:
case 0:
    exec_func(my_array_0);

You can even avoid the switch/case altogether by using an array of
pointers, but that is irrelevant to your current problem.
Your idea of initializing only the array you actually need can work if
you manage to do it procedurally, i.e. implementing some recipe with
instructions, rather than copying a set of constant:
case 0: {
    int my_array[array_size];
    for (int i = 0; i < array_size; i++) {
        my_array[i] = some_expression_to_compute_this_array_item;
    }
    exec_func(myarray);
}

This is not always feasible though.
If you really have to store the constants in the program, and you are
using an AVR-based Arduino (like the Uno, Mega, Micro...), then you can
save RAM by storing the arrays of constants in flash memory, and copying
only the one you need to RAM:
// At global scope:
const int my_array_0[] PROGMEM = {...};
const int array_size_0 = sizeof my_array_0 / sizeof my_array_0[0];
const int my_array_1[] PROGMEM = {...};
const int array_size_1 = sizeof my_array_1 / sizeof my_array_1[0];

// Within the switch/case:
case 0: {
    int my_array[array_size_0];  // array in RAM
    memcpy_P(my_array, my_array_0, sizeof my_array);
    exec_func(my_array);
}
case 1: {
    int my_array[array_size_1];  // array in RAM
    memcpy_P(my_array, my_array_1, sizeof my_array);
    exec_func(my_array);
}

Check the documentations of PROGMEM and memcpy_P() for
the details.
If you go this route, you may consider modifying the function
exec_func() so that it expects its parameter to be a pointer to flash
instead of a pointer to RAM. Then you will completely avoid the copy in
RAM.

Edit: expanding on the idea of passing a pointer to flash.
The C++ compiler doesn't really know the difference between a pointer to
RAM and a pointer to flash. If you want to pass a pointer to flash to a
function, you have to write the function in such a way that it expects a
pointer to flash. For example, this function prints out the contents of
a flash-based array:
// The argument should be a pointer to flash.
void exec_func(const int *data)
{
    for (int i = 0; i < array_size; i++) {
        int number = pgm_read_word(&data[i]);
        Serial.println(number);
    }
}

Note that the array is not accessed directly (evaluating data[i] would
give garbage). Instead, the address of the element you want (&data[i],
a flash address) is passed to the macro pgm_read_word(), which uses
inline assembly to get the relevant data from the flash.
Now you can call this function passing it the address of a PROGMEM
array, as in exec_func(my_array_0);.
Just for completeness, I will show you how to use an array of pointers
to avoid the switch/case construct:
const int my_array_0[] PROGMEM = {...};
const int my_array_1[] PROGMEM = {...};
...

const int *arrays[] = {my_array_0, my_array_1, ...};

int looper = 0;

void loop()
{
    exec_func(arrays[looper]);
    if (++looper == number_of_arrays) looper = 0;
}

Note that here arrays is a RAM-based array. That's why you can access
the elements directly as arrays[looper]. These elements, however, are
pointers to flash-based arrays. If you have so many arrays that arrays
gets too big, you might consider putting it also in flash.

Thank you very much for this detailed answer! The problem is: doing this will not help you save memory. Where do you think the compiler is going to store {DATA HERE}?  Well, my logic behind this thought, was that I have seen much larger codebases in arduino. I thought that the CODE part was different than the variable assignment. I am reading about PROGMEM right now. One more question. If i pass a pointer to flash location, then i don't need the my_array[] at all? I just give a pointer to the my_array_0[] (for example)?

@user1584421 That depends on if you want to change the data. exec_func() can be written to read the data from flash, but you cannot change it there. If you need to do transformations to the raw array data, then you still need to copy it to RAM like Edgar did in his last code snippet.

@chrisl No they arrays would be constants. So i don't even need my_array[]. Just pointers for the const arrays in Flash memory. Thanks for the tip!

LOL! You just edited it in the same time i managed to get it to work! I will give it a read and mark it as accepted it later! Thank you so much for your answer!

I tried the pointer to array to flash before but it didnt work. Of course, maybe i did something wrong. However, i managed to get it to work with the code snippet you provided just before the edit. With the extra work of having to deduce the number of elements in the array in the flash. int ArrayElements = sizeof(my_array_0) / sizeof(int); And then i would create the empty array, just like your example, passing the arrayelements as its size. Yes, maybe its not as fast and memory efficient, but its three lines of code. And only one array in memory. I can get away with it.

I am facing another problem. While i am able to assign an array from PROGMEM and pass it to a function, the program would have to move from case 0 to other cases. Thus, the base array would have to be reinitialized. Considering i have not used new, can i somehow or reassign the array? The arrays in PROGMEM are not of the same size.

@user1584421: I amended the answer to cope with arrays of different sizes. Note that there are now multiple variables that share the name my_array, but they are different variables, each local to a {} block in the switch/case.


text:
Serial.write() prints a variable twice
I have this code:
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

#define GPS_RX_PIN 2
#define GPS_TX_PIN 3

TinyGPSPlus gps;
SoftwareSerial ss(GPS_RX_PIN, GPS_TX_PIN);

void setup()
{
  Serial.begin(9600);
  ss.begin(4800);
}

char clat[11];
char clng[11];

void loop()
{

        bool isGpsLocationValid = false;
        do
        {
            while (ss.available()>0)
            {
                char c = byte(ss.read());
                if (gps.encode(c))
                {
                    if (gps.location.isValid())
                    {
                        dtostrf(gps.location.lat(), 11, 6, clat);
                        dtostrf(gps.location.lng(), 11, 6, clng);
                        isGpsLocationValid = true;
                    }
                }
             }
        } while (isGpsLocationValid == false);
        Serial.write(clat);
        Serial.println();
        Serial.write(clng);
}

Now when all is done, the clng value is printed twice in the serial monitor.
The value i get is in this format:
27.275869  15.151013
  15.151013

As you can see, clng is printed twice. Any ideas why is that?

I think your question may already be answered here: http://arduino.stackexchange.com/questions/1197/strange-behaviour-of-dtostrf

The width parameter to dtostrf() is the width of the resulting string NOT including the null terminator. So you are overflowing the array.
Change:
char clat[11];
char clng[11];

to
char clat[12];
char clng[12];

and it should work.

bear in mind, my number is this : 27.275869 . and i have declared 11 digits. i think they are more than enough. i will provide more feedback on this tomorrow

The width parameter is the minimum width not the maximum width.  See the docs.  If you have signed lat/long values you will need 11 characters plus the null terminator. Unsigned will only need 10 plus the null.

2 digits + 1 sign + 1 dot + 6 decimal digits + 1 NULL = 11. Why do i need to declare more?

Because dtostrf will pad the result string with spaces so that it is at least 11 characters long, so you need 12 chars in your variable. Instead of arguing, you should just do it and see that it works with 12.

I did with up to 14 digits and the results remain the same

you were right! I didnt pay too much attention to your answer and i misunderstood i should increase the dtostrf parameter instead of the array size!

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


text:
What is the best way to create a library from existing functions?
I was tasked to take functions that work, and create a library with these functions.
Take a look at the following function that existed inside a program:
char* Num_to_HEX_char_array(int32_t value)
{
  Clear_array(MyTempArray, MY_TEMP_ARRAY_LENGTH);
  ltoa(value, MyTempArray, HEX);
  return MyTempArray;
}

(Let's ignore the fact that this function)
This cannot be immediately made into a library, as MyTempArray is non existant.
This, in the .cpp file, i will have to manually create these lines:
#define MY_TEMP_ARRAY_LENGTH 20
char MyTempArray[MY_TEMP_ARRAY_LENGTH];

Now the library compiles fine.
However, this library can be called by many programs that I create, and some of them might require a different array length, while others ay require a different name than this one.
So what is the best way to create this library?
*One approach that I thought was to dynamically create these arrays with malloc().
And then, on the main program, you will have to realloc() the arrays with the ones you want.
Also, use undef and re#define.
The drawbacks to this approach is that you have to remember to ALWAYS use these statements, if you want your library to work
*Another approach is to place all this code:
#define MY_TEMP_ARRAY_LENGTH 20
char MyTempArray[MY_TEMP_ARRAY_LENGTH];

inside a configuration header file. The variables will be of global scope.
Then, when you create an application, you will only have to change this file.
My question to this approach is How exactly can you make sure that this configuration file is read by all the libraries?
Maybe you many libraries, for example, string-handling, or sensor-handling...
Each and every one of these user-created libraries have to #include and see that configuration header file, in order to make sure that the definitions and arrays of correct/name and size.
How can you do this so that it is visible by all your user-created libraries?
Where is the optimal location to place that file?
In general, what is the best approach to solve this issue?

what do you mean when you say best?

I'd write such a function to expect the calling function to allocate the array and pass it and its size as arguments. That leaves the memory allocation and deallocation up to each library user, who may want/need (for other reasons) to use a static array, heap memory, or an automatic array and allows them to de-allocate it (or not) when their application no longer needs it. Coding these details into your library would restrict its usability.

First of all, I must say I have an issue with the example you provide.
The function Num_to_HEX_char_array() should use an array that has the
maximum size that ltoa() may ever need. No more, no less. There is no
point in letting the user of the library choose this size. Here is how I
would implement this function:
char *Num_to_HEX_char_array(int32_t value)
{
    static char buffer[2 * sizeof(long) + 1];
    return ltoa(value, buffer, HEX);
}

That being said, I am willing to accept the idea that your library has
some static buffers for which it does make sense to let the user choose
the size. You could probably find a better example to put in the
question though.
In this case, I would suggest you first consider the approach proposed
by JRobert, and let the user provide those buffers. Using static buffers
in a library can make the API easier to use in the most common cases.
There are many function in the C standard library that do this, like,
e.g. ctime(). This, however, comes at a cost:

the user must be well aware that calls to the library can clobber
data returned by previous calls

the functions are not re-entrant, meaning they cannot be used in
multiple threads, and they cannot be used both in interrupt and
non-interrupt contexts.

This is why you have functions such as ctime_r(): to provide an
alternative that lets the user handle the buffer, and does not suffer
from the previous shortcomings.
If you still believe you want static buffers inside your library, then
you should first consider whether it is possible to fix the size, like
in the Num_to_HEX_char_array() example. If this is not possible, then
the best I can think of is to use C++ templates. For example:
template<size_t size> class CircularBuffer {
    int buffer[size];
    // ...
};

which would be instantiated like this:
// Let `queue' be a 42-slot circular buffer.
CircularBuffer<42> queue;

Keep in mind, though, that this technique forces you to put most of the
code in the header file.

Command line compilers and most IDEs for C and C++ enable to set project defines as -D parameters in project settings. Arduino IDE does not enable this yet, because it doesn't have a project configuration file.
With Arduino IDE you can add defines for platform or for board definitions with build.extra_flags in platform.local.txt or in boards.local.txt. Example for boards.local.txt for Arduino Mega:
mega.build.extra_flags=-DUIP_CONF_UDP_CONNS=20 -DUIP_CONF_MAX_LISTENPORTS=30
platform.local.txt and boards.local.txt must be in boards package folder nect to platform.txt and boards.txt.


text:
Read status of digital pin 11, when it is set as OUTPUT
I have set pin 11 as output.
pinMode(11, OUTPUT);
However, I want to be able to read its state (if it is HIGH or LOW),  however since it is set as OUTPUT, I am not able to use digitalRead().
I found this online though:
Serial.println(bitRead(PORTD,3));
//Reads bit 3 of register PORTD which contains the current state (high/low) of pin 3

If I want to read the state of pin 11 then this:
Serial.println(bitRead(PORTD,11)); will be enough? Or do I have to change the PORT as well?

Why not try it?

please don't ask what will happen if I do this? ... do it first, then ask, if you do not understand something

however since it is set as OUTPUT, I am not able to use digitalRead().

Where did you hear that? digitalRead() will return the state of a pin set to OUTPUT mode. (In that case, it will be the state you last set it to). As a demonstration, this is a common idiom for inverting the state of an output pin:
digitalWrite(LEDPIN, !digitalRead(LEDPIN));


text:
SDI-12 protocol, working with SoftwareSerial
I have a Teros 11 moisture sensor that I have managed to make it work with the SDI-12 arduino library.
However, this library does not work with SoftwareSerial and this is critical for me.
There is a known open issue in Github for years, located here: https://github.com/EnviroDIY/Arduino-SDI-12/issues/8
A person claims to have mitigated the issue by commenting out some code that should be omitted, specifically code of extra interrupts.
The changes are committed  in a separate branch here:
https://github.com/EnviroDIY/Arduino-SDI-12/pull/84/commits/4def0046eb8d465c4079b3115aade50d3ff85b4d
I made the change myself, but while the code compiles fine now (along with the SoftwareSerial library), the data that I get back from the sensor is junk.
Does anyone know this issue, or can understand what happens? The code that is being left out is only a few lines, so if anyone could take a look, I would greatly appreciate this.

can understand what happens ... one child grabs all of the crayons

@jsotola I don't get you, sorry....

software serial grabs all of the interrupts

@jsotola Even the third interrupt?


text:
Relay feedback control
I have a two-relay system set up to a DC motor. So, if I close one relay, the motor moves on one way and if I close the second relay (and open the first) the motor goes on the other direction.
I compare two variables (target inclination and real inclination) if they are not the same I would like to open one of the two relays UNTIL the are the same value.
Both variables are calculated based on inclinometer input and some aritmethics.
I do know how to calculate the variables, how to close the relay based in the comparation of variables and which relay open.
But I don´t know how I can tell to open the relay because the motor has reached target inclination.
How I can recalculate and compare constantly target inclination and real inclination when the relay is closed and the motor moving?
Is this posible on Arduino? Is this multithreading?
Thank you very much, any ideas are welcome!

What do you use for an inclinometer? How do you read it? How long to return a reading? Do the readings make sense when the motror is operating or does movement scramble trhe results?

Thanks for looking into Russel!  1.- I measure inclination using a Murata SCA100T-D2 chip. 2.- The chip is conected to the Arduino board using SPI.  3.- The reading has no delays.     4.- I don´t know , but Its a very interesting idea, it looks something logical as the movement is not perfect and the sensor is very precise (and fast!) Maybe I need to ad some delay?

IF the sensor can be read "on the fly" with motor moving it sounds easy to do. Is not target inclination fixed and only real changes? If so then a loop that reads sensor and compares and exists when target is reached seems all that is needed. Am I missing something?

This is a classic system where PID will really pay off. Basically this will allow you to tune your system so that if you are off by 5 degree it will open the relays for 3 seconds. But if you are off by 1 degree it will open them for half a second. (Or whatever works for you). It might be tricky for you to get right but it will give you the smooth response that looks really good and feels natural.
Take a look here http://playground.arduino.cc/Code/PIDLibrary

Thank you very much portforwardpodcast! Will be looking into PId, really seems what I need!

Answering my own question, I think I found some way to get the solar panel face the sun.
As said before, the inclinometer reads the position and makes some calculations using lookposition() function, then this happens:
void lookforsun() {
  while ((targetElevation + 3) < realElevation | (targetElevation - 3) > realElevation) {

    Serial.println("Elevation is not correct");

    while (realElevation < targetElevation)
    { Serial.println("Moving to south");
      digitalWrite(south, LOW);
      lookposition();
    }
    digitalWrite(south, HIGH);

    while (realElevation > targetElevation)
    { Serial.println("Moving to north");
      digitalWrite(north, LOW);
      lookposition();
    }
    digitalWrite(north, HIGH);
  }

  while ((targetHourangle+3) < realHourangle |  (targetHourangle-3) > realHourangle  ) {

    Serial.print("Hour angle is not correct");
    while (realHourangle > targetHourangle)
    { Serial.println("Moving to east");
      digitalWrite(east, LOW);
      lookposition();
    }
    digitalWrite(east, HIGH);

    while (realHourangle < targetHourangle)
    { Serial.println("Moving to west");
      digitalWrite(west, LOW);
      lookposition();
    }
    digitalWrite(west, HIGH);
  }

As you can see I took the frightening way of nested while loops, but appears to work.
The first while measures if realElevation is between +-3 degrees of targetElevation, if realElevation is far away (target+-3) enters the second while loop, which determines if needs to go up or down.
I included the +-3 because the sensor is so very sensible.
Thank you very much  Russell McMahon and portforwardpodcast for your ideas!

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


text:
Do all serial ports on an Arduino MEGA 2560 have the potential to "brick" attached items when being flashed?
I was browsing through the hookup guide for SparkFun's OBD-II UART breakout and found something particularly worrying written half way down in a quite casually presented way:

Keep in mind when you upload this to your board, you will want to disconnect the OBD-II board RX line from the Arduino TX-0, to prevent issues during code upload, such as bricking the OBD-II board.

For my money I think bricking your device should come with a more stark warning than one stuffed part way down a guide starting with "keep in mind" and continuing with "issues". Nonetheless it caught my attention as I tend to build sealed boxes that aren't sprawled in front of a keyboard ready to be rewired any time a re-flash might happen.
Is the real risk here the fact that all of the flashed data would stream past the RX pin of the UART board and potentially accidentally send a 'self-destruct' signal? (Also I'm not sure a system is really up to scratch if you can accidentally tell it to kill itself.)
Surely the programming port is not the one being borrowed by the UART hookup? On a MEGA 2560, using a different serial port, is this still a risk or is that only on boards with one serial port?

fwiw, when updating ESP8266s, even via OTA, i'll often see the GPIO's "go nuts". On my light dimmers, that means the light is flashing and dimming rapidly and randomly. if it were more complex than a dimmer, it could be a very bad thing...

In the Sparkfun example the Arduino Uno is used. The Uno has only one hardware serial port, and that is used to upload a sketch and for the serial monitor. Pin 0 (RX) and pin 1 (TX) can be overriden for something else. However, then you must know what you are doing, and connect and disconnect modules as required.
The Arduino Leonardo and (Pro) Micro use a USB CDC implementation and have a unused hardware serial port at pin 0 and 1.
The Arduino Mega 2560 uses the hardware serial port at pin 0 and 1 to upload a sketch, just as the Uno. However, the three other hardware serial ports are not used, and you are free to use them.
If you use an unused hardware serial port for the OBD-II, there is no risk at all. You can use that port and nothing else messes with that port.
If you use a serial port that is also used to upload a sketch, or a software implementation of a serial port, you probably are going to make a mistake some day, and there is a risk to send the wrong data to the wrong hardware.
[ADDED]
I see that the example code in the SparkfunHookup Guide uses the Arduino Uno and SoftwareSerial on pin 2 and 3. That is independent of the hardware serial port. The SoftwareSerial is something that should be used as a last resort, since it almost completely takes over the Arduino board. It's good to have SoftwareSerial, but try to avoid it.
If you do want to use an Arduino Uno, perhaps the AltSoftSerial can be used. The AltSoftSerial works okay for 9600 baud as long as no other code uses too much time in interrupts and no one else uses TIMER1.


text:
How can I identify, debug or fix a faulty IMU?
I have an LSM9DS1 breakout board by Sparkfun, and am communicating with it using a Mega 2560 over I2C. The board is given 3.3 V power as defined in the data sheet, though there seems to be confusion whether the SDA and SCL pins need level shifting for communicating with the 5 V Mega. In theory it shouldn't need to.
I am able to connect with the device and get its accelerometer and magnetometer data, however the gyro is just returning noise and no signal. I have dug in to all the registers I know of regarding high pass filters, logging rates, enabling and powering the sensor, but the only hints are that when the gyro is disabled and then polled, it returns a constant nonzero value on all three axes, as though a bit somewhere is stuck. With any other setting the results are unchanged: finite noise on a constant DC signal. Is this even possible? How can I dig deeper to understand and solve this problem?

In theory you must use a level shifter for SDA and SCL. The Arduino Mega 2560 board has internal pullup resistors of about 50k for SDA and SCL and extra 10k pullup resistors of 10k to 5V and according to the datasheet the ATmega2560 requires 3.5V to detect a high level for the I2C bus.
Those pullup resistors might damage the LSM9DS1.
5V-3.3V / 50k//10k times two (both SDA and SCL) = 400nA that might be pushed into the sensor (I assume there are protection diodes, and the maximum voltage is 3.6V, therefor the 400nA is just an indication).
I assume the 10k pullup resistors to 3.3V on the sensor module are enabled. They will take away some over-voltage.
The current by the pullup resistors (to 5V) is a very small current, and I don't know if the sensor is in sleep mode during startup.
To be sure you need to buy another LSM9DS1 and a level shifter. Or even better: buy a 3.3V Arduino board, like the Due or the Zero, M0, and so on.
Have to compared the raw sensor data with others ? Those sensors are very noisy. That is why there is so much to do about filter algoritms to get data that can actually be used. The LSM9DS1 does not do processing or smart filtering with the raw data. All you get is the raw data. Did you assume that the values would be zero ? They never will be, because such sensors are far too noisy and too sensitive for that.

I am confused genreally by your suggestion that I2C communications requires a level shifter. Your description is fair of the reality but I was under the impression the design spec for I2C was for voltage tolerance by communicating on open collector. I am using a 3.3 V supply to the chip, it is only the SDA and SCL that are running at the Mega-native 5 V. On the noise, of course I expect noise that is there, but what I am not getting is any signal on top of it. Additionally this is the second system I've used using the exact same model of IMU and Arduino, the other unit works perfectly.

Further, this is the information I am using to determine the necessity of using a level shifter with I2C. It says that is there is a 3.3 V supply, that I2C will not need level shifting: https://learn.sparkfun.com/tutorials/lsm9ds1-breakout-hookup-guide?_ga=2.254733000.1526785080.1494864932-308821833.1490272070

That voltage tolerance might have been a design feature long ago, but it does not really work with Arduino or todays sensors. They have ESD protection diodes inside, so there is a path from SDA and SCL to VCC. That sentence at Sparkfun says that with a 3.3V board everything is okay at 3.3V. That is the same as when I wrote: "Or even better: buy a 3.3V Arduino board". You have bad luck with the Arduino Mega 2560, it has 10k pullup resistors at SDA and SCL. And the Arduino Mega also requires 3.5V for SDA and SCL for a valid high. It's not a joke, 3.3V sensors have been damaged with Arduino Mega.

Well luckily I have a level shifter in this latest build for the I2C connection with an SD card and it has spare channels, so it's not a bit deal to add this to it. Nonetheless I am able to communicate with the chip and see meaningful data. Are you suggesting that the SCL and SDA pins going over voltage might influence the power to the gyro sensor even it the accelerometer and magnetometer are okay?

Yes. I don't know what the LSM9DS1 will do, but other gyro and accelerator MEMS sensors can get damaged. They might still work, but the data could be noisy and drifting (even when returning to normal voltages). Perhaps the gyro is the most sensitive part in the chip for voltages that are too high.

I needed to get this sorted and ran out of time to do level shifting. I bought a new LSM9DS1 chip, identical to the previous, and wired it the same as the last one. This one works without the shifting. Perhaps the other one is faulty or I've just been lucky 2 from 3 that they can deal with the mismatch. I will hunt for a suitable MOSFET based solution as you mentioned in the other answer when I get a chance.


text:
Arduino Mega 2560 bootloader delay
I need to make my program run immediately on a reset or power up. However, the bootloader delays program startup by around 2.5 seconds. How can I get over this? Is there a way to turn off the bootloader wait period?

Not the easiest solution, but I've modified the bootloader on a Trinket, to have it wait only if the board was reset, and not on regulator power on. Something similar can be done for the Mega. That way you can still use serial to program the board, unlike Majenko's solution.

@Gerben: +1 - this is worth making into an answer.

Yes.  You remove the bootloader completely and program the Arduino using a hardware programmer.
If you could "turn off" the wait period you would never be able to get into the bootloader to program the board, so the bootloader would be completely useless.  So either way you would then need a hardware programmer to do anything constructive with the board.
A hardware programmer could be another Arduino, or a real hardware programming adapter.

I am using a Mega 2560, so I guess I need to use another Arduino for programming the Mega via the ICSP connector. Is that right?

Yes, that's right.  There's plenty of tutorials on the web of how to wire it up. It's just the same as how you install the bootloader on a blank chip, but instead you're installing your sketch. It can be done direct from the IDE if you select the right programmer and programming operation.

I used an AVRISP Mk2 programmer.
I selected AVRISP V2 in 'Arduino IDE 1.6.5, with Tools > Select Prorammer
When I select Sketch > Upload using Programmer, I get the following error...

"Error while uploading: missing 'program.tool' configuration parameter"
I'm using Ubuntu 14.04 with Arduino IDE 1.6.5

AVRISP is not using an Arduino as a programmer - there should be a separate entry for that.

OK. So I connected an Arduino Uno

I loaded Arduino ISP program from Examples
Selected Tool > Programmer > ArduinoISP
Then Sketch > Upload Using Programmer
And I get this error: "avrdude: Error: Could not find USBtiny device (0x2341/0x49)"

Yes, I've checked and rechecked - I have indeed selected ArduinoISP and not USBtiny.


text:
Driving multiple LED arrays with shift registers
The project I'm building requires multiple LED arrays. I'm going to wire these LEDs in parallel and then connect the arrays to individual pins on a shift register. In addition to the LEDs running in parallel I've connected resistors in series to each LED. I've been prototyping this on a couple of breadboards and I've noticed my parallel LEDs are much more dim then my LEDs I have in series. The resistors I'm using are around 550 OHMs and I'm powering the registers through my arduino uno. I think this may be part of the reason why they're so dim, as the arduino is only providing 5V. My question is, can I/should I have my registers connected to my arduino via the data connections and power them using an external source? Will this provide me with brighter LEDs? I don't want to dump the resistors, and I have around 21 arrays, if it matters, each with a varying number of LEDs

To more clearly and definitely present your circuits, please include  schematic circuit diagrams.  Numerous free circuit diagram maker programs are available.

What shift registers are you using? How many LEDs are you running in parallel per pin?

What shift register? Multiple LEDs in parallel will share the output of an output pin, so to get 20 mA per LED with 5 in parallel would require 100 mA from the output pin.

You haven't provided enough information to allow definitive answers to your questions, but you can apply LED resistor calculators and formulas to determine how much current is available to drive LEDs of various voltages.
Here is an example:  Suppose you hook up a red LED that drops about 1.6 V when it's on and operating at a current of 5 to 25 mA.  Suppose the LED is in series with a 550 Ω resistor, between a 5 V source and ground.  Current will be about (5-1.6)/550 A ≈ 0.0062 A = 6.2 mA.
If you wished to limit current through Arduino Uno pins to safe-area amounts like 25 mA, you could drive at most 4 such LEDs per output pin.  If you decrease the resistor to get more current, the number of LEDs allowed per pin decreases too.
Because pin voltage drops slightly as the pin drives more current, LED brightnesses will also decrease slightly as more LEDs are attached to a pin, so putting different numbers of LEDs on different pins is likely to make light levels uneven.
Limits on output currents from 74HC595 shift register pins are similar to those on Arduino Uno pins; eg 35 mA absolute max ratings for the Qn pins.
Rather than driving LEDs directly from Uno pins or '595 pins, you can use transistor driver stages.  Most transistor drivers will allow higher voltages (ie more LEDs in series, rather than in parallel) and higher currents.  Also consider using LED driver chips; many of them contain PWM circuitry for brightness control and registers for storing drive levels.


text:
Motorcycle Battery Powering Arduino UNO

Folks
I am planning to power my Arduino, which will be mounted on a motorcycle, using the motorcycle's battery. So the same battery will be starting the engine and powering other electrical components.
I am wondering if this circuit will work fine.
C1 - 1000uF 50V;
C2 - 1000uF 25V;
D1 - 1N4001 ;

Your circuit is 'going in the right direction' but can be improved.
If you wish to use the regulator shown:

The larger the input capacitor (C1) the better; it will survive noise spikes and low voltage "droops", eg during starting.

Adding a series resistor to drop some of the input voltage will help C1 filter out noise.
Rin should be V/I = V_drop_max/I_maximum .
With a 9V regulator and 12V supply you cannot afford much drop in the resistor.
If you use the 6V output system I recommend below then you could allow closer to 3V drop in Rin.
If Imax is 100mA then Rin = V/I = 3/0.1 = 30 Ohms.
Typically you'd use 27 Ohms (which is the closest E12 standard value.

Power dissipation is the resistor = I^2 x R.
So for eg 27 Ohms and 0.1 A (100 mA) power dissipation in the resistor is
I^2 x R = 0.1^2 x 27 = 0.27 Watt
So you'd use at least a 0.5 Watt resistor and ideally  Watt or more. Air cooled resistors are relatively low cost and a much better way of dealing with heat than trying to cool a regulator.

Adding a ~15V zener diode at the input to U1 will help protect against spikes. This works better if Rin is used. Without Rin the zener may be destroyed by spikes. If you use the LM29xx regulators that I mention below the zener is not needed as the regulator has its own internal protection circuitry.

The LM7809 regulator is somewhat unusual. If you have them available they could be used but there are much more common and/or modern regulators available.
The regulator's Vout should be fed to the Arduino's Vin terminal, which supplies the Arduino's internal regulator, to provide 5V or 3V3 depending on which Arduino you are using. With a 5V Arduino, using Vin of 6V or more will be adequate. Higher Vin causes more heat in the Arduino on board regulator. (As Chaaarlie2 noted, 6V on Vin may be a bit on the low side for heavy loads on the Arduino 5V supply - as may happen if shields use the 5V supply. Increasing Vin to say 6.5V should allow the Arduino's internal regulator to supply its maximum rated current if desired.
9V output is higher than the Arduino needs. It is an acceptable voltage but 6V to 7V will cause less heat on-board the Arduino (and more in the external regulator).
Vehicle power systems can have extremely high voltage spikes present and sudden changes in supply voltage. Some regulators are made to work well in the automotive environment. One such family are the LM29xx series of regulators.
One superb version of this regulator is the LM2931-N [Data sheet here] - this is available in a range of versions but the simplest is the 3 lead type in a range of packages. The TO220 package is recommended due to its good power dissipation capability and ease of heatsinking if necessary. This data sheet covers versions with about 100 mA output rating, but higher output examples are available. Fixed 3.3V and 5V output versions are available but in this application the variable output version, set to about 6V or maybe 6.5V is "safest". These are very similar to the common LM317 in operation. The basic regulator produces 1.26V output and 2 resistors are used to set the desired output voltage. The advantages over the LM317 are the lower dropout voltage and the protection against typical automotive input problems.
The datasheet description states:

Designed originally for automotive applications, the LM2931-N and all regulated circuitry are protected from reverse battery installations or 2 battery jumps.
During line transients, such as a load dump (60V) when the input voltage to the regulator can momentarily exceed the specified maximum operating voltage, the regulator will automatically shut down to protect both internal circuits and the load.
The LM2931-N cannot be harmed by temporary mirror-image insertion. Familiar regulator features such as short circuit and thermal overload protection are also provided.

6V isn't quite good enough for Vin, especially when the OP has the means to provide more. Despite the Arduino website saying 6V is suitable - although not recommended - looking at the datasheet for the 5V regulator (on the genuine board) the dropout voltage at 100mA load is up to 1.1V; I wouldn't be comfortable so close to this limit. On clone boards the dropout could be even higher. Therefore, why not just provide 5V to the 5V input? The inclusion of the Vin and power jack is for convenience, not necessity! This will help minimise wasted power, as the voltage is only regulated once.

@chaaarlie2 You may be right about the std regulator. I've had no problem with clones at 6V. If you use the Arduino to supply an unknown external load you could (of course) have problems. The reason for suggesting using the internal regulator is several fold. It adds another layer of protection against the nasty automotive (or motorbikeomotive) environment. If things go wrong at the input the Arduino may not die with 12V++ on Vin. With 12V++ on the 5V pin you usually don't even see the magic smoke. I've been blowing things up for somewhat over 50 years and have become averse to giving ....

@chaaarlie2 ... Murphy more chances than possible. Adding another 0.5V to Vin is easy if an LM2931 is used. Low Vin keeps dissipation down on the Arduino board. |Power wasted is the ame whatever the regulator arrangement. You use 5V x Iin and you dissipate (V12in - 5V) x Iin somewhere or other. Dissipating as much of it as possible in the resistor I mentioned is often a very good idea.

@chaaarlie2 Added comment on using 6.5V for heavier loads with hat tip to you.

My batch of Uno clones all shut down at ~6.8V - looks like I've been mugged off! As you've championed the LM2391 so heavily, why now doubt its ability to provide a safe 5V without frying the Arduino even "if things go wrong" ? Of course I see the benefit of belt and braces, which is why I'd use a zener and quick-blow fuse as a backup. Ultimately it's going to depend on the OP's situation, so it's relatively moot. As I side note (from experience of the very same), cooling a regulator on motorbike isn't difficult - attach the simplest of heatsinks and hang it somewhere windy!

@chaaarlie2 I trust the LM2931 well enough when fed and watered as per growing guide - but reality often does not match desire, as I know you know. || You have an imnteresting profile page - closer to mine than many. ME both. I had C4-C5 spinal fusion Jan15 and MAY need another foray early 2016 but will resist if all all possible. Results very good but indications that spinal cord is still being impacted in a way that may cause progressive issues. Gaabapentin helped less for me than I'd expected. | Diclofenac worked utter miracles for me pre-opn. Do try if you have not done so.  ...

@chaaarlie2 ... it has risks and also progressively degrades renal function :-( so gains need to be balanced against issues. I do not now use it regularly except as 1 off prophylactic for 'big days out' - eg with 2 heavy cameras flash etc when it helps muchly. ('EE is day job'  - Photography an obsession  my wife says ) (Balboa (unarmoured version) was foreign to me - I'd take photos :-)  )

@chaaarlie2 Re UNO clones and Vin min. I have had very good results from Baite electronics via AliExpress. I have a UNO and a Spark Core at the same Vin=6V  talking to it . Both are happy. | I just did a test. Clone UNO:  5V output drops out of regulation at around 5.9 -  5.95V on Vin with Uno only on Vin. | Added first 60mA and then 120 mA loads to 5V out pin (82 Ohm resistor then 2 in parallel). Dropout voltage rose maybe 0.05V to say 5.95V - 6V on Vin for load of UNO + 120 mA on 5V out pin. | Once they use other than original regulator they can use anything. Looks like Baite chose well.


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

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

EthernetServer server(80);

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

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

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

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

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

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

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

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

More info at this link Arduino Ethernet Shield2

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

// initialize the library instance:
EthernetClient client;

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

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

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

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

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

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

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

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

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


text:
Simply Button Problem (Teensy 2.0)
I am getting back into doing some hardware stuff after a fairly long time away and am having a hard time getting back into it. I have a Teensy 2.0 and am trying to run a basic sketch that when a button is pressed will output 0, but my button is always High. I think that I miswired something but my breadboard looks like all the tutorials so I'm just confused as to what is going on and would appreciate any help.
const int pinBtnUp = 0;
const int pinLEDOutput = 11;

void setup()
{
  Serial.begin(38400);

  //Setup the pin modes.
  pinMode( pinLEDOutput, OUTPUT );
  //Special for the Teensy is the INPUT_PULLUP
  //It enables a pullup resitor on the pin.
  pinMode( pinBtnUp, INPUT_PULLUP );

}

void loop()
{
  Serial.println(digitalRead(pinBtnUp));
}

Am I correct in assuming those side rails are all connected? Where is the schematic for this?

You should post a higher quality version next time.
Wiring:
First of all, the button looks like it's not all the way in. Fix that first.
Also, from your picture, it looks like the green wire isn't in the right row:

I can't tell for sure. Also, like mentioned before, you to put the button over the gap between the two sides of the breadboard.
Also, you have a pullup resistor in your circuit and you enable it on the Arduino. And your physical pullup resistor isn't connected to your signal line. And you short your signal line to ground. All of this is incorrect wiring...
If utilizing the internal pullup resistor (like you are in your code), all you should need to do for a circuit is like this:

Just be sure to connect the 5V rail to 5V and the green wire to your digital pin.
Code:
That's all fine. When doing logic with a button, be sure to debounce it.

You would need to place your button over the "valley" in the centre of the breadboard, separating teh top 2 and bottom 2 legs of the button.
Currently the wire connecting the button to Pin 0 on your teensy is also connected to your pullup resistor on the breadboard, as it is in the same row.
To help troubleshoot this kind of thing I always find a digital multimeter very useful.


text:
There is any way to simulate an arduino due?
As the title says there is any program that can simulate an arduino due? I like the design of Proteus 8 but he can't simulate it. Only the arduino Uno R3, Mega and another one that I forgot the name.


text:
Uploading sketch to ESP8266
I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.
I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red).
To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.
The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

espcomm_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:
9V battery --> 3.3V converter --> ESP---> TTL
Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.
My goal is to do this tutorial:
https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf
Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp

If when I tried to do the commands and now doesn't work, means that I have to reflash the AT firmware again?

Are you using the original AT firmware?

Are you releasing GP0 from ground once the ESP has turned on?

Following on from user1637451 the following sequence has always worked for me:

Before download, pull both GPIO0 and RST to ground.
Release the pull down on RST, but keep GPIO0 low.
When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.
As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.


text:
Help with arduino car project
So in computer engineering I've got to make a arduino based car, I've added a whole bunch of features such as IR tracking, obstacle avoidance(proximity sensor), optical tracking(follow a black line), and remote control through an android based phone.
Since I'm a total newbie to technology I'm having trouble. I would appreciate it if You guys can point me towards resources and arduino libraries(for coding) that will work for me. Right now for coding I've only got basic pseudo-code setup since I do not know what libraries to use. I have searched up many sketches online and looked at them but didn't really understand any of the code.
Here's the basic pseudo-code I got setup on the things that I've got to work on:
DC Motor (4 of em for the wheels) (I also plan to add a stepper motor for turning right and left so if you could direct me on that as well)
//Import necessary library
//Setup the motors and pins
//If signal for forward received
//Code for moving forward
//Set speed
//Else If signal for backward received
//Code for moving backward
//Set speed
//Else If signal for right received (keep turning right till stop signal received)
//Code for moving right
//Set speed
//Else If signal for left received (keep turning left till stop signal received)
//Code for moving left
//Set speed
//Else If signal for stop is received (Should we slow down to a stop or just stop?)
//Code for stop
//Set speed
IR (I've got transmitting and recording diodes)
//Import Library
//Declare Pin for the IR Sensor
//While loop: Move Right
//If IR signal is received
//move forward
//Else
//Jump back to top of loop
Proximity Sensor (obstacle avoidance mode) (I might either use the one from Lego kit or buy a separate one )
//Import Library
//Declare Pin for proximity sensor
//While Loop: Send out sonar(echolocation or whatever) every second
//Is there any obstacle?
  //Yes, turn right so many degrees, and go back to while loop
  //No, move on forward at set speed
//If you’re surrounded and cannot exit send out a message through flashing LED's

I'm not asking for the code or for any of you to do all my stuff for me, I'm just asking for direction and resources.
Thank You

1) start simple - adding extra features will not help you, especially if you have a deadline
2) implement and test code for each low level function separately - however, in case you use libraries and or snippets, make sure that if a library/snippet requires exclusive use of a certain feature (ex: a timer), others do not need it.
3) test the overall logic elsewhere, where it easier to debug (ex: on a PC), by replacing the actual function calls to low level actuators/sensors with mockup functions that do I/O through either a file or a console.
Said this, what do you mean that you didn't understand the examples you found? To understand most of them, you need at least to read the API/interface of the libraries they use. And also reading the reference manual of the ATMega328P for the HW blocks referred by each library will help getting an overall feeling of what the library does.
About the basic physical model: once you have 4 DC motors (but 2 plus a caster would be enough), why do you want to add a stepper? Youc could do all of it with just 2 stepper motors , which will give you a simpler way to control precisely the orientation of the robot.
I'd suggest you to get the basic movement sorted out, before worrying about the rest. Just make sure that it doesn't make exclusive use of the microcontroller.


text:
Passing a static array to a function
I have a functon that creates a instance of KeyReport and I want to fill statically the KeyReport.keys array. I'm new in the Arduino world so I'll put a example to explain it better:
void sendKey(byte keys[6], byte modifiers)
{
  KeyReport report = {0};

  report.keys = keys; // This is my main trouble
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

void setup(){
delay(3000);
sendKey( {0x17,0,0,0,0,0}, 0x5); // I want to send hardcoded reports like this
}

void loop(){}

report.keys = keys; // This is my main trouble

You can't assign the contents of one array to the contents of another array.  You can only copy the contents manually from one to the other.
The simplest way is with a loop:
for (int i = 0; i < 6; i++) {
    report.keys[i] = keys[i];
}

There is a helper function - memcpy() - which can do it for you if you prefer:
memcpy(report.keys, keys, 6);

It effectively does exactly the same thing - copy 6 bytes starting from the address of keys into the addresses starting at report.keys.
As for the "hard coded" reports I suggest you create some const arrays in the global context - and even use PROGMEM to ensure they consume no RAM. That, of course, requires an entirely different way of passing and accessing the data.  It may be simpler to split the report into 6 individual variables and pass each byte separately:
void sendKey(byte k0, byte k1, byte k2, byte k3,
             byte k4, byte k5, byte modifiers)
{
  KeyReport report = {0};

  report.keys[0] = k0;
  report.keys[1] = k1;
  report.keys[2] = k2;
  report.keys[3] = k3;
  report.keys[4] = k4;
  report.keys[5] = k5;
  report.modifiers = modifiers;
  report.reserved = 1;
  Keyboard.sendReport(&report);
}

sendKey(0x17, 0, 0, 0, 0, 0, 0x05);

Yes, it's a little more long winded in the function, but calling the function is somewhat more simplified over the other options.

+35: Really good answer. Your last method is the best for me.

One last question: Is ok to use a for loop to clear the report.keys array?

Yep, perfectly fine. for (int i = 0; i < 6; i++) { report.keys[i] = 0; }


text:
Simple URL decoding
How can I do a readable, small, smart and good URL decoder in Arduino?
Now I'm using this code:
String GetRidOfurlCharacters(String urlChars)
{

  urlChars.replace("%0D%0A", String('\n'));

  urlChars.replace("+",   " ");
  urlChars.replace("%20", " ");
  urlChars.replace("%21", "!");
  urlChars.replace("%22", String(char('\"')));
  urlChars.replace("%23", "#");
  urlChars.replace("%24", "$");
  urlChars.replace("%25", "%");
  urlChars.replace("%26", "&");
  urlChars.replace("%27", String(char(39)));
  urlChars.replace("%28", "(");
  urlChars.replace("%29", ")");
  urlChars.replace("%2A", "*");
  urlChars.replace("%2B", "+");
  urlChars.replace("%2C", ",");
  urlChars.replace("%2D", "-");
  urlChars.replace("%2E", ".");
  urlChars.replace("%2F", "/");
  urlChars.replace("%30", "0");
  urlChars.replace("%31", "1");
  urlChars.replace("%32", "2");
  urlChars.replace("%33", "3");
  urlChars.replace("%34", "4");
  urlChars.replace("%35", "5");
  urlChars.replace("%36", "6");
  urlChars.replace("%37", "7");
  urlChars.replace("%38", "8");
  urlChars.replace("%39", "9");
  urlChars.replace("%3A", ":");
  urlChars.replace("%3B", ";");
  urlChars.replace("%3C", "<");
  urlChars.replace("%3D", "=");
  urlChars.replace("%3E", ">");
  urlChars.replace("%3F", "?");
  urlChars.replace("%40", "@");
  urlChars.replace("%41", "A");
  urlChars.replace("%42", "B");
  urlChars.replace("%43", "C");
  urlChars.replace("%44", "D");
  urlChars.replace("%45", "E");
  urlChars.replace("%46", "F");
  urlChars.replace("%47", "G");
  urlChars.replace("%48", "H");
  urlChars.replace("%49", "I");
  urlChars.replace("%4A", "J");
  urlChars.replace("%4B", "K");
  urlChars.replace("%4C", "L");
  urlChars.replace("%4D", "M");
  urlChars.replace("%4E", "N");
  urlChars.replace("%4F", "O");
  urlChars.replace("%50", "P");
  urlChars.replace("%51", "Q");
  urlChars.replace("%52", "R");
  urlChars.replace("%53", "S");
  urlChars.replace("%54", "T");
  urlChars.replace("%55", "U");
  urlChars.replace("%56", "V");
  urlChars.replace("%57", "W");
  urlChars.replace("%58", "X");
  urlChars.replace("%59", "Y");
  urlChars.replace("%5A", "Z");
  urlChars.replace("%5B", "[");
  urlChars.replace("%5C", String(char(65)));
  urlChars.replace("%5D", "]");
  urlChars.replace("%5E", "^");
  urlChars.replace("%5F", "_");
  urlChars.replace("%60", "`");
  urlChars.replace("%61", "a");
  urlChars.replace("%62", "b");
  urlChars.replace("%63", "c");
  urlChars.replace("%64", "d");
  urlChars.replace("%65", "e");
  urlChars.replace("%66", "f");
  urlChars.replace("%67", "g");
  urlChars.replace("%68", "h");
  urlChars.replace("%69", "i");
  urlChars.replace("%6A", "j");
  urlChars.replace("%6B", "k");
  urlChars.replace("%6C", "l");
  urlChars.replace("%6D", "m");
  urlChars.replace("%6E", "n");
  urlChars.replace("%6F", "o");
  urlChars.replace("%70", "p");
  urlChars.replace("%71", "q");
  urlChars.replace("%72", "r");
  urlChars.replace("%73", "s");
  urlChars.replace("%74", "t");
  urlChars.replace("%75", "u");
  urlChars.replace("%76", "v");
  urlChars.replace("%77", "w");
  urlChars.replace("%78", "x");
  urlChars.replace("%79", "y");
  urlChars.replace("%7A", "z");
  urlChars.replace("%7B", String(char(123)));
  urlChars.replace("%7C", "|");
  urlChars.replace("%7D", String(char(125)));
  urlChars.replace("%7E", "~");
  urlChars.replace("%7F", "Â");
  urlChars.replace("%80", "`");
  urlChars.replace("%81", "Â");
  urlChars.replace("%82", "â");
  urlChars.replace("%83", "Æ");
  urlChars.replace("%84", "â");
  urlChars.replace("%85", "â¦");
  urlChars.replace("%86", "â");
  urlChars.replace("%87", "â¡");
  urlChars.replace("%88", "Ë");
  urlChars.replace("%89", "â°");
  urlChars.replace("%8A", "Å");
  urlChars.replace("%8B", "â¹");
  urlChars.replace("%8C", "Å");
  urlChars.replace("%8D", "Â");
  urlChars.replace("%8E", "Å½");
  urlChars.replace("%8F", "Â");
  urlChars.replace("%90", "Â");
  urlChars.replace("%91", "â");
  urlChars.replace("%92", "â");
  urlChars.replace("%93", "â");
  urlChars.replace("%94", "â");
  urlChars.replace("%95", "â¢");
  urlChars.replace("%96", "â");
  urlChars.replace("%97", "â");
  urlChars.replace("%98", "Ë");
  urlChars.replace("%99", "â¢");
  urlChars.replace("%9A", "Å¡");
  urlChars.replace("%9B", "âº");
  urlChars.replace("%9C", "Å");
  urlChars.replace("%9D", "Â");
  urlChars.replace("%9E", "Å¾");
  urlChars.replace("%9F", "Å¸");
  urlChars.replace("%A0", "Â");
  urlChars.replace("%A1", "Â¡");
  urlChars.replace("%A2", "Â¢");
  urlChars.replace("%A3", "Â£");
  urlChars.replace("%A4", "Â¤");
  urlChars.replace("%A5", "Â¥");
  urlChars.replace("%A6", "Â¦");
  urlChars.replace("%A7", "Â§");
  urlChars.replace("%A8", "Â¨");
  urlChars.replace("%A9", "Â©");
  urlChars.replace("%AA", "Âª");
  urlChars.replace("%AB", "Â«");
  urlChars.replace("%AC", "Â¬");
  urlChars.replace("%AE", "Â®");
  urlChars.replace("%AF", "Â¯");
  urlChars.replace("%B0", "Â°");
  urlChars.replace("%B1", "Â±");
  urlChars.replace("%B2", "Â²");
  urlChars.replace("%B3", "Â³");
  urlChars.replace("%B4", "Â´");
  urlChars.replace("%B5", "Âµ");
  urlChars.replace("%B6", "Â¶");
  urlChars.replace("%B7", "Â·");
  urlChars.replace("%B8", "Â¸");
  urlChars.replace("%B9", "Â¹");
  urlChars.replace("%BA", "Âº");
  urlChars.replace("%BB", "Â»");
  urlChars.replace("%BC", "Â¼");
  urlChars.replace("%BD", "Â½");
  urlChars.replace("%BE", "Â¾");
  urlChars.replace("%BF", "Â¿");
  urlChars.replace("%C0", "Ã");
  urlChars.replace("%C1", "Ã");
  urlChars.replace("%C2", "Ã");
  urlChars.replace("%C3", "Ã");
  urlChars.replace("%C4", "Ã");
  urlChars.replace("%C5", "Ã");
  urlChars.replace("%C6", "Ã");
  urlChars.replace("%C7", "Ã");
  urlChars.replace("%C8", "Ã");
  urlChars.replace("%C9", "Ã");
  urlChars.replace("%CA", "Ã");
  urlChars.replace("%CB", "Ã");
  urlChars.replace("%CC", "Ã");
  urlChars.replace("%CD", "Ã");
  urlChars.replace("%CE", "Ã");
  urlChars.replace("%CF", "Ã");
  urlChars.replace("%D0", "Ã");
  urlChars.replace("%D1", "Ã");
  urlChars.replace("%D2", "Ã");
  urlChars.replace("%D3", "Ã");
  urlChars.replace("%D4", "Ã");
  urlChars.replace("%D5", "Ã");
  urlChars.replace("%D6", "Ã");
  urlChars.replace("%D7", "Ã");
  urlChars.replace("%D8", "Ã");
  urlChars.replace("%D9", "Ã");
  urlChars.replace("%DA", "Ã");
  urlChars.replace("%DB", "Ã");
  urlChars.replace("%DC", "Ã");
  urlChars.replace("%DD", "Ã");
  urlChars.replace("%DE", "Ã");
  urlChars.replace("%DF", "Ã");
  urlChars.replace("%E0", "Ã");
  urlChars.replace("%E1", "Ã¡");
  urlChars.replace("%E2", "Ã¢");
  urlChars.replace("%E3", "Ã£");
  urlChars.replace("%E4", "Ã¤");
  urlChars.replace("%E5", "Ã¥");
  urlChars.replace("%E6", "Ã¦");
  urlChars.replace("%E7", "Ã§");
  urlChars.replace("%E8", "Ã¨");
  urlChars.replace("%E9", "Ã©");
  urlChars.replace("%EA", "Ãª");
  urlChars.replace("%EB", "Ã«");
  urlChars.replace("%EC", "Ã¬");
  urlChars.replace("%ED", "Ã");
  urlChars.replace("%EE", "Ã®");
  urlChars.replace("%EF", "Ã¯");
  urlChars.replace("%F0", "Ã°");
  urlChars.replace("%F1", "Ã±");
  urlChars.replace("%F2", "Ã²");
  urlChars.replace("%F3", "Ã³");
  urlChars.replace("%F4", "Ã´");
  urlChars.replace("%F5", "Ãµ");
  urlChars.replace("%F6", "Ã¶");
  urlChars.replace("%F7", "Ã·");
  urlChars.replace("%F8", "Ã¸");
  urlChars.replace("%F9", "Ã¹");
  urlChars.replace("%FA", "Ãº");
  urlChars.replace("%FB", "Ã»");
  urlChars.replace("%FC", "Ã¼");
  urlChars.replace("%FD", "Ã½");
  urlChars.replace("%FE", "Ã¾");
  urlChars.replace("%FF", "Ã¿");

  return urlChars;
}

However I want to make a loop and only replace a url escaping if it exists, not trying to replace all the (possible) occurrences.

The fact that you're using a String (urgh, shudder shudder... you should read this: http://hacking.majenko.co.uk/the-evils-of-arduino-strings) actually makes it a little harder to work with.  Instead you should have your String data in a character array ("C string"). Then a parser is much easier to write using a pair of character pointers.
Basically the theory is you scan from the start of the string to the end of the string using both pointers copying characters as you go, and as soon as you hit a % you read ahead 2 characters using the first pointer (the second pointer stays where it is) and you convert the two read characters as hex into the ASCII equivalent and use the second pointer to replace the %.
Then both pointers keep moving forward, but they stay out of step. As each % crops up the pointers get further and further out of step until you reach the end of the string and all the %xx have been replaced with a single character.
For instance, this code I have just knocked up does the job:
char data[50] = "http://foo/bar?x=hello%20there%3A%20majenko";

// Create two pointers that point to the start of the data
char *leader = data;
char *follower = leader;

// While we're not at the end of the string (current character not NULL)
while (*leader) {
    // Check to see if the current character is a %
    if (*leader == '%') {

        // Grab the next two characters and move leader forwards
        leader++;
        char high = *leader;
        leader++;
        char low = *leader;

        // Convert ASCII 0-9A-F to a value 0-15
        if (high > 0x39) high -= 7;
        high &= 0x0f;

        // Same again for the low byte:
        if (low > 0x39) low -= 7;
        low &= 0x0f;

        // Combine the two into a single byte and store in follower:
        *follower = (high << 4) | low;
    } else {
        // All other characters copy verbatim
        *follower = *leader;
    }

    // Move both pointers to the next character:
    leader++;
    follower++;
}
// Terminate the new string with a NULL character to trim it off
*follower = 0;

The data array now contains:
http://foo/bar?x=hello there: majenko

+35: Thank you very much! I'm not a C/C++ programmer, I only used Bash, Python and Gambas3 with a good level ;-). I'm beginning to contribute to this project: https://github.com/esp8266/Basic and I wanted to simplify the above code because it seemed ugly and badly implemented. However, would you recommend me to drop the use of String on all the project, or should I convert the input String to a char?

Strings are lazy and overly wasteful of resources. Not as critical on an esp8266 as it is on an Arduino, but still not good. I never ever use them.

I wrote a Tiny web server for the Arduino which has a similar thing in it. You might find it useful for your project. Inside there is a function that decodes the URL codes on-the-fly (ie. in a state machine). The code is a bit different to Majenko's because he assumes that you have the string in memory. In my case I am decoding a byte at a time (so you don't have to hold a long string in memory before you decode it).
The snippet that does the decoding is this:
  // percent-encoding: possible states
  enum EncodePhaseType {
    ENCODE_NONE,
    ENCODE_GOT_PERCENT,
    ENCODE_GOT_FIRST_CHAR,
  };
  // percent-encoding: current state
  EncodePhaseType encodePhase;
  byte encodeByte;  // encoded byte being assembled (first nybble)

...
// ---------------------------------------------------------------------------
// add a character to the value buffer - percent-encoded (if wanted)
// ---------------------------------------------------------------------------
 void HTTPserver::addToValueBuffer (byte inByte, const bool percentEncoded)
  {
  if (valueBufferPos >= MAX_VALUE_LENGTH)
    {
    flags |= FLAG_VALUE_BUFFER_OVERFLOW;
    return;
    }  // end of overflow

  // look for stuff like "foo+bar" (turn the "+" into a space)
  // and also "foo%21bar" (turn %21 into one character)
  if (percentEncoded)
    {
    switch (encodePhase)
      {

      // if in "normal" mode, turn a "+" into a space, and look for "%"
      case ENCODE_NONE:
        if (inByte == '+')
          inByte = ' ';
        else if (inByte == '%')
          {
          encodePhase = ENCODE_GOT_PERCENT;
          return;  // no addition to buffer yet
          }
        break;

      // we had the "%" last time, this should be the first hex digit
      case ENCODE_GOT_PERCENT:
        if (isxdigit (inByte))
          {
          byte c = toupper (inByte) - '0';
          if (c > 9)
            c -= 7;  // Fix A-F
          encodeByte = c << 4;
          encodePhase = ENCODE_GOT_FIRST_CHAR;
          return;  // no addition to buffer yet
          }
        // not a hex digit, give up
        encodePhase = ENCODE_NONE;
        flags |= FLAG_ENCODING_ERROR;
        break;

      // this should be the second hex digit
      case ENCODE_GOT_FIRST_CHAR:
        if (isxdigit (inByte))
          {
          byte c = toupper (inByte) - '0';
          if (c > 9)
            c -= 7;  // Fix A-F
          inByte = encodeByte | c;
          }
        else
          flags |= FLAG_ENCODING_ERROR;

        // done with encoding it, or not a hex digit
        encodePhase = ENCODE_NONE;

      } // end of switch on encodePhase
    } // end of percent-encoded

  // add to value buffer, encoding has been dealt with
  valueBuffer [valueBufferPos++] = inByte;
  valueBuffer [valueBufferPos] = 0;  // trailing null-terminator
  } // end of HTTPserver::addToValueBuffer


text:
How to vary the frequency of a PWM sinewave with arduino uno?
I'm generating a sine wave using a table, a PWM pin and an RC filter on the output. I would like to be able to control the frequency of the sine wave, how can I do that easily?
By the way, which is the maximum frequency achievable and why? As far as my understanding goes, the limit is given by the time arduino needs in order to run the loop() function.
This is the code I am using on arduino UNO. Please point it out if this is a horrible way to generate a sine wave with arduino, and if it is, feel free to provide a better solution.
const int8_t SIN1024_DATA [] = {... data table values (1024 values) ...};
int i = 0;
void setup()
{
  pinMode(9, OUTPUT);
}

void loop()
{
  digitalWrite(9, SIN1024_DATA[i]);
  i++;
  if(i == 1024){i = 0;}
}

I haven't seen this method of generating a sin-wave. Most I've seen use a PWM pin, and analogWrite. But to get a bit more performance out of this method, i'd wrap the code inside loop, in a while(true){ ... }. Making it a few cycles faster. Secondly, don't use digitalWrite, as it's quite slow. Either use direct port manipulation, or use something like digitalWriteFast.

First thing, you must find a way to output the samples at a steady rate.
Your best bet is to use a timer. Ideally, you want to use the same timer
used for the PWM output, in order to have them synchronized. See for
example how it is done in the Mozzi sound synthesis
library.
Then you can lower the frequency by repeatedly outputting the same
value: if you output every value once, you get the “base” frequency
(sample frequency ÷ 1024). If you output each value n times you get
the base frequency divided by n. Conversely, you can get higher
frequencies by skipping samples. For example, if you output only every
other sample, you get twice the base frequency.
These two approaches can be conveniently combined in a very simple code:
you keep a phase variable and, on every sample, you increment it by an
amount proportional to the desired frequency. You then use the higher
bits of the phase as an index into your array. The lower bits then serve
only to increase the frequency resolution and allow frequencies lower
than the base one. Here is a simple implementation:
const uint8_t pin = ...;
uint8_t frequency;

// Call periodically.
static inline void output_a_sample()
{
    static uint16_t phase;
    analogWrite(pin, SIN1024_DATA[phase>>6]);
    phase += frequency;
}

This lets you set the frequency in units of the sampling frequency ÷
216, i.e. the base frequency ÷ 26.
Note that the phase here is 16-bits: 10 bits for the array index and 6
bits for the fractional part. Since all the bits are used, you do not
need to handle the rollover: a uint16_t automatically rolls over
modulo 216, which is just what you want here. You can use a
32-bit variable if you need more frequency resolution.


text:
Arduino UNO GPS module
I am thinking about buying a gps module for Arduino UNO.
I would like to install it on a self-build RC-car which is also controlled by Arduino.
The problem is, I cannot install the gps module on the top of the car (on the surface), only the bottom and or/middle space is "free".
My questions are:
1)Is there a module which can overcome a small layer of steel (max 2cm thick) and some plastic and still get a good signal?
2)It would be nice to be able to store the data into a memory card.
3)It would be a great plus to be able to gather data real-time through some kind of connection. Sadly I do not know how to do here. Is there some place where I can look up any of this?
Do you think that this http://www.adafruit.com/products/1272 is what I need?
thank you

1) Just break out the headers on the GPS module to make for connections to the UNO.
2) Add a SD expansion slot on top of the GPS Module and break out the pins for those as the required pins for those as well.
3) I am not sure what you are asking exactly, but it seems to me that you want to analyze the data real-time.  Get a network shield and make sure you can SSH into it through another computer.
Note: When I say "break out the pins", I am simply saying either solder on some extra headers, or wires.


text:
How can I generate a sinewave with Arduino Uno?
I would like to generate a sine wave with my Arduino Uno. As far as I know, there is no library for Uno to generate such a signal (correct me if I'm wrong), so the only option available is to write a function to generate the signal from scratch.
As far as my understanding of digital electronics goes, I believe it is possible to generate a sine wave signal by using PWM and varying the duty cycle accordingly. However, this route seems to me quite long, what other options do I have?

As far as I know, there is no library for Uno to generate such a
  signal (correct me if I'm wrong)

You are wrong, there is Mozzi, the sound synthesis library for
Arduino. It works essentially along the lines sketched by uint128_t.
Take a look at the Sinewave.ino for an example on how to make a
(lookup table-based) sine wave. It can also do much more.
In its default mode, Mozzi works with a 16,384 Hz sample rate and a
32,768 Hz (not audible) PWM frequency.

I found Mozzi to be very heavyweight for a limited memory footprint. It is fine if there is no plan to perform a number of tasks with one Arduino board, pushing the limits of program executable space.

There are two parts to this:
One is the creation/derivation/storage of the digital representation of a sine wave. The other is the conversion of the digital representation of a sine wave to an analog voltage (if I understand what you want).

The easiest way to obtain the digital representation of a sine wave is a lookup table. Precompute the digital values, and store them in an array. Simple. It is up to you to decide how much resolution (both in vertical accuracy/number of bits and horizontal accuracy/number of samples) you require.
It is also possible to compute the values directly. There are a number of ways of doing this, but be aware that using floating point math on the Arduino is very slow and space-intensive. You may want to look at CORDIC for one possible solution to this.

Next is the conversion to analog. You are right, PWM is one way to do this, and one of the easiest as far as external components go: you only need an RC filter to smooth the PWM. However, PWM is limited in resolution, and performs poorly when your wave frequency becomes a significant fraction of your PWM frequency. Also, the Arduino doesn't run very fast, so your PWM frequency is limited.
Other DAC solutions (there are many many many, so I'm not going to go in depth on this):

R2R DAC: simple to construct, but requires precision resistors for decent resolution, limited in resolution, and requires many IO pins.
"proper" DAC: an I2C/SPI DAC can give you far better performance, but you will have to learn how to communicate with it. And it's going to be more expensive, and involve several components.

However, this route seems to me quite long, what other options do I have?

I'm not sure what you mean by "quite long", but this is pretty straightforward. For example, here's how I'd go about it:

store a sine wave in a lookup table
set up an interrupt to trigger at regular intervals
in the interrupt, pull a value from the lookup table and write it to PWM

You can now vary the frequency of your sine wave by either adjusting your interrupt interval, or adjusting the increment of your LUT position. You can vary the amplitude by simply multiplying the LUT values by a variable.
This is quite straightforward.

I meant that using the PWM option would be longer to implement compared to something easier such as a lookup table as you suggested. I think the lookup table option you suggested is exactly what I was looking for. It is fast and provides a quick way to tune frequency. Thanks.

You still need both. And the PWM option is very difficult to implement, at most, you'll need to learn how interrupts work, and how PWM works, which might be a lot of work, but should be worthwhile if you're interested in Arduino in general.

@uint128_t: Did you mean "not very difficult..."?

@JRobert I did, thank you. OP: PWM is not very difficult.

You can get a very fast, accurate, and compact sin(theta) function using a simple table of values.  Just pull the code you need from the cordic.c here: https://people.sc.fsu.edu/~jburkardt/c_src/cordic/cordic.html.  C runs in Arduino sketches almost out of the box.  You may or may not need some things from the cordic.h.  That's why I said "almost".  The cordic_prb.c test file has a function test002() that shows you how to call the sine function.
Because the Uno does not have a real D-to-A converter, you will only get a rectangular wave that has digital noise over the primary harmonic.  That's the down side of the pulse width modulation of the lower end Arduino chips.  You will need a filter on the analog output if you need to remove the higher frequency noise harmonics.

I found that the Mozzi sinewave.ino demanded more and more include files during compile efforts, and once these (easy) problems were resolved, it ended up with horrific compile errors due to something missing in the code. NBG for a "C" dummy like me!

Douglas, So did I (have endless trouble) with Mozzi. It was said elsewhere in stack exchange that I might not have picked up on all the include files. If I solve in 2017 I'll post the solution!

Am also a C dunmy

You could look at.          http://interface.khm.de/index.php/lab/interfaces-advanced/arduino-dds-sinewave-generator/     which gives badly commented code and a PWM output on a digital pin. You need a low-pass filter to clean up the signal & reveal the sinewave. I still don't understand how the interrupt works . . .

Actually this code although it works (I think) is possibly the worst example of coding I have ever seen. Sorry!


text:
How to send numbers to Arduino UNO via Python 3 and the module serial
I am new to Arduino (and computer programming in general), so I apologize if this question  looks silly.
Once I set up a basic arduino-LED connection, I have problems sending INTEGERS to arduino through the serial port. I can easily send characters such as 'm', 'o' and so on.. However if I send a number it looks like it simply does not get it.
Here is the Arduino code, ideally it should get a value from the usb port through python or the serial monitor and then adjust the brightness of the LED according to the value. (value must be in range [0,255]).
NOTE: I am using ARDUINO UNO and PYTHON 3
//--------------------------
int LED = 10;
int number;

void setup(){

pinMode(LED,OUTPUT);
Serial.begin(9600);
}

void loop(){

number = Serial.read();
Serial.print(number);
Serial.print('\n');
if(number == -1){
number = 0;
}

else if(number > 255){

number = 255;

}

else if(number < 0){

number = 0;
}

analogWrite(LED,number);
delay(1000);
}

However, when I input a value into the Serial port or through Python, for instance 0, it gives me 48 as answer (which, interestingly, is the ASCII code for 0!) and lights up the LED which is not what should happen since at 0 the LED should be off!!
I am missing something but I cannot find what... Could you please tell me what is wrong?
Here is the code I use in Python:
import serial
import time
try:
    arduino = serial.Serial(port,speed)
    time.sleep(2)
    print("Connection to " + port + " established succesfully!\n")
except Exception as e:
    print(e)

#Note: for characters such as 'a' I set data = b'a' to convert the data in bytes
#However the same thing does not work with numbers...
data = 0
data = arduino.write(valueToWrite)
time.sleep(2)
arduino.close()

what am I doing wrong or misunderstanding? Thank you.

Try arduino.write(chr(valueToWrite))

This solution does not work even for characters.. Furthermore, as far as characters are concerned, it works fine just sending them as bytes such as: b'm'. Anyway, thanks for the answer.

Parsing on the Arduino can be slow and time-consuming (which is bad if you use clock prescaling or have time-critical tasks), so let's do it in Python.
The problem is that you're sending the numbers as ASCII whereas you need to be sending them as raw binary. This is where struct comes in.
3>> import struct
3>> print(struct.pack('>B', 0))
b'\x00'
3>> print(struct.pack('>B', 255))
b'\xff'
3>> print(struct.pack('>2B', 255, 0))
b'\xff\x00'
3>> print(struct.pack('>H', 9000))
b'#('

So what you really want is:
data = arduino.write(struct.pack('>B', valueToWrite))

or something to that effect.

Thank you very much! This is exactly what I was looking for!

Despite what the empty comment box greyed text says, I'm going to say thanks! Was trying to write a bit-stream (FPGA .bin program file) to a SPI flash chip using a Teensy 3.2 with Arduino as the PC -> flash interface, and this was the key to making it work on the PC end.

Serial.read() reads only ONE character from the serial port and returns its ASCII value, which explains the 48 you got.
To read a complete number, you have 2 options:

Use Serial.parseInt() that reads as many characters as needed and performs the conversion before returning the read number as an int. Please further check the reference here.
You read eachn character in a loop (with Serial.read()) until the last one, put each read charcater into a buffer (char array) then convert the resulting string to a number with the standard C function atoi.

Of course, the first option is the easiest one but it will return 0 if nothing is read after a 1s timeout (configurable with Serial.setTimeout()).

This answer was not exactly what I was asking for, however it has been very useful and I'll be using it! Thank you very much for the help!


text:
Don's NDEF library and bluetooth
I am trying to connect my Android smartphone with my Arduino Uno by sending a NDEF message to my phone.
I know that the MIME type for bluetooth is application/vnd.bluetooth.ep.oob but in my PN532 library I don't know what's the right prefix.
You can see prefixes here : https://github.com/Seeed-Studio/PN532/blob/master/PN532/PN532.h#L66
Thank you