text:
Question of proper usage for F Macro
Here are three use cases. Are all preferred or is the use of the F() macro pointless on some?
1.
Serial.println(F("some string"); // definitely useful here

2.
String str = F("some string");
Serial.println(str);

3.
int num = 5;
String str = F("some string with int ");
str += (String)num;
Serial.println(str);

Note that in case 3. you can just use two Serial.print commands like so: Serial.print(F("some string with int ")); Serial.println(num);

@Gerben are there any performance benefits to doing it this way?

You don't need to use a String object. And you don't need to have a variable for storing the entire string.

Any time String is involved F() becomes pointless. Avoid String like the plague if you value your memory integrity.

Does this apply to c++ in general? I just finished replacing String with char* through my Arduino program's code.

No. String is a custom Arduino class that does dynamic allocation. F() is also Arduino-specific. When you assign anything to a String it is copied into RAM (dynamically allocated in the heap), so it wastes RAM when you don't need to.

I have never used String in a program, and I never will use String in a program. It's all char * or const char *, the latter with PROGMEM when needed, though I don't often use platforms that need it.

@Majenko, Should I use F() everywhere or with Serial.print* only?

Use it whenever you have a string literal and a function that will take a FlashString. Anything that inherits Print is a good candidate.


text:
How can I tell how large my program is?
Scenario
When I upload my project via the Arduino ide I see this at the bottom:
Writing | ################################################## | 100% 4.14s

avrdude: 25698 bytes of flash written
avrdude: verifying flash memory against /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
avrdude: load data flash data from input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex:
avrdude: input file /var/folders/r4/s_j4c02s3wvcx6wy41__rnwh0000gp/T/build5447a2e9a95ee46ba2ad71abe5de02d6.tmp/SwatBotSpine.ino.hex contains 25698 bytes

Question
I'm uploading to an Arduino Uno, does this mean I have 32256 - 25698 bytes left?

Only if you're using a 512byte bootloader.

@IgnacioVazquez-Abrams Are there unos with a bootloader other than 512b? I suppose people could be using custom bootloaders..

Older Arduinos used larger bootloaders, then they switched to the smaller “optiboot”. I do not know when they did the switch, but it may well be after the first Unos started shipping.

Short answer: Yes.
At the end of a successful compilation (not upload), at least in ArduinoIDE 1.6.9, the final 2 messages look like:

Sketch uses 23,442 bytes (72%) of program storage space. Maximum is
  32,256 bytes. Global variables use 1,093 bytes (53%) of dynamic
  memory, leaving 955 bytes for local variables. Maximum is 2,048 bytes.

In this case, 8814 bytes of flash remain unused, and 955 bytes remain for the use of the stack and the heap, combined.

I see it now. I was looking in the avrdude messages but the sketch info is right before that.

source: Stack Exchange

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

sort: votes


text:
Pros and Cons of using a non-pointer class object
In this example I have an one object which uses a pointer and one object which does not.
class MyClass {
  public:
    void myMethod() {
      // do nothing
    }
};

MyClass* mc1;
MyClass mc2;

void setup() {
  mc1 = new MyClass();
}

void loop() {
  mc1->myMethod();
  mc2.myMethod();
}

Is one implementation better than the other? Why?

Are you looking for an answer from an Arduino/small scale embedded programming perspective or general C++. "new" implies using a heap and pointers implies using indirection (which is slower but may be used for dynamic binding, e.g. redirecting mc1 during the execution of the program to another instance such as mc2; "mc1 = &mc2").

@MikaelPatel That's a tough one. I would love to hear both sides if you have the time.

In this situation, where you are just working with globals, the static declaration is preferred, although it makes little difference.
The static declaration (MyClass mc2) will reserve space in the BSS. The dynamic allocation (mc1 = new MyClass()) will allocate space on the heap at run time at the start of your sketch. Both are in pretty much the same area of RAM (the heap is directly above the static data area).
The only trouble starts to come when you want to free (delete) the object created with new. That can, over time, make a complete swiss-cheese mess of your heap which can cause memory allocation problems.
For that reason the dynamic method is shunned, but if all you ever do is allocate at the start and never deallocate then there is little practical difference between the two methods.

Fortunately I'm familiar with C style garbage collection as wall as ObjC retain/release. I assumed Arduino followed a similar suit so thank you for pointing out the effects of allocation.

It depends on what you are trying to do and partly a matter of taste but I tend to take this one step further when the class corresponds to a specific hardware resource. In this case you can use static methods exclusively to guarantee a 1 to 1 correspondence. Templates come to rescue when you want to bind a specific physical instance of some finite resource (e.g. one of the timers) and this can be further refined using specialization and traits (each timer has different characteristics).

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


text:
Answer power IN from two sources
Items:

Arduino Uno
Laptop
7.4V 2s LiPo Battery
Neewer 30A ESC

Scenario:
The LiPo powers the ESC while the Laptop USB powers the Arduino. If I unplug the USB from Arduino is loses power (obviously) and when I plug in the ESC to the arduino I get power again to the Arduino. I need the USB plugged in to receive Serial information from the laptop and I need pow+gnd plugged into the Arduino or else I get a lot of PWM noise rendering my ESC useless.

ESC is 5V
USB is 5V

Question:
This is my due diligence to not blowing anything up. What is the safest way to plug in power from both USB and the ESC? Same voltage, difference sources. Or can I just connect the grounds and call it good?

Connecting the grounds would work.
You could also connect the 7.2V lipo to the Vin pin on the UNO. The UNO will automatically switch from USB to Vin, if it's present.


text:
How can I get analog-in reading from Digital-PWM-out on the same board?
I have a wire going from PWM4 to A0 but I don't dare turn on my Arduino Mega in case this is incorrect.
PWM4 will eventually go to an analog device but I want to make sure the read value is what I expect it to be. Am I okay to proceed with my current setup or do I need to throw in a resistor / conversion?

A resistor/capacitor conversion?  Yes.  An RC filter on PWM4 could smooth out the square wave.  If you don't, you'll get the 0 or the +5 values into A0, depending on the sample time.

@DaveX So with the correct sample time would my analog pick up the pseudo analog signal?

No-The default analog sample time (<0.0001s) is short compared to the PWM frequency 490Hz, 980Hz , so the value you read at any particular point in time will be probabilistic.  If you average enough samples of the binary +5 and 0V PWM output, it would approach the analog value statistically.  Or you could use an RC filter to make an exponentially-weighted moving average in electrical-analong component space, rather than programming space.

You are fine by doing that, but you won't get what you expect.
A PWM signal isn't an analog value. It's a series of pulses, the duration of those pulses is set by the (not accurately called) analogWrite. So sometimes the value is 5V and sometimes it's 0V. You need to get the average value by adding e.g. an RC-filter.
Another option is to add a proper DAC (digital to analog converter) chip to your circuit.

If I understand you correctly, I need to set the correct on/off interval for my pwm out before I can get the desired value for my analog read but this is otherwise doable and safe?

No, you set the on/off interval ratio using analogWrite. The average voltage will be proportional to the ratio. However to get the average voltage you need to create a filter average the 0V and 5V signals going out of the PWM pin.


text:
What's with the debug error messages, like VMDPE_1|1_VMDPE?
I'm using visual micro for visual studio, and I understand this kind of thing is caused by conflicting serial data when I try to read and print to the main serial at the same time, right?
Well, I need to read serial data from the main serial on my Mega 2560, and then I need to see it on my LCD screen, which is controlled by the board via SPI. I know I can use those two at the same time because I'm doing it with my transmitting arduino and I can see that it's transmitting correctly.
When I try to view my serial data in the serial port, I get nothing but a stream of these error codes, or whatever they are. They generally look like this: VMDPE_1|1_VMDPE. Usually there are some numbers in there too, like: MDPE_1|2571143_VMDPE. I sort of expected that, since you can't read and write at the same time on one serial. But that would be fine, because my project is not going to be plugged into a PC anyway.
So of course I try to pipe my data directly to the LCD screen so I can plug my recieving arduino into external power and not have to see the error messages, which I thought were coming from the debugger of my compiler. Here's my code:
//on the receiver side

#include <stdint.h>
#include <TFTv2.h>
#include <SPI.h>

char incoming[3];

void setup() {
    Serial.begin(9600);
    //TFT_BL_ON;      // turn on the background light
    //Tft.TFTinit();  // init TFT library
    //Tft.setDisplayDirect(DOWN2UP);
    //TFT_BL_ON;      // turn on the background light
    //Tft.drawString("INCOMING:", 20, 301, 3, RED);
    Serial.println(incoming);

}

void loop() {

    if (Serial.available()) {

        Serial.readBytesUntil(',', incoming, 3 ) ;

        //Tft.fillRectangle(64, 236, 45, 165, BLACK);

        //Tft.drawString(incoming, 65, 235, 4, WHITE);
        Serial.println(incoming);

    }
}

But nope! I get the same error codes on my LCD screen! Even worse, now they seem to have screwed up my zigbee module! I took it off the board, plugged it into my computer, and now the XCTU utility is reading all sorts of messed up values that are total nonsense. Somehow, this seems to have overwritten the zigbee's actual SERIAL NUMBERS!!! What are they now? Take a guess!
Serial number high: E_1|2571092_VMDPE
Serial number low:  MDPE_1|2571143_VMDPE

Your incoming buffer is not big enough to handle the data that you're giving it. Cutting away the comments from your code:
char incoming[3];

This declares a buffer for two characters, allowing for the (required) 0 on the end. println() needs to know when to stop printing characters: it does this when it sees a NUL (0) character.
Serial.readBytesUntil(',', incoming, 3 ) ;

You're passing in that you want to read 3 characters - but that completely fills incoming, leaving no room for the trailing NUL (0).
Serial.println(incoming);

This then prints the first character, the second character, the third character... then the 4th, 5th, 6th, 7th etc. in memory until it finally reaches a NUL and then quits.
What you call "debug messages" are actually printed gibberish in memory... To fix it, you need to make incoming larger.
Also, it's a good idea when using buffers like this to use the sizeof() function, as follows:
Serial.readBytesUntil(',', incoming, sizeof(incoming)-1 ) ; // Note the -1!

Thanks!I see what you mean about the buffer overflow.Last night I loaded both my arduinos using "start without debugging", and the output changed to something more like numbers, bit also gibberish.
I do believe the "VMDPE_1|1_VMDPE" stuff is some kind of VisualMicro-specific error related to debugging.I have a big sketch, and it prints on the serial every time I flash the board. I read about it here: http://www.visualmicro.com/forums/YaBB.pl?num=1365950696/0
I still have no idea how it got into my sketch while not hooked up to PC, or how it invaded my Zigbee!

"I still have no idea how it got into my sketch while not hooked up to PC" Because Visual Micro's debugging works by adding a bunch of hidden serial prints to your sketch. Once you upload the sketch to your board they will be in the flash whether it's connected to your PC or not.

I had the same problem. The problem seems to come from AVR Studio serial debugging. If you turn off the serial debugger the problem will go away. Remember to also turn of "Automatic Software Debugging (Release/Debug)", as shown below.

I have seen the same messages, using VS2017 and Arduino Unu and Visual Micro. Messages start with "DPV..." or "VMDPV...".
The solution is to upload the sketch to the Arduino using Release mode. Then the hidden debug serial prints that Visual Micro seems to put in are gone.

This might hide the unwanted output, but it is not a solution the the question.

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


text:
Can anyone help me spot where my buffer overflow might be occuring?
I'm using dtostrf() to transcribe a float into a string for my touchscreen. I'd leave it as a float, but my screen orientation library function only works with a string.
So I have a char array, then a float value. then dtostrf().
char buffer[6]
float X; //changes each loop with incoming sensor data from pixy camera
float thingposition = X * .0064  //float calculations are performed.

void loop(){
Camera.Get_X();   //retrieves X from the camera. waits until X has been recieved via UART serial
dtostrf(buffer, 5, 2, thingposition) // writes float to string with a controled decimal place and all that - dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
Tft.drawString(buffer, 70, 215, 5, WHITE);   //print output to screen
}

Note that this is a simplified version. In my code I also have methods for overwriting my last string value on the LCD when the new one has changed.
I also have several "if" conditionals that control whether I write the buffer value to the screen or instead send an error message. Those things do not seem to be causing me problems though, except to say that my buffer overflows only occur when I cause the sensors to flip the conditionals at just the right interval.
For example, when I place my hand in front of the camera, that triggers the error message. Take my hand away, and then the number "thingposition" is printed to the screen. But if I time my hand just right, the buffer overflows and numbers loop across the screen. Usually this freezes the whole sketch. The best I can figure is that since dtostrf() does not check bounds, and since the calculated float values can be longer than the buffer has room for, that sometimes dtostrf() tries to write too many digits to the buffer. Something timing-related seems to trigger the problem, but what I need is some way to prevent the overflow in the first place.
I've tried rounding "thingposition" to a certain number of sigfigs, but I can't seem to truncate it at the desired decimal point. That shouldn't matter though, since dtostrf has controls for the minimum total length including the decimal point, as well the number of digits after the decimal. I also tried making sure that the last byte in my char array is null by adding this right after dtostrf():
stringval[5] = NULL;   //make sure buffer is null-terminated to prevent buffer overflow

I've tried doubles, different ways of rounding, and anything I could find, but the problem has persisted for several weeks and a few steady days worth of searching for a solution. I'll be glad to provide further information if anyone has any ideas on what to try. Thanks everyone.

If thingposition is 100000 or more, then dtostrf() will use more than 5 characters to represent the number. It will use no more than 2 decimal digits (less if they won't fit in 5 characters), but it won't compromise the main number to fit it inside your buffer. If you don't want that, clip the number to less than 100000

The problem with using "simplified code" is that your 'simplification' may not have captured your problem. But I will take your code as given and assume that it's correct (which I'm afraid it isn't).
var
    char buffer[6]  // Won't compile - no semicolon (';')
    float X;        // Uninitialised value - could be 1000000000000
    float thingposition = X * .0064 // No ';', and .0064 of 10000000000 is huge!

void loop(){
    Camera.Get_X(); // Should this be "X = Camera.Get_X();" ?
    dtostrf(buffer, 5, 2, thingposition)  // No ';'. You NEED to recalculate thingposition!

If the above code is a good representation of what you've got, you seem to be assuming that you define the formula once (in the thingposition line), and it automatically applies that formula, like Excel, when you change its input, X. Sorry, programs don't work that way.
Once you calculate thingposition, it becomes independent of where it came from. If you change other variables, thingposition kees its value until you explicitly change it.
How do you fix it? You recalculate thingposition every time:
var
    char buffer[6];      // Hopefully big enough - see below
    float X;             // Used by Camera.Get_X()
    float thingposition;

void loop(){
    X = Camera.Get_X();        // Get X from Camera
    thingposition = X * .0064; // Calculate thingposition
    dtostrf(buffer, 5, 2, thingposition);

Note that dtostrf() will try to obey your size parameters, BUT. If the float is larger than your maximum size, it WILL print out the full number anyway. That is, if thingposition is 1000, it will produce 5 characters all right: "1000.". But if it's 1000000, it will produce "1000000" which is seven characters. You need to ensure that buffer is big enough to handle larger numbers than you expect.
Do the maths. If X is guaranteed to be between 0 and 255, then multiplying it by 0.0064 will result in a maximum value of 1.632, so the above dtostrf() woud produce " 1.63". No problem!

I'm interested in your comments on dtostrf() and buffer size. Not much of the other stuff applies, because of course I calculate at every loop. Apologies for not including everything, but I didn't want to take up all your time and bore you. Also it's proprietary. I didn't think much of laying out the whole thing because I had assumed anyone would overlook all that and focus on the buffer, assuming all else is functional.

My floats are almost always guaranteed to be a little longer than the buffer after the calculation is performed. I'd like to cut them off at the appropriate digit after rounding if I could because I think that would solve the problem. dtostrf() seems to handle it well... until it doesn't.

And there's your problem. dtostrf() won't "lie" in its output. Rounding's OK, but truncating orders of magnitude? Like I said: either increase the buffer size going into dtostrf(), or be explicit and truncate the number first: do a thingposition = fmod(thingposition, 100000); to knock off the hundred-thousands-and-above digits that won't fit. Then the onus is on you rather than the function!

I'm a little confused. You said that dtostrf() would produce "1.63" from     1.632. But you also are saying that dtostrf() can't lie to adjust its output. Is that a contradiction? And I'm not sure what you mean by "truncating orders of magnitude". the float value 1.63 is the same magnitude as 1.632, it's just been reduced an order of precision. Also, the function fmod() does not seem to work for truncating ending digits, and I can't find a function that does. In fact, your example seems to add more digits.
`Serial.println(fmod(x, 100000),24);`

output: `9.123456954956054687500000`

That is, if x = 9.123456789

I said "dtostrf() won't lie in its output". By "lie" I meant outputting "21.01" if the number was 987654321.012345 - which some people expect when they ask for ",5,2". I went on to say that rounding's OK, since that's (one of) its jobs. I then went on to say that if you wanted to print out "21.01" for that large number, you needed to chop off the higher digits yourself, which is what fmod() does - fmod(f, 100); If you're having decimal rounding problems, you have yet to state what you're getting versus what you expect...


text:
Solid-state relay boards: Can they be used to switch audio signals?
So I tried to use one of those widely available solid-state relay boards to switch some 12V power, and I found out the hard way that they are not designed to switch DC current. They use some sort of variac that only works when AC voltage is applied. Do I have that right??
So I got this other project where I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this. If I send audio through these relays, is it going to work as planned? Will I suffer any noticeable delay, signal degradation or attenuation?

no, it will sound terrible because of the internal capacitance, junction voltage drops, the SSR's lock-on state, and DC biasing (half-wave). they make cheap audio muxer ICs like the 74HC4051 that would be perfect. If you want cheap and available, BJTs can be used to some extent.

That's a nifty little breakout board. And much less bulky! I like it.

a breakout board will be 10X as expensive as the bare DIP, but that's still not much ;)

A solid-state relay seems to be the totally wrong tool for the job. The image you posted shows it is intended to switch 240V AC. So it is designed to switch something like a 240V light on and off.
Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals.

I need to multiplex some audio signals in a mixer board, and I was already planning on using those solid-state relays before I learned all this

The expression "when the only tool you have is a hammer, everything looks like a nail" springs to mind.
There are chips designed to multiplex analog signals (as I describe on this page). That would be closer to what you need.
However that chip (the 74HC4067) is a "choose one input from many" sort of design. It isn't going to let you fade one audio signal in or out (neither would the relay for that matter).

"Relays in general are things designed to connect one thing to another (eg. power to a light). They just aren't designed to switch audio signals." I absolutely agree for SSRs. But, for an electromechanical relay why not? There's plenty of relay switching action happening in Audio Video Receivers during source selection.

@EnricBlanco: for turning a source on or off they would be fine, but for mixing they are useless.

Yeah, I'm not mixing, I'm selecting signals by turning them on and off.

And contrary to Nick's assertion, any type of relay is a reasonable go-to for switching signals on and off. dandavis's recommendation to use the 74HC4051 is a much more practical solution though.

The link I gave specifically mentions the 74HC4051 multiplexer / demultiplexer. In fact it was about it. I don't know why you said the "74HC4051 is a much more practical solution" when that was the exact solution I offered to you. The 74HC4067 is its 16-channel cousin, which would be useful if you need to multiplex 16 signals.

No. SSRs are completely wrong for switching audio.
Consider using the CD4066 chip. But be aware that will mean you'll need to ask a whole bunch of new questions I'm sure.
I hope this answer helps you.


text:
Odd Serial behavior with Uno
I'm not understanding what's going on with my Uno. I have a very simple piece of code. no peripherals are connected. Just a bare genuine uno. I program in VisualMicro for Visual Studio.
void setup()
{
    Serial.begin(115200);

    char stringy[9] = { 0x7E, 0x00, 0x05, 0x08, 0x01, 0x44, 0x33, 0x04, 0x7B };

    for (int i = 0; i < 9; i++) {

        Serial.print(stringy[i]);
        //delay(300);
    }

    Serial.println("");
    Serial.print("done");
}

void loop()
{
    while (1) {  }
}

Without a delay of around 250msec or greater in the for loop, I don't get all the characters. In fact, without the delay, the code doesn't even finish executing. I only get the first character '~'. It doesn't seem to matter what my baud rate is.
This code runs fine without a delay on my Nano. What could possibly be the issue?

Your program works as expected on my Uno.

Weird. You get the whole array of gibberish in your serial pane? I'm starting to think its just a difference in compilers.

Not the serial pane (I'm not using the IDE). I typed stty -F /dev/ttyACM0 raw 115200 && hd -n 15 /dev/ttyACM0 on the Linux console and got 00000000  7e 00 05 08 01 44 33 04  7b 0d 0a 64 6f 6e 65     |~....D3.{..done| (hd is a hexdump utility).

You are printing the unprintable.
Do you think it should print:
~0581,34{

or
0x7E 0x00 0x05 0x08 0x01 0x44 0x33 0x04 0x7B

What you will get is
tilde
null
enquiry
backspace
start of heading
comma
three
end of transmission
open brace

I think you can call
Serial.print(stringy[i], HEX);

To see the number you put in come out.

I expect it to come out gibberish, like this: ~    D3 {  (three of those white spaces actually show as strange characters that I can't paste here.) The actual content of the array is an Xbee AT command, and I designed this as an experiment to see why it's not working.
See, when I use the Xbee library with the nano and monitor the serial output without the xbee connected, ~    D3 { is what I see. But on the Uno, all I get out is ~. In this experiment I was trying to replicate the output with serial.print(), and the result is the same.


text:
Xbee AT Commands failing. Something wrong with Serial? Tx commands working fine
The Xbee API library is working fine for TxRequests on my Arduino, but AT commands are failing every time. I've been at this for three days.
It seems that there is some sort of conflict happening with my hardware serial port, because if I try to repeat the command a second time (after a 3sec delay), I see that the 2nd transmission (which should trigger the "D_in" light on my Xbee shield to flash) never gets sent. Then if I try to load and execute the sketch again (this shield on the nano allows me to do so with the Xbee still plugged in), I get an avrdude error suggesting that my arduino serial is busy. My PC should be out of the picture here, since I have no Serial.print() functions and the cable is plugged into a wall adapter with power only.
Basically I get no response and the parameter I'm trying to change remains unchanged. I'm at a total loss for why this is not working. Heres my code:
#include <XBee.h>

XBee xbee = XBee();

uint8_t D3[] = { 'D', '3' };
uint8_t high[] = { 0x05 };/////for DI03 pin parameter
uint8_t low[] = { 0x04};////for DI03 pin parameter

AtCommandRequest AtRequest = AtCommandRequest();
AtCommandResponse atResponse = AtCommandResponse();

void setup()
{
    Serial.begin(9600);
    xbee.setSerial(Serial);
    delay(10000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

    delay(3000);

    AtRequest.setCommand(D3);
    AtRequest.setCommandValue(low);
    AtRequest.setCommandValueLength(sizeof(low));
    xbee.send(AtRequest);

}

void loop()
{

}

And in addition, here's the code for the Tx example that works just fine:
/**
* Copyright (c) 2009 Andrew Rapp. All rights reserved.
*
* This file is part of XBee-Arduino.
*
* XBee-Arduino is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* XBee-Arduino is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with XBee-Arduino.  If not, see <http://www.gnu.org/licenses/>.
*/

#include <XBee.h>

/*
This example is for Series 1 XBee
Sends a TX16 or TX64 request and checks the status response for success
Note: In my testing it took about 15 seconds for the XBee to start reporting success, so I've added a startup delay
*/

XBee xbee = XBee();

unsigned long start = millis();

// allocate two bytes for to hold a 10-bit analog reading
uint8_t payload[5] = { 0x41, 0x42, 0x43, 0x44, 0x45 };

// with Series 1 you can use either 16-bit or 64-bit addressing

// 16-bit addressing: Enter address of remote XBee, typically the coordinator
Tx16Request tx = Tx16Request(0x03, payload, sizeof(payload));

// 64-bit addressing: This is the SH + SL address of remote XBee
//XBeeAddress64 addr64 = XBeeAddress64(0x0013a200, 0x4105B41E);
// unless you have MY on the receiving radio set to FFFF, this will be received as a RX16 packet
//Tx64Request tx = Tx64Request(addr64, payload, sizeof(payload));

TxStatusResponse txStatus = TxStatusResponse();

int statusLed = 11;
int errorLed = 12;

void flashLed(int pin, int times, int wait) {

    for (int i = 0; i < times; i++) {
        digitalWrite(pin, HIGH);
        delay(wait);
        digitalWrite(pin, LOW);

        if (i + 1 < times) {
            delay(wait);
        }
    }
}

void setup() {
    pinMode(statusLed, OUTPUT);
    pinMode(errorLed, OUTPUT);
    Serial.begin(9600);
    xbee.setSerial(Serial);
}

void loop() {

    // start transmitting after a startup delay.  Note: this will rollover to 0 eventually so not best way to handle
    if (millis() - start > 10000) {

        xbee.send(tx);

        // flash TX indicator
        flashLed(statusLed, 1, 100);
    }

    // after sending a tx request, we expect a status response
    // wait up to 5 seconds for the status response
    if (xbee.readPacket(5000)) {
        // got a response!

        // should be a znet tx status
        if (xbee.getResponse().getApiId() == TX_STATUS_RESPONSE) {
            xbee.getResponse().getTxStatusResponse(txStatus);

            // get the delivery status, the fifth byte
            if (txStatus.getStatus() == SUCCESS) {
                // success.  time to celebrate
                flashLed(statusLed, 5, 50);
            }
            else {
                // the remote XBee did not receive our packet. is it powered on?
                flashLed(errorLed, 3, 500);
            }
        }
    }
    else if (xbee.getResponse().isError()) {
        //nss.print("Error reading packet.  Error code: ");
        //nss.println(xbee.getResponse().getErrorCode());
        // or flash error led
    }
    else {
        // local XBee did not provide a timely TX Status Response.  Radio is not configured properly or connected
        flashLed(errorLed, 2, 50);
    }

    delay(1000);

}

So it turns out that it was working the whole time. The problem was that that the values were not being written to the xbee, only changed. Hence, hen I would check the radio in XCTU, the values would have reverted to previous. I had no idea I needed to be calling a "write" function to save the parameters to the radio.

Just a thought from a point of ignorance.. When I use serial comm, I always use an interrupt watching loop.  When data hits UART, a data available pin throws an interrupt that causes the loop to read the input register.

That doesn't really have anything to do with Xbee AT commands, but I do like that idea for the rest of my project.


text:
I2C FRAM read/write is very slow. Taking over 500 microseconds per read, almost 500 per write
I've used the example code for the Adafruit I2C FRAM breakout board, but I've made it even simpler by just writing the same thing to each byte location and then reading them all off, doing nothing with the data.
I can tell it works because I can read off any byte and get the expected value, but the problem is that it works way too slowly. writing and reading 512 bytes takes almost a full half a second. This just won't work for my application, but I suspect there's something fundamentally wrong with what I'm doing.
I tried calling Wire.setClock(400000);, which supposedly is the maximum speed my Nano can drive an I2c slave at, but no matter what argument I input, the operation takes the same amount of time (498616 microseconds, within about +/- 20 microseconds).
I also tried calling Wire.begin(); TWBR = 10;, because I read that somewhere. But again, I get no difference. Here's my whole code- It's pretty simple
#include <Wire.h>
#include "Adafruit_FRAM_I2C.h"

/* Example code for the Adafruit I2C FRAM breakout */

/* Connect SCL    to analog 5
Connect SDA    to analog 4
Connect VDD    to 5.0V DC
Connect GROUND to common ground */

Adafruit_FRAM_I2C fram = Adafruit_FRAM_I2C();
uint16_t          framAddr = 0;

byte p = 55;   //any old value- just write the same thing into all locations

void setup(void) {
    Serial.begin(153600);
    //Wire.begin();
    //TWBR = 10;
    //Wire.setClock(400000);

    if (fram.begin()) {
        Serial.println("Found I2C FRAM");
    }
    else {
        Serial.println("I2C FRAM not identified ... check your connections?\r\n");
    }

}

void loop(void) {

    int i = 0;

    long a = micros();

    for (i ; i < 512; i++){  //write 512 bytes to the FRAM board
        fram.write8(i, p);

    }

    for (i = 0 ; i < 512; i++) {  //read 512 bytes from the FRAM board
        fram.read8(i);

    }

    long b = micros();

    Serial.println(b - a);
    Serial.println("");
}

You are running at 400000 bits per second, or 200000 per half second you say it takes.
You have about 1000 transactions (actually 1024 but for simplicity I will call it 1000)
200000/1000 = 200 bits per transaction.
Wire is blocking and not very efficient. So say it is actually only transmitting 25% of the time.

That's 50 bits per transaction. Now I don't know the protocol that chip uses, but if it's like the SPI chips it would need 5 bytes per transaction - 1 for the I2C address, 3 for the FRAM address, and 1 for the byte. With start, ack, etc call it 10 bits per byte.
That makes 50 bits per transaction.
So yes, half a second to write then read it all is perfectly possible.
The slowness stems from the fact that you are working a byte at a time instead of larger blocks of data in one transaction.

Now I  am at my computer I can take a look at the datasheet and get some more accurate numbers.
A write of a single byte requires 4 bytes in a transaction. That's 4 bytes, 1 start, 4 ack and 1 stop bit. So (4x8)+1+4+1 = 38 bits.
A read of a single byte, with "repeated start", requires 5 bytes per transaction, with 2 start, 4 acks, 1 nack and 1 stop. That's (5*8)+2+4+1+1 = 48 bits.
So for a read and write it's 38+48 = 86 bits.
Therefore you'd require 86*512 I2C clock cycles to transfer all 512 bytes in both directions - that's 44032 clock cycles.
At 400,000 bits per second it is 44032/400000 = 0.11 seconds, or 110ms of the time spend transferring data, not counting the time it takes to actually process and prepare the data, fill registers, look for status flags, etc.
If it is taking half a second then at 400,000 bits per second you have 44032 / (400000/2) * 100 = 22% of the time it's actually transmitting or receiving data over I2C.
So not a bad guestimate of 25% transmission in my original surmising.

Jeez, thanks for the breakdown on that. I wonder what the manufacturer had in mind to be able to do this, since the library only includes the single byte read and write functions.

The Adafruit library https://github.com/adafruit/Adafruit_FRAM_I2C has indeed only functions to write and read a single byte. You could add your own functions to write and read 32 bytes. I think that the FRAM is fast enough to keep up with the I2C write or read and I assume that the FRAM itself causes no extra delay.

The manufacturer provides many ways of reading and writing, not just single byte. Adafruit chose to only implement byte reads and writes for simplicity. Read the data sheet and control the chip without the crutch of a library to do more.

400kHz I2C clock, assuming at least 4k7 pullup resistors and very short wires, trying to write and read 32 bytes... that is hard to calculate, but 100ms is possible and perhaps 50ms. The Wire buffer is 32 bytes, that means when writing data already 2 bytes are taken for the register-address and 30 bytes are left for data.

@Jot - If I need two bytes for addressing, does this mean that I won't be able to write a 32 bit float?

You're mixing bits and bytes. You have 32 bytes of buffer space, which is 256 bits.


text:
Suddenly I can't compile any sketch. Not even a blink sketch that I compiled earlier
I use visual Micro for Visual Studio. Out of nowhere, I can't compile for any board. I tried a blink sketch for the nano, and I get intelisense red underlines for simple things like pinMode, digitalWrite, and Serial.print. Here's what I get for an output:
Compiling debug version of 'Nano_Trials' for 'Arduino Nano w/ ATmega328'
Build folder: file:///C:/Users/jf051e/AppData/Local/V.Micro/Arduino/Builds/Nano_Trials/nano_atmega328
Additional Defines: VM_DEBUG;VM_DEBUG_ENABLE 1;VM_DEBUG_BANDWIDTH_THROTTLE_MS 50;VM_DEBUGGER_TYPE_HARDWARESERIAL 0;VM_DEBUGGER_TYPE_SOFTWARESERIAL 1;VM_DEBUGGER_TYPE_FASTSERIAL 2;VM_DEBUGGER_TYPE_USB 3;VM_DEBUGGER_TYPE_TEENSY 4;VM_DEBUGGER_TYPE_UART 5;VM_DEBUGGER_TYPE_USART 6;VM_DEBUGGER_TYPE_USBSERIAL 7;VM_DEBUGGER_TYPE_TTYUART 8;VM_DEBUGGER_TYPE_NET_CONSOLE 9;VM_DEBUGGER_TYPE_Uart 10;VM_DEBUGGER_TYPE_COSA 11;VM_DEBUGGER_TYPE_CDCSerialClass 12;VM_DEBUGGER_TYPE VM_DEBUGGER_TYPE_HARDWARESERIAL;VM_DEBUG_BREAKPAUSE;
Architecture Tools: {runtime.tools.avr-gcc.path}/bin/
Sketchbook: file:\\\C:\Users\jf051e\Documents\Arduino
Sketch Include Paths
Include Path 'C:\Users\jf051e\Documents\Arduino\Nano_Trials'
Core Include Paths
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino'
Include Path 'C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs'
Library Include Paths (1)
"{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
The system cannot find the file specified
    Preprocess: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\Nano_Trials.cpp" -o "nul"
Unknown error during deep search source code for includes. Attempting alternative regex exploration
System.NullReferenceException: Object reference not set to an instance of an object.
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, Boolean isTopLevel)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino.TryRunPreProcessIncludesDiscoveryUntilDone(String sourceFilePath, Board brd, List`1 includePaths, SketchLibraryList knownLibs)
   at Visual.Micro.MiroAppAPI.SketchCompilerArduino._compile(SketchBuilder lsketch, String primaryClassName, Boolean verbose, Boolean isDebug)
Library Include Paths (1)
Build Core Paths: C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino
Using library VM_DBG version 0.0.0 in folder C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG
"{runtime.tools.avr-gcc.path}/bin/avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
The system cannot find the file specified
    Process: "{runtime.tools.avr-gcc.path}\bin\avr-g++" -c -g -Os -Wall -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=106011 -DARDUINO_AVR_NANO -DARDUINO_ARCH_AVR -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\variants\eightanaloginputs" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers" -I"C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG" -I"C:\Program Files (x86)\Arduino\libraries" -I"C:\Program Files (x86)\Arduino\hardware\arduino\avr\libraries" -I"C:\Users\jf051e\Documents\Arduino\libraries" "C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\zq2favuv.ley\Micro Platforms\default\debuggers\VM_DBG\VM_DBG.cpp" -o "C:\Users\jf051e\AppData\Local\V.Micro\Arduino\Builds\Nano_Trials\nano_atmega328\VM_DBG\VM_DBG.cpp.o" -DVM_DEBUG -DVM_DEBUG_ENABLE=1 -DVM_DEBUG_BANDWIDTH_THROTTLE_MS=50 -DVM_DEBUGGER_TYPE_HARDWARESERIAL=0 -DVM_DEBUGGER_TYPE_SOFTWARESERIAL=1 -DVM_DEBUGGER_TYPE_FASTSERIAL=2 -DVM_DEBUGGER_TYPE_USB=3 -DVM_DEBUGGER_TYPE_TEENSY=4 -DVM_DEBUGGER_TYPE_UART=5 -DVM_DEBUGGER_TYPE_USART=6 -DVM_DEBUGGER_TYPE_USBSERIAL=7 -DVM_DEBUGGER_TYPE_TTYUART=8 -DVM_DEBUGGER_TYPE_NET_CONSOLE=9 -DVM_DEBUGGER_TYPE_Uart=10 -DVM_DEBUGGER_TYPE_COSA=11 -DVM_DEBUGGER_TYPE_CDCSerialClass=12 -DVM_DEBUGGER_TYPE=VM_DEBUGGER_TYPE_HARDWARESERIAL -DVM_DEBUG_BREAKPAUSE
Error compiling libraries

I swear I didn't touch anything. i was working on a different sketch and when I hit compile, Visual Studio froze and said it was busy. i had to kill the process and try again. I did this like 8 times before i realized that I could do longer compile ANY sketch. I even restarted my PC to no avail. What the heck??

Did your trial period run out?

So I seem to have fixed it. One way or another, I think VisualMicro suffered some type of problem with the installed boards. My first clue was that my sketches still compiled int the native Arduino IDE. So I went into the VisualMicro explorer and noticed that there was an update to 1.6.19 in the board manager (I was running 1.6.13). I don't know exactly what the problem was, but installing the update to 1.6.19 seems to have fixed it.

There are a few suggestions here, here and here:

Ensure you are using the latest Arduino software that is compatible with Visual Micro (this is not necessarily the latest Arduino software!)

Go to Visual Micro menu -> Board pulldown -> Find or install a
board--> Rescan. You should get "Toolchain reload complete". The
Visual Micro forum administrator suggests that you do this twice.

Reset the User's Appdata Arduino folder

Close all IDE's

Delete the C:\Users<USERNAME>\AppData\Local\Arduino15 folder

Start the Arduino IDE once. Close after it has fully started

Then try Visual Micro again

Delete the preferences.txt file (if it exists)
Goto C:\Users<USERNAME>\AppData\Roaming\Arduino and delete the preferences.txt file.

Thanks for the ideas, but none of these worked. I'm still getting errors for basic functions like pinMode(), digitalWrite(), and Serial.print(). It's almost like my standard libraries were corrupted or something.

Hey guys, I seem to have fixed it. I'll edit the post.


text:
Are pins 0 and 1 (Rx and Tx) parallel with the USB jack? Can I connect another USB jack th 0 and 1 and use it to upload sketches?
I have a compact weatherproof enclosure and the onboard USB jack of my Mega is close to the edge. I didn't want to add a bulky weatherproof USB jack, so I'd like to just leave a female USB pigtail loose inside the enclosure.
The only thing is, I want to avoid the extra assembly step of soldering leads directly to the lugs on the board. I'd like to make a shield instead, with screw lug headers to attach all my wires to. That way a lot of my connections can be solderless and the assembly tech can just plug in the shield.
Can I connect the four wires of a USB cable to the header pins? I suspect I'd use Vin, GND, pin 0 and pin 1, but I'm not 100% sure. Thanks for your advice, gentlemen.

Have you had a chance to look at its schematic yet?

I have, but unfortunately I could not make sense of it.

No. For many reasons. No. USB is not TTL. You need an adapter to connect rx/tx pins of arduino to USB. And the on-board adapter has the DTR line connected to reset the Atmega before writing a program into it. Without it, you would need to push the reset button in the right moment.


text:
Servo Control using Pushbutton
I was trying to build a system that when the user pushes the button, the servo rotates 45 degrees and than returns back to zero. This system is going to be duplicated as there will be two servos and pushbuttons.
Here's my code:
#include <Servo.h>
Servo solservo;  // create servo object to control a servo
Servo sagservo;
// twelve servo objects can be created on most boards

int possol = 0;    // variable to store the servo position
int possag = 0;
int degsol=0;
int degsag=0;

int ledPin = 13; // choose the pin for the LED
int solPin = 7;   // Pushbutton
int sagPin = 8;     // variable for reading the pin status
int valsag = 0;
int valsol = 0;

void setup() {
  solservo.attach(9);  // attaches the servo on pin 9 to the servo object
  sagservo.attach(10);
  pinMode(solPin, INPUT);
  pinMode(sagPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {
  digitalWrite(ledPin, HIGH);    //Arka İsik
  valsag = digitalRead(sagPin);  // read input value
  valsol = digitalRead(solPin);
//Sag Servo

  if (valsag == HIGH) {
    sagservo.write(45);              // tell servo to go to position in variable 'pos'
    delay(100);                       // waits 15ms for the servo to reach the position
    sagservo.write(-45);

  }
//Sol Servo
  if (valsol == HIGH){
    solservo.write(45);
    delay(15);
    solservo.write(0);
  }

}

There'll probably be lots of small errors in this code, like unnecessary ints and such, but when I upload this program and push the button, it just rotates 45 deg, and doesn't come back. Is there a way that I can solve it?
Thanks in advance

Change sagservo.write(-45); to sagservo.write(0);.

When I stop pushing the button in the middle of the rotation (With the changes,) , it rotates back to 0, and does not complete the loop itself. Is it possible to keep it rotating and complete the loop even I stop pushing?

Change delay(100) to delay(1000)


text:
Arduino randomly does incorrect addition
I've been trying to make an accelerometer calibration tool for my Arduino Nano and MPU6050, but the arduino seems to randomly do incorrect addition. If you look at the output of the console, it works fine for the first 4 iterations, then on the fifth, decides that -31904+-7964 is equal to 25668. It is supposed to be -39868. It does this every time I run it, usually between the 3rd to 6th iteration, but with different numbers.
bool calix = true; //X calibrated or not
      while(calix)
      {
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("PrevAvgX: "); Serial.println(axo/i);
        Serial.print("Axo: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        axo = (float)ax + (float)axo;
        i += 1;
        Serial.print("Axo2: "); Serial.println(axo);
        Serial.print("RawX: "); Serial.println(ax);
        float cax = axo/i; //Current Average (x)
        Serial.print("AverageX: "); Serial.println(cax);
        delay(100);
        accelgyro.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);
        Serial.print("NewX: "); Serial.println(ax);
        float offsettocurrent = ax-(axo/i);
        Serial.print("AverageX-RawX: "); Serial.println(offsettocurrent);
        if(offsettocurrent>5 or offsettocurrent<-5)
        {
          Serial.println("Offset not accurate enough. Continuing.");
        }
        else
        {
          Serial.println("Offset accurate enough. Finishing calibration");
          break;
        }
        delay(100);
      }

Serial console output:
Initializing I2C devices...
Testing device connections...
Connected to MPU6050
Attempting full calibration
PrevAvgX: -1
Axo: 0
RawX: -8048
Axo2: -8048
RawX: -8048
AverageX: -8048.00
NewX: -8028
AverageX-RawX: 20.00
Offset not accurate enough. Continuing.
PrevAvgX: -8048
Axo: -8048
RawX: -7940
Axo2: -15988
RawX: -7940
AverageX: -7994.00
NewX: -7964
AverageX-RawX: 30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7994
Axo: -15988
RawX: -7972
Axo2: -23960
RawX: -7972
AverageX: -7986.00
NewX: -8016
AverageX-RawX: -30.00
Offset not accurate enough. Continuing.
PrevAvgX: -7986
Axo: -23960
RawX: -7944
Axo2: -31904
RawX: -7944
AverageX: -7976.00
NewX: -8016
AverageX-RawX: -40.00
Offset not accurate enough. Continuing.
PrevAvgX: -7976
Axo: -31904
RawX: -7964
Axo2: 25668
RawX: -7964
AverageX: 5133.00
NewX: -7944
AverageX-RawX: -13077.00
Offset not accurate enough. Continuing.

What do you want to calibrate ? Do you use the sensor for fast 3D motion with accelerometer/gyro fusion or as a spirit level ? For a spirit level you only need the accelerometer. For 3D motion there is an alternative using the AHRS calculations. This code has also a selftest and calibration: https://github.com/kriswiner/MPU-6050/blob/master/MPU6050IMU.ino

I'm going to use the MPU6050 for a quadcopter, so gyro and accel. I'll check out that link, thanks.

int only goes from -32768 to 32768, and rolls-over, as you've seen.
Use a long data type instead and you can go MUCH further from zero. Use double instead of float likewise, when you need more room. Be aware however that larger types use more RAM, and in the case of double, execute a bit slower as well.

Double doesn't give more room - it gives more precision. Also, on Arduino, double and float are exactly the same thing.

Changing all the variables to doubles and longs fixed it. Thanks!

Although an overflowed int usually rolls overs this way, you cannot even count on that, as in C and C++ it's undefined behavior. Use unsigned integer types if you want predictable roll-over.


text:
Get servo to travel full length
Recently we purchased servos for use in an Arduino and began testing with servos. It turned out that the uSec for the servos differed from the online documentation and we had to find the min and maxes of the uSecs manually:
while (Serial.available()) {
    char c = Serial.read();  //gets one byte from serial buffer
    readString += c; //makes the string readString
    delay(2);  //slow looping to allow buffer to fill with next character
}

if (readString.length() >0) {
    Serial.println(readString);  //so you can see the captured string
    int n = readString.toInt();  //convert readString into a number
    Serial.print("writing Microseconds: ");
    Serial.println(n);
    myServo.writeMicroseconds(n);
    readString = ""; //empty for next input
}

The issue is that the servos don't travel the full 180 degree advertised price (more like 135-160) and that lack of angular distance is affecting performance of one of our products. The servos can even mechanically travel a noticeable distance farther than 180, but not "programmatically" farther even when given a larger PWM uSec value that the observed "max" PWM value

What I've found
I looked around and apparently there are "Servo Programmers" to calibrate endpoints and midpoints, but cost an arm and a leg. I find it strange that I would have to "program" my servos. I was part of an First (FTC) robotics team using tetrix/nxt electronic control systems, and never noticed a problem with uSec values or not getting the full range of motion using the same brand of servos I currently am now.

How can I perform a low cost, easy way to simply get the full range
  of motion I paid for?

what do they say about this where you bought the servos from? they get paid to give you that service?

This servo can operate 180° when given a pulse signal ranging from 600usec to 2400usec I have tried giving it more than 2400usec, but it is noticeably off from 180°.

do you have a logic analyzer? you might want to check the actual length of the pulse.

No we don't have a logic analyzer/oscilloscope, nor do we have the funding for one. I don't think the PWM would be incorrect becuase the problem is at longer PWM than shorter PWM. For example, manual implementation of Pulse Width Modulation: void loop() {   digitalWrite(pin, HIGH);   delayMicroseconds(100); // Approximately 10% duty cycle @ 1KHz   digitalWrite(pin, LOW);   delayMicroseconds(1000 - 100); }

This is an analog servo, so there is no endpoint calibration on the servo side. This type of calibration is for digital servos (which can be tuned) and controllers.
On the servo description page, they talk about a stretcher. This is a translation tool to help with old controllers:  usually servos have a narrower band: 1000us to 2000us for 0° to 180°. Therefore old controllers can only do 1000us to 2000us, and would fail to achieve full range with this servo, which requires 600us to 2400us
Also, note that RC servo input signal isn't really a PWM: duty cycle doesn't matter, only lengh of the pulse does.
Your servo doc says: 600us to 2400us for -90° to +90°, which correspond to what the Servo lib does by default according to its documentation. You should be fine. What are the results of a super simple sweep-like code? eg:
loop() {
  myServo.writeMicroseconds(600);
  delay(2000);
  myServo.writeMicroseconds(2400);
  delay(2000);
}

With super simple code, it doesn't travel full angular length. Using uSecs higher/lower than 600-2400 range doesn't do anything different.


text:
Using Multiple 4 Digit displays with the same pins
I currently have a ton of 4 Digit 7 Segmented displays(TOFD-5465GGH-B).

The display is driven by a PT6961 LED Driver. Using a Library that I found here I was able to use the display with no issues. The pin out on the display is as such:
1) 5V
2) CS
3) CLK
4) DIN
5) DOUT
6) Common

Since the display has a DOUT does this mean I can run multiple display is series off of the same pins? If so, can someone point me in the right direction to do so. I am currently using a Particle Photon and I am limited as to the number of PWM pins.

Datasheet says?

My understanding is very limited but the datasheet for the PT6961 doesnt state anything about the DOUT. Im assuming you are just supposed to know how to use it. And I am unable to find a datasheet for the Display itself.

If it doesn't say anything about daisy-chaining then it doesn't have daisy-chaining.

That is an SPI interface.  Using multiples should be easy.  Each one has a CS pin.  When that pin is pulled low it selects that chip as the one you are talking to.  Several displays could all share the CLK, DIN, and DOUT pins on the Arduino and each would have it's own pin on the Arduino for CS.  To update any given display, you pull its CS pin low and then transmit your data.  If you pull the CS pins on two displays low at the same time you'll send the data to both.  Whichever has the CS pin pulled low on it is the one that listens.
Google SPI and do a little investigation on SPI with Arduino.  That will help you learn a little about how SPI works and you will certainly get your question fully answered about how to drive multiple chips while sharing pins.  Driving multiple things with the same pins is the whole point of SPI.
The connection would look like this for an UNO -
Pin 13  ----  CLK pin on all chips
Pin 12  ----  DOUT on all chips
Pin 11  ----  DIN on all chips
Choose a different pin on Arduino for each chip and connect to the CS pin.
To use SPI, pin 10 MUST be configured as an output.  It cannot be an input.  So it would be a good idea to use 10 for one of the CS pins just to make sure it is going to stay an output.
EDIT:
I just looked at the page you linked to and it looks like the library you are using isn't using the SPI hardware but is bit-banging SPI from software using other pins.  The concept is still the same, all share CK and DIN and the CS pin picks the one you're talking to.
The code would be a lot faster and much more compact if you changed this library to use the SPI hardware instead of software.  It just limits which pins you have to use to the ones I listed above.
EDIT AGAIN:
I feel generous and it was really really really easy to do so I switched his code to run on the SPI hardware.  It compiles but hasn't been tested.  It should work though.  Hooking DOUT to pin 12 is optional, but you still can't use pin 12 for anything else so you might as well.
PT6961_SPI.h
/*
  PT6961.h - Library for communicating with PT6961 LED driver.
  Created by Garrett Blanton January, 16, 2013.
  Released into the public domain.
*/

#ifndef PT6961_SPI_H_
#define PT6961_SPI_H_

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

class PT6961
{
  public:

    PT6961(uint8_t CS);
    void initDisplay();
    void initRAM();
    void sendCmd(char cmd);
    void sendDigit(char digit, char val);
    void sendNum(int num, char colon);
    void sendDigits(char digit1, char digit2, char digit3, char digit4, char colon);

    const static char _DISPLAY_6X12 = 0x02;
    const static char _DISPLAY_7X11 = 0x03;
    const static char _AUTO_INCREMENT = 0x40;
    const static char _FIXED_ADDRESS = 0x44;
    const static char _DISPLAY_OFF = 0x80;
    const static char _DISPLAY_1_16 = 0x88;
    const static char _DISPLAY_2_16 = 0x89;
    const static char _DISPLAY_4_16 = 0x8A;
    const static char _DISPLAY_10_16 = 0x8B;
    const static char _DISPLAY_11_16 = 0x8C;
    const static char _DISPLAY_12_16 = 0x8D;
    const static char _DISPLAY_13_16 = 0x8E;
    const static char _DISPLAY_14_16 = 0x8F;

  private:

    uint8_t _CS;

};

#endif

PT6961_SPI.cpp
/*
 PT6961.cpp - Library for communicating with PT6961 LED driver.
 Created by Garrett Blanton January, 16, 2013.
 Released into the public domain.
 */

//0 - A
//1 - B
//2 - C
//3 - D
//4 - E
//5 - F
//6 - G
//7 - Colon
#include "Arduino.h"
#include "PT6961_SPI.h"

PT6961::PT6961(uint8_t CS) {

    pinMode(CS, OUTPUT);
    _CS = CS;

    SPI.begin();
    SPI.setBitOrder(LSBFIRST);

}

void PT6961::initDisplay() {
    sendCmd(_DISPLAY_6X12);
    sendCmd(_AUTO_INCREMENT);
    initRAM();
    sendCmd(_DISPLAY_14_16);
}

// Initializes RAM to all zeros
void PT6961::initRAM() {
    //first clear 8 bytes of the display RAM
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);
    for (int i = 0; i < 8; i++) {
//      shiftOut(_DIN, _CLK, LSBFIRST, 0x00);
        SPI.transfer(0x00);
    }
    digitalWrite(_CS, HIGH);
}

// Use to send command based on enumeration
void PT6961::sendCmd(char cmd) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, cmd);
    SPI.transfer(cmd);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendDigit(char digit, char val) {
    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, digit);
//  shiftOut(_DIN, _CLK, LSBFIRST, val);
    SPI.transfer(digit);
    SPI.transfer(val);
    digitalWrite(_CS, HIGH);
}

void PT6961::sendNum(int num, char colon) {
    int digit1 = num / 1000;
    int digit2 = (num % 1000) / 100;
    int digit3 = (num % 100) / 10;
    int digit4 = (num % 10);

    sendDigits(digit1, digit2, digit3, digit4, colon);
}

void PT6961::sendDigits(char digit1, char digit2, char digit3, char digit4,
        char colon) {

    const char DISP[17] = { 0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 0x07,
            0x7f, 0x6f, 0x77, 0x7c, 0x58, 0x5e, 0x79, 0x71, 0x61 };

    digitalWrite(_CS, LOW);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC0);
    SPI.transfer(0xC0);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1] | 0x80);
        SPI.transfer(DISP[digit1] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit1]);
        SPI.transfer(DISP[digit1]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC2);
    SPI.transfer(0xC2);

    if (colon == 1) {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2] | 0x80);
        SPI.transfer(DISP[digit2] | 0x80);
    } else {
//      shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit2]);
        SPI.transfer(DISP[digit2]);
    }

//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC4);
    SPI.transfer(0xC4);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit3]);
    SPI.transfer(DISP[digit3]);
//  shiftOut(_DIN, _CLK, LSBFIRST, 0xC6);
    SPI.transfer(0xC6);
//  shiftOut(_DIN, _CLK, LSBFIRST, DISP[digit4]);
    SPI.transfer(DISP[digit4]);
    digitalWrite(_CS, HIGH);
}

Example.ino
#include "Arduino.h"
#include <SPI.h>
#include "PT6961_SPI.h"

PT6961 LED(10);   /// This is the pin number for CS pin on each chip
// PT6961 LED2(9);  // The next might look like this if it were connected to pin 9
void setup()
{
     LED.initDisplay();
     Serial.begin(9600);
}

void loop()
{
     //count through 0-9,a-f
     for(int i=0; i<16; i++)
     {
          LED.sendDigits(0,0,0,i,0);
          Serial.println(i);
          delay(500);
     }
}

Thanks. That helped a lot. I got it working only using one extra pin per display now.


text:
Right way to convert 120VAC to 5V?
I am currently using a Particle Photon to control a relay that turns a lamp on and off. I would like to power the Photon and the lamp from the same power cord.
Currently, I have a power cord for the lamp and I am also using a usb cable to power the Photon.
I found this (Enclosed AC DC Converter) and I am wondering if this will work if I split the 120V power cord to go to the relay and the converter. Will I need anything else? Are there any other concerns I should worry about? Do I need to worry about polarity?
Thanks for your help in advance.

I highly recommend reading the datasheets for any electronics because they have an incredible amount of information.
Short Answer, No
If you read the datasheet for the Particle Photon, it recommends no less than a 1A power supply. Unfortunately, the datasheet for the AC/DC Converter you found shows it has a maximum output current of 30mA, which is nearly 30x smaller than you would want for the Photon.
How to Make This Work
Because you're trying to get ~1A @ 5V and you're working with 120VAC, you don't have to reinvent the wheel--or in this case, the USB Charger Brick!
Literally any off-the-shelf USB charging brick for a phone or tablet will work. I can't think of any that are less than 1A-rated anymore, but if you want a hobbyist-level supply, something like this one may be right for you (not to plug for Adafruit, though they are a great learning resource).
Basically, you'll have a box that houses the Photon and the relay. You simply put this in the box with it, and voila! you have 5V power for the Photon.
Bonus Points
You can even go nuts and remove the device from its housing (DISCLAIMER: This may void the UL listing and any warranty) and just grab the innards to package neatly in a nice enclosure.
EDIT:
Easiest Solution
Just install one of these at the receptacle you intend to use.

Where did you get the 1A value from? The recommended conditions table on the datasheet you have linked mentions Avg Operating Current to be 80-100mA.  1A is mentioned in absolute maximum ratings, which I think defines a safe limit.

Under the "Power" section of the linked documentation, it says typical operating current is 80mA (still above the AC/DC the OP asked about), but the author recommends, "[...] the power source should be sufficient enough to source 1A of current to be on the safe side." Given the OP is asking this question, I doubt the OP is likely to calculate their exact power needs, so going with the manufacturer recommendation seems wise. Also, with WiFi, peak current goes as high as ~400mA.

You've also got options like these DC 5V 2A Switching Power Supply Board Converter Transformer since anyway you have to put your mains relay in an enclosed box.

Thanks for the response. I didn't even look at how many amps this gives off. After looking at the Particle Photon data sheet it says that it operates at a peak of 430mA so you are right this wouldn't work. Im not trying to use a usb block because I want to keep the size down. Also this is more of an exercise for me to learn more about how things work. Unfortunately, Im teaching myself via internet resources so I'm bound to make stupid mistakes.

As someone who does this semi-regularly, I'd simply gut an off-the-shelf component and throw it in my enclosure. There are times when it's worth reengineering something, but this really isn't one of those times. If it is to you, I'd recommend going full-on and building a transformer-rectifier-SMPS system. That will really teach you something.

Also, the USB power brick can be in your enclosure too.


text:
Arduino not running code without connection to PC via USB
I have an Arduino UNO and esp8266 connected to it. Both devices has separate power lines. Each connected via USB cable, for Arduino USB used as power line and standard firmware uppload line, for esp8266 only as power suppli line. If I connect all to computer's USB ports, everything working fine. But, if I connect Arduino to separate charger that has USB port, then Arduino not running code. I can see it by Serial interface work, because code using it intensively, and when I'm turning Arduino on the RX and TX lines are down all the time, that I think indicates, that code is not running, and Arduino in boot mode, somehow.
I've made a search through same issues and nothing helped from theirs suggestions. I tried to pull RX line to GND through resistor, to make sure that there are no noise on the line, added capacitors for power supply line, to make exclude pulsations on the line. But nothing helped.
Arduino not running code independently from esp8266. I tried to run Arduino separately, without any other connections, but it not helped. Still not running.

Diagrams would help ("a picture is worth 1000 words...") but it seems like everything regarding the ESP8266 can be removed from your question because at the end, you say: "I tried to run Arduino separately, without any other connections, but it not helped. Still not running." You didn't say exactly how you know it is not running. Overall, I suggest to simplify your test and clarify your question; add diagram / photos of minimum non-working config; remember not all "chargers" are good quality; this topic might be better moved to the Arduino SE, as they have more Arduino experience there.

I believe this is happening because of electrical interference between wires. If you are running somewhat long wires (100mm or longer), every wire you run acts as an antenna that can either transmit or receive singles to/from other close wires. If you separate your wires or better yet, shield your data wires from each other, your issues should resolve.
Signals out of an Arduino board are very weak and are easily susceptible to interference from your environment such as motors, radio waves, wifi, or even a microwave oven running.
Either shield your data wires, make your wires shorter, or add circuitry that can transmit/receive signals over long distances, even if it's only 100mm. At 3.3volts with very low amps doesn't take much to noise up your data signals.
Hope this helps!


text:
How to power an Arduino using automated mains/rechargeable battery switching?
I'd like to power my Arduino circuit like a smartphone. That is:

When the device is unplugged, power by rechargeable battery
When the device is plugged in, power by mains and charge battery at the same time

I'd like to not go the expensive shield route and instead purchase some inexpensive breakout boards from Aliexpress or eBay if possible. I'm willing to put in the time to learn if someone will point the way.
Can someone please provide some guidance?

Yes, charging a battery and supplying an Arduino at the same time is possible as long as we manage the caveats (see below) of in-circuit charging.

This is what I use:

a 3.3V Arduino (a Pro Mini in my case),
a regular Li-Ion battery,
a charging controller that supports constant voltage (CV) and constant current (CC) charging,
optionally, a 6V solar panel.

This is how it works:

charger is fed via solar panel and/or USB supply,
battery is continuously supervised and charged on demand
Arduino is connected to the output side of the charger

This works because the load that the Arduino presents is relatively small compared to what the charger can feed (and what the battery can take).
During recharging the charge current will predominantly flow through the battery.
And since the current through the battery drops once it gets full, the charger can still recognise this drop and finish the charge cycle – even though the Arduino is connected all the time.

Example setup:
I took some quick snapshots, please excuse the image quality. Charger is in the center, Arduino to the upper left, battery in a holder to the lower left, solar panel to the upper right.
The Arduino has a voltage regulator, but I don't use it in this setup. An explanation why and when to use the regulator is beyond the scope of this question and a matter for another answer.

In the first photo the charger input is only connected to the solar panel, but the panel voltage is low. So the charger is actually off and the Arduino is running off the battery.

In the second photo the charger is now connected to a USB power supply. The charger is on and in CC/CV charge mode (as indicated by the red LED of this charger model).

In the third photo the charge cycle is completed, the battery is full (as indicated by the blue LED of this charger model). Note that the charger could determine the charge completion even though the Arduino is connected and running (no power saving tricks involved here).

Background info:
The charger switches between CC and CV mode, depending on the level of discharge the battery is in. Particularly, my charger uses CC mode in case the voltage on the battery side is below 4V and CV mode in case the voltage on the battery side is above 4V. The current limit can be configured and the voltage limit is hard coded to around 4.2V, which makes the circuit save for a device like Arduino.

Image source: Nanjing Top Power
Other chargers may have other thresholds, but that doesn't matter as long as it fits your battery type and uses constant current/voltage only.
I have no particular recommendation for a charger, but so far have a good impression of the one I used in this answer.

Caveats:
There are a couple of cases to consider, though:
Deep discharge
Should the battery voltage ever go below around 2.9V (e.g. deeply discharged battery), the charger will switch into trickle charge mode where only very small amounts of current are passed to the battery – too little current (i.e. too low a voltage) for the Arduino to run. Arduino will go into brown-out and try to restart until the battery has recovered. So this can become a state in which your Arduino won't respond for an unknown amount of time.
High load
If the load connected to the battery draws a current that isn't small anymore – compared to the battery charge current – then the charger cannot recognise a full battery anymore, since the current as seen by the charger will never fall off at the end of any charge cycle. So watch out how many gadgets you connect to this kind of in-circuit charger.
Wrong charger type
There are a multitude of ways to charge a battery. Things like trickle charge, pulse charge, timer based charging, and so on.
None of these would likely work, as the voltage those charger types generate could upset the Arduino and the load the Arduino presents could upset the charger.
Please also note that some chargers don't supervise the battery. With Li-Ion or Li-Poly (and other) batteries this would be a very bad idea. Always choose a charger appropriate for your battery.

Alternatives
The charger I use employs a linear regulator. That's not very efficient, other topologies are possible. But they might require supply filtering for the Arduino.

Shameless plug
I wrote a library for the purpose of supervising an Arduino's supply voltage (and chip temperature). This technique allows to check the battery level without any additional components. That library is called CoreSensors.

Further links:

New TP4056 Lithium Cell Charger Module with Battery Protection
Solar Pannel and LiOn or Lipo
How to autoregulate a TP4056 for maximum solar power extraction

There are many ways you can do this, as you mention there are ready made shields that do this.
You need to take a few thing into consideration:

Power - how much power will your cirquit be drawing, as many of these boards will only be able to deliver 3-600mah is this enough, at the same time you will find out how long your cirquit will be able to stay on battery power.
Complexity - a ready made controller/charger is already made to work togheter, if you go for a separate charger and booster module you might end up with unwanted power loss, or you need ekstra buttons/sliders to control power.

You could in theory use 1 lipo cell directly to power your MCU, as the voltage spans from 3,6 to 4,7 Volts pr.cell and charge the lipo when NOT in use (you cannot charge a lipo directly while in use, thats why you need a controller). This would be the cheapest way.

That got me puzzled: "you cannot charge a lipo directly while in use". While it's true that the charging circuit would be irritated by an additional load in parallel to the battery, are you saving you can't have battery charging without turning off the device? Because that's not the case (e.g. see your phone/computer). I think a good answer should address exactly this issue, as everything else follows from there.

Charging lipo is done in stages:

Sure, but there are controllers that handle load switching. Since you suggest a controller, why not suggest one that does? I would if I could. ;)

sparkfuns LiPower shield would get the job done, but OP is looking for cheap china solution. and I gave a few considerations to think about. My comment reg. Lipo's was aimed at directly connecting the battery to the 5v line, a full lipo will supply (aprox) 4.7V and deliver down until brown out. I should also mention that draining a lipo too much might destroy it.

I've been looking at the SparkFun DEV-13158. Ignoring the fuel gauge and the fact that it produces multiple output voltages, we have: charger -> battery -> voltage regulator -> Arduino. So, no magic compared to a breakout board. Of course I agree that the battery voltage has to be monitored in order to prevent a deep discharge.

Can someone please provide some guidance?

power your arduino from a power bank and then power the power bank via ac adapter.
simplest and likely most inexpensive solution.


text:
'Non-Deterministic' memory usage on Arduino
I had a problem with a memory leak in my sketch and cornered it with MemoryFree.h. This works great and I was able to fix my leak.
My sketch is not really static, but My var sizes are. I observed, that the free memory on the arduino reaches a different values and stays there.
For Example

Run 1: 1655 Bytes Free
Run 2: 1659 Bytes Free
Run 3: 1654 Bytes Free

For every run, I get a different, but over a short time, fixed memory usage. Is this normal?
P.S: The serial input to the script just repeats forever with the exact same data.

You haven't posted any code, so any answer is guesswork. However ... if your code makes decisions based on external events (eg. readings from sensors) then it may allocate memory differently, and in a different order, each time.
Sometimes memory allocation leaves gaps (known as "heap fragmentation"). Small differences in your results probably show slightly different sized gaps, due to the allocation order.

Indeed, I added no code, because I wanted an abstract answer. Since it is just an observation, not a real problem. Thanks anyway.

I see. This site is not supposed to be used to ask questions which are not about real problems. I am pleased I could help, but please ask practical questions in the future, about real problems.

Thanks for your reply and any bit of information, you shared with me. I am fully aware of the rules and would categorize this as 'potential real future problem'.


text:
How to program arduino due without arduino ide
Is it possible to program the Arduino Due without the Arduino IDE? Is there a standalone program that can be downloaded, and be used to upload a .bin file (which has already been generated from the arduino IDE) to the Due? Any guidance appreciated.
I read about SAM-BA programmer, downloaded it but double clicking the .exe file does nothing. Something seems to open but it disappers.

The standalone program for most arduinos is avrdude: http://www.nongnu.org/avrdude/
However, for the Due, it is BOSSA:

Unlike other Arduino boards which use avrdude for uploading, the Due
  relies on bossac.
   -- Arduino Due Overview

thanks. Do you know if this one can upload the code via the native USB port? or does it need to have a jtag port?

It can use the USB port.  avrdude is the program the IDE uses to do its stuff.

Err… are you sure it's avrdude? The DUE features a SAMX ARM microprocessor, not an AVR.

I was wrong.  Edited.

Usually when on opening a program you get a console that pops on, it means that this program is meant for commandline usage and not CLI.
You should open a terminal, cd in the downloaded .exe directory, and then type that tool's name. You might want to try adding --help after the program's name to learn how to use it.
Another good idea is to look at what Arduino does by clicking on the verbose option in the preferences. Then you'll be able to copy/paste the command call and modify it to upload the firmware blob you want.
Finally, if you look up "AVR SAMX upload tool windows" on google you might find a GUI wrapper for the command line tool.


text:
How do I statements for the various conditions of this function?
I am still new to Aduino and I am trying to use a library's example sketch but I don't understand the following part of the code. I want to trigger an led when the "Pressed" condition is fulfilled. Pardon my ignorance.
if (b != ClickEncoder::Open) {
Serial.print("Button: ");
#define VERBOSECASE(label) case label: Serial.println(#label); break;
switch (b) {
  VERBOSECASE(ClickEncoder::Pressed);
  VERBOSECASE(ClickEncoder::Held)
  VERBOSECASE(ClickEncoder::Released)
  VERBOSECASE(ClickEncoder::Clicked)

  case ClickEncoder::DoubleClicked:
      Serial.println("ClickEncoder::DoubleClicked");
      encoder->setAccelerationEnabled(!encoder->getAccelerationEnabled());
      Serial.print("  Acceleration is ");
      Serial.println((encoder->getAccelerationEnabled()) ? "enabled" : "disabled");
      setMode = true;
       value = 0;
    break;
}

}

I'm no expert either, but I think this is just Displaying the status of the button out to the Serial port, whether it's been Pressed, Held, Released etc.

You will have to explicitely expand the case ClickEncoder::Pressed. So instead of
VERBOSECASE(ClickEncoder::Pressed);

you should write something like
case ClickEncoder::Pressed:
    Serial.println("ClickEncoder::Pressed");
    digitalWrite(ledpin, HIGH);
    break;

Of course then you'll have to turn it off then, but.. Well, that's another problem


text:
Low power RGB LED for wearable device
I am trying to prototype a wearable device which will have about 120 RGB LEDs. I was considering the WS2812B but they seem to draw about 50mA and so may not be a good option since I will be powering them from a battery.
I would be glad to know of other options or ways to implement the LEDs in order to consume less power.

It would help to give an actual figure. "Less power" is pretty vague. How much, per LED, are you hoping to consume? (1 mA might be your hope, but I mean a practical hope). Obviously 120 LEDs at 50 mA each will consume 6 amps. Are you hoping for 500 mA?

You can reduce the current by simply reducing the duty cycle. For example, to display red, rather than sending 255 as the red component, send 42.
If you divide each of the R/G/B values by the same figure you get the same colour, just duller. In a quick test I found that a 24-pixel strip only used 67 mA if I sent red=0, green=0, blue=42 which made them look a dull blue. If you send a value of 8 (in a single channel) then it takes 25 mA for 24 pixels.
A bit more testing reveals a base consumption of 21 mA even if you are sending black. That is, the overhead is 21 mA, which works out at about 1.1 mA per neoPixel.
Based on that, you would consume 335 mA to make 120 NeoPixels show a moderately bright red.
I don't think there is going to be some "magic bullet" that lets you light up 120 LEDs brightly, but not use much power. However using the NeoPixels which lets you have fine control over the brightness of each of the R/G/B pixels is probably going to be about as close as you can get.
The figure of 50 mA which you quoted is to have "full brightness" on all three colours (ie. bright white).

"If you divide each of the R/G/B values by the same figure you get the same colour, just duller." : oops, that's a common misconception. color scale values are not linear. you will find colors get very "bandy" at the low end like that. the rest is good stuff though. it would be interesting to PWM incoming power and still use 0-255 instructions to maintain relative contrast...


text:
Can multiple xbees send data to one xbee
I am new to xbees. I want to have multiple xbees (up to 400 xbees) send data constantly to one xbee (receiver).This is just simple data like lets say 0 or 1 . Is this possible? Are there any limitations?

Yes, you can send data from 400 XBees to a single xbee. I would like to clarify one thing. XBees are connecting to a network, not to a particular xbee. And the devices connected in a network can communicate each other.

Thank you. My goal afterwards is for the receiver xbee connected to wifi module to send the data from all 400 xbees to the server.I am assuming that is also possible?


text:
Sending binary data to HTTP server
I am new to low level programming.I am trying to send binary data to the http server.At the moment i just fill up the byte array with numbers and send them to the server(eventually i want to send image file). I can see the request in the server log as
2016-05-18T23:30:26.688040+00:00 heroku[router]: at=info method=POST path="/api/users" host=myapp.herokuapp.com request_id=ed2b7852-7021-4642-a663-f9709e1aea70 fwd="99.89.114.63" dyno=web.1 connect=0ms service=2ms status=404 bytes=221
Questions
1.My question is as you can see in the log, what is bytes=221 i thought if i sent byte array of length 32 i should see 32 bytes(or around 40s).And i made the buffer of length 1024 byte array, still in the server log is bytes=221.Are my bytes are even being sent?
2.How would i handle the bytes received on the server side just to be sure client.write actually succeeded?(Just in high level...doesn't matter you can guide me in any language,Java,ruby,C,NodeJS)
Here is my code.Thank you in advance.
#include <ESP8266WiFi.h>
#define SSID "ssid"
#define PASS_SSID "password"
#define HOST "myapp.herokuapp.com"
WiFiClient client;

byte buffer[32];
int bufOffset = 0;
byte startByte = 0;
byte nextByte = 0;

void setup() {
    Serial.begin(115200);
    checkConnection();
}

void loop() {

  if (client.connect(HOST,80)) {
           Serial.begin(115200);
           Serial.println("conected to the server");
           String start_request = "";
           String end_request = "";
           start_request = start_request  + "--AaB03x" + "\n"
                                   + "Content-Disposition: form-data; name=\"picture\"; filename=\"cam.jpg\"" + "\n"
                                   + "Content-Type: image/jpeg" + "\n" + "Content-Transfer-Encoding: binary";
          end_request = end_request + "\n" + "--AaB03x--" + "\n";
          client.println("POST /api/users HTTP/1.1");
          client.println("Accept: */*");
          client.print("Content-Type: multipart/form-data; boundary=AaB03x");
          client.println(start_request);

         //Fill the buffer with values
            nextByte = startByte++;
            for(int ii = 0; ii < sizeof(buffer); ii++) {
            buffer[ii] = nextByte++;
        }

          //write it to the server
        int count = client.write(&buffer[bufOffset], sizeof(buffer));

       //end the request
       client.println(end_request);
        client.stop();
       }
      }

You should forget about MIME, that is only needed if you are sending multiple files to the server. Your best bet is to just send these headers, then a blank line, then your data:
POST /api/users HTTP/1.1
Accept: */*
Content-Type: application/octet-stream
Content-Length: 123

On the other end, you just look at "request.body" and it should have your binary data. (Replace 123 with sizeof(buffer))

Thank you BraveNewCurrency. If i send a jpeg bytes though application/octet-stream, on the other hand how hard is it to handle those bytes back to the image(what do i need to do)?Thank you again.

Er, you don't need to "do" anything, bytes are bytes.  If you prefer, you can set Content-Type to be image/jpg. I suppose it could matter if your web server is checking content-types. (I assumed you were sending to a custom server, so you were not checking the content-type.)


text:
Trying to send data to the server and AT+CIPSEND not working correctly
Sending data to the server(thingspeak.com/184.106.153.14) with AT commands on serial monitor works fine but whenever i upload the sketch ,the following always return false if(Serial.find( ">" ) ). I am not sure if AT+CIPSEND is not working correctly or what. I am using Arduino with ESP8266. Any help will be appreciated.Thanks you in advance. Here is my code.
  #include <SoftwareSerial.h>
  SoftwareSerial softSerial(2, 3); // RX, TX

  #define SSID "myssid"
  #define PASS "Mypass"
  #define IP "184.106.153.149" // ThingSpeak

  void setup()
  {
   uint32_t baud = 9600;
   Serial.begin(baud);
   softSerial.begin(baud);

   connectWiFi();
   }

   void loop()
   {
    updateTS();
    }

    void updateTS()
    {
    String cmd = "AT+CIPSTART=\"TCP\",\"";// Setup TCP connection
    cmd += IP;
    cmd += "\",80";
    sendDebug(cmd);
    delay(2000);

    String url = "GET /update?key=P55Z0BDASNQBFQKT&field1=15&field2=25\r\n\r\n"; //hard code value 15 and 25
    String stringLength="AT+CIPSEND=";
    stringLength +=String(url.length( ));
    Serial.println(stringLength);
    //delay(10000); I even tried to delay for few seconds

   //Here is where it fails,it jumps to closing the connection
   if(Serial.find( ">" ) )
    {
     softSerial.print(">");
     softSerial.print(cmds);
     Serial.print(cmds);
    }
    else
    {
     sendDebug( "AT+CIPCLOSE" );//close TCP connection
    }

    }

   void sendDebug(String cmd)
    {
      softSerial.print("SEND: ");
      softSerial.println(cmd);
      Serial.println(cmd);
     }

     boolean connectWiFi()
    {
      Serial.println("AT+CWMODE=1");
      delay(2000);
      String cmd="AT+CWJAP=\""; // Join accespoint
      cmd+=SSID;
      cmd+="\",\"";
      cmd+=PASS;
      cmd+="\"";
      sendDebug(cmd);
      delay(5000);
      if(Serial.find("OK"))
      {
       softSerial.println("RECEIVED: OK");
       return true;
      }
      else
      {
       softSerial.println("RECEIVED: Error");
       return false;
       }
     }

To what Arduino pins have you connected the ESP?

On arduino i made pin 2 as Rx and 3 as Tx.All these go through logic converter. But like i mentioned above when i run the AT commands on serial monitor data get sent fine to the server only when i upload the sketch.

Your code looks like you connected the ESP to the hardware serial port, but your comment says otherwise so:
Your sketch isnt working because you're writing to the wrong serial port half the time, and even when you do use the right serial port (softSerial) you're sending garbage along with it.
Serial.println(stringLength); and Serial.find("OK") should be softSerial.println(stringLength); and softSerial.find("OK").
Serial.find( ">" ) should be softSerial.find( ">" ). You should look for '>' in the buffer between the Arduino and the ESP8266 and not the one between the Arduino and the PC.
softSerial.print(">");, softSerial.println("RECEIVED: OK"); and similar statements should not be there at all. They are not commands or arguments to a command so why are you printing them to the ESP? Whenever you write to softSerial, make sure its a command. Dont send your debug messages to softSerial; use Serial instead.
There's no variable called cmds and yet you're printing it to the serial port. Assuming this code compiled, its probably a typo in your question?
Finally, your code structure is unreliable at best, what with all the delays in it and not a single Serial.available() or softSerial.available(), not to mention the abundant usage of Arduino Strings. I suggest you first learn how to read from a serial port and build C strings from the results and then re-design your code again. Majenko's blog is as good a tutorial as any. Or you could download a library like this one that provides an easy API to the ESP8266, shielding you from the mess of AT commands, while providing you with example sketches that already do what you want. Of course, you could choose to go through their library (.cpp and .h files are the place to be) and figure out how they used AT commands with the ESP and then write your own sketch, library or whatever. Good luck.


text:
Using AVR Timer Within an ISR
I'm trying to create an ISR which operates for 15 seconds when a particular button is pressed. I'm attempting to use the AVR functions on my Arduino Uno to start counting when it enters the ISR, then quit the loop when it reaches 15 seconds.
I'm having difficulty reasoning out where the counter is actually stored that I want to use for my while loop.
Here is my code so far:
#define button_pin 2
#define duration 15
#define osc_in 0

#include <avr/io.h>
#include <avr/interrupt.h>

const float convert = 5.0/1023.0;

void setup() {

  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1 = 0;
  attachInterrupt(digitalPinToInterrupt(button_pin), button_interrupt, CHANGE);

  sei();

  pinMode(button_pin, INPUT);
  Serial.begin(9600);
}

void loop() {
    //int channel1 = analogRead(osc_in);

//while (millis() < 10000)
  //Serial.println(millis());
  //Serial.println(channel1 * convert);
  //channel2 = channel1;
}

void button_interrupt(){
  //(# timer counts + 1) = (target time) / (timer resolution)
  //int timer_counts = duration/(pow(6.4, -5));
  //int dur = 234374;
  OCR1A = 234374;
  TCCR1B |= (1 << CS10);

  while (????????){
    int channel1 = analogRead(osc_in);
    Serial.println(channel1 * convert);
  }
}

Doing serial inside an ISR is typically a bad idea.  Maybe consider doing your sampling continuously, and using an ISR to set a flag and initiate a 1-shot timer.  The the loop code could check the flag and do the 9600 baud serial reporting as needed.

Don't do delays inside an ISR. Don't do serial prints inside an ISR. Read this.
You need to redesign. The ISR can set a flag, that you then test in loop. Do the delay in loop.


text:
Problem with ATtiny85 and RF modules
I am doing a project on a ATtiny85 which involves using 433MHz RF modules. Whenever I want to compile any sketch using the Manchester library I always get these errors : "Manchester library doesnt support your microcontroller". Could anyone help me solving this?

Somehow I got it working. I don't know the cause of the problem but in order to fix it I had to Arduino 1.0 IDE; use this ATtiny support and this Manchester library. Thank you all for your help.

Could you share your code?


text:
How to use printf with Arduino's serial ports without an intermediary buffer?
How to use printf with Arduino's streams without an intermediary buffer? The following seems unnecessary:
char buf[256];
sprintf(buf, ...);
Serial.print(buf);

Is there a way to connect HardwareSerial or SoftwareSerial to a libc stream or is there a custom implementation of printf that does this?

Sure - here's a Hello, World program that uses printf(). Everything that mentions "uart" is what connects printf() to your output stream. uart_putchar() does the actual outputting to ... someplace. That's what you'd modify to direct the C standard output to a different device - SofwareSerial, for instance:
// Hello, World program using printf()

#include <Arduino.h>

static FILE uartout = { 0 };   // FILE struct
static int uart_putchar(char c, FILE *stream);

void setup() {
   // For printf: fills in the UART file descriptor with pointer to putchar func.
   fdev_setup_stream(&uartout, uart_putchar, NULL, _FDEV_SETUP_WRITE);
   stdout = &uartout;

   Serial.begin(9600);
   printf("Hello, World!\n");
}

void loop( void ){
   printf("Elapsed time: %ld\n", millis());
}

// uart_putchar - char output function for printf
static int uart_putchar (char c, FILE *stream)
{
   if( c == '\n' )
      Serial.write('\r');
   Serial.write(c) ;
   return 0 ;
}


text:
AVR has no vprintf_P?
Well this was unexpected. AVR libc has many the variants of printf, including vprintf, but is missing vprintf_P. Is this really just not present or implemented elsewhere?

It has vfprintf_P and stdout is a FILE. Why would you want to waste time and space with implementing vprintf_P as well?
If you really want it, you can make your own:
#define vprintf_P(...) vfprintf_P(stdout, __VA_ARGS__)

Incidentally, the source code to vprintf looks like this:
int
vprintf(const char *fmt, va_list ap)
{
    return vfprintf(stdout, fmt, ap);
}

That does exactly the same job as a preprocessor macro - just forwards your request on to the FILE-based function.
It is actually more efficient to use a preprocessor macro than needlessly nesting functions like that - less stack usage, less calls, etc (unless the compiler happens to choose to inline that function, which since it is in a library it likely won't).
The non-FILE based functions can be considered simple wrapper functions to the FILE-based ones. They are mostly provided for convenience, but are actually completely redundant and can all be replaced with direct calls to the FILE-based variant.  They mostly still exist purely for historical compatibility. And since _P is specific to AVR libc there is nothing historical for it to be compatible with.

That wouldn't be a good explanation for why it does have printf, sprintf, snprintf, vsprintf, vsnprintf, fprintf, vfprintf and all of their _P variants, would it?

It would be just idiotic to miss out printf. All the others either take a file or string as their target, which means they are the base ones. All other functions can be made from them. You don't like it? Then submit a patch to the repository and stop complaining.

Wow. Fair question met with an obnoxious attitude. Okay, I'm going to go waste everyone's time and space with the patch!

I was going to say the same thing - fair answer met with an obnoxious attitude. You ask a question, get the answer, but don't like that answer because it doesn't agree with the answer you have already formulated inside your head, so start with the 'tude.

I asked yes/no question. I would've accepted the answer "no, it's not implemented". I didn't ask for your opinion on whether the function is a waste of time and space, did I? It's also a laughable answer in itself since you yourself illustrated that it's a trivial one-liner. That's okay. This is all public. Let others judge.

So you don't think it's even slightly valuable that, since as you say this is public, other people might not want to know why it might not have been implemented, and how to implement it themselves should they want to? Maybe you should have privately emailed one of the developers of libc instead.


text:
How does Arduino distinguish between SPI programming data and regular data?
The Arduino can be programmed using SPI without a boot loader. Without a boot loader, the Arduino starts running its sketch right away. So, how does the Arduino know that it is being programmed via SPI vs regular SPI traffic already present on the SPI bus? Was is the pin-level, electrical signal that let's the Arduino know the difference?

In-system programmer is activated with RESET line. During normal operation reset line is not active and ISP module is disabled.
You can find detailed description of AVR ISP in this document:
http://www.atmel.com/images/doc0943.pdf