text:
LCD Wiki screen (ILI9341) works on Mega. How to get it working on the Due?
I have this exact LCD shield: http://www.lcdwiki.com/2.8inch_Arduino_Display
SKU: MAR2808
Driver IC: ILI9341

It works on an Arduino Mega 2560 using the old libraries the manufacturer (I assume) provides on the wiki page. I was sending data to show on the screen through USB serial. Quickly realizing that was very limited, I heard that the Arduino Due would have a faster USB connection as it is "native".
So now I'm trying to get the shield to work on the Due.
The Due has a different operating voltage but the wiki said that the shield has an automatic level shifter, I decided to take a chance and put it on and see if anything broke. It seems it is fine as I can put the shield back on the Mega and it still works.
Back on the Due, I managed to find the original libraries that the Lcd Wiki guys copied and modified as I wanted to get a later version that supported the Due. They have not made that available so it seems it's up to me (and maybe you).
It seems they used this library (an older version): https://github.com/adafruit/TFTLCD-Library
So since the library had some updates since their hacks, I tried out the latest version (1.0.3 at the time of writing). Then I re-applied their changes to the pin_magic.h file. That got the latest library to work with the Mega.
It also allowed me to use the latest versions of other dependent libraries which is nice as I can now keep these all up to date.
adafruit/Adafruit TouchScreen@^1.1.3
adafruit/Adafruit GFX Library@^1.11.9

The issue comes in with their changes. I don't quite know how to translate them into Due related code as it seems you need to have a deep knowledge of the Due and the Mega hardware to understand what they did.
So they changed the following Mega code in the original library (pin_magic.h) from:
#define write8inline(d)                                                        \
{                                                                            \
    PORTH =                                                                    \
        (PORTH & B10000111) | (((d)&B11000000) >> 3) | (((d)&B00000011) << 5); \
    PORTB = (PORTB & B01001111) | (((d)&B00101100) << 2);                      \
    PORTG = (PORTG & B11011111) | (((d)&B00010000) << 1);                      \
    WR_STROBE;                                                                 \
}

to:
#define write8inline(d)                                                        \
{                                                                            \
    PORTE = (PORTE & B11001111) | ((d << 2) & B00110000); \
    PORTE = (PORTE & B11110111) | ((d >> 2) & B00001000); \
    PORTG = (PORTG & B11011111) | ((d << 1) & B00100000); \
    PORTH = (PORTH & B11100111) | ((d >> 3) & B00011000); \
    PORTH = (PORTH & B10011111) | ((d << 5) & B01100000); \
    WR_STROBE;                                                                 \
}

That's a lot of binary and ports that I don't understand. I feel like an important part is they change the ports(?) that it uses.
So the problem lies in how to change the original Due code to work in the same way the new code worked with the Mega?
This is the current Due code in the library:
#define write8inline(d)                                                        \
{                                                                            \
    PIO_Set(PIOD, (((d)&0x08) << (7 - 3)));                                    \
    PIO_Clear(PIOD, (((~d) & 0x08) << (7 - 3)));                               \
    PIO_Set(PIOC, (((d)&0x01) << (22 - 0)) | (((d)&0x02) << (21 - 1)) |        \
                      (((d)&0x04) << (29 - 2)) | (((d)&0x10) << (26 - 4)) |    \
                      (((d)&0x40) << (24 - 6)) | (((d)&0x80) << (23 - 7)));    \
    PIO_Clear(PIOC,                                                            \
              (((~d) & 0x01) << (22 - 0)) | (((~d) & 0x02) << (21 - 1)) |      \
                  (((~d) & 0x04) << (29 - 2)) | (((~d) & 0x10) << (26 - 4)) |  \
                  (((~d) & 0x40) << (24 - 6)) | (((~d) & 0x80) << (23 - 7)));  \
    PIO_Set(PIOB, (((d)&0x20) << (27 - 5)));                                   \
    PIO_Clear(PIOB, (((~d) & 0x20) << (27 - 5)));                              \
    WR_STROBE;                                                                 \
}

How do I change this code for the Due to do the same thing that the new Mega code does on the Mega?
I also don't understand why the Mega code uses binary and the Due code uses hex code all over. I'm hoping someone knows these things off-hand before I spend years researching how all this works.
An extra thing to note is that there is an option in the library to let it know the LCD is on a shield:
// **** IF USING THE LCD BREAKOUT BOARD, COMMENT OUT THIS NEXT LINE. ****
// **** IF USING THE LCD SHIELD, LEAVE THE LINE ENABLED:             ****

//#define USE_ADAFRUIT_SHIELD_PINOUT 1

That option must NOT be un-commented. It seems this LCD only works as if it was not a shield. Doesn't make sense to me but it continues what feels like not a thought in the world for maintainability/upgradability from the manufacturer.
The following is my current full pin_magic.h file with the modified Mega code and unmodified Due code. I may have removed some original library code in there while testing to narrow down the issue. The Mega code works correctly in this file.
#ifndef PIN_MAGIC
#define PIN_MAGIC

// This header file serves two purposes:
//
// 1) Isolate non-portable MCU port- and pin-specific identifiers and
//    operations so the library code itself remains somewhat agnostic
//    (PORTs and pin numbers are always referenced through macros).
//
// 2) GCC doesn't always respect the "inline" keyword, so this is a
//    ham-fisted manner of forcing the issue to minimize function calls.
//    This sometimes makes the library a bit bigger than before, but fast++.
//    However, because they're macros, we need to be SUPER CAREFUL about
//    parameters -- for example, write8(x) may expand to multiple PORT
//    writes that all refer to x, so it needs to be a constant or fixed
//    variable and not something like *ptr++ (which, after macro
//    expansion, may increment the pointer repeatedly and run off into
//    la-la land).  Macros also give us fine-grained control over which
//    operations are inlined on which boards (balancing speed against
//    available program space).

// When using the TFT shield, control and data pins exist in set physical
// locations, but the ports and bitmasks corresponding to each vary among
// boards.  A separate set of pin definitions is given for each supported
// board type.
// When using the TFT breakout board, control pins are configurable but
// the data pins are still fixed -- making every data pin configurable
// would be much too slow.  The data pin layouts are not the same between
// the shield and breakout configurations -- for the latter, pins were
// chosen to keep the tutorial wiring manageable more than making optimal
// use of ports and bitmasks.  So there's a second set of pin definitions
// given for each supported board.

// Shield pin usage:
// LCD Data Bit :    7    6    5    4    3    2    1    0
// Digital pin #:    7    6   13    4   11   10    9    8
// Uno port/pin :  PD7  PD6  PB5  PD4  PB3  PB2  PB1  PB0
// Mega port/pin:  PH4  PH3  PB7  PG5  PB5  PB4  PH6  PH5
// Leo port/pin :  PE6  PD7  PC7  PD4  PB7  PB6  PB5  PB4
// Due port/pin : PC23 PC24 PB27 PC26  PD7 PC29 PC21 PC22
// Breakout pin usage:
// LCD Data Bit :   7   6   5   4   3   2   1   0
// Uno dig. pin :   7   6   5   4   3   2   9   8
// Uno port/pin : PD7 PD6 PD5 PD4 PD3 PD2 PB1 PB0
// Mega dig. pin:  29  28  27  26  25  24  23  22
// Mega port/pin: PA7 PA6 PA5 PA4 PA3 PA2 PA1 PA0 (one contiguous PORT)
// Leo dig. pin :   7   6   5   4   3   2   9   8
// Leo port/pin : PE6 PD7 PC6 PD4 PD0 PD1 PB5 PB4
// Due dig. pin :  40  39  38  37  36  35  34  33
// Due port/pin : PC8 PC7 PC6 PC5 PC4 PC3 PC2 PC1 (one contiguous PORT. -ish…)

// Pixel read operations require a minimum 400 nS delay from RD_ACTIVE
// to polling the input pins.  At 16 MHz, one machine cycle is 62.5 nS.
// This code burns 7 cycles (437.5 nS) doing nothing; the RJMPs are
// equivalent to two NOPs each, final NOP burns the 7th cycle, and the
// last line is a radioactive mutant emoticon.
#define DELAY7                                                                 \
  asm volatile("rjmp .+0"                                                      \
               "\n\t"                                                          \
               "rjmp .+0"                                                      \
               "\n\t"                                                          \
               "rjmp .+0"                                                      \
               "\n\t"                                                          \
               "nop"                                                           \
               "\n" ::);

#if defined(__AVR_ATmega1281__) || defined(__AVR_ATmega2561__) ||            \
    defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1280__)

// Arduino Mega, ADK, etc.

// #define write8inline(d)                                                        \
// {                                                                            \
//     PORTH = (PORTH & B10000111) | (((d)&B11000000) >> 3) | (((d)&B00000011) << 5); \
//     PORTB = (PORTB & B01001111) | (((d)&B00101100) << 2);                      \
//     PORTG = (PORTG & B11011111) | (((d)&B00010000) << 1);                      \
//     WR_STROBE;                                                                 \
// }

#define write8inline(d)                                                        \
{                                                                            \
    PORTE = (PORTE & B11001111) | ((d << 2) & B00110000); \
    PORTE = (PORTE & B11110111) | ((d >> 2) & B00001000); \
    PORTG = (PORTG & B11011111) | ((d << 1) & B00100000); \
    PORTH = (PORTH & B11100111) | ((d >> 3) & B00011000); \
    PORTH = (PORTH & B10011111) | ((d << 5) & B01100000); \
    WR_STROBE;                                                                 \
}

#define read8inline(result)                                                    \
{                                                                            \
    RD_ACTIVE;                                        \
    DELAY7;                                           \
    result = ((PINH & B00011000) << 3) | ((PINE & B00001000) << 2) | ((PING & B00100000) >> 1) |((PINE & B00110000) >> 2) | ((PINH & B01100000) >> 5); \
    RD_IDLE;                                                             \
}

#define setWriteDirInline() { DDRE |=  B00111000; DDRG |=  B00100000; DDRH |= B01111000;}
#define setReadDirInline() { DDRE &=  ~B00111000; DDRG &=  ~B00100000; DDRH &= ~B01111000;}

// All of the functions are inlined on the Arduino Mega.  When using the
// breakout board, the macro versions aren't appreciably larger than the
// function equivalents, and they're super simple and fast.  When using
// the shield, the macros become pretty complicated...but this board has
// so much code space, the macros are used anyway.  If you need to free
// up program space, some macros can be removed, at a minor cost in speed.
#define write8 write8inline
#define read8 read8inline
#define setWriteDir setWriteDirInline
#define setReadDir setReadDirInline
#define writeRegister8 writeRegister8inline
#define writeRegister16 writeRegister16inline
#define writeRegisterPair writeRegisterPairInline

#elif defined(__SAM3X8E__)

// Arduino Due

#define RD_PORT PIOA /*pin A0 */
#define WR_PORT PIOA /*pin A1 */
#define CD_PORT PIOA /*pin A2 */
#define CS_PORT PIOA /*pin A3 */
#define RD_MASK 0x00010000
#define WR_MASK 0x01000000
#define CD_MASK 0x00800000
#define CS_MASK 0x00400000

#define write8inline(d)                                                        \
  {                                                                            \
    PIO_Set(PIOD, (((d)&0x08) << (7 - 3)));                                    \
    PIO_Clear(PIOD, (((~d) & 0x08) << (7 - 3)));                               \
    PIO_Set(PIOC, (((d)&0x01) << (22 - 0)) | (((d)&0x02) << (21 - 1)) |        \
                      (((d)&0x04) << (29 - 2)) | (((d)&0x10) << (26 - 4)) |    \
                      (((d)&0x40) << (24 - 6)) | (((d)&0x80) << (23 - 7)));    \
    PIO_Clear(PIOC,                                                            \
              (((~d) & 0x01) << (22 - 0)) | (((~d) & 0x02) << (21 - 1)) |      \
                  (((~d) & 0x04) << (29 - 2)) | (((~d) & 0x10) << (26 - 4)) |  \
                  (((~d) & 0x40) << (24 - 6)) | (((~d) & 0x80) << (23 - 7)));  \
    PIO_Set(PIOB, (((d)&0x20) << (27 - 5)));                                   \
    PIO_Clear(PIOB, (((~d) & 0x20) << (27 - 5)));                              \
    WR_STROBE;                                                                 \
  }

#define read8inline(result)                                                    \
  {                                                                            \
                                                                               \
    RD_ACTIVE;                                                                 \
    delayMicroseconds(1);                                                      \
    result = (((PIOC->PIO_PDSR & (1 << 23)) >> (23 - 7)) |                     \
              ((PIOC->PIO_PDSR & (1 << 24)) >> (24 - 6)) |                     \
              ((PIOB->PIO_PDSR & (1 << 27)) >> (27 - 5)) |                     \
              ((PIOC->PIO_PDSR & (1 << 26)) >> (26 - 4)) |                     \
              ((PIOD->PIO_PDSR & (1 << 7)) >> (7 - 3)) |                       \
              ((PIOC->PIO_PDSR & (1 << 29)) >> (29 - 2)) |                     \
              ((PIOC->PIO_PDSR & (1 << 21)) >> (21 - 1)) |                     \
              ((PIOC->PIO_PDSR & (1 << 22)) >> (22 - 0)));                     \
    RD_IDLE;                                                                   \
  }

#define setWriteDirInline()                                                    \
  {                                                                            \
    PIOD->PIO_MDDR |= 0x00000080; /*PIOD->PIO_SODR =  0x00000080;*/            \
    PIOD->PIO_OER |= 0x00000080;                                               \
    PIOD->PIO_PER |= 0x00000080;                                               \
    PIOC->PIO_MDDR |= 0x25E00000; /*PIOC->PIO_SODR =  0x25E00000;*/            \
    PIOC->PIO_OER |= 0x25E00000;                                               \
    PIOC->PIO_PER |= 0x25E00000;                                               \
    PIOB->PIO_MDDR |= 0x08000000; /*PIOB->PIO_SODR =  0x08000000;*/            \
    PIOB->PIO_OER |= 0x08000000;                                               \
    PIOB->PIO_PER |= 0x08000000;                                               \
  }

#define setReadDirInline()                                                     \
  {                                                                            \
    pmc_enable_periph_clk(ID_PIOD);                                            \
    pmc_enable_periph_clk(ID_PIOC);                                            \
    pmc_enable_periph_clk(ID_PIOB);                                            \
    PIOD->PIO_PUDR |= 0x00000080;                                              \
    PIOD->PIO_IFDR |= 0x00000080;                                              \
    PIOD->PIO_ODR |= 0x00000080;                                               \
    PIOD->PIO_PER |= 0x00000080;                                               \
    PIOC->PIO_PUDR |= 0x25E00000;                                              \
    PIOC->PIO_IFDR |= 0x25E00000;                                              \
    PIOC->PIO_ODR |= 0x25E00000;                                               \
    PIOC->PIO_PER |= 0x25E00000;                                               \
    PIOB->PIO_PUDR |= 0x08000000;                                              \
    PIOB->PIO_IFDR |= 0x08000000;                                              \
    PIOB->PIO_ODR |= 0x08000000;                                               \
    PIOB->PIO_PER |= 0x08000000;                                               \
  }

// Control signals are ACTIVE LOW (idle is HIGH)
// Command/Data: LOW = command, HIGH = data
// These are single-instruction operations and always inline
#define RD_ACTIVE RD_PORT->PIO_CODR |= RD_MASK
#define RD_IDLE RD_PORT->PIO_SODR |= RD_MASK
#define WR_ACTIVE WR_PORT->PIO_CODR |= WR_MASK
#define WR_IDLE WR_PORT->PIO_SODR |= WR_MASK
#define CD_COMMAND CD_PORT->PIO_CODR |= CD_MASK
#define CD_DATA CD_PORT->PIO_SODR |= CD_MASK
#define CS_ACTIVE CS_PORT->PIO_CODR |= CS_MASK
#define CS_IDLE CS_PORT->PIO_SODR |= CS_MASK

#else

#error "Board type unsupported / not recognized"

#endif

#if !defined(__SAM3X8E__)
// Stuff common to all Arduino AVR board types:

// When using the TFT breakout board, control pins are configurable.
#define RD_ACTIVE *rdPort &= rdPinUnset
#define RD_IDLE *rdPort |= rdPinSet
#define WR_ACTIVE *wrPort &= wrPinUnset
#define WR_IDLE *wrPort |= wrPinSet
#define CD_COMMAND *cdPort &= cdPinUnset
#define CD_DATA *cdPort |= cdPinSet
#define CS_ACTIVE *csPort &= csPinUnset
#define CS_IDLE *csPort |= csPinSet

#endif

// Data write strobe, ~2 instructions and always inline
#define WR_STROBE                                                              \
{                                                                              \
    WR_ACTIVE;                                                                 \
    WR_IDLE;                                                                   \
}

// These higher-level operations are usually functionalized,
// except on Mega where's there's gobs and gobs of program space.

// Set value of TFT register: 8-bit address, 8-bit value
#define writeRegister8inline(a, d)                                             \
  {                                                                            \
    CD_COMMAND;                                                                \
    write8(a);                                                                 \
    CD_DATA;                                                                   \
    write8(d);                                                                 \
  }

// Set value of TFT register: 16-bit address, 16-bit value
// See notes at top about macro expansion, hence hi & lo temp vars
#define writeRegister16inline(a, d)                                            \
  {                                                                            \
    uint8_t hi, lo;                                                            \
    hi = (a) >> 8;                                                             \
    lo = (a);                                                                  \
    CD_COMMAND;                                                                \
    write8(hi);                                                                \
    write8(lo);                                                                \
    hi = (d) >> 8;                                                             \
    lo = (d);                                                                  \
    CD_DATA;                                                                   \
    write8(hi);                                                                \
    write8(lo);                                                                \
  }

// Set value of 2 TFT registers: Two 8-bit addresses (hi & lo), 16-bit value
#define writeRegisterPairInline(aH, aL, d)                                     \
  {                                                                            \
    uint8_t hi = (d) >> 8, lo = (d);                                           \
    CD_COMMAND;                                                                \
    write8(aH);                                                                \
    CD_DATA;                                                                   \
    write8(hi);                                                                \
    CD_COMMAND;                                                                \
    write8(aL);                                                                \
    CD_DATA;                                                                   \
    write8(lo);                                                                \
  }

#endif /* PIN_MAGIC */


text:
Shared memory space for locally defined buffers?
Within a class I have a method that is using a basic char buffer to print some data, something like
char buffer[64];
sprintf(buffer, "%s: some text: %u, %u, %u %u", string_var, u_var1, u_var2, u_var3, u_var4);
Serial.println(buffer);

All variables are defined locally to that method within the class.
For the moment I have commented out the Serial.println(buffer), as it is part of precompiler debugging section. I know that this buffer is not being printed from this location. The buffer is still being loaded with data but is NOT being printed.
In my main code I have another function using a similar format, but the buffer has a different name.
char json_buffer[256];
Serial.println(json_buffer);

again all defined locally, NOT globally.
Now this serial print line is printing the contents of the first char buffer[64], UNLESS I create it with a null termination from the off, like:
char json_buffer[256] ={"\n"};

Why is this happening? is it a memory leak? buffer overflow? I have tried increasing the size of each buffer, for example the first buffer I have tried with 512 characters size, and the 2nd with 512 also, but no matter what I try the contents of the first buffer are being printed when I print the 2nd one.
Just looking for an explanation and a robust way of preventing this. Thanks!
Full code is at:
https://github.com/practable/refrigeration/tree/dev/fw/refrigerationFirmware
But is a fairly extensive program

Why would you want to print a non-initialized buffer?

Perhaps if you post all of your code, and not just a few snippets.

@EdgarBonet If I sprintf the content I want to be in that buffer, it also prints out the contents of the first buffer infront of the string I actually wanted to be in there, I eliminated that extra step during debugging and found that the unexpected behaviour was still present.

@NickGammon The entire code is 7 pages long, I have posted the excerpt I feel is relevent to this issue. The entire program can be found at https://github.com/practable/refrigeration/tree/dev/fw/refrigerationFirmware
I will edit the question to contain this.

If your code is a bit too long, post instead a Minimal, Reproducible Example showing the problem.

From your linked code this doesn't look valid to me:
sprintf(json_buffer, "%s%s", json_buffer, json_footer);

It looks like you are trying to append json_footer to json_buffer, however the sprintf will start writing to the start of json_buffer, discarding what is already there. I suggest you use strcat instead.
You are doing that a lot, and there is a possibility of a race condition, where, in the process of writing to json_buffer in that invalid way, the sprintf gets out of control and writes much more than it should.

Just as a complement to Nick Gammon's answer: if you want to build the
JSON string using sprintf(), you should keep track of the current
position of the end of the string (the \0 that terminates it): that's
where you should write the next bit, thus that's the pointer you will
provide to sprintf().
Also, you may want to use snprintf() instead, just to make sure you
never overflow your buffer.
Here is an example of building a string by multiple calls to
snprintf(), while keeping track of the current writing position:
char *build_json() {
    static char buffer[620];
    char *end = buffer + sizeof buffer;  // end of buffer
    char *p = buffer;                    // current writing position

    p += snprintf(p, end-p, "{\n");
    p += snprintf(p, end-p, "  \"timestamp\": %d,\n", 1704391201);
    p += snprintf(p, end-p, "  \"valves\": {\n");
    p += snprintf(p, end-p, "    \"V1\": %d,\n", rand() % 2);
    p += snprintf(p, end-p, "    \"V2\": %d\n", rand() % 2);
    p += snprintf(p, end-p, "  },\n");
    p += snprintf(p, end-p, "  \"relays\": {\n");
    p += snprintf(p, end-p, "    \"foo\": %d,\n", rand() % 2);
    p += snprintf(p, end-p, "    \"bar\": %d\n", rand() % 2);
    p += snprintf(p, end-p, "  }\n");
    p += snprintf(p, end-p, "}\n");
    return buffer;
}

Automatic variables live on the stack for the duration of the block in which they were created - probably the whole of each of those functions. They are not automatically initialized, but merely considered to be in use for the durations of execution of each function.
So the likely answer is that buffer and json_buffer overlap, at least to some degree. In that case, since you didn't initialize 'json_buffer', whatever will be printed from it is whatever data was previously left in the memory area it now occupies. We can't see your code, to say definitively, but since this scenario can describe exactly what your are seeing, I'd say it is highly likely the right explanation.

Just looking for an explanation and a robust way of preventing this.

Easy, peasy: Don't use the contents of uninitialized variables; always initialize them before use.

For the not-yet-initiated the terms might be not that clear.

"To initialize" generally means to write a value into a variable by some means.
"To use" generally means to read from the variable.

The programming language here is C++, which roughly works like this:

A non-static (dynamic) variable local to a function or method is not initialized without an explicit initialization or assignment:
/* ... */ {
    int not_initialized;
    int initialized = 23;
    int written_to; // here uninitialized
    written_to = 42; // now "initialized"
}

A static variable without explicit initialization is default-initialized:
static int default_initialized; // = 0; by the standard's specification

This is independent of the scope of the variable. It can live inside any function or method, or outside at unit level.
A global variable without explicit initialization is default-initialized:
// outside any function or method
int default_initialized; // = 0; by the standard's specification

With this in mind, it makes no sense to initialize dynamic variables and to write into them (what some consider as "to use") without an intermediate usage (reading it). Some compilers can even warn about that code smell:
/* ... */ {
    int initialized = 0;
    // other code without access to "initialized"
    initialized = 2024; // second write
                        // Strange, why not initialize it directly?
                        // Or did the programmer forget something in between?
}

If your compiler optimizes well, it might remove the initialization.

I was seeing the same behaviour when I was initialising the json_buffer variable by sprintf'ing some data into it, the unexpected string from the other buffer was being printed out ahead of the new data

@ImogenWren Please edit your question and provide a minimal, complete and reproducible example of the issue. I will not wade through your big source on some external web site. You can start by removing parts that are not relevant, until just about 10 to 20 lines of code are left.

source: Stack Exchange

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

sort: votes


text:
How does the serial monitor know where a string terminates when we use Serial.print instead of Serial.println?
EDIT: I thought I had to parse the things coming into the program but the speed it is running at makes it indistinguishable to the eye that the word is being printed piecewise.
I am trying to create a serial monitor in rust using the serialport crate. I am using the following modification of blink code on the uno to test it:
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
  Serial.begin(9600);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  Serial.print("HIGH");
  delay(700);
  digitalWrite(LED_BUILTIN, LOW);
  Serial.print("LOW");
  delay(700);
}

with println, I am thinking of just concatenating the received buffers and printing on receiving nl or cr. The serial monitor is doing a pretty good job with how it is able to discern a string if a has ended without NL or CR on running the code. How is it doing that? Here is my code right now:
use std::time::Duration;
use serialport;

fn main() {
    let open_port_config = serialport::new("/dev/cu.usbmodem1201", 9600).timeout(Duration::from_secs(10));
    let open_port_result = open_port_config.open();

    let mut port = match open_port_result {
                    Ok(res) => res,
                    Err(_) => panic!("Couldn't open the port")
                };

    println!("Data bits: {}", port.data_bits().unwrap());
    println!("Flow control: {}", port.flow_control().unwrap());
    println!("Parity: {}", port.parity().unwrap());
    println!("Stop bits: {}", port.stop_bits().unwrap());

    loop {
        let mut serial_buf: [u8; 8] = [0; 8];
        port.read(&mut serial_buf[..]).expect("Found No data");
        let output = String::from_utf8(serial_buf.to_vec()).unwrap();
        println!("{:?},{:?}: {}", serial_buf, output.trim_matches('\0'), output);
    }
}

You could experiment with delays shorter than 700 ms, and see at what point the serial monitor starts concatenating messages together.

@EdgarBonet I am not really able to clearly make out if messages are being concatenated as I lower the delay. I think I caught a stutter here and there but it looks as though it is printing the entire word / string at one go.

It is unclear to me, what you mean with discerning strings. The Serial Monitor just reads the byte data from the serial port and outputs it in a textbox. It doesn't know of individual strings, just bytes. What exactly is your problem with your current code?

please copy the content of serial monitor and paste it into your question ... no screenshots

the serial monitor should not be adding characters that are not received ... it is not a parser, so it has no knowledge of human meaning of received data ... the answer to your title question is it does not know

The answer is: It does not know. Or, if you want to look at it in a different way: Timing and chance.
You simply never stumbled upon the case that you read the serial buffer on the PC side in the exact moment when the Arduino is in the middle of writing to it. That special case would be where you read and empty the buffer and output "HI" (followed by newline, because you add it in your code) on your serial monitor; then, during the next loop in your rust code, the remaining characters would be read, outputting "GH".
I'd say that you've been lucky that it always worked so far.
The better way would be to always use println on the Arduinos side; and on the PCs side: the rust function to "read until newline" from a serial connection (I'm guessing it exists because it does exist in other standard libraries; I never worked with rust before). This way, you'll have in-band signalling for "the next data block begins HERE".

If you are building a serial monitor, you are not in control of how it will be used. Some users will fail to systematically add line terminators.

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


text:
uBlox LEA 6H and UNO no data
While using NEO 6M and getting close-to-perfect accuracy, connecting the 3dr uBlox LEA 6H shows incoming characters, but gibberish data (at 38400) like it is connecting to a wrong baud rate (although it isn't, i've checked it with u-center and works when connected to Ardupilot).
So i guess it is some kind of configuration to show only certain parts of NMEA (if it is showing NMEA and not something else).

what accuracy does your ublox lea6h gps have? I want to control quadcopter and need to find 1 GPS module has the high accuracy( may be < 1m)

Your uBlox LEA 6H is most likly configured to use the UBX binary protocol and not NMEA at all. This protocol, as well as how to switch your LEA 6H between NMEA and UBX is in this document, from the uBlox website:
http://www.u-blox.com/images/downloads/Product_Docs/u-blox6_ReceiverDescriptionProtocolSpec_%28GPS.G6-SW-10018%29.pdf
You may be able to use the code from the ArduPilotMega project to communicate in UBX, they use the UBX protocol and the code is open source, but I can't guarantee its very good quality.

Using u-center, i'll try to change the output sentences. This pdf is extremely helpful!

You can configure the ublox lea6H GPS to read either through NMEA protocol or the UBX protocol. You just need to send some configuration messages. For good data rate it is better to use UBX protocol as it gives data in binary format inducing less delay.In case you need to test your device you can use my GPS code for arduino mega - customized ardupilot gps code  - UBX protocol.
https://github.com/ksskarthik/Team_Pushpak/blob/master/TP_GPS

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


text:
Attaching an Si4703 to an Arduino
SparkFun sells an FM Tuner Board (here) and provides code to work it.  However, neither libraries that I found in other places, nor the example code that they provided, worked.  I have checked the wiring multiple times and I am nearly certain that the fault is in the code but I can't find it.  Thanks...
ECC

Could you provide more details about what you've done so far: wiring, code used? And then describe precisely what you observe. Just saying "it does not work" cannot be considered a good description of a problem!

In the provided example code it says to wire the Si4703 to the Arduino like so:                             3.3V : VCC
GND : GND
A5 : SCLK
A4 : SDIO
D2 : RST  I did this and I tried using the Arduino Library provided (here) and the example code provided.  When I upload the example code, it says "Initializing I2C and Si4703" and then does nothing more... When I use the library's example code (here),  it fails to start the "void loop()" (discovered by some debugging).

It stops at the "radio.powerOn"  Thanks (Sorry for going over)

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


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

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

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

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

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

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

client.stop();
}

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

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


text:
Unable to power an Arduino Pro Mini through the RAW pin
I've recently bought an Arduino Pro Mini, the 3.3V and 8MHz version. The first time I powered it, using the VCC pin, all worked. But, as soon as I attempt using the RAW pin instead, nothing lights up... Is my regulator broken ? Or is this a typical issue ?

What is the power source you are attempting to connect to the RAW pin?

@Majenko It's an unregulated 5V source

Check there is solder on the solder jumper SJ1

I am not completely familiar with that specific board, but according to the schematic there is a solder jumper which is used to isolate the RAW voltage regulator from the rest of the system "for low power applications".

I don't know off hand if that comes pre-soldered or not, but check it to make sure it is connected, otherwise the RAW input will do nothing.


text:
Clone pro micro serial port 'COM4' already in use
So I just got this board I ordered from ebay and tried to play with it for the first time. http://www.ebay.com/itm/Leonardo-Pro-Micro-ATmega32U4-Arduino-IDE-1-0-3-Bootloader-replace-Pro-Mini-/310634777706?pt=LH_DefaultDomain_0&hash=item4853468c6a
I connected it to my PC and it was installing a driver. I didn't pay much attention to it but I think it finished installing it successfully. I then installed arduino IDE 1.6.3(latest) and tried to compile and upload the empty default sketch just to see if it uploads it. the progress bar got to the end but it was stuck on "uploading..". I waited for a few minutes but it didn't seem like it is going to end so I unplugged the USB and re inserted it back. I then looked in the tools menu and saw it was set to port COM1 which is the communications port on my pc, so I changed it to port COM4(Arduino Leonardo) and the board to Leonardo and again tried to compile and upload the default sketch but now I got this error:
Arduino: 1.6.3 (Windows 7), Board: "Arduino Leonardo"
Error opening serial port 'COM4'. (Port not found)
trying to open the serial monitor gives the same error.
So I checked the item listing on ebay and it said that the board was supported under arduino IDE 1.0.3 so I downloaded it and tried to compile and upload the default sketch but it gave me the serial port 'COM4' already in use error.
I tried resetting the board, uninstalling and reinstalling the driver and the IDEs and disabling/re-enabling the device in the device manager. nothing helped.
I am not sure what I am doing wrong as I am new to this.
Thank you.

Reboot you PC, see if that clears it.
If not then fire up Device Manager and have a look at what COM ports you are using.
I think there is a way of reassigning the ports used by the boards within the control panel, but I can't remember what it is at the moment, so have a quick google.
Its not the fact that its a Clone that's causing you an issue, its Windows drivers that have caused you issues.  If all else fails, uninstall the drivers, reboot twice and try again.  I also don't think using a newer version of the IDE will have a negative affect.

I had already solved that issue months ago though I forgot to comeback and add an answer... I don't remember what I did exactly but it worked since then. I think I just played around with the USB ports trying to connect it in different ones until I got it to work but I am not 100% sure.


text:
How to control 220V RGB Led Strip with Arduino/ESP32
I need to control 220V RGB Led strip with Arduino/ESP32-wroom over internet.
Single color led is easy (just with a relay), 12V RGB can be done with PWM and maybe external power source. But how can I control 220V RGB via MCU?
I couldn't find any answer yet.

there is no such thing as 220 V AC LED (yet). it is a 12 V LED and an AC/DC power supply. what controls does it have?

In Australia, we have LED light bulbs that screw into the 240V light socket. Sure there is circuitry in the bulb to convert the incoming power to suitable ranges for the LED's to operate, but the light bulb is LED based and does require 240V AC. I'm surprised these are not available elsewhere. https://www.beaconlighting.com.au/lighting/globes-bulbs-lights/led-globes-lights

@GMc, yes the LED bulb has AC/DC adapter insight. a dimmable version senses the AC voltage and dims the DC side with PWM. a not dimmable version would not dim with triac. and a RGB version needs some additional controls, usually wireless

Try looking at a relay or a triac.
Also, you can not simply "use PWM to control a 12V circuit from your MCU" which is most likely running at 5V. You need to use a component such as a MOSFET. The MCU controls the MOSFET via the Gate. The MOSFET switches the 12 V circuit off or on based upon the signal at the gate.
Alternatively, like the AC solution, you can use a Relay to control the 12V circuit.

@alper, WARNING! DANGER! this accepted answer is wrong and can destroy your equipment and harm you! Controlling a switching power supply of the AC/DC adapter for the LED strip will destroy the triac and/or the AC/DC adapter.

@juraj, can you elaborate?  From https://www.electronics-tutorials.ws/power/triac.html (and other similar sites) "This makes the triac ideal to control a lamp or AC motor load with a very basic triac switching circuit". Here is a shield designed to do it  https://www.circuitar.com/nanoshields/modules/triac/. And yes, I absolutely agree the voltages the OP is asking about are dangerous and if there is any uncertainty he/she shouldn't go anywhere near it.

@Alper, there are some excellent safety warnings on the site https://www.circuitar.com/nanoshields/modules/triac/ Juraj is 100% correct about the dangers of playing with mains voltages. I encourage you in the strongest possible terms to read the safety information

a switching power supply turns the AC line on and off fast. capacitor does the smoothing of the output. triac dimmer turns the AC line on and off fast too. imagine the resulting effect.

https://www.digikey.com/en/articles/techzone/2011/jul/dimming-leds-with-traditional-triac-dimmers

That is good advice, thanks for including it. I wonder if OP wants to dim or just switch off and on. The OP was pretty vague in general, but the "question" has served to generate some useful contributions (IMHO). Although I would still question as to whether my answer is "wrong" as the digikey article explains how Triacs can be correctly used to Dim an LED.


text:
Programming 5 inch TFT Display + Arduino Mega with Touch Shield (w/SSD1963)
I am newbie on Arduino and TFT Screens. But I am a semi-professional on programming and I decided to develop a device that can be controlled by Arduino via capacitive touch screen (there will be 2 buttons on the screen and while one of them will increase the current of a device, other will decrease). To do that, I've bought a complete solution (Arduino Mega + 5" TFT LCD + Arduino Shiled but without Resistive touch screen - this one), instead of resistive touch screen, I've bought this one and I've bought a separate PSU.
At the end, I have an Arduino Mega, 5 inch TFT Display, 5 inch Multi Touch Screen Panel with Controller GSL1680F (assembled to the Display) and Arduino Shield which is produced for this system. But I don't know how to communicate these three devices with each other. I know that, Arduino has built-in storage for the codes, and both TFT Display and Shield have micro-sd storage slots for placing codes. E.g. I don't know what is the aim of micro-sd storage slot on the shield.
As a result, is there any code samples / tutorials / video that I can follow to develop with this system? Thanks.

BuyDisplay have a full archive of libraries and samples for the TFT screen on the page you link to.

Hi @Majenko , Thanks for your reply. Can I use same codes on the product page for capacitive screens? Because, it is written as "8080 16-bit 5"Resistive Touch Shieid+SD Card" or can I use touch screen codes directly?)In addition what is the aim of SD Card Slot on the shield?
Because, all examples that I downloaded from product page are about Resistive Screens.

There is example code for the touch on the touch sensor page. You will need to adapt it for Arduino, or ask Google for a library. The SD card is for you to store data on, such as images to display, or sensor data that you want to record. It is the same as an SD shield.


text:
Reusing LED from RC helicopter controller
I have an old RC helicopter controller, but not the helicopter.  I recently purchased an Arduino Uno and would like to do something with LEDs(beside the on-board one built-in). Can I use an LED from the controller, that is already soldered in, cut it free and plug into my breadboard.
Side Note
I have no experience in soldering and don't own a soldering iron.

Yes, you can. For convenience, cut a bit shorter the lead on the side of the package where the flat part is so that you can identify the leads easier.

Ignacio's drawing shows you how to connect a LED. If you don't have any soldering tools you can use a solderless breadboard. This small one from Adafruit is ideal for small circuits:

(They exist in all sizes from very small to very large). The holes in each 5-hole row are all internally connected.
The problem with cutting the LED from the board may be that the remaining wire length is too short to fit in the breadboard. (You'll need at least something like 6 mm.) LEDs are a nice way to start with electronics, since you need minimal part count to make something visible. If you can't cannibalize the LED from the controller, just buy one from your local electronics shop. They're dirt cheap.

Yes you can. Make sure you have a resistor in series with your led. It is much, much better to guess and use the wrong resistor, than not to put a resistor in at all. I use http://led.linear1.org/1led.wiz to calculate my resistor. Your source voltage will be 5v. Each thing you have to fill has help on what value you're likely to want to put here.
It doesn't matter which side of the led you put the resistor.
If you can cut the led out, it should be fine, so long as you have long enough legs to go into the breadboard.


text:
Detect closed shutter
I want to controll some ambient lights in my living room.
Therefore, I got some 433mhz outlets which can be turned on or off with an remote, a 433mhz transmitter and receiver on the arduino.
The arduino receives the remotes signals and knows which lamp has which state and will turn any lamp off at specific times.
Now I want to turn on the lights automatically when I close the shutter, but I have no idea how I could do this.
A light sensor behind the window won't do the job. I don't want to turn on the lights when it get's dark, but when the shuhtter get's closed.
Edit:
What came to my mind first was an light sensor inside the window, facing outside, and a IR LED. I'd attach some tinfoil to the inside of the shutter to return the IR light, which the sensor will notice. But maybe the're are some simpler solutions? Also, the tinfoil would fall off quickly...

Is there some cord or something you could attach a magnet to, which you could detect, being in the closed position?

Not without getting ugly =(

What is this mythical shutter? How does it operate? What is it made of? Does it slide like a blind, or close like a door? Roll? Solid? Made of pressed geranium leaves? Please, we need some actual information.

It's a roller shutter. It rolls up in a box inside the wall, above the window. Aside the window there is a cord which i pull to let the shutter down.

I'd use a magnet in place of the tinfoil and a (latching) hall-effect-sensor/reed-switch instead of the photo-reflector you were planning to use.

Nice idea. I could simply drill a little hole in the lowest shutter-bar and glue in an magnet. Simple. But these sensors are surprisingly expensive, what are they made of, pure gold? I mean, IR sensors cost about 10-20% of that price o.O

Maybe you're looking for the wrong things.  Think household security - reed switch / magnet pairs for doors. Very cheap.

To avoid doing anything to the shutter itself you could use an ultrasonic sensor. These also have a benefit of working over a longer range than door/window magnet-and-reed-switch setups, thus the shutter doesn't need to close all the way to activate the lights. You can set the threshold in code.

I have a cat which walks on the windows sill now and then. Ultrasonic is usually a good idea, but doesn't fit the situation.

I would go for a normally open read switch (should cost >$0.1) and a magnet on the shutter (again should cost >$0.1).  There are formulas to work out the distance that the reed switch will operate at, and it depends on the magnet, but the common ones are about 40mm.
(If you can wait 2 weeks for delivery you can get the parts off AliExpress.com)


text:
Can I close an input?
I wan't to build a diversity controller similar to this one.

A diversity controller is basically a circuit which detects the strongest RSSI Signal of multiple receivers and provides the data signal of that (the strongest) receiver.

As a receiver I use boscam RX5808 receivers.
This receiver can be switchen between 8 channals through a 3 bit output interface. The CH1-3 outputs are active high 5V which got to be pulled to ground.
Is it possible to put these receiver-outputs on an arduino digital inputs, to either put them on ground or not?
How exactly do I implement this in software?

According to the document you linked to, the channel select pins look like internally pulled-up inputs, not outputs.

When you output HIGH you connect the pin to +5V. When you output LOW you connect the pin to ground.  It's called a push-pull interface, and looks like this:

When it's set HIGH the p-FET is turned on and the n-FET is turned off. That connects the output direct to VDD. When it's set LOW the p-FET is turned off and the n-FET is turned off. That connects the output direct to GND.
They are just like switches, as depicted to the right. Only one is closed at a time - when HIGH the upper switch is closed, when LOW the lower switch is closed.
So you just connect the output pins of the Arduino direct to the input pins of your device and write either HIGH or LOW to them to set the 5V or GND connections you need.

So basically, If i set the arduino I/O on HIGH, it's +5v vs +5v which get's 0v, and if I set the I/O to LOW it's +5v vs GND which get's +5V, right?

.... pardon .... ?


text:
What would be the architecturally-right place to put custom -D defines?
What I am trying to accomplish is to include information about the state of my environment at build time in my code. For example, I may want the setup() code to print the git sha it was built against, and the time of build.
There are two related issues here:

How to include that information in the code
How to specify to the build environment what to generate in the first place.

The first can be addressed in a number of ways:

-D options can be generated at build time, and the corresponding defined macros expanded in the code. For example, the compiler could be invoked as g++ -DGIT_SHA=$(git rev-parse HEAD) -DDATE=$(date '+%Y%m%d-%H:%M:%S'), and my code could have something like #define strfy(_x) #_x followed by Serial.println(strfy(GIT_SHA));. Or the build tool could generate a header file that would define these as external string variables, which the main sketch could then include and print. Or any other number of tricks.

The question I am really asking is: how should I specify this sort of stuff for arduino-builder?
Ideally, it would be a custom recipe in platform.txt, but if there is a way to invoke shell commands in recipes and use the results to modify other variables (such as preproc.macro.flags), I haven't been able to find it (if there is documentation, it's really well hidden). Ideally I would want to be able to say preproc.macros.flags=-w -x c++ -E -CC -DGIT_SHA=$(git rev-parse HEAD) and have the shell command be executed at the point.
So, before I set out to hack arduino-builder, do people have any opinion on this? My main criterion is something that would be of general value and has a chance of being incorporated in the code, rather than a kludge that only works for me and which I have to patch every time I upgrade. Please do not suggest workarounds. I can think of several myself!
I did try to search, and this sort of issue has come up before, but I didn't see any satisfactory answers from people who knew what they were talking about.
Thanks!
/ji

That is a tough one...  Because arduino-builder is basically a custom go script you don't get the facilities you get in a Makefile, like shell execution.
I would be inclined to do this kind of thing outside that environment - use some external program or tool to generate a config.h file (maybe use something like GNU Autotools) that contains your custom defines. That can then be #included in your sketch.

For the date and time of compilation there are predefined preprocessor symbols: __DATE__ and __TIME__.

Unfortunately these are at compile time and not at link time.

Seems appropriate; the OP used compiler command-string examples.

I'm not stating it is inappropriate. I'm adding that this solution has a drawback.
From experience I learned that a IDE that only builds changed files (like the newest versions of the arduino IDE) will end up with outdated dates and time on the Arduino.


text:
Arduino Micro disappears on osX 10.11.6
so I have an arduino micro, and it was working fine until the latest security update for OSX 10.11.6 now the port won't show up in the arduino IDE. This doesn't seem to be a problem with the Uno / Huzzah / Mega or Makey Makey, but the port shows up when the micro is booting up, then disappears when the boot is done.
Anyone else having this issue? I've googled and found something about signed ktels. I've also installed some extra FTDI drivers, but no dice. Cord is fine, and works w/ other devices.
Suggestions?
Thanks!

Found it. It was a weird timing thing, and I had to hit reset as the sketch was uploading. Seems to be fine now.


text:
Arduino hangs after 3-4 minutes on battery power, but not on USB
I have a simple sketch running on a BE Leonardo-compatible board.
It reads input from a potentiometer, and outputs to two RGB LEDs which change colour over time - in a different pattern if certain inputs are received.
Other than that, the only code is serial I/O for debug purposes.  (It's disabled using a #define in the running version, to prevent serial buffer overflow when not connected.)
When the board is powered by USB, everything works.
When the board is powered by 9V battery, after about 4 minutes it hangs - the LEDs go off, and the L13 light on the board starts glowing at varying strength.  (There is nothing connected to pin 13.)  Even the reset button doesn't work.
If the board is then connected to the computer's USB port, after a few seconds the hang clears and the program resumes.
Can anyone offer a possible explanation for (and solution to) this fault?

If I could I'd offer a bounty, because I need this thing running as a prop tomorrow night.  Since I can't, I offer my heartfelt thanks to anyone who can help. ;)

Try using a AA battery pack instead of a 9V. Or parallel 2 9V batteries together (not in series!). 9V batteries can't provide that much current. So your project is probably drawing near it's limit. Then after a few minutes the batteries voltage drops too low for the arduino, which resets. This continues starting, resetting will explain the board led flickering.

@Gerben: Ah.  That will be it.  The draw should only be about 120ma (2 RGB LEDs), but perhaps the battery isn't fully charged.  (For comparison, the same battery has run a project involving 2 2.5in 7-segment LEDs and a medium size servo for several hours... so I simply hadn't thought of it drawing low from 2 LEDs, even RGB ones.)
(Heads off to try to figure out where he can fit in more batteries withot making a noticeable problem...)

Could yo post the simple sketch so that we can check it cannot be the source of your problem?

As somebody else suggested, 9V batteries are pretty weak. They only provide a very small number of mAh (milliamp/hours) before their voltage starts to drop. Once the voltage drops to around 7 volts, the regulator in the Arduino can't keep providing 5 volts, so your Arduino resets.
Wire up 6 AA batteries in series. That will provide a much "stiffer" 9 volt supply (more instantaneous current) plus a lot more mAh of total power. If you REALLY want long life, wire up 6 C or D batteries in series, or an external 9V supply through a "wall wart" power supply.

Yep, this was it.  (Unfortunately there was a reason for the 9V battery, and it was battery pack space, so the obvious solutions are not an option... but I can manage 2x9V parallel, and recode for power saving.)

Instead of the second 9v, use a more efficient switching regulator.  Also consider if you can make your application work at a slower clock speed and reduced voltage, or sleep your processor when it is not doing useful work.


text:
Arduino vs Old Computers
How does an arduino microprocessor compare to some of the older computers in RAM, and computational speed? Like how does it compare to the Intel 400 or the original IBM PC. I'm interested in both the Atmega328 and the 2560. Just how much better/worse is the arduino compared to an old computer?

Compared to an 8088 IBM PC, faster CPU clock, 2-3 orders of magnitude less RAM, and half the ALU width.  Ultimately, you have to make such comparisons in terms of applications (especially, speed to accomplish what?) and they are targeted at quite different roles.

Comparing an MCU with a CPU seems like comparing apples and oranges... Comparing an Arduino to a computer is also plain wrong as it is NOT a computer.

Of course it is a computer!  It is just not one with much of a human interface.

@jfpoilpret According to the Merriam-Webster dictionary, a computer is "an electronic machine that can store and work with large amounts of information." An Arduino would fit this definition. You need to be more specific.

Please be more precise in terms of what features you want to compare. Think of RAM, memory architecture (Harvard vs. v. Neumann), instruction pipelines, caches etc. There literally are as many differences as transistors inside the CPUs, an exhausting answer is impossible and any other try won't meet what you want to read.

Similar capability in turns of processing power if you compare back 10 -20 years.
arduino is a micrcontroller not a microprocessor.
A good example is the pdp11 minicomputer and the ti msp430 micro controllers. They share the same instruction set (approx 90%) . Both can (or could) do realtime event handling but pdp11 was more for data processing. Though pdp11 didn't have integrated peripherals
see bottom of this page http://www.cpushack.com/CPU/cpu4.html

Good answer. However I thought that the Arduino(s) ran on an 8 bit design at the bottom of the article it said 16 bit registers on the MSP which would mean that they wouldn't be in the same class. I paged through the PDP manual once and didn't see anything about realtime event handling. Could you link to the source?

20 years ago - 1995 - was 32 bit pentiums at 100 Mhz with megabytes of RAM.  Try 30-35 years.

Yeah, I would say Arduino is on par with a VIC-20 except without the video output. That's going back 35 years to 1980. The Arduino clock speeds are 8-16X faster though.

@HSchmale arduino is an atmel mega 328 (assuming uno) as you most likely know http://www.atmel.com/devices/atmega328.aspx. For an older discussion on msp430 vs pdp11 see http://www.embeddedrelated.com/groups/msp430/show/20183.php  and a good comparison here http://web.archive.org/web/20070609012513/http://users.easystreet.com/jkirwan/new/msp430.html

pdp manuals here http://research.microsoft.com/en-us/um/people/gbell/Digital/DECMuseum.htm

@HSchmale msp430 isn't that different. larger but less registers (depending on which version and which chip) 16x 16 bit registers. Both are single cycle for most ops and are around the same processing power. The msp430's are a bit more powerful especially when using 16 bit . 16 bit comes in very handy when working with adc's and conversions. In my experience avr's (with gcc and aver studio)are a bit easier to work with. –  lxx 4 hours ago


text:
SFML Packet and Arduino
Can the sf::Packet class of SFML-network be ported over to arduino for use with the Ethernet library or would it be too big? I'm working on a client-program where an arduino is a server and a regular computer is the client making a request. I'm using the SFML-network library to make networking easier on myself and would prefer to use the built in features of SFML to make networking easier. If it is not feasible would I be better off using fixed width data to communicate with the arduino

Without knowing how it all works, my guess is that you would have to port the whole of SFML, which would be HUGE.  So, "No!" is the answer.
You could, of course, write a library of your own that had an SFML-like interface, but the Arduino networking libraries are already pretty simplistic and easy to use, so what's the point?

I'm sending complex packets that must be deconstructed in a specific way. So I would prefer to have a way to send and receive data in such a way that it will always be the same.

That's what structs are for.


text:
Port register not working
I am trying to read my ultrasonic sensor. It sends a pulse in the trigger pin and the echo pin receives the pulse. Using pulseIn I can know exactly the time it took to the pulse go and back. But I need to use port register which is much faster and I need it to be fast in this specific case.
My code is very simple:
void setup() {

    Serial.begin(9600);
    //pin 12 as output
    DDRB = B00010000;
    //pin 12 as low
    PORTB = B00000000;

}

void loop() {

    //pin 12 as high
    PORTB = B00010000;
    delayMicroseconds(10);
    //pin 12 as low
    PORTB = B00000000;

    long start_time = micros();

    //While reading high in pin 13 keep running the loop
    while (PINB & B00100000)) {

    }

    Serial.println(micros() - start_time);

    delay(1000);

}

The problem is that it does not work, I mean, the while loop is not being processed so the serial is always printing a very small number. It doesnt matter if I move the ultrasonic sensor to distant walls the while loop still does not work. What am I doing wrong?

How have you wired it up?

VCC to 5V, GND to GND, trigger to 12 and echo to 13.

And does echo follow the behavior described in your code (normally high, pulls low on receive)? Where is the datasheet for the sensor?

It's the HC-SR04 ultrasonic sensor. With pulseIn it works perfectly, but using PINB it does not.

According to anything I could find, the Echo output is normally low and then goes high for a duration equal to the range. Your initial while condition is inverted, and you need to check for both edges.
unsigned long up, down;

// trigger pulse
while (!(PINB & _BV(PB5)))
  ; // wait for leading edge
up = millis();
while (PINB & _BV(PB5))
  ; // wait for trailing edge
down = millis();
Serial.println(down - up);

Thank you so much for helping but there is a problem: in your code you putted PIND, but it should be PINB right? Another thing: when I try to copile your code I get error saying that PB5 was not declared. I changed it to only 5 ok? But it still does not work. Could you please check what am I doing wrong? I edited your question to add my code cause I couldnt add it here in the coments ok? Sorry for that.

Use PINB5 instead.

still having problem. Look: when my sensor is doing nothing it registers LOW. When an ultrasonic pulse arrives it registers HIGH right? So why do I need 2 whiles? Couldnt I just start a timer when the trigger sends a pulse and stop the timer when sensor reads HIGH? I tried "while sensor is not high keep looping" but it does not work. What am I doing wrong? The HIGH/LOW logic of mine is wrong?

The duration the Echo signal is held high is proportional to the distance detected.

So you are saying that this image is wrong?  http://forum.arduino.cc/index.php?action=dlattach;topic=283286.0;attach=104940;image


text:
Infrared sensor has a frequency to activate it?
I am trying to understand 2 sensors that I have here. One says that is "infrared sensor of 38kHz" and the other is "infrared optical reflexive sensor -> http://www.robosoftsystems.co.in/wikidocs/index.php?title=TCRT_5000_Reflective_Optical_Sensor"
I thought that infrared sensor would tell me if an infrared light is passing on it. Infrared light has a wavelenght, right? Can infrared light be emited in different frequencies? Or the frequency of infrared light is the same to all infrared lights?

The 38kHz sensor (such as the Vishay series e.g TSOP1838) are designed for use with IR remotes and IR barrier type applications. They are designed to work with IR emitters that oscillate the IR at 38Khz and additionally modulate that frequency with lower frequency pulses. The sensor (receiver) is designed to have high gain at 38Khz and demodulates the signal. The demodulated output signal pulses can be directly decoded by a microprocessor. The main benefit is reliable functioning even in disturbed ambient light thus protecting against uncontrolled output pulses.

thank you so much! But the infrared optical reflxive sensor? Does it also read 38k or any infrared light with any frequency?

The TCRT5000 will detect just regular IR light. The output is also analog, so between 0v and 5v depending on how much IR light is reflected. These light sensors will however also pickup sunlight etc.

You are amazing, you helped a lot :)

38Khz is not the frequency of the IR light but the frequency it is pulsed on and off at, the receiver is designed to accept that frequency and reject others so as to avoid interference from sunlight etc. I see you have asked the question again in a slightly different way and received a similar answer.
Infrared led and sensor: how it work


text:
Infrared led and sensor: how it work
I am having a difficult time to understand how an infrared sensor and led work. I have an infrared LED (like the ones you buy anywhere), does it mean that the infrared LED has the frequency os 38khz?
I know that infrared light has a wavelegnth, but does it also have a frequency?

Frequency and wavelength are the same thing. This isn't an Arduino question, it's an incredibly basic Physics question. Answered here: http://en.wikipedia.org/wiki/Frequency#Frequency_of_waves    (frequency x wavelength = velocity)

it's arduino question cause I am using an infrared sensor in arduino with 38kHz. If the speed is different then the wavelenght can have different frequency. JRobert cleared this to me.

No, it's really not. You're asking about the wavelength and frequency of the LED itself, which is not 38kHz. Infrared frequencies are in the 300GHz to 430THz range. That's the frequency of the light itself. The frequency of the electrical signal you send to the LED to light it at various brightness levels has nothing to do with that. The LED doesn't have a frequency other than the frequency of the light it produces. You're getting that confused with the frequency of the POWER SUPPLY to that LED.

An infrared LED just emits its light (primarily) in the infrared range as described by this Wikipedia article. Any emitted radiated signal (including sound) has both a frequency and a wavelength. The frequency = the velocity of the signal through space divided by its wavelength (F = V / W), or vice-versa: (W = V / F). The natural frequency of light, infrared or visible is far, far higher than 38 KHz; around 4 x 10^14 Hz.
38 KHz is simply a convenient chopping frequency for switching the LED on and off so the sensor can distinguish between infrared in sunlight, for instance, which is relatively constant - from that emitted by the LED. Your circuitry would have to create the 38KHz chopping signal.

Awesome! :) So you mean that the speed of infrared, x ray and visible light is the same? The speed in which the wave travles is the same?

YES! Light waves/particles travel at the speed of light, which is a constant of the universe and is the same everywhere. Please educate yourself about "Electromagnetic Spectrum" here: http://en.wikipedia.org/wiki/Electromagnetic_spectrum

@Samul: Yes, with the exception that I also referred to the speed of sound. The velocity of sound in air is much, much slower but the principle will be the same.

You helped me a lot!


text:
Cheap medium range wireless communication with a linux PC
I have a project that's currently using Arduino Uno with a cheap class-2 bluetooth serial adapter from ebay to send and receive data and control a LED light strip.
However, it struggles to establish connection at distances more than couple meters. I'd like to expand that range a bit - 15 meters with two load-bearing walls in the way. Bandwidth requirements are next to none - it should just move couple integers around.
Any suggestions how to do that on the cheap? From what I've seen, class-1 bluetooth adapters go for ~60$, two xbee modules + usb adapter end up costing even more, and wifi solutions seem to reside in the same price range. At that price point, it seems better to get a raspberry pi, wifi dongle and a couple beers for the software re-write. Am I overlooking some solution?

Since one end is a PC I would look into a Wifi shield for the arduino. That way you would not need any extra hardware on the PC side.
You can get a Wifi shield for less than 2 xbee modules. But using wifi will require changes to your code since it won't be using the serial port for communication.
Another wireless option that I have no personal experience with is NRF2401 modules -- you can get them dirt cheap on ebay (caveat emptor) but they use an SPI interface so you can't directly interface with them directly on the PC side.
Be aware that depending on the LED strip you may not be able to drive it directly from a raspberry pi.  For example WS2811 driven LEDs (AKA adafruit NeoPixels) need precise timing that you can't get (or is tricky to get) with the raspberry pi.

I'd suggest the NRF24L01 too. Though you'd need to attach something like an arduino to the PC, to receive the serial commands over usb, and send it to the RF24 module.

"Smart home automation webserver on OpenWRT router WR703N interfaced to Arduino, compared to Raspberry Pi and Ubuntu" may lead you to some answers...
Just think of that solution as a kind of "homegrown Arduino YÙN"... just older and cheaper: "Nah, you don’t need an Ethernet module for your Arduino"


text:
Questions on programming logic?
So I am learning arduino code by going through examples and playing with them, and I came across something interesting. I am not fluent in any coding language but I am fully familiarized with computer logic and function so I can read what you suggest just fine.
What I want to know is, why are these two code pieces different?
const int ledPin =  13;

int ledState = LOW;

long interval = 1000;

void setup() {

pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis > interval) {

    currentMillis = 0;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }
}

This is my code, or rather modification to this code:
const int ledPin =  13;

int ledState = LOW;
long previousMillis = 0;

long interval = 1000;

void setup() {

  pinMode(ledPin, OUTPUT);
}

void loop()
{

  unsigned long currentMillis = millis();

  if(currentMillis - previousMillis > interval) {

    previousMillis = currentMillis;

    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;

    digitalWrite(ledPin, ledState);
  }

}

How is it that the first code works, and the second code turns the led on and either terminates or never turns the LED off? The code is designed to blink the LED once every 1 second.

Ah yes, this problem.
Note the declaration of currentMillis:
unsigned long currentMillis = ...;

And now note the declaration of previousMillis:
long previousMillis = ...;

You wouldn't think that one little word could make that much difference, but it does. It completely changes how C performs mathematics. previousMillis must also be unsigned or you will get undesired results.

How so? That is what confuses me. I /can/ fix it in this scenario, but should this happen with my own code I would be stumped.

Answer this question: What is the value of a negative number when stored in an unsigned variable?

Unsigned is essentially absolute value, no? So, positive.

It is not the absolute value. You need to be more precise than "positive" to understand.

Then what is it?

http://stackoverflow.com/questions/2084949/arithmetic-operations-on-unsigned-and-signed-integers

Okay. That makes some sense. So, to fix it, I should..? I'm thinking make them both regular ints? Sorry, I may know what's up with programming but I'm not really a genius.

What is the return type of millis()?

I'm not sure. And I can't test right this minute. Should I set the unsigned/signed based on the millis() return type?

Yes, you should. That will ensure that your results make the most sense. Also, this


text:
How much current and voltage has my resistor + LED
I have a very simple circuit: 5v -> LED (5mm, forward voltage of 2 V and max. current of 20mA) -> 1k ohm resistor -> GND.
I want to know how much current is flowing in my circuit. I am using this formula:
U = R x I
Since U = 5, and R = 1000 the current is (according to the formula): 5/1000 = 0.005A.
So far so good. The problem is when I try to check the voltage drop over the resistor and the LED. For calculating the voltage drop in the resistor I would use the same formula where I is my current (0.005A) and R is the resistor 1k ohm. The result is: 5 V.
Something very weird is happening here cause the voltage drop around my resistor should not be 5 V cause I know there must be another voltage drop around the LED. If 5V is in the resistor it would mean that 0v is around the LED (and it should not light up but it does).
Thank you helping me with this basic calculus.

The problem is that if you're trying to measure the current directly, you're going to get the wrong answer. Whether it's due to burden voltage or the (in)accuracy of the meter, it's a hopeless situation. The 0.005A your meter is showing is actually closer to 3mA in reality, but your meter can't distinguish between the two well enough.
If you need to measure current this small then the only way to do so accurately is to use a very low-value shunt resistor and an amplifier. This is the method the µCurrent uses, and it's essentially the defacto gold standard for measuring current in small circuits.

thank you ignacio. But my question is moer about this: if I use a higher or lower resistor, will always my LED drag 2 V? I thoght that if I used a different value of resistor I would be changing the current and voltage drop across the LED. Isnt that true?

It is. But unless you change the current to either almost nothing or to too high for the LED to handle, you may not be able to measure the change; a diode's ohmic region is very steep.

Leds have a voltage-current curve. If less current is going through the led, the voltage drop will decrease somewhat. Lower voltage drop means higher voltage across the resistor, leading to slightly higher current. So the resistor and led are (kind of) working together to limit the current. So e.g. doubling the voltage doesn't mean twice the current, but less than twice.

Thank you :) So just to be clear: if I use any resistor value my LED will always drag 2V, no more no less than that? I am asking this to you cause I measured the voltage across my resistor and it was supposed to be 3 V (5 V is the source power and 2 V should be used in the LED) but it's 1 V. What is going on?

@Samul: Approximately 2V, until the current is low enough that the LED enters its flat region.

Gerben thank you! But you left me with more question: if I have a ciruit with a resistor in series with a LED of 2V forward voltage. If I use a resistor with X ohm, and them I change the resistor do 10X ohm, will the voltage across the resistor be the same and the voltage across the LED be also the same (2v)?


text:
How this smal infrared work
I have a code that sends 384 pulses at 38kHz with an infrared LED. It's very easy to understand it. At the beggining the code sends the pulses using the LED and in the middle of the code I check the sensor if it has any signal coming. So far so good, yes? Please, take a look:
for(int i=0;i<384;i++) {
  digitalWrite(IRledPin,HIGH);
  delayMicroseconds(13);
  digitalWrite(IRledPin,LOW);
  delayMicroseconds(13);
}

if (digitalRead(IRsensorPin) == LOW){
  digitalWrite(D13ledPin,HIGH);
} else {
  digitalWrite(D13ledPin,LOW);
}

My question is this: I first send the pulses, so when I reach the line if (digitalRead(IRsensorPin) == LOW){ the pulse should already have passed the sensor. So why does it work? It should not work cause I first send the pulse and then I check for the pulse but as I understand the 384 pulses should already have passed the sensor.
I have no idea why this code works. I would be glad to listen smarter people to help me understand this.
Thank you.

What does the hardware look like?

The IR receiver does some filtering on the signal. It doesn't signal a LOW immediately if it lost a single pulse of light. A speck of dust, hanging in the air, might just be blocking the IR phototransitor. Or some brief flash of light, making two pulses seem like one or more.
These IR receivers a specifically build to filter out the 'noise' coming from other light sources and light obstructions.
Identically, you would want this receiver to give you a HIGH if it detect only 2 pulses of light 13uS apart. I could just be some sunlight reflected from a puddle, accidentally matching 38kHz.

Just a final question: if I send pulses of 38kHz for 10 seconds (in the for loop) and I try to read those pulses in the next line, how many pulses I will be able to read? Just the 5 last ones? 100 last pulses? What I dont understand is this: if I send all the pulses in the for loop, when the compiler reaches the digitalRead the pulses should already be gone and nothing should be registered as HIGH. What am I misunderstanding?

The ir receiver doesn't return a HIGH if it detects IR light. It only returns HIGH if it detects a 38kHz signal. It will remain HIGH for as long as the 38kHz signal is present.

thanks. But you agree with me that when the arduino stops processing the for loop it alredy sent all the pulses right? So when arduino process the next lines like digitalRead it should return nothing cause the pulses already passed it. Right? I have no idea why this code works :(

In an ideal word, it should indeed not work. But in reality the ir receiver isn't sure the signal has stopped, or if it just missed a single light pulse. So it waits a little longer, before returning a LOW.


text:
Can a DC motor use more current than its datasheet?
I am using small dc motors connected to the 5V of the arduino which is known to provide 200mA without damaging it.
The motor I am using is a very common one found in toys -> https://www.sparkfun.com/datasheets/Robotics/ROB-09608.jpg
As I see the maximum current of this motor is 170mA. Does it mean that the motor will not drain more current than that or it means that I need to use a resistor in series with my 5V in order to make sure the current will not pass 170mA?

Note that (like you say) the 200mA is the limit of the VCC pin only. For the IO pins there is a safe limit of 40mA. See the playground for the numbers.

YES (typically resulting in melting the coils). The current used by standard or brushless motors is related to the voltage applied and the load applied. As you approach the load limit, current rises over the limit. There are many ways to control this but controlling the load is the easiest way. DO NOT run the motor through the Arduino even if you think it will be under the 200mA limit. Motors produce a lot of spikes and back-flow.
Here's a tutorial on safely running a motor and controlling the speed: https://learn.adafruit.com/adafruit-arduino-lesson-13-dc-motors/overview

Thank you so much. But if in the specs of the motor says that it consumes 170mA should I even use a resistor if my source provides more than that? I will not connect it to arduino, you told me it will damage it I will not. I will use an external plug that provides 9 V (same as motor) but it provides 1A. Do I really need to use a resistor in this 1A? I think the motor will only consume what it is designed to, isnt?

No, there is nothing about the motor itself that limits the current that will be used. The rating of the motor is how much current it can handle before something fails - usually the insulation on the coil wires overheats and melts, causing shorts and destroying the motor. I have photos of that kind of damage somewhere. It was caused by too much weight/load on the motor. Tuning the current load involves tuning the actual load on the motor. Most motor usages never come close to the limit, so people tend to ignore this issue sometimes. ALL the example programs are like that.

thank you I didnt know that. I believed that the current specified in the motor datasheet was the current it was gona use and nothign else even if I provided more current. I just did not understand this phrase of yours "Most motor usages never come close to the limit,". If I provide more current, according to you the motor would pass the limit, isnt? Or am I wrong?

What I meant by that is, in the examples, they are not loading the motor with a significant load, so they don't need to use any current-limiting scheme. It's such a light load you don't have to worry about it. I would bet most of the examples from the tutorials pull about 30mA from that motor. They are "playing it safe" with the examples, but if you want to get the most from your motor, you won't be playing it safe.


text:
What is this PIND command
I have a code that reads the value of a sensor and because it needs to be very fast it does not use digitalRead but a strange form of reading. In the top of the code it shows:
#define IRSENSOR PIND
int irpin = 2;

I have no idea why this PIND referes to my arduino pin 2, but it only work if my sensor is in pin 2. If I want to change to pin 9 and only change the irpin varialbe it does not work. Why?
To read the sensor I use this code:
while (IRSENSOR & (1 << irpin )) {

Have no idea why this work. Does anyone know this kind of programming with arduino?

That's not a strange form of reading, that's the normal form of reading. The Arduino libraries are the strange form of reading.

Agree, but I am a beginner, sorry. Do you know how to create a variable/const of PIND without using define?

http://www.arduino.cc/en/Reference/PortManipulation

PIND refers to the arduino's IO register for input in port D
Without arduino, one has to refer to pins by specific bits in 3 different sets of registers for each port (PIN*, DDR*, and PORT*; B,C, and D).
The arduino code makes it simpler to pick out a single pin by hiding all of this, but it does make reading a pin take much longer.
In the code, the specific pin is being selected by masking off all but the "irpin" bit in PIND, so changing irpin will pick a different bit and thus a different pin.
Pin 9 is actually bit 1 of port B, not D, so see if this works:
#define IRSENSOR PINB
int irpin = 1;

alternatly, using a reference instead of define,
volatile uint8_t& IRSENSOR = PINB;
int irpin = 1;

Thank you so much, it worked perfectly! One final question: I would like to change #define pino_sensor_infravermelho_PIN  PIND -->> const byte pino_sensor_infravermelho_PIN = PIND;    BUT it does not work, IDE does not allow me to compile. How to solve this?

How did you know it's 1? It worked but I would like to know how to discover it!

I just looked at this cool image I found on google to get the pin numbers, http://www.pighixxx.com/test/portfolio-items/uno/?portfolioID=314 If you are really interested in how all these registers work it is all described in the atmega328 datasheet.

You can get rid of the #define with a reference to a volatile unsigned 8 bit value. See my edit for the code

Nice!!!! I am not lazy, I used the image http://arduino.cc/en/Hacking/PinMapping168 but your link is much better cause in the link I showed you the pins are not right. tHANK YOU so much really I could not use define and it helped me alot!

@Samul: I don't see any difference between the two, other than one shows the Arduino and the other shows the IC.

Reason explained by @BrettM. To be more perfect use macros everywhere, e.g.:
#define IRSENSOR PIND
#define IRSENSOR_PIN PD2

while (IRSENSOR & _BV(IRSENSOR_PIN)) {

Arduino's digitalWrite(),digitalRead(),pinMode() functions are useless for more serious coding because they are 1) slow 2) you cannot address pins not connected to headers (e.g. at Arduino2560).

Thank you so much! do you know how to declare those 2 variables without using define?

It's rather complex task because depends what is intended usage. To be precise you need consider using in inline assembler, proper resolving variables in debugger when watching, IO vs. MEM access (_SFR_MEM vs. _SFR_IO) etc. PIND, PD2 itself is also #define. I would not experiment with it without good reason to make more reusable and readable code (=writing common libs not hardcoded to particular device), e.g. define port+pin as WORD (hi=port, lo=pin) and implementing own macros.

BTW: You do not need using define at all, if define is problem:
*while (PIND & _BV(PD2))*

You are awsome, I will use it inside the while without declaring any variable. Could you please help me understand this: -->> while (porta_pino_sensor_infravermelho & (1 << pino_sensor_infravermelho)) { <<--. I know & is bitwise and and << is bitshift but it does not make any sense to me! Have you ever seen this way of reading a pin HIGH/LOW?

HIGH=1, LOW=0, it's just strange macroization of trivial things (done even wrong way because HIGH and LOW are really not too unique names in namespace). Almost any port has normally 8 pins, it equals BYTE, particular pin corresponds to bit. Just trivial bitwise opration if bit is high level then do looping.

so you are saying that if I am using pin 9 then pino_sensor_infravermelho should have 01000000 ? I cant understand this 'while" cause I dont know the value of pino_sensor_infravermelho

@Samul: I recommend retaining the macro definitions. They don't cause any slowdown during runtime and they make the code easier for others (and eventually yourself) to read and understand.


text:
Source power with 2 V and LED with forward voltage of 2 V
I have a source power with 2 V and 100mA. I have an LED that has a forward voltage of 2 V and a max current of 20mA.
Should I use a resistor to reduce the current? I see many formulas in the internet saying the the resistor value should be:
(Source Voltage - LED forwared voltage)/LED max current
This formula always worked fine for me, but now that I have a 2 V source power this formula tells me that the resistor should be 0 ohm. Of course this would damage my LED cause the 100mA provided by my source power is way above the 20mA current limit of the lED.

No, it would not damage your led. The forward voltage of a led is, the voltage at which the led 'conducts' the maximum current it can handle. Since diodes have a (exponential) curve, the current though a diode depends on the voltage across it.
So if you give the led 2V, it will use only 20mA. However if the voltage goes to e.g. 2.1V the current might be 25mA (since the curve is exponential), which is a bit too high, and will reduce the leds lifespan.
So for safely I'd add some resistors. E.g. a 10Ohm resistor will limit the current to 20mA max, as long as the voltage doesn't go over 2.2V
PS note that led Christmas lights use the same method to limit current, without a single resistor. I have here a 24v string of leds, grouped into 10 leds connected in series. So the voltage across each led is 2.4V. They are white leds, so they probably have a forward voltage of around 3.2v. But since they only get 2.4v, they will probably use only 5mA or less.

Thank you so much but if I add a 10 ohm resistor it will consume voltage, isnt? If it consume voltage the LED will not have it's forward voltage required in the specs ov 2V cause some of the voltage will be lost to the resistor. Will it work anyway?

The led will be a slightly less bright.

You most likely will not be able to use that power supply with that LED properly. The resistance graph of an diode is quite peculiar.

As you can see, there isn't a "hard" forward voltage, but rather a smooth curve that changes depending on what current is passing through the diode. You can try to use a value of, say 1.95V for the LED, but then you won't pass the same amount of current that you used in your calculations.
Extended reading: Load line (Wikipedia)

Thank you so much I read the wikipedia and understood well the non linear with the linear part in a circuit and the exponential behaviour of the LED with current/voltage. But if I use a 100 ohm resistor, there will be a voltage drop across the resistor right? So the LED will have not the 2 V to operate, but will it work? Can I calculate the voltage across the LED with the 100 ohm resistor in series?

The LED will still drop some voltage. Use load line analysis to figure out how much.


text:
Does Arduino run AC or DC
Does arduino run AC or DC? Based on my small knowledge on the crystal in an arduino, it seems like AC makes sense. True? No?

You are correct about the crystal producing an alternating signal, but it is a timing signal only and doesn't power the arduino. In fact, the crystal timing circuit is powered Arduino's DC power.

Thanks. Could you reference me to materials to help me understand amplifier circuits/resonator circuits such as the one that crystals use? I have already read the wikis.

(Edited):  Try these two: Wikipedia; Circuits Today. Also this question about how crystals work on Electrical Engineering Stack Exchange.

Lol I asked that question man

(Oops!) Good answers there, though - I learned a bunch, too.

The clock signal that CPUs use is switched DC, not AC. It alternates between the logic 1 voltage (usually +5) and zero volts, but doesn't go negative.

As a general rule, any modern electronic device with computational ability has to use DC. The reason is that they use specific voltage levels to indicate binary/logical states (i.e. 0's and 1's).
In theory, an ideal DC supply (Direct Current) should provide a constant voltage. That allows the circuit to effectively turn it on an off to represent binary states. (In reality, there's no such thing as truly "off" though, because voltage is relative.)
However, the voltage from an AC supply (Alternating Current) is constantly varying. If you plot it on a chart, you should see a nice sine wave, flowing smoothly between positive and negative several times per second. Hypothetically, if a digital circuit tried to use AC then it would get very confused, because everything would seem to be turning on and off all the time.
With all that said, it's very common to turn AC into DC through a process called rectification. For example, that's what allows DC devices to get power from an AC outlet (e.g. to run your computer or charge your phone).

Rectification, filtering, and regulation. Simple rectification leads to switched DC, where the negative part of the sine wave is inverted and you just have a series of positive humps that still drop to zero. Filtering smooths out the power to a flat DC voltage. However, the voltage from a filtered but not regulated supply will vary based on load. The more current you draw from it, the more the voltage will drop. A regulated power supply will adjust the output to keep the voltage constant. Logic circuits run much better with a regulated supply. Some logic circuits like TTL require it.

All digital logic circuits run on DC.
Most Arduino boards include a voltage regulator. You can feed them an input ranging from 7 to 12 volts, and they "clean up" that input and lock it to precisely 5 volts, the voltage needed by the Arduino.
They can also run directly off the regulated 5 volts from the USB connector.

Have a look at this: http://arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf and try and have a guess.
I don't want to be nasty, but have you at least googled this? Google: "Arduino Power Source" and the first hit is http://playground.arduino.cc/Learning/WhatAdapter
It runs from USB as well as from an external power source.
To answer your question: DC

@Sciiiiience, the general rule with SO is that you should exert a little effort yourself before posting a question. If a casual google query answers your question on the first page, don't ask it. (People resent it when you expect them to put more effort into answering your question than you put into asking it.)