text:
Efficiency of a cast vs a shift
I'm using a supplied library which uses a number of (non-sequential) outputs to latch a multiplexer. The code looks (in part) like this:
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 3)>>1);
 digitalWrite(_S2, (chan & 7)>>2);
 digitalWrite(_S3, (chan & 15)>>3);

Those masks seem a little odd, but it would work. More natural to me would be:
 digitalWrite(_S0, (chan & 1));
 digitalWrite(_S1, (chan & 2)>>1);
 digitalWrite(_S2, (chan & 4)>>2);
 digitalWrite(_S3, (chan & 8)>>3);

But overall, would it be more efficient to do this?
 digitalWrite(_S0,       (chan & 1));
 digitalWrite(_S1, (bool)(chan & 2));
 digitalWrite(_S2, (bool)(chan & 4));
 digitalWrite(_S3, (bool)(chan & 8));

...or is shifting already pretty efficient?
I've actually re-written the code to build a mask and use PORTx to latch it all at once, so this is really an academic question, but I'm still curious.

The digitalWrite calls are the slowest parts in here. It takes about 50 (or more) instruction cycles (if I remember it correctly), so few more or less cycles won't make so big difference.

@KIIV - Sure, that's why I replaced all this with an array of bitmasks and a single PORTx access. It's probably 20x faster. I was just curious about efficiency in general.

I tried compiling your three snippets with avr-gcc 4.9.2 at the -Os
optimization level (standard with Arduino) but without -flto. The
results were:

The first snippet generated inefficient code: the ands and shifts were
translated in assembly quite literally, the shifts were done on
16 bits even though chan was declared uint8_t, and the last
shift was even implemented as a loop roughly equivalent to
uint16_t tmp1 = chan & 15; uint8_t tmp2 = 3; while (--tmp2) tmp1 <<= 1;
The second and third snippets were translated identically and
efficiently, using the bst (bit store) and bld (bit load)
instructions to copy the relevant bit of chan into the second
argument of the digitalWrite() call.

Personally I would just write
digitalWrite(_S0, chan & 1);
digitalWrite(_S1, chan & 2);
digitalWrite(_S2, chan & 4);
digitalWrite(_S3, chan & 8);

as digitalWrite() expects an integer as its second argument, and it
interprets it just like the (bool) cast does. If you want to be sure
to always call digitalWrite() with either 0 (LOW) or 1 (HIGH),
then use either your second of third form. The first form seems formally
equivalent to the second, but since it is not an usual C idiom, the
compiler could not catch the optimization opportunity.

Thanks for the analysis. I can see how the (bool) cast would be redundant in this case. Also very interesting that the compiler knows 'idioms'.

If you look at the assembly code the compiler produces, you can see it compiles to the exact same thing - when using a constant.:
void setup() {
  ....
  digitalWrite(_S1, (chan & 2)>>1);
 282:   84 e0           ldi r24, 0x04   ; 4
 284:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>
 ....
  digitalWrite(_S1, (bool)(chan & 2));
 29a:   84 e0           ldi r24, 0x04   ; 4
 29c:   0e 94 6b 00     call    0xd6    ; 0xd6 <digitalWrite.constprop.0>

However, using a variable produces different results:
void loop() {
  digitalWrite(_S0, (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (chan & 2)>>1);
 2b4:   6c 2f           mov r22, r28
 2b6:   66 95           lsr r22
 2b8:   61 70           andi    r22, 0x01   ; 1
 2ba:   84 e0           ldi r24, 0x04   ; 4
 2bc:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (chan & 4)>>2);
 2c0:   c2 fb           bst r28, 2
 2c2:   66 27           eor r22, r22
 2c4:   60 f9           bld r22, 0
 2c6:   85 e0           ldi r24, 0x05   ; 5
 2c8:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (chan & 8)>>3);
 2cc:   c3 fb           bst r28, 3
 2ce:   66 27           eor r22, r22
 2d0:   60 f9           bld r22, 0
 2d2:   86 e0           ldi r24, 0x06   ; 6
 2d4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

 ....

  digitalWrite(_S0,       (chan & 1));
 2a2:   c0 91 00 01     lds r28, 0x0100 ; 0x800100 <__data_start>
 2a6:   d0 91 01 01     lds r29, 0x0101 ; 0x800101 <__data_start+0x1>
 2aa:   6c 2f           mov r22, r28
 2ac:   61 70           andi    r22, 0x01   ; 1
 2ae:   83 e0           ldi r24, 0x03   ; 3
 2b0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S1, (bool)(chan & 2));
 2b4:   be 01           movw    r22, r28
 2b6:   76 95           lsr r23
 2b8:   67 95           ror r22
 2ba:   61 70           andi    r22, 0x01   ; 1
 2bc:   84 e0           ldi r24, 0x04   ; 4
 2be:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S2, (bool)(chan & 4));
 2c2:   be 01           movw    r22, r28
 2c4:   76 95           lsr r23
 2c6:   67 95           ror r22
 2c8:   76 95           lsr r23
 2ca:   67 95           ror r22
 2cc:   61 70           andi    r22, 0x01   ; 1
 2ce:   85 e0           ldi r24, 0x05   ; 5
 2d0:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>
  digitalWrite(_S3, (bool)(chan & 8));
 2d4:   be 01           movw    r22, r28
 2d6:   23 e0           ldi r18, 0x03   ; 3
 2d8:   76 95           lsr r23
 2da:   67 95           ror r22
 2dc:   2a 95           dec r18
 2de:   e1 f7           brne    .-8         ; 0x2d8 <main+0xc0>
 2e0:   61 70           andi    r22, 0x01   ; 1
 2e2:   86 e0           ldi r24, 0x06   ; 6
 2e4:   0e 94 76 00     call    0xec    ; 0xec <digitalWrite>

Your test is not really significant. The compiler noticed that you were always calling digitalWrite() with 0 (i.e. LOW) as its second argument. It then generated a specialized variant of digitalWrite() that sets an output to LOW and it translated your code into something like digitalWriteLow(3); digitalWriteLow(4); digitalWriteLow(5); digitalWriteLow(6);. In order for the test to be significant, you should make sure chan is not a compile-time constant. Alternatively, compile without the -flto flag to force the compiler into creating a non-specialized translation of your code.

Sorry, I should have specified that chan is a passed-in variable. Using a constant chan would make this trivial, as you say.

@EdgarBonet Fair assessment. I did make it a const. Will update...

Your updated test is flawed again. The compiler computed chan & 2 while translating (chan & 2)>>1, and it stored this intermediate result in the r11:r10 register pair. Then, when translating (bool)(chan & 2), it used the fact that chan & 2 was already in a the register file, which made that translation shorter.

@EdgarBonet Thanks for your input. The answer turned out to be more complex than I initially assumed.


text:
What is causing this 'narrowing conversion' warning?
Because I'm still figuring out 'Arduino C' I leave all warnings on.
Recently I got this one:
narrowing conversion of '(int)(((unsigned char)bx_0) | ((unsigned char)bx_1))' from 'int' to 'const byte... etc.
...referring to this line:
const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

...pointing to the or symbol.
The code in question (much simplified to recreate this):
const int latch[2] = {2, 4};

const byte bx_0 = 1 << latch[0];
const byte bx_1 = 1 << latch[1];

const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};

(This happens whether I use byte, uint8_t, or unsigned char everywhere.)
Without the or operator, no warning. If bx_0 and bx_1 are simple bytes, not shifted into existence, no warning. If I do this:
const byte pinMask[3] = {bx_0, bx_1, (byte)(bx_0 | bx_1)};

...again, no warning.
However, I get no complaints about this:
const byte notMask = !(bx_1 | bx_0);

...so a further condition is that the problem or has to be in an initializer list. Yikes.
I don't get it. There's no way an or of two bytes can force widening, so where did the (int) cast come from? It apparently has something to do with the 1 << latch[0] code, but the result of that is still a byte, by definition.
I have a solution -- the (byte) cast -- but in the real code it's ugly and feels unnecessary. Everything is already just bytes.

That warning message arises when a compiler complies with C/C++ specifications.
According to ISO/IEC 9899:2011 part 6.5.12.2 (“Bitwise inclusive OR operator”),

Each of the operands shall have integer type

Thus, in the evaluation of bx_0 | bx_1 within the statement const byte pinMask[3] = {bx_0, bx_1, bx_0 | bx_1};, the operands bx_0 and bx_1 are converted to int type before being OR'd together.  This produces an int result, which then must be narrowed to byte before it can be stored in the  byte array.
Knowing that the (byte) cast is necessary because of C/C++ specifications should convert your view of the cast from “ugly” and “unnecessary” to “necessary” and either “ok” or “oh well”.  :)

Thanks, I suspected that might be the issue, except that all the conditions are necessary for the warning: complex definition, bitwise operator, initializer list. Remove any one and it doesn't warn. And OK, I'll accept 'necessary' (-: but I'm keeping "ugly" because in the actual code there are 16 elements to pinMask[], some with three or's.

source: Stack Exchange

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

sort: votes


text:
How does Arduino handle passing this union?
I'm unsure how this will be handled by the Arduino compiler. If anyone can explain what and why, I'd appreciate it. This is obviously very simplified, but it does contain the actual issue.
At the module level I have this union. I understand that this is strictly speaking not correct C++, but it does work for me, at least when used directly and not passed as a argument to a function.
  union _TAT {          // access as bytes or uint32
    uint32_t wide = 0;
    uint8_t bytes[4];
  };

  _TAT oneTAT;        // a variable of _TAT

Suppose I also have a function that works on these:
  void fix_Term(_TAT atat) {
    atat.wide = 0;
    atat.bytes[3] = 17;
  }

...and I invoke it with:
  fix_Term(oneTAT);

As I understand it, passing AnArray[] is equivalent to passing *AnArray, so the function might/should see atat.bytes[3] as a pointer to that byte of the variable. But what about atat.wide? I haven't explicitly passed oneTAT by reference, so...?
What might actually happen here? It does compile without complaint but I can't test it because the hardware it depends on isn't available yet. Besides, even if it works, I'd like to know why.
And of course, if it's just wrong, how do I best accomplish passing and modifying a variable like this?

you can test your native code in tinkercad's Arduino simulator. Arduino is usually about the same as plain c++, so compiler explorer is another online option.

It is confusing in C and C++ that arrays are passed as pointers but an instance of class, struct or union is always passed by value (so as a copy) including the arrays which are part of the memory space of the structure as in the case of your union.
If you want to pass by reference, declare the function's parameter as a reference 'type'. For example void fix_Term(_TAT& atat) {.

Thanks, this seems to be the missing piece for me. I do want to pass by reference but was confused (as you note) by the * / [] .

Yes passing AnArray[] is equivalent to passing *AnArray. But declaring uint8_t *anarray1 is not equivalent to declaring uint8_t anarray2[4] in a struct/class/union definition. The former includes a pointer to a byte in the struct, the later actually includes 4 bytes in the struct. So in the later case, anarray2 already points to data, and using variable.anarray2[0] correctly gets you the value in the structure, while calling variable.anarray1[0] would result in undefined behavior, because the pointer just points anywhere.
So your code is compiling and executing without error, but since you're passing the union by value, the effect of your fix_term function is discarded, much like if you had passed in an ordinary value type instead (such as int).

However he can pass it by reference:  void fix_Term(_TAT & atat) + call is the same and then it'll change the original union variable.

@KIIV Sure, but the question was about the existing code, I think.

Yes, the question was about what the original code is doing, but it also solicited advice on making it work. Got it now, I think, thanks to you and Juraj

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


text:
Synchronizing an internal frequency to an external one
In this question:
Procedure for changing frequency of Nano or similar, @EdgarBonet gave a very nice method of generating timings that don't divide the system clock evenly. He also said that it would require tuning of the exact value by measuring the resulting frequency. I'd like to see if that tuning could be made automatic.
Suppose I had a precise external reference that could interrupt at a a sub-multiple of my frequency, say 60Hz. Is there a way to use that precision to, over time, bring my generated frequency into rough agreement with it?
In other words, for a frequency of 2400 Hz, and a reference of 60 Hz, I would adjust the period of the generator so that there are exactly 80 cycles of the 2400 Hz signal in each 60Hz period, even though there might be variations within the periods of those 80 cycles.
In effect this is a crude phase-locked loop multiplier. I know it can't be highly precise, but even close would be very valuable.

You could use the input capture feature of Timer 1 to timestamp the
edges of the reference input signal. This way you can compute the period
of the input relative to the CPU clock, compare to the expected nominal
period, and use this to adjust the interrupt period.
Combining this idea with the answer to the previous question gives:
const float input_frequency = 60;
const float interrupt_frequency = 2400;
const uint32_t nominal_input_period = round(F_CPU / input_frequency);
const uint32_t nominal_interrupt_period =
    round(F_CPU / interrupt_frequency) * 65536;

volatile uint32_t interrupt_period = nominal_interrupt_period;

uint16_t last_input_timestamp;

ISR(TIMER1_COMPA_vect) {
    // Update the timer for the next interrupt.
    static uint32_t accumulator;
    accumulator += interrupt_period;
    OCR1A = accumulator >> 16;

    // The periodic task goes here...
}

void setup() {
    // Configure Timer 1.
    TCCR1A = 0;            // normal mode
    TCCR1B = _BV(CS10);    // clock @ F_CPU
    TIMSK1 = _BV(OCIE1A);  // enable COMPA interrupt

    // Capture the first input edge.
    TIFR1 |= _BV(ICF1);  // clear interrupt flag
    loop_until_bit_is_set(TIFR1, ICF1);
    TIFR1 |= _BV(ICF1);  // clear interrupt flag again
    last_input_timestamp = ICR1;
}

void loop() {
    // Detect edges of the input signal.
    if (bit_is_set(TIFR1, ICF1)) {
        TIFR1 |= _BV(ICF1);  // clear interrupt flag

        // Update the interrupt period.
        uint16_t input_timestamp = ICR1;
        uint32_t input_period =
            (int16_t) (input_timestamp - last_input_timestamp
                - (uint16_t) nominal_input_period)
            + nominal_input_period;
        last_input_timestamp = input_timestamp;
        uint32_t new_interrupt_period = round(nominal_interrupt_period
                * ((float) input_period / nominal_input_period));
        noInterrupts();
        interrupt_period = new_interrupt_period;
        interrupts();
    }
}

Note that rounding the input period to an integer number of cycles comes
with a rounding error of 1.25 ppm, well within your 10 ppm
requirement. You can do better if needed, by using fixed point or
floating point computations. Note also that the Timer rolls over
multiple times per cycle of the input signal, which is dealt with by
some arithmetic tricks, hence the casts to uint16_t and int16_t in
the expression of input_period.
Strictly speaking, this is not a phase lock loop. It is more like a
frequency lock loop. A real PLL would probably be a bit more involved.
However, if you can tolerate your resulting frequency to be 10 ppm
off, this approach is likely to be good enough.

This is great. I never would have worked out the subtleties of int vs uint vs float here. I'll have to study this more to completely get it. You've clearly mastered this device.

One thing is unclear to me. Reading the Atmel docs, it seems that the ICF1 flag in the TIFR1 register is set when an interrupt occurs, and at one point you check if (bit_is_set(TIFR1, ICF1)), so that makes sense. But then you TIFR1 |= _BV(ICF1) to clear the interrupt, which seems to be the opposite of clearing the bit. What am I missing?

@JimMack: Re “the ICF1 flag [...] is set when an interrupt occurs”: No, it is set when a capture event occurs. We could enable the capture event interrupt, but given that this is not time critical (60 Hz is slow), I prefer to just poll the flag in loop(). Re “TIFR1 |= _BV(ICF1) [...] seems to be the opposite of clearing the bit”: As per the datasheet: “ICF1 can be cleared by writing a logic one to its bit location.” This is how most (all?) interrupt flags work, which is indeed confusing!

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


text:
Understanding a PWM spec
I have to send a PWM signal to a controller module from an Arduino Uno. I'm not sure how to interpret the spec I've been given, and how to translate it into a PWM signal. The module is a Castle Creations Mamba Monster 2, if that helps.
The spec says the unit wants a 50Hz carrier, and the control is:
1500 microsec = idle
2000 usec = full forward
1000 usec = full reverse

I get that the period of the carrier is 20,000 usec but how does that relate to the control periods? Does it mean that for "idle" the PWM signal is high for 1500 usec and low for (20000 - 1500) usec?
Any help or insight is appreciated. Are there libraries that can deal with PWM in the given terms? Any good tutorials? I generally understand how PWM works, I just don't get the notation used here.

For a full 50Hz wave you have 1/50 seconds, or 20,000 microseconds, as you have already determined.
That is split into two portions - the ON period and the OFF period. With a 50% duty cycle the ON and OFF periods are equal - 10,000 microseconds each.
With a 25% duty cycle it is ON for 25% of the time (5,000 microseconds) and OFF for 75% of the time (15,000 microseconds).
Every time the ON and OFF must add up to 20,000 microseconds.
So for a 1,500 microsecond "idle" time that's 1,500 microseconds on, and (20,000 - 1,500) 18,500 microseconds off.
Or to see it as a duty cycle - 1,500 / 20,000 * 100 = 7.5% duty cycle.
With an 8-bit resolution that's a value of 19.2 (256 * 0.075), or the closest integer match of 19.

Thanks, so it's what I assumed. I'd just never seen it expressed in that way, rather as a duty cycle as you show..

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


text:
Safely extend TCNT1 / ICR1 to 24 bits using TOV1
I'm hoping to time external events on a '328p Arduino that will occur slowly enough that they'll overflow the 16-bit counter TCNT1. In a different scenario I'd prescale the counter, but I need the full timer resolution in this case for other purposes.
So I enable the TOV1 interrupt and just increment an 8-bit value, letting it roll over as needed.
Then on an ICP1 interrupt, I shift this value << 16 into a 32-bit variable, and add in the value captured in ICR1, yielding a 24-bit value that I can use to measure the slow interval.
Are there hidden gotchas in this plan? Possible race conditions where TOV1 hasn't yet been updated if ICR1 is latched just when TCNT1 has just rolled over, or generates a TOV1 after capturing ICR1 but before I shift in the overflow count?

There is, indeed, a possible race condition. Consider this naive code,
which provides 32-bit timestamps:
/* Count overflows. */
volatile uint16_t timer1_overflow_count;
ISR(TIMER1_OVF_vect)
{
    timer1_overflow_count++;
}

/* Timestamp input events. */
volatile uint32_t captured_timestamp;
volatile bool did_capture;
ISR(TIMER1_CAPT_vect)
{
    captured_timestamp = timer1_overflow_count << 16 | ICR1;
    did_capture = true;
}

Since TIMER1_CAPT has higher priority than TIMER1_OVF, then:

If ICF1 rises before TOV1, TIMER1_CAPT_vect runs first, which
is fine.

If ICF1 and TOV1 rise simultaneously, TIMER1_CAPT_vect runs
first, which is still fine, as the captured value is 0xffff.

If TOV1 rises before ICF1, either ISR may run first:

if the CPU can process the TIMER1_OVF IRQ right away, then
TIMER1_OVF_vect runs first and the result is correct

if the interrupt processing is delayed until after ICF1 has
risen, then TIMER1_CAPT_vect runs first and grabs a wrong value
for timer1_overflow_count.

Solution
There is an unhandled overflow when bit_is_set(TIFR1, TOV1). The
overflow may have happened at the same time or after the capture, in
which case it doesn't affect the timestamp. We know it happened before
the capture when the captured value is small, where “small” could be
defined as having its most significant bit clear. If this is the case,
we have to add 0x10000 to the timestamp we obtained.
A race-proof ISR can be written as follows:
ISR(TIMER1_CAPT_vect)
{
    uint16_t captured_low = ICR1;
    uint16_t captured_high = timer1_overflow_count;
    if (bit_is_set(TIFR1, TOV1) && !(captured_low & 0x8000)) {
        captured_high++;
    }
    captured_timestamp = (uint32_t) captured_high << 16 | captured_low;
    did_capture = true;
}

Thanks for your analysis. I get everything about your solution except the phrase we have to add 0x0100 to the timestamp. In code you (effectively) add 0x10000, which is what I'd expect for a missed overflow. Typo?

@JimMack: Oops! You are right, I made a typo. Fixed, thanks!


text:
Serial.print and char[] & null
I don't write a lot of C, so I'm always discovering things I only partly understand in the Arduino variety. One of these is how Serial.print handles char[].
Does Serial.print always require a null terminator? In the case of (say) Serial.print(88, DEC); is a null implied?
What happens in the following cases?
char buff[3] = "ABC"; // warned because no room for a null
Serial.print(buff);   // will absence of a null cause overrun?

char buff[4] = "ABC"; // now there's a null
Serial.print(buff);   // will the null character be sent too?

Any references appreciated.

When passing a char* you need to also pass some way of telling the function where it ends. In C that is usually the null terminator and that's all a null terminator is for. If that is missing then you get a buffer overrun.
The null terminator is not sent.

The "Serial" is a object/class and that makes it possible to have more than one function for Serial.print(). According to the type of the parameter the proper Serial.print() is selected.
This is the include file for the Serial.print(): Print.h
And these are the possibilities:

size_t print(const __FlashStringHelper *);
size_t print(const String &);
size_t print(const char[]);
size_t print(char);
size_t print(unsigned char, int = DEC);
size_t print(int, int = DEC);
size_t print(unsigned int, int = DEC);
size_t print(long, int = DEC);
size_t print(unsigned long, int = DEC);
size_t print(double, int = 2);
size_t print(const Printable&);

The reference for Serial.print() is short, but it explains pretty well that those different parameters are possible.
Your Serial.print(88, DEC); does not use a string of text, it uses the integer number 88.
As soon as a string of text is used, it should be zero-terminated.
The line char buff[3] = "ABC"; is indeed wrong, as you already wrote. That is one of the things of the 'c' language. The "ABC" gets a zero-terminater and that makes 4 bytes.


text:
Gas Sensor Library for Proteus
Does any one know how to use Gas Sensor module in Proteus. I wanna use Gas Sensor but I am unable to find it in Proteus. So, does anyone know any way of adding Gas Sensor Library for Proteus software. Thanks in advance.

I have found the Gas Sensor Library for Proteus, so I thought to share it here so that others can also get benefit out of it. They have also posted the complete method of How to use this Gas Sensor Library and have also given an example to download.
Thanks.


text:
Bluetooth HC-05 Library for Proteus
I m working on a project in which I am using HC04 module so can anyone give me any Arduino Library for Proteus which have HC05 in it. Or tell me how to use HC05 in Proteus.
Thanks.

I have found this Bluetooth Library for Proteus. Thanks for helping me out guys. I am posting it here so that others can also get benefit out of it.
Thanks.

I don't know Proteus, but I think HC05 a bluetooth module? If so, the module interface from HC05 <==> arduino is done through Serial (UART) communication.
Arduino has built in support for this - you don't need any special libraries besides SoftwareSerial.
wire up the module as such:

Then run the following code:
#include <SoftwareSerial.h>

#define rxPin 10 // connected to TX pin of HC05
#define txPin 11 // connected to RX pin of HC05

SoftwareSerial mySerial(rxPin, txPin); // RX, TX
char bt;

void setup() {
  Serial.begin(9600);
  Serial.println("Hello");

  mySerial.begin(9600);
  mySerial.println("World");
}

void loop(){
  while(mySerial.available()){
    bt = mySerial.read();
    Serial.print(bt);
  }

  while(Serial.available()){
   bt= Serial.read();
   mySerial.print(bt);
  }
}

There is no Proteus Library for HC05. (Not one I know of.)
Now, your HC05 is a serial device i.e. it acts as a Serial monitor. and fortunately there is Serial Monitor in Proteus. You can use that.
Here, Have a look.
P.S. if you are using ISIS 7.x. there is a thing to be noted. You have placed a serial monitor and connected to arduino and you started execution and its working fine. Now, what happens sometimes is that when you stop execution and start again, serial monitor might not work. No need to worry about. Stop execution, delete that serial monitor and place a new.That will work.


text:
Can ZigBee API and ZigBee AT work together in the same network?
I'm currently trying to make 3 arduinos talking to each other with ZigBee, and it's kinda working.
But I currently use AT mode on the Bees and it's a little bit harsh when I have to switch the destination address in the Coordinator of the network (1 Coordinator and 2 Routers)
Can I put the Coordinator in API mode (to make it easier to switch addresses with xbee-api for Arduino) but still be able to communicate with the AT routers and be able to send/receive data from them?
Thanks for your answer :)

My question has been answered on Stack Overflow, if you ask
https://stackoverflow.com/questions/28765288/can-zigbee-api-and-zigbee-at-modules-work-together-in-the-same-network


text:
Which thermometer for home brewing
Hello,
I have an Arduino Yun and I brew beer.
I would like to log the temperature of the beer at all time during the fermentation process (final stage).  This means the thermometer would have to remain in the beer during this time (10 days).  The temperature would be < 40 degrees Celsius (probably around the 20 degree mark).
Question: What temperature sensor would be best suited to this task?
It must be:

Food grade
Can be used in alcohol for extended periods
Can be hooked up to Arduino (i.e. add a library and ready to go)

Thanks, Dan.

http://www.adafruit.com/products/381 and/or http://www.adafruit.com/products/1020

You can relax the immersion requirement if you tape the thermometer to the side of the fermenter and cover it with some insulation--I cover the stick-on thermometer on my carboy with a rag to make it match the contents more than the ambient temperature.

I am not a brewmaster but from what I understand the temperature will change slowly. Your problem is not to contaminate the beer, you can use a stainless possibly even a plastic tube that is sealed on the immersion side and use a
DS1820B sensor commonly used on Arduinos as well as other platforms. The response will be slower then if the sensor is inserted directly but since the change is slow it should work AOK. This keeps it simple and probably something you have done before.

You are looking for a thermocouple.
They need some specific chip to be read, so you'll probably want to spend a bit more and get a chip with a digital interface, there are some witch has arduino library, like MAX6675 (output at 1Hz, 0.25° precision).
As this chip read "C type" thermocouple, you just have to find the right probe for your needing, with probably can be found in many specialized store.
You may even buy a normal k probe, and then wrap it up in some protective case. Obviously that case should be designed to let the heat flow easily, but without short circuiting the probe; a food plastic bag;
or just spend a little more money and buy a stainless steel probe

Thanks - I will take a look at thermocouples (new term for me thanks). I don't mind spending a little bit of money.  I would prefer not to use plastic bags due to the fact there will be an aquarium heater in the container also.

yeah, the chip can be found for 10-15$, the probe i think others 30-30$, because you need to be sure it is food grade.
Please try to spend a bit more but stay safe.
And remember to calibrate it putting in ice and boiling water, and/or using a better quality thermometer; it is fine to have to compensate for a bit of error

A Thermistor is what you are really looking for, I would downvote this answer but I don't have the rep here to do so.  A thermistor is a type of resistor whose resistance varies significantly with temperature, more so than in standard resistors.  On the other hand, a thermocouple is a temperature-measuring device consisting of two dissimilar conductors that contact each other at one or more spots, where a temperature differential is experienced by the different conductors (or semiconductors).  Two differnt technologies, for your usage you are really looking for the thermistor.

A thermocouple generates a few millivolts of current, and is most typically used in the flame of a pilot light and connected to a fail-safe gas valve.  On the other hand a thermistor must be powered by it's circuit and is much more useful at 20-40C than a thermocouple.

@tyson write it as your own answer, not as comment. I don't think a thermistor is better as it is slower and with less precision.

First, speed doesn't matter in a long term monitoring application with a lot of its own thermal mass like this.   Next, a thermocouple is not more accurate, but less.  Thermocouples do not measure temperatures directly, but rather compare them. Therefore to use one you need to establish a reference temperature.  That can be done literally, by means such as dunking the reference junction in an ice-water bath, or virtually by measuring the temperature of the other junction or isothermal terminal block where it is located - typically with a thermistor or other type of resistance-based sensor.


text:
Arduino IDE Board Manager: Unable to install Due on 1.6.5
I have an Arduino Due I'd like to start using. I've been using Unos, Megas etc no problem. The newer IDEs have removed the Due support. I've been trying to install Due support through the Board Manager, but when I open the Boards Manager, I get :
Error downloading http://downloads.arduino.cc/packages/package_index.json
and when I try to install Due support, I get :
Error downloading http://downloads.arduino.cc/cores/sam-1.6.4.tar.bz2
I understand I may be behind proxies, but in IDE version 1.6.5, that has been removed from the Preferences, so I can't change that. I have tried to allow the IDE past the Windows Firefall, but that has not changed anything.
I have manually downloaded sam-1.6.4.tar.bz2 and extracted the contents to C:\Arduino\arduino-1.6.5\hardware\arduino\sam (I had to manually create the sam folder). With this, I can see the options of Arduino Due Native USB Port and Arduino Due Programming Port when selecting the board, and when I look for it in the Ports, it can recognise the board at the port (eg "COM5 (Arduino Due (Programming Port))" ). When I try to compile anything, I get the error message :
Cannot run program "{runtime.tools.arm-none-eabi-gcc.path}\bin\arm-none-eabi-g++" (in directory "."): CreateProcess error=2, The system cannot find the file specified
Any other idea as to how I can install the Due? Is there an option for a manual installation? The same happens with Libraries Manager (I don't get a connection), so I guess, the same can be applied to that.


text:
Integrating Freescale Multi Sensor board with Arduino
I recently bought Freescale's FRDM-FXS-MULTI-B, and have been trying to integrate it with an Arduino UNO. The board descriptions say that it has the shield layout that matches that of an Arduino shield. So in theory, I should be able to integrate it fine.
The problem comes when I plug it in and try to program the Arduino. As soon as I plug it in, the board resets and hangs. If I try to upload a simple code (just reading the analogue signal from the light sensor), the IDE hangs when uploading. Sometimes, I can fix it by removing the shield and pressing the reset button, but sometimes that doesn't work: the computer doesn't recognise the Arduino on the port, and the IDE removes the port from the Port Selection option. When I do remove it and it resumes functioning normally, and I re-attach the shield, the board resets and hangs again, until I go into the Serial Monitor.
With this board, I realised the Bluetooth module is connected to the Serial Receive pin, which explains the hang in the IDE, but I cannot understand why it resets and hangs when I plug it in.
Does anyone have any experience with this board, and can help me out? Why can I not find any tutorials online? With the multitude of sensors on this shield, I'm guessing you can access them via normal I2C and SPI communications, right? How do you use the Bluetooth module on the board?

What are you using to tell that the sketch is hanging even when it isn't connected to the serial monitor?

@BrettAM The sketch compiles fine, but when it is uploading, it freezes and stays in the same spot for ages. If I do press the reset button on the board, I get the 'avrdude: stk500_getsync()' error, but sometimes the code uploads, sometimes not.

So... 20 months later I stumbled upon this question, only to find out I wrote it. Awkward! Anyway, for anyone who stumbles across this question in the future, here is the answer.
The Rx pin is connected to the Bluetooth module, and as such the module will keep the pin in an idle state (either idle-high or idle-low). The Rx pin of the Arduino UNO (or the Rx0 pin on the Mega/Due) requires to be free of anything that may interfere with the upload. The Arduinos rely on the Rx pin for the sketch upload. If anything is connected to it, the IDE will freeze and nothing will be uploaded. Simply disconnect the FRDM board, upload the code, and put the board back in place. Then it should work.


text:
How to read a 25 kHZ PWM signal from PC fan header?
I would like to control a DC motor's speed using the PWM output from my motherboard header.
Here's the standard pinout for a 4-wire PC fan header:
╔═══╦════════╦═════════════════╦════════╗
║ # ║  Name  ║   Description   ║  Wire  ║
╠═══╬════════╬═════════════════╬════════╣
║ 1 ║ GND    ║ Ground          ║ black  ║
║ 2 ║ +12V   ║ Fan Power       ║ yellow ║
║ 3 ║ SIGNAL ║ Fan RPM         ║ green  ║
║ 4 ║ PWM    ║ Digital Control ║ blue   ║
╚═══╩════════╩═════════════════╩════════╝

Since my DC motor doesn't have a PWM input, I thought of using an ATmega328P in my custom board to read the PWM output of the fan header -- pin 4 -- so that I can use a motor driver to control my motor's speed.
However, I'm not sure how I should read the PWM signal from the motherboard.

What is the HIGH voltage level of PWM output?
Do I need a voltage divider resistor for it?
A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.
Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
Can the ATmega328p handle this frequency range?

I prefer to use Arduino's bootloader with the wiring library, but if you have AVR-specific examples that I could follow, I'd appreciate it.

The PWM signal controlling the fan is allowed to be from 21 to 28kHz.  The pulses for the RPM indicator are simply one (or two) pulses per rotation.  Assuming 10000RPM (insanely high speed for a fan) and two pulses per rotation, you only get RPM pulses at a little over 300Hz.  Those can easily be read by an Arduino.

But, not neccessarily using the "pulse" command.  That gives you the width of the pulse, but not the time between pulses.

Should I use pulseIn() function for the 25kHZ (21~28kHZ range) PWM output?
  Can the ATmega328p handle this frequency range?

No, and No; 1/25000 = .000040 or 40 microseconds (μS) and the documentation for pulseIn() says:

Works on pulses from 10 microseconds to 3 minutes in length

However the PWM frequency is the maximum on time, at 50% you will have a square wave that is HIGH for 20 μS and low for 20 μS. pulseIn will not work if the PWM duty cycle goes below 25%
What you want to do is put an 'accumulator' (an RC filter) between the PWM output and an analog input pin, and read the voltage off of that.
However since you want to

... control a DC motor's speed using the PWM output from my motherboard header

and the fanspeed header is already designed to do this, you just use the PWM signal to drive a transistor that drives the motor, the motor itself will act as an accumulator here; no micro controller needed!

... so that I can use a motor driver to control my motor's speed.

you will need to generate an extremely similar, almost certainly identical, PWM signal to drive your motor controller/driver

A source for the fan control specifies this to be 5.25V at maximum, but since I haven't tested it out myself, I don't want to risk feeding a 12V signal to my microcontroller's input lines.

Trust your documentation or test it if you don't trust the docs!

+1, Thanks for the well-explained answer, your solution makes sense! Although in addition to driving a motor, I still would really like to read the PWM output with something and feed the data to my microcontroller, so I can for instance display it. Is there a way I can achieve this digitally instead of using an RC filter?

@DavidRefoua analogRead(...) will return a value between 0..1023; where 0 is 0V and 1023 is 5V; the RC filter is to stabilize the voltage so the ADC can read it.


text:
Reading multiple DI pins in parallel as one byte/word
I need to capture a single parallel 'snapshot' from a 10-bit shaft encoder. I understand that I can read individual bits and shift them into position, but any given input pin might change while reading the bits sequentially, which would give an bogus value. In fact, given the asynchronous nature of the device this is guaranteed to happen on occasion.
I've read hints that it might be possible to combine pins into a 'port' for this purpose but I can't find any examples. Is this ability available only on certain processors? Or is there some way to latch the input pins while scanning them into a pair of bytes, to avoid them changing while I read?
If not I suppose I could use external latches but I'm hoping to avoid additional hardware.
It did occur to me that I could sync readings using an ISR triggered by a change in the LSB, but alas, this encoder outputs Gray code. :(

Which encoder? It seems odd you have to read all bits at precisely the same moment. You haven't said which Arduino you have but most of them are 8-bit processors so the maximum you can read atomically is 8 bits.

@NickGammon It isn't so odd, it's just asynchronous. I didn't specify which Arduino in case there are only some that support this, but I'd lean toward the Uno. I realize that with 8-bit ports I'd have to make two reads but I can handle the possibility of data smear with only two sequential reads as opposed to ten.

What encoder? Link to datasheet?

@NickGammon Sorry, but I don't see the point. I'm not asking anyone to diagnose at a different level or to solve any problems. It's a fairly simple question about reading data in parallel which could have many applications. Maybe we could forget the encoder and think of it more generically...?

If you would like to read multiple inputs, you can access port register directly. For 8 bit AVR:
DDRA = 0;            // set pins A0-A7 as input, modeInpit() in Arduino
uint8_t data = PINA; // read all A0-A7 inputs (8 bits)

To read more than 8 bits, you need 32 bit ARM based MCU/board like Arduino Due, other Atmel SAM, STM32Fxxx MCU etc. For STM32, there is Arduino like IDE available - http://www.stm32duino.com/
Even on 32 bit MCU you can read only 16 GPIO simultaneously (GPIO registers are 32 bit but handles 16 GPIO).

Moving over here... the reason I'm asking about examples is that what I've read is inconsistent. Some docs, including the two you reference, use different names for the port registers. Is there a "port A" and a PINA instruction? Not in most docs, which say that "port C" is for the analog pins and PINC reads them. Also, you reference "GPIO_xx designations" which I can't locate in the docs I have, as a way to limit ambiguity. Any docs for that syntax?

in AVR world, PINA and PORTA are both REGISTER names; they refer to same physical GPIOA (general purpose input output) pins belonging to A register (pin might designated as PA or GPIOA); for reading PINA is used, for writing PORTA register is used; so they are kinda aliases; same goes for PINB/PORTB, PINC/PORTC etc; exact physical pin and function (mostly) different on every MCU, so this is where the datasheet is needed; On Atmega328 UNO, PINC/PORTC (PC) are analog inputs (while on Atmega128 it is digital); GPIO is kinda universal naming for physical pins, IMHO it is preferred

Nice drawings here for some Arduino GPIOs

I'm sure time has already passed for this persons project. But for those visiting this page for whatever reason (mine was different than the information here) here is a solution I would implement. Also this is assuming the individual is not willing to use a latched external buffer where they can read from it however they need to. Simply split the total pins among 2 registers making sure the following

The pins used are in sequential order to both the MCU and the encoder (gray coding will require some thought to this).
Group as many on a single register as possible and this will be the low order value.

Read from the low order value first (the one that will be changing at the highest rate). Then read from the high order value (where it will be far less likely to change between the low order and the high order read). You need to understand bit masks and bit shifting to do this...
uint16_t nEncoder = (PINB & 0x1F);   // Example if your 5 pins are the low ones on PORTB
uint16_t nEncoder = ((PINB & 0x7C) >> 2);  // Example if your 5 pins are 6:2 where you pull your set of pins off of PORTB then bitshift them down into their proper place.
then you read in the high order part
nEncoder |= ((PIND & 0x1F) << 5);  // Example if your 5 pins are the low ones on PORTD. However you pull them off of the next port, you will need to make sure you bitshift them into the upper 10 bits of nEncoder to get your final value.
In the above, you can see that the more bits (pins) you can use on your first register (port), the less likely your second read will have a pin change.
Gray coding will be different than binary. The above example assumes binary where the high order bit will change the least and the low order the most. Gray coding is specifically used because of how minimally the bits change in-between each number change (i.e. they are suppose to only have 1 bit change per number change no matter the number rather than 10 bits change when a binary count rolls over - i.e. it minimizes this exact problem). So for the original poster, most of this should be irrelevant (since they said they were using a gray code encoder).
But for those seeking an optimal solution (for binary counters or just because) where they cannot stick all pins on a single port. Splitting it between two registers with only two reads will optimize your read time and minimize the pin change possibility.

Without knowing the encoder in question (which you seem extremely reluctant to disclose for some reason that I have trouble understanding) it is hard to give a good answer. However ...

The 8-bit AVR processors can only read 8 bits atomically. This is indeed called a port. The Atmega328P (used in the Uno) organizes its I/O ports as ports B, C and D (I don't know where A went).
Exposed on the board are PORTB (bits 0 to 5), PORT C (bits 0 to 5) and PORT D (bits 0 to 7) - that's 20 pins in total.
Thus, port D is the closest you will get, as you could read 8 bits at once. However having said that, two of those bits are used for serial I/O so you couldn't use the serial hardware at the same time.
To read all of port D you could just do this:
byte foo = PIND;

(For inputting it is PINx, for outputting it is PORTx).

What could help is an I/O expander such as the MCP23017.

I'm hoping to avoid additional hardware

Well, that's a pity.

I'm a tiny bit surprised that the device doesn't support some sort of "latching" of the data which gives you a finite time to extract the information from it. However without reading the datasheet I can't comment further.

It's not reluctance to disclose, it's a desire to avoid distractions. I know the hardware and how it operates; I'm constrained to use it; so the problem domain is 'reading data in parallel'. Thanks for addressing that, and for the pointer to the I/O expander.

Given the answer from @Flanker, would it be possible to combine a read of PORT D (which I gather uses the digital pins) with a read of PORT A (which I gather uses the analog pins) to get a 16-bit wide value in two reads?

I know the hardware and how it operates; - you might, I don't.

... with a read of PORT A - where did you find PORT A on the datasheet? I can't spot it.

it's a desire to avoid distractions - distractions like the people who are trying to answer your question knowing what hardware you are talking about?

I didn't find PORT A, it came from @Flanker's answer, unless I misread him. Is it not possible to do what he shows?

you might, I don't  No need to get shirty, it's not intended as an insult. I'm too well aware of the tendency for well-intentioned and knowledgeable folk to want to "solve the problem" instead of "answer the question", on the (sometimes reasonable) assumption that the questioner doesn't know what he really wants.or needs.

@Jim, there is register PINA (port input) not PORTA (which is port output) in my answer. BTW bad register designation from ATMEL, easily confused with (physical) port/pin meanings (for these better to use GPIO_xx designation)

@Flanker - Thanks, I confused the two by thinking of the generic term "port". If you can point to any docs or example code I'd appreciate it.

@JimMack Please check Direct port manipulation, also How to access IO ports and ultimately ATmega328 datasheet :)

I mean, you could look up the port and the pin in the port and read in the portByte. This example does work:
//given two GPIOs on a port(PortC) eg: 12(right button) & 13(left button)
byte portByte = (*portInputRegister(digitalPinToPort(rightButtonGpio)));
rightButtonPinHigh = portByte & (digitalPinToBitMask(rightButtonGpio));
leftButtonPinHigh = portByte & (digitalPinToBitMask(leftButtonGpio));

However, in my experience, your output will look pretty much the same as if you had done two sequential Arduino blessed digitalRead. I suppose you might (in the example above) get the leftButtonHigh value 1 instruction ealier, but I don't know if the register can even update at that resolution.

digitalRead() can be super slow, something like 100 CPU cycles. In contrast, reading a port input register is a single cycle. And the register updates at the CPU clock speed, i.e. 16 million times per second on an Uno.


text:
Allocation, initialization and scope
I realized I don't fully understand how Arduino code handles variable lifetime. My tendency is to keep variables in the narrowest scope (which I realize isn't as important in Arduino code, but, habits...). But how inefficient is this?
Given these possible variations:
 const int c1 = 2, c2 = 7, c3 = 9;

 void functy();

 int foo[3] = {c1 | c2, c3, c2 | c3};

 static int foo[3] = {c1 | c2, c3, c2 | c3};

 const int foo[3] = {c1 | c2, c3, c2 | c3};

  ....

In case 1, foo is both allocated and initialized each call.
In case 2, foo is allocated only once, but is it initialized on each call?
In case 3 I assume that allocation and initialization are done only once? Is that true?

Here's a pretty definitive list for you:
// Allocated once in the global area and assigned during
// program startup
int foo = 1;

// May not even be allocated - the compiler will most likely
// optimise it out.
const int foo = 1;

// Allocated once and assigned during program startup. Cannot be
// accessed from outside the file.
static int foo = 1;

// The static here has no real effect.
static const int foo = 1;

void function() {
    // Allocated in the stack each call and initialised each call.
    // Only accessible from inside this function.
    int foo = 1;

    // Allocated in the global area and initialized on the first call
    // of the function. Only accessible from inside this function.
    static int foo = 1;

    // May not be allocated at all. Only accessible from inside
    // this function.
    const int foo = 1;
}

Note that non-simple const values, things like arrays and strings, depending on the architecture (i.e., if it's a Harvard architecture or not) may be copied into a block of global RAM for simpler access. See PROGMEM in the Arduino Reference Manual for more information.

Thanks, that does seem to cover it. But in case 3 (const array) I assume the compiler can't optimize it away if later in the function the array is accessed through a passed-in variable index. In that case, is the memory allocated and initialized at compile time?

Yes. If it is PROGMEM then it is stored only in flash and special instructions are used to access it. If it's not PROGMEM it gets copied into the global ram area at boot time and that ram address is used instead.

JimMack, Arduino use gcc with LTO (Link Time Optimization), that means a further overall optimization. The Arduino Uno uses an Atmega microcontroller which has 32 registers. Although the gcc compiler does not use all those 32 registers for maximum optimization, locally declared variables might stay in registers and might not exist on the stack. I think the list by @Majenko is not "definitive" but rather "how it is supposed to work in theory".

@Jot That's pretty definitive. Pretty as in "fairly" (not totally), not pretty as in cute.


text:
Optimizing for speed using const, static, constexpr etc in a function
In an ISR I want to keep things quick. At the same time I want to limit variable scope. Storage space is not a factor.
I have this line:
const char trigs[] = "aAbBcCdDeEfFgGhHiIjJ";

When this is global, the resulting compile stats show:
Sketch uses 3418 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

When it's inside the function (to limit scope) I get:
Sketch uses 3470 bytes (10%) of program storage space.
Global variables use 431 bytes (21%) of dynamic memory.

The extra program space is 52 bytes, which is more than the size of the variables, so there must be extra code in there. That might be something to do with initialization checks... but why? Isn't a const already known? If there's a difference in where it's stored, why doesn't global variable space change?
If I prefix this as static const I'm back to the first behavior (3418 / 431).
So the immediate answer is just to use static const, I suppose. But I'm still curious what's going on. Can someone elucidate?

Can you show us your entire sketch?

@VE7JRO - I don't think that's practical. If it's important to see more context I could try to create a minimal sketch that illustrates this, but it seems pretty straightforward now. Is more context really needed?

with const char* trigs = "aAbBcCdDeEfFgGhHiIjJ"; the size of sketch is always the same for global or local with static or without static. if I call the function twice, the local version without static is better

To optimize for speed, add this in the top of your sketch: #pragma GCC optimize("-O3")

const char trigs[] is an auto - it's allocated on the stack at function entry time - and must be initialized at each invocation. The literal used to do that is stored in globals space, which is why the globals allocation doesn't change.
static const char trigs[] is allocated in globals space and used in place. The symbols' scope is still local, though, so trigs[] isn't visible outside the function.
So why does code space increase by 52 bytes? That seems a lot for copying a string from place to another. So I'll take a guess that the need to copy a string loads a library module that includes it and a few other functions as well.

OK, good info. I get that the stack allocation has to occur for variables, but what I guess I missed is that a const would be considered a variable in that sense. On reflection I guess it couldn't be done any other way.

this is not an answer. the question was: why, if it is const and the value is known at compile time, it is not optimized like static?

@Juraj - That was my real question, but with more reading I learned that const here doesn't mean what I naively thought. Here trigs[] is a variable like any other -- the const attribute simply makes it read-only. That's not intuitive to someone coming from a language that has 'true' constants, but it's how the spec is written.

@JimMack what I think you want is constexpr, which means the expression can be evaluated at compile time. Therefore it must be a literal, or depend only on constexpr variables.


text:
Decide on baud rate for a project using Arduino Uno R3
I am using an Arduino Uno R3 with the MPU 6050 to get motion data. Different example codes use different baud rates, without any proper explanation as to why.
So how do I know which baud rate is perfect for my project?

I most cases it doesn't matter!
In some cases the highest possible is preferred, as it prevents delays. That is when the buffer is full (when sending large amounts of data through the serial connection). As Serial.write will block until there is room in the buffer. In most cases this won't be an issue.
When running your arduino at slower speeds, you have to select a lower baudrate, or the micro-controller can't keep up.
When connection to other devices (e.g. GSM shield) using serial, that device may require a specific baudrate.

"at slower speeds" -- sounds weird :)


text:
Powering Arduino Uno R3 with battery packs
I am using Arduino Uno R3 with MPU 6050 for a personal project. MPU 6050 is being powered by the 3.3V supply pin in the Arduino board.
In order to make the sensor mobile, I ordered this battery, which has one power output of 5V 1Amp that I plan on plugging into the Uno's USB Power/Data Outlet.
I know that when plugged into the computer via the same USB port, around 5V 500 mA is supplied. I was wondering if someone could tell me, whether the 1A battery that I ordered would burn my board or not.
Also, is there a built in fuse inside this board?

Power sources like batteries and wall warts are voltage sources: they will deliver a fixed voltage, more or less. The current that they supply will be determined by the load you attach to them.
The "Amps" listed on a power supply is not how much current it will put out, it is the maximum current that the manufacturer has decided it can put out safely, without acting funny or overheating. So when you read that the USB port on a computer supplies 5V and 500mA, that means that it will supply 5V and up to 500mA. If you draw more than a 500mA current from your USB port, you would exceed the max current rating of the USB port. USB ports usually have an emergency shut-off mechanism built in, so they would just turn off if you drew more than 500mA out of them. I wouldn't try it though :). Your battery seems to have pretty similar safety features: "Super protection: overshoot, over-discharge, short circuit, over voltage, leakage, and many other protective functions".
If you had a 5V 20 Amp power supply, it will act the same as the USB port power supply, except it will be able to handle putting out much more current. As long as you don't exceed a voltage source's max current rating, the amount of current that a voltage source puts out depends on how much current the load draws, not on the voltage source. For example, a resistor will draw a current in Amps equal to the voltage supplied to it divided by the resistance (I=V/R), via Ohm's Law. For microcontrollers, you can often find their current draw on their datasheet: your MPU 6050 with the Gyro + Accel running has an operating current of 3.8mA when you give it ~3.3V. An Arduino Uno draws about 80mA by itself, though I don't think this includes the 3.3V power regulator on the 3V3 pin. So you're looking at somewhere a little over 84mA (=0.084A) in total. Your battery can supply 2.5A or 1A depending on which of its ports you use, so you are nowhere near exceeding the battery's max current rating, which is a good thing.
There are no fuses built in to the Arduino Uno R3. If you exceed its maximum current limitations, you will mess it up. There's a ruggedino available with more safety features if you're worried about frying your arduino. But as long as you're careful you should be fine with a standard R3.

The battery will be fine; the 1A rating is just a maximum, if your device only wants up to 500mA then it's got spare capacity, is all.
The battery appears to have in-built short protection etc, so better than a fuse..


text:
Make upload stuck on osx 10.10 bare-arduino-project
I followed the instructions in here, including to use arduino IDE v 1.0.5, but when I tried to make upload it stuck. I can upload it when using Arduino IDE.
Here is what I got:
  mkdir -p /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject
 /Applications/Xcode.app/Contents/Developer/usr/bin/make reset
 /Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/Arduino-Makefile/bin/ard-reset-arduino  /dev/cu.usbmodem1421
 /Applications/Xcode.app/Contents/Developer/usr/bin/make do_upload
 /usr/local/bin/avrdude -q -V -D -p atmega328p -c arduino -b 57600 -P /dev/cu.usbmodem1421 \
        -U flash:w:/Users/bagustrihatmaja/Documents/Projects/MyAwesomeProject/bin/mega328/mySecondProject/mySecondProject.hex:i

What did I miss?
I use: Bare-Arduino-Project, OSX 10.10, XCode 6.1, Arduino Uno, my Makefile

I'm the maintainer of the Bare-Arduino-Project, thanks for using it :)
Have you installed pyserial and avrdude?
To install avrdude just run brew install avrdude and to install pyserial, you need python installed, then you can run pip install pyserial.
https://github.com/WeAreLeka/Bare-Arduino-Project/blob/master/INSTALL.md#3-install-pyserial
Hope it helps :)
Next time, feel free to open an issue in the Github repo as it might also help others.
EDIT: my bad, I did not read your Makefile carefully!
the problem is with:
BOARD_TAG         = mega328
# it should be
BOARD_TAG         = uno


text:
SD Initialization Failing
I am using a SEEED SD Card Shield. Everytime I attempt to write the card, I get
When Using File> Examples> SD > CardInfo:
initialization failed. Things to check:
* is a card is inserted?
* Is your wiring correct?
* did you change the chipSelect pin to match your shield or module?

Or when using File>Examples> SD> Files:
Initializing SD card...initialization failed!

I even tried SdFat (IDE couldn't find anything), the "SD Library" by Adafruit (No change), and other things.
I'm using a Funduino MEGA 2560. Could that be the problem?!

Are you using an Ethernet shield as well? I have had problems with chip select line definitions on a Freetronics EtherMega2560 which is basically a standard 2560 with an inbuilt Ethernet shield.

I also use a Seeed Studio SD Shield, and used to have the same problem. To rectify this I have to insert the SD card into my PC and Format it. This almost always helped. If you have a card that has too large of storage, the Arduino will take too much time to check the full memory for information stored on it (initialize). Some SD card readers require a card of 2 gigabytes or less to work. Check the Data Sheet for this limit (if there is one). That should do it for you.

I spent ages failing to get my SD card working. Then installed an earlier version (1.0.8) of the SD library which fixed the issue for me.


text:
Why are pin 18 and 19 always HIGH?
I wired my switch just like in the default button program. I know it works because it works fine on other pins, just not pin 18 or 19. What am I doing wrong?
const int buttonPin = 18;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

// variables will change:
int buttonState = 0;         // variable for reading the pushbutton status

void setup() {
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
  // initialize the pushbutton pin as an input:
  pinMode(buttonPin, INPUT);
}

void loop(){
  // read the state of the pushbutton value:
  buttonState = digitalRead(buttonPin);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == HIGH) {
    // turn LED on:
    digitalWrite(ledPin, HIGH);
  }
  else {
    // turn LED off:
    digitalWrite(ledPin, LOW);
  }
}

The Uno only goes up to 13...

@ignacio And then there are 6 analog pins 14-19

Those are designated A0 through A5.

The analog pins function as digital pins number 14 - 19, with 14 being A0 and 19 being A5. I had hooked it up backwards.
This time we're gonna get funky
Everybody check your pins
Check check check check your pins
Check check check check your pins


text:
How do you benchmark an Arduino?
I am trying to run a test of the speed of an Arduino, and how it's affected by different temperatures. Does the following code assess this properly?
long num = 0;
long startTime = 0;
long endTime = 0;
int duration = 0;
String buffer;

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

void loop(){
  startTime = millis();
  benchmark();
  endTime = millis();
  duration = endTime - startTime;
  Serial.print(startTime);
  Serial.print(", ");
  Serial.print(endTime);
  Serial.print(", ");
  Serial.println(duration);
}

void benchmark() {
  num = 0;
  for(num = 0; num < 1000000; num++);
}

I'm using an Uno, if that matters.

Is there a particular reason why you're doing this?

I have an idea. An Arduino with GPS and real time clock, using this https://www.sparkfun.com/products/10710 . I'd replace for millis.

Thank you everyone for helping. I will post my results when the trials are completed.

No.
That is because millis will be equally affected by any frequency change (due to temperature) as the benchmark code. You would need an external clock source that is precise enough.
Note that temperature doesn't have that big an impact on crystal oscillators. Somewhere around 10ppm between -20 and +20 degrees C. The crystal itself is probably already 50ppm precision to start with (higher precision ones are more expensive).

Would it work to use a serial output to a PC, and having it measure the interval?

Maybe. But how precise is you PCs clock? How does Serial.print() affect your benchmark? What is the latency of the serial connection (I don't think you have a realtime OS)?

It doesn't have to include Serial. I'd just like to know how fast the Arduino is running, so I can determine the difference temperature makes.

20ppm is only a 0.002% difference. You'd need some pretty precise instruments to measure this tiny difference.

Ah, I see. I only need to be precise enough to see there is no large difference.

"Large" is relative. 20ppm is about 10.5 minutes over an entire year.

But then you'd have to have a constant temperature during this entire period :-)
What is it you want to achieve with the results? You can just look at the datasheet of the crystal to get an idea of what the difference would be.

I really just want to measure real world performance.

Quite simply, you cannot measure the stability of a device using routines that themselves depend on the device clock.
To do this properly you need an external measuring device that has a clock source at least 10 times more stable than the Arduino xtal. Most frequency counters would qualify.
Just set up a timer to provide a constant output frequency, and attach the counter to the pin.

First of all, compiler will just remove your loop, unless you disable compiler optimization, witch will invalidate your test.
Also don't worry about clock drift; as clock also run instruction, a faster clock will also mean a faster instruction cicle, so in the end if you calculate instruction/s the value will be valid.
Also serial communication slowness is not a problem as you calculate the value BEFORE sending anything.
Now, exactly what you want benchmark? In your case, you should put some instruction the for, like a variable++, and then print that sum (if you don't use it, again compiler will optimize all away)
But the you are bancharking for and ++. You may use a NOP() instruction, and then a float, a bitshift, a function call, and so on; you will find very different result, sometimes, sometimes compilator will trick your code.
Then when you'll have banchamark, against what will you compare your result?

Thanks for the answer. I'm not going to compare it to another device, but instead just graph speed vs ambient temperature.

Whoa missed that. Basically you want measure the clock drift, witch means you need to find a more precise clock. As far as i know there are very expansive thermo compensated clock. Pc clock may drift lot, they need to output fast clock, its stability may have relatively great error


text:
Delay not working in function other than loop
So I just got an Arduino and thought I would play around a bit.
However not five minutes in I already ran into a problem.
I tried programming a simple SOS blinking light sequence. To get rid of code duplication I refactored the on and off turning of the LED into functions and then again refactored a short blink and a long blink function which are expected to turn the LED on for a short time and then for a long time.
The problem is the delay in those functions is completely ignored.
int ledPin = 13;

void on()
{
 digitalWrite(ledPin,HIGH);
}

void off()
{
 digitalWrite(ledPin,LOW);
}

void shortB()
{
 on();
 delay(1000);
 off();
}

void longB()
{
 on();
 delay(2000);
 off();
}

void setup()
{
  pinMode(ledPin, OUTPUT);
}

void loop()
{
 shortB();
 shortB();
 shortB();
 shortB();
 longB();
 longB();
 longB();
 shortB();
 shortB();
 shortB();
 delay(5000);
}

My expected behavior would be that it does an SOS and then waits 5 seconds and repeats.
What really happens however is that it stay continuously lit for a second or so then turns off for 5 seconds.
Using
on();
delay(1000);
off();

In the main loop works so I guess it simply ignores the delays that are put into the other functions. My question would be why and ho do I fix it?
I know that I can use other timer function constructs however I really think this is something that should work by default.

You have no delay in between turning the LED off and turning it back on. Add one.

Ouch ... that was a really bad beginners error. That fixed it.

And it looks like your code sends 'H', 'O', 'S' (the first character is four short 4 blinks). Are you really seeing 'S', 'O', 'S'?

In addition to the other problems, you should have a break between letters. So, for example, "S" is not just dot-dot-dot it is dot-dot-dot-pause.
Example code below that implements pauses between letters, as well as longer pauses between words.
const byte LED = 13;

char * letters [26] = {
   ".-",     // A
   "-...",   // B
   "-.-.",   // C
   "-..",    // D
   ".",      // E
   "..-.",   // F
   "--.",    // G
   "....",   // H
   "..",     // I
   ".---",   // J
   "-.-",    // K
   ".-..",   // L
   "--",     // M
   "-.",     // N
   "---",    // O
   ".--.",   // P
   "--.-",   // Q
   ".-.",    // R
   "...",    // S
   "-",      // T
   "..-",    // U
   "...-",   // V
   ".--",    // W
   "-..-",   // X
   "-.--",   // Y
   "--.."    // Z
};

char * numbers [10] =
  {
  "-----",  // 0
  ".----",  // 1
  "..---",  // 2
  "...--",  // 3
  "....-",  // 4
  ".....",  // 5
  "-....",  // 6
  "--...",  // 7
  "---..",  // 8
  "----.",  // 9
  };

const unsigned long dotLength = 100;  // mS
const unsigned long dashLength = dotLength * 3;
const unsigned long wordLength = dashLength * 2;

// get a line from serial
//  forces to upper case
void getline (char * buf, size_t bufsize)
{
byte i;

  // discard any old junk
  while (Serial.available ())
    Serial.read ();

  for (i = 0; i < bufsize - 1; )
    {
    if (Serial.available ())
      {
      int c = Serial.read ();

      if (c == '\n')  // newline terminates
        break;

      buf [i++] = toupper (c);
      } // end if available
    }  // end of for
  buf [i] = 0;  // terminator
  Serial.println (buf);  // echo what they typed
  }     // end of getline

void dot ()
  {
  digitalWrite (LED, HIGH);
  delay (dotLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dot

void dash ()
  {
  digitalWrite (LED, HIGH);
  delay (dashLength);
  digitalWrite (LED, LOW);
  delay (dotLength);
  }  // end of dash

void setup ()
  {
  Serial.begin (115200);
  Serial.println ();
  pinMode (LED, OUTPUT);
  }  // end of setup

void loop ()
  {
  Serial.println ("Enter your message ...");
  char buf [60];
  getline (buf, sizeof buf);

  // for each letter
  for (char * p = buf; *p; p++)
    {
    char c = *p;
    char * sequence = NULL;

    if (c >= 'A' && c <= 'Z')
      sequence = letters [c - 'A'];
    else if (c >= '0' && c <= '9')
      sequence = numbers [c - '0'];
    else if (c == ' ')
      {
      delay (wordLength);   // gap between words
      continue;
      }

    // ignore not in table
    if (sequence == NULL)
      continue;

    // output sequence for one letter
    for (char * s = sequence; *s; s++)
      {
      if (*s == '.')
        dot ();
      else if  (*s == '-')
        dash ();
      }
    // now a gap
    delay (dashLength);
    }  // end of for each letter

  }  // end of loop


text:
Include my header files
let's suppose I have folder called AES, in this folder is file "AES.ino" where is code and folder "AESLib" what is library. In "AESLib" is file called "AESLib.h",
now when I try to include AESLib.h with
#include "AESLib/AESLib.h"

in my AES.ino, then Arduino command line tool complain that its not able to find "AESLib.h"
Where could be the catch?
Thanks

Have you installed AESLib as a library, according to the official instructions?

Hi Peter, including code as Arduino custom library is another approach and of course working.  But this is about including your custom code, without use "library approach"

Maybe this similar post is what you are looking for. In your case, you should use the path to the sketch folder as 'PROJECT_ROOT'.
Here's the link:
https://arduino.stackexchange.com/a/9575/7741
Hope it helps.

I have the same problem using the Arduino IDE 1.5.6 beta.
Adding the library(s) using the menu (Sketch->include library->something) makes it work until the IDE is closed.


text:
Interfacing arduino due to MAX5724 DAC
I have a MAX5724 8 channel 10 bit DAC's connected to a due, i believe i have it wired up correctly, however when  i try to write a value to it doesn't seem to output anything. Either i misunderstood the datasheet in the wiring or im writing incorrectly to it. Since i have the LDAC connected to GND i think i can just use the CODEn command on page 21 of the datasheet.
A link to the datasheet:
http://datasheets.maximintegrated.com/en/ds/MAX5723-MAX5725.pdf
Here the code i use to write:
#include <SPI.h>

#define CS 52

void setup()
{

  Serial.begin(115200);
  SPI.begin(CS);
  SPI.setBitOrder(MSBFIRST);
  SPI.setDataMode(CS, 1);
  SPI.setClockDivider(CS, 3); // 28MHz
  pinMode(CS, OUTPUT);
}

void loop()
{
  digitalWrite(CS, HIGH);
  digitalWrite(CS, LOW);

 byte msg1 = 0b11000010;
 byte msg2 = 0b11111111;
 byte msg3 = 0b11111111;

 SPI.transfer(CS,msg1,SPI_CONTINUE);
 SPI.transfer(CS,msg2,SPI_CONTINUE);
 SPI.transfer(CS,msg3,SPI_LAST);
 delay(4000);

}

wiring:
1 = 5V,
2 - 9 = OUTPUT,
10 = 5V,
11 = 5V,
12 = MOSI (middle pins),
13 = MISO (middle pins),
14 = SCK (middle pins),
15 = PIN 52,
16 = OUTPUT,
17 = 5V,
18 = GND,
19 = GND,
20 = GND,

I'm guessing the SAM3X didn't have enough DACs?

You swapped the MISO and MOSI. DIN should be connected to MOSI (Master Out Slave In). DOUT to MISO.

aye i realised my mistake, thanks a lot for you help


text:
Issue with adding a library: No such file or directory
I downloaded a Library called "Morse" which I got from the Arduino website:
http://arduino.cc/en/Hacking/LibraryTutorial
(all the way at the bottom of the page there is a link called Morse.zip)
And basically added the library. Then when I import the library, it is included to the sketch. However when I try verifying it, the following error message appears:

to see the image clearer you can right click it and click on "Open image in new tab"
Basically it says:
In file included from sketch_nov28a.ino:1:
C:\Users\Marko\Documents\Arduino\libraries\Morse/Morse.h:10:22: error: WProgram.h: No such file or directory
Now I tried reinstalling the Arduino IDE, I tried adding the library again as well as using the manual method that was stated in that first link above, and the error persists.
What I did notice was that in that second line of the error message, something caught my eye: "...\Morse/Morse.h:10:22:..."
There is a forward slash!(/) Now it seems weird to me that with would happen, especially given that all the other examples I saw of this error online have a backslash (\). This could be the problem.... but even if it is, how do I fix it? I tried going to preferences... does anyone know?

That library is for the older version of the Arduino ide. To fix this you need to open Morse.h and change WProgram.h to Arduino.h.


text:
Bluetooth shield/module for file transfer?
I'm currently working on a project that requires to display images on a touchscreen on my arduino. These images are neither stored in arduino nor any memory card. I want to be able to send the images via Bluetooth from an app and display it on the touchscreen. The problem is I couldn't find a good and solid Bluetooth shield or module that provide file transfer via bluetooth from an iOS app to arduino. If you can name a few bluetooh shields or modules that'd be great. In the thread below, someone claimed hc-05 works. Can anyone support that claim? Thanks.
http://forum.arduino.cc/index.php?topic=208306.0

Bluetooth shields do (mostly) not have built-in file-transfer support. For the reason  that Microcontrollers (mostly) don't have file-systems. You could however, write your own protocol, or directly store the characters you get and attempt to display that as an image.
For projects with: images/camera/filesystems/USB I would recommend using a raspberry PI.

where you successful in transferring text file over bluetooth to your android app???? if yes, then can you share your code?

I would use an HC-05 (or HC-06 - there seems to be little difference) - You will need to do your own file transfer protocol - for small images, zmodem or xmodem (usual file-over-serial) are probably completely overly complex. You would also need your own app for the phone.
Alternatively, you could use a network (ethernet or wifi) addon on your arduino - I think I read the Arduino Yun has built in ethernet and wifi.http://arduino.cc/en/Tutorial/WebServer has a webserver, this could be adapted to accept uploaded files. You can then use a webbrowser on your phone (or indeed anywhere else!) to send the files. If you want to send from outside your local network, you may need to set up port forwarding on your router (google: port forward) - the port you want to forwards is 80.

I'm going to go with the first approach but using a different bluetooth module. I'm already using bluetooth to talk with my iPad; i want to keep the cost down so I'd decided not to use WIFI. Thanks for the tips.


text:
Why is the loop() stopping?
I would like to move my servo motor (SM-S2309S) between random angles. In order to do so, I used this simple code:
#include <Servo.h>
Servo servoMain; // Define our Servo

// SM-S2309S angular speed
float speed = 0.12/60;

void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}

void setup()
{
   servoMain.attach(10); // servo on digital pin 10
   Serial.begin(115200);
   // move to center as a start
   servoMain.write(90);
   delay(1000);
}

void loop()
{
  // the previous angle, initially set as center (per the setup() call)
  static int oldangle = 90;
  // apparently 15 to 165 deg is a safe range
  int newangle = random(15,165);
  Serial.println(newangle);
  move(oldangle,newangle);
  oldangle = newangle;
}

It starts by placing the arm in the center (in the setup() function) and then should generate a random number (the new angle to go to), in a loop.
What I get is the initial position, then two moves (counterclockwise, then clockwise). The output on the serial console shows 22 and 64, which is consistent with the two moves.
Then everything stops. There is no error message on the console (I do not expect one to be, but I am not sure if there could be any feedback from the Arduino, being a complete beginner). What can be the reason for this stop, after two successful loops?

Does it STOP or it RUNS but nothing happens?

@DatHa: sorry, I do not really understand your question - should there be a feedback informing me whether the program still runs or has stopped/crashed? I saw the two random values for the angle output on the console (associated with the two movements of the servo motor) and then nothing else. How can i check if the program is still running or whether it has crashed (it should at least output the new random angles if it was still running, I believe).

flash a led in the background

@DatHa: ok, thank you very much for the hint. I will look at how to have the LED blink independently of the main loop() (I guess that this is what you meant, otherwise the output of the new angles on the console would have been enough, no matter of the servo moves or not)

Just a small mistake! Not much big of a deal :D
In the move function
void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * int(from-to));
}
suppose the values passed are 20, 35 then the last line would be 1000*speed*(-15) Which is negative therefore the arduino delay function converts the - signed bit to a very large unsigned number.
All you have to do is to take the magnitude of from - to ie |from - to | by calling the abs() function.
your move function would look like this:
void move(int from, int to)
{
  // initiate the move to the new angle
  servoMain.write(to);
  // wait for the movement to actually happen over the actual angle to move through
  delay(1000 * speed * abs(int(from-to)));
}
Just alter your move function or copy mine and you'll have no problem at all!

Ah! Thank you! I used int() when I actually meant abs() to exactly handle the case you mention.

Hahaha Pleasure is mine!

“The arduino delay function hangs as it does not allow negative parameter”  is absurd nonsense.  That is, it is wrong, wrong, wrong.  The parameter to delay() is an unsigned long, which is never negative.  When (as in your example) from-to is -15, the delay called for is about 2147483618 ms, or about 3.5 weeks.  So  delay() isn't hung, it's just doing what it was told to do.


text:
Can I control my Arduino using just a 2.4GHz Wireless Transceiver and a wireless Xbox 360 controller?
I want to control my Arduino using my wireless Xbox 360 controller. I've been looking up tutorials, and they all seem to recommend using a USB shield and the Xbox 360 wireless receiver.
I don't own either of those things, but I do own a 2.4 GHz wireless transceiver. Can I use it to listen to what buttons are being pressed on the controller? For example, if I press the A button on the controller, can I make an LED turn on?

Short answer is no, unless you have the machine and tools to do reverse engineering on the xbox controller proprietary 2.4Ghz protocol and you must have xbox 360 itself to see what goes on between Xbox 360 and the xBox controller. The time and money spent on these tools(hardware and software) aren't worth it.
The easiest way to do this is to buy the xbox controller receiver, Arduino USB shield and you can easily use your xbox 360 controller with your Arduino.

I contributed to this USB XBOX360 controller library to add multiple controller support, and to fix a couple of issues, including battery level indication. It worked fine for me with a cheap non-official version of the USB controller receiver, and a cheap version of the USB shield.

Would be good if you put this comment under the question. It will benefit the person that asked the question.

I don't know much about the engineering that goes into these kind of radios, but just being 2.4Ghz does not make them potentially compatible. xbox 360 controllers coexist with wifi and bluetooth without interfering, but they are all in the 2.4Ghz spectrum.
The xbox 360 controllers have some kind of proprietary frequency hopping system to avoid interference that you would first have find and reverse engineer before you could even get to the part about decoding the data, and your 2.4Ghz receiver probably can't match the 360 controllers even if you did know the pattern.
I'm relativly confident that it is practically impossible for that receiver to read 360 controller signals.

From the hardware side it should be possible but from the software it may not be easy.
Unless you find some documentation on the protocol that is used for communication between controller and receiver, you will need to decode the protocol (handshaking, commands, idle signals etc.) yourself.
Depending on the complexity of the protocol that could be rather frustrating.
I would recommend to do some research on the Internet first and see if there is material describing the protocol so you don't have to start from scratch.


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

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

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

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

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

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

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

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

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

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

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

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


text:
Can't power mg2639 cellular shield with battery
I have a SparkFun MG2639 cellular shield attached to an Arduino Uno R3.  I have had both the cell modem and the GPS unit working when the shield is powered from the Uno.  I followed the instructions on SparkFun's site to switch the shield to be powered by battery (cut SJ2, short SJ3) and connected a fully charged Li-ion battery.  I measure over 4.1 volts at the battery connection pads on the shield but the power LED isn't on and the shield isn't responding.  It looks as though it's not getting any power.  I also powered it from my bench supply with 5V and it shows no current draw.
Did I miss something in the conversion instructions?

Turns out the soldered short of SJ3 was not complete.  After resoldering the shield powers up as expected.


text:
Serial Data through Pin 13 LED
I am looking to utilize Pin 13 and an external LED to flicker as either the Rx or Tx LEDs do when Serial data is transferred through the Arduino. The existing code is all in real time to function with external buttons, so there can't be any delay.
I came across this link which seems useful, but I can't quite get it to read from Serial:
http://arduino.cc/en/Tutorial/BlinkWithoutDelay
Thanks in Advance

Software fundamentally does not do things without one or more clock cycles of delay, and the ATmega is not an FPGA which allows you to route signals to desired pins electrically.  If you want exactly the same data without delay, then don't use pin 13, but rather use the Tx or Rx pin.  If you merely want similar functionality, then either use a software serial on the pin to which your LED is connected, or write a custom Serial output routine which twiddles an LED pin every time it writes a character to the UART peripheral or services the UART Rx interrupt.

when you say "there can't be any delay" you are referring to the use of delay(ms); and other blocking code, and not "must happen the exact same moment" correct?

I think that pins 0/1 should blink similar to the TX/RX LEDs but not entirely sure. Might be worth it to see if that works and then let us know.

BrettM, your are assuming correct. When i connect and LED to 0 or 1, it's constantly lit, no change with data transfer, even though data is indeed flowing.

If you are going to use an external LED, then using software to make the LED blink when the RX or TX line is busy is a waste of your CPU.
Instead, simply connect the LED to the RX or TX line using a transistor as a buffer to prevent the current draw from messing with the serial signal.
To borrow an image from this answer to a similar question:

You can try omitting the transistor buffer, but the serial waveform will be altered, possibly to the point where data becomes corrupted. The transistor prevents the current draw of the LED and resistor from loading down the RX or TX lines.