text:
Arduino Servo won't move when using classes
I'm trying to make a class work with Arduino, however it doesn't seem to trigger properly. The code is compiling perfectly, and it's supposed to control the leg of an hexapod. Also, the example sweep works on this servo, so no problem here. However, the servo is not actually moving. I'm thinking it has something to do with the order of declaring the variables:
#include <Servo.h>

// Abstract each leg, so only those functions can be accessed
class Leg {
  // Actions that can be triggered from outside
  public:
    Leg(int hipPin, int kneePin);
    void up();

  // These should be only available for the leg
  private:
    Servo hip;
    Servo knee;
  };

Leg::Leg(int hipPin, int kneePin) {
  hip.attach(hipPin);
  knee.attach(kneePin);
  }

// Testing the leg: move it up
void Leg::up() {
  for(int pos = 0; pos < 180; pos += 1) {
    hip.write(pos);
    delay(15);
    }
  }

// Initialize the leg
Leg topLeft(9, 10);

void setup() {
  }

// Test the function up()
void loop() {
  topLeft.up();
  }

I'm testing only the pin 9 (leaving the 10 empty). It seems in pain, meaning, you can see the servo trembling but not moving really at 0 degrees.

Note: similar question to this one, but since the solution didn't work for me, I'm assuming it's not the same problem. Any help debugging it is also welcome (:

Does the same setup work with the same pin when you test just the hip servo code outside of class? Does the problem only occur when the code is inside the Leg class?

Your problem may be similar to this question: http://arduino.stackexchange.com/questions/830/timer2-does-not-work-as-it-should

It looks this problem may be due to bad order of initializers calls for global variables.
In C++, the order of global variable initialization is unpredictable across different compilation units (i.e. C++ source files, not header files). Initialization order is only respected inside one compilation unit.
In your program, there are several global variables that, if initialized in the wrong order, will fail your program:

Leg topLeft; this is your class instance
servo_t servos[MAX_SERVOS];, int8_t Channel[_Nbr_16timers ]; and uint8_t ServoCount = 0; all defined in Servo.cpp

Calling Servo.attach() requires that the 3 variables above have already been initialized, which you cannot be sure of.
How can you fix that?
By not performing the attach() in Leg constructor but delegating it to some kind of init() method that you can call from setup():
class Leg {
    // Actions that can be triggered from outside
    public:
    void init(int hipPin, int kneePin);
    void up();

    // These should be only available for the leg
    private:
    Servo hip;
    Servo knee;
};

Leg::init(int hipPin, int kneePin) {
    hip.attach(hipPin);
    knee.attach(kneePin);
}

// Testing the leg: move it up
void Leg::up() {
    for(int pos = 0; pos < 180; pos += 1) {
        hip.write(pos);
        delay(15);
    }
}

// Declare the leg
Leg topLeft;

void setup() {
    // Initialize the leg
    topLeft.init(9, 10);
}

// Test the function up()
void loop() {
    topLeft.up();
}

Just for clarification, the initialization order of global variables is not defined only between different translation units. In the same translation unit, it is the order of their definitions.

+1 this is gold, the explanation just solved about 100% of the unresolved problems I've ever had with arduino and C++. Thank you, I'll test it when I get home.

@Omer thanks for the clarification which I had forgotten to include. I have just edited my answer.


text:
strange behaviour of dtostrf()
I'm trying to program a little bit in Arduino, but I'm stuck with probably something trivial.
This is what I have:
char ang[3], lat[9];
dtostrf(GPS.angle, 3, 0, ang);
dtostrf(GPS.latitude, 9,5, lat);

Serial.println(lat);
Serial.println(ang);
Serial.println("-------");

I would expect the following in the serial monitor:
5111.60160
267
-------

But instead, I'm getting this:
5111.60160
2675111.60160
-------

So it looks like the ang holds both the angle and the latitude....
Why is this happening? And how can I solve this?
My goal is to make one big string, comma separated, from the data stored in GPS

You might need to null-terminate the string. The last byte should be \0

Euuh, ok. How do I do that???

Increase the size of the arrays by 1 and then do ang[3] = '\0';

Your arrays are both too short for the strings they're meant to hold. In particular, ang has three digits and only three bytes. The string-terminator, NUL, ends up in the 1st byte of lat. Since you generated the ang string first, lat over-wrote ang's NUL character, effectively getting appended to ang.
The lat string will need at least (10+1) bytes; ang will need (3+1) bytes, counting only the actual data in your question.
I make it a habit to declare string arrays just as I wrote the sums above, to make it clear that I've counted both the contents and the NUL byte, so:

char ang[3+1], lat[10+1];

I doubt that you need to specifically add the NUL terminator; it would quite unusual (counter-conventional) for a C/C++ function that generates a string to leave off the terminator (except in a few special cases).
Try increasing just your array sizes first; it'll probably work.

source: Stack Exchange

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

sort: votes


text:
Change device Function Summary for Teensy-LC
I found this thread here which describes procedure to change the produce-name of Teensy
However when we open device properties we see 'Teensy USB Serial (COM xx) in the Device function summary.
Please find the image below to understand what I am referring to.

So is there any way to change this details as well?

I think that string is inside the USB code in the Teensy. Conceivably you could locate the appropriate library and change it.

Could this string be inside the Teensy bootloader and presented to the USB device layer (Windows) when waiting for upload? In that case I don't think it is possible to change as the Teensy bootloader is not open-source.

Could you link or give the URL of the "thread" you found? Thank you.

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


text:
Arduino over a Network
I am new to arduino programming. I want to sense temperature and send it to a server in my college. I am using Arduino Uno R3 board which has ATmega 328P micro-controller. I am able to get serial output on my PC but is there a way in which I can send temperature data to the server in a packet format using Arduino Programmer and not using Ethernet Shield ? Please answer in a less complex way.

Without an ethernet shield or some kind of other internet connectivity shield/circuitry you cannot communicate directly with the internet through the arduino. However, if having a computer as the internet communicator isn't a problem you could try a setup like:
arduino->serial (usb)->processing->internet
This way you create the internet packet in processing using the temperature information received through serial from arduino.
see also https://processing.org/

Use an Arduino Yún: it's a Leonardo coupled with a CPU running GNU/Linux (a flavour of OpenWRT).
Using the Bridge library, your sketch can delegate tasks to the linux side.
HttpClient example (Examples > Bridge > HttpClient) GETs a page from the Arduino web site, but the HttpClient class may POST whatever data to a server of choice.
There is also a nice example called SendDataToGoogleSpreadsheet (Examples > Bridge > Temboo > SendDataToGoogleSpreadsheet): it accumulates sensor readings on a google spreadsheet. I've used something like that on a project of mine.


text:
Teensy 2.0++ SDA SCL pins not accesible using ARDUINO software
Hi I was looking to interface Teensy++ 2.0 with MPU6050 for a simple IMU project.
I have done this previously using Teensy 3.1 by trying the project of kriswiner however I also wanted to try it out on my Teensy++ 2.0 board.
But when I went to check the pin assignments for Teensy++ 2.0 on the pjrc website it has been mentioned that the pins PD0 and PD1 can be used as SDA and SCL using C Language but there is no assignment of SDA SCL on Teensy ++ 2.0 using Arduino Software
Does that mean we cannot use these pins using Arduino software at all? Or is there a workaround to this?

Here is more info https://www.pjrc.com/teensy/td_libs_Wire.html.

BW What do you mean by ARDUINO software? The core for the Teensy++ 2.0 board is provided by PJRC (and not Arduino LLC). And you can use D0 and D1 for as digital pin, pwm, interrupt or I2C.

The pin assignments for Teensy ++ 2.0 were mentioned as such on the pjrc page. using arduino software this and using C language this

Thanks for the update. Guess that ARDUINO software should be interpreted as Arduino API. In any case, I2C is not an issue. You might consider posting PJRC a message about the "misleading documentation".


text:
arduino leonardo stops transmitting once hdmi cable is connected to a screen
I am using arduino leonardo for moving mouse pointer with head tracking using MPU6050. It works fine in general. But as soon as I connect an external lcd screen to my laptop via hdmi cable, it stops transmitting. (that is the TX led goes off altogether and the mouse stops moving) I am not able to figure out what the issue is here Will using a teensy 3.0 instead of leonardo solve this problem?

The issue is that the mouse coordinates are being set by the display device that it's attached to.
The computer sends a descriptor about the display to the HID device ( the mouse ) the mouse then uses the information about the logical size of the screen to co-ordinate the movements.
For example, to move with Mouse.move(100,100,0); you are not actually moving by 100 pixels, but by 100/(127-((-127)).
The only option is can suggest is to STOP the mouse and Restart it again - this will be easier to restart calculations again.
Heres my Logic Function to convert Percentage to appropriate values for Mouse.move();
int percentToLogic(int percent) { return percent*254/100; }

I have no idea how this answers this nearly six your old question, but I can see you put some effort into it. Typical mice transmit relative coordinates and have no idea how large the screen is or even whether or not one is plugged in.  Absolute position mice send information with respect to where they are within their own coordinate system, and likewise normally completely unaware of the monitor connectivity and its geometry.

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


text:
Controlling a 240v AC high current relay
Should I use 2 relays, one for the hot wire and one for the neutral ?
I'm talking about 16A.

I read elsewhere putting only 1 relay on the hot wire should be sufficient, depending on configuration, when having 2 relays, if the one connected to neutral fails, could lead to dangerous behavior.

1 relay, 2 poles as others say BUT at 16A use a guaranteed quality relay GUARANTEED rated at the load type, current, voltage etc that you are using. DO NOT use the cheap Chinese relay modules sold for hobbyist use. They are excellent value for low voltage and safe things but risk death and destruction on higher loads and voltages. | AC load I assume? 230 VAC/ 110 VAC ? Inductive resistive capacitive motor contactor ...? It matters. Even NC and NO matter at 16A.

Use 1 relay, more precisely a DPST (Double pole, single throw) type. You'll only need 1 signal to drive both, and be sure that both lines are switched off. Electrical installation regulations require double throw relays/switches for certain applications, e.g. in wet rooms like bathrooms.
Note that relays are more delicate devices than they appear to be. A 16A relay may not always be suitable for switching 16A. They have to be derated according to their type of load. And that is almost everything. Not only for capacitive or inductive loads you'll have to limit the current to a fraction of the rated 16A, but even for incandescent lighting (due to the high current peak when switching on). See the manufacturer's datasheet or application documents for the amount of derating.

@Majenko: thanks for pointing that out. Corrected.

As mentioned in the comments, if switching both, and the neutral relay fails open, unpredictable things may happen.
If you really want to switch both then use a two pole relay which switches both the live and the neutral together.
For instance, I use these relays:

http://uk.farnell.com/finder/22-22-9-012-4000/relay-modular-dpst-no-12vdc-20a/dp/1169296

20A, 250VAC contact rating, double pole.


text:
Send numbers bigger than 256 by SPI
How can i send numbers like 300 or 1024 ?
I'm using the recommendation of the atmel's manual.
void SpiTransmitir(unsigned char data)
{
   SPDR = data;
   while(!(SPSR & (1<<SPIF)));//{Serial.println("While");}
}

I imagined that one bit shift could be the solution, but it still fails.

You need to send two bytes - a high byte and a low byte.
There are two things you need to know with SPI:

You must wait for one byte to finish transmitting before you send the next
The whole transaction needs to be wrapped with a digital chip select signal.

So you have:

Chip Select idles HIGH
You lower Chip Select
You send one byte
You send the other byte
You raise chip select

At the receiver you:

Wait for chip select to go low
Receive one byte
Receive a second byte
Chip Select rises
You combine the two bytes together into one integer.

Can i use the arduino's functions  lowByte() highByte()?

You can, yes.  Or just do it manually with >> 8 and & 0xFF

Try to join the numbers as follows:
#define NUMERO 342

void setup() {
  Serial.begin(9600);
  Serial.println(NUMERO, BIN); // Mostra valor do número em binário

  uint8_t MSB = 0, LSB = 0; // Dois números de 8 bits

  uint16_t junta = 0; // Valor junto em 16 bits

  MSB = NUMERO >> 4;
  LSB = NUMERO << 4;

  junta = (MSB << 4) | (LSB >> 4) ;

  Serial.println(junta, BIN);
}

void loop() {}


text:
How do I know when the connections is ready between Arduino and QSerialPort
I am trying to send data from QSerialPort to Arduino Mega 2560. The proccess always takes some time to establish the connection.
How do I know with QSerialPort is the connections is ready to send data?
I don't know how much time do I have to wait for that and it happens every time when I run the application.
The configuration of my QSerialPort instance is:
mSerialPort = new QSerialPort();
mSerialPort->setPortName("COM3");
mSerialPort->setBaudRate(QSerialPort::Baud9600);
mSerialPort->setDataBits(QSerialPort::Data8);
mSerialPort->setParity(QSerialPort::NoParity);
mSerialPort->setStopBits(QSerialPort::OneStop);
mSerialPort->setFlowControl(QSerialPort::NoFlowControl);
mSerialPort->open(QIODevice::ReadWrite);

I check the device configuration of COM port:

I also changed and play the Arduino delay but nothing changed.
I am sending to Arduino little piece of data. Example:
X100.10,Y10.23, H9999, ...others

And these data work when I am debugging the functions of my application. Everything is writting and work. So I am lost.
I hope all this information be usefull to give me an answer or at less some tips.

I am guessing that what you are seeing is not the port taking some time to open, but the Arduino resetting as soon as you open the serial port.  That means there is a short time while it's in the bootloader looking for an "I am here" signal from avrdude.  The timeout of that signal is configured in the bootloader, and is usually something like 1 second.
The simplest thing you can do is, as one of the first commands in your program, send an "I am ready to receive" signal to the computer (maybe just the word "OK" or something like that), which you then wait for before sending your data.

I just send a command from my Application with QSerialPort but it take a little time. I wait the answer from Arduino and after a 40 seconds I get the answer? I don't know why and I don't understand this behaviour

40 seconds is unusual.  It could be that you are sending the message too soon and the Arduino isn't receiving it.  Add a delay of 2 seconds between opening the serial port and sending the message, see if that helps.

I put an sleep of 2 seconds but nothing... it takes a long time to get an answer.


text:
Arduino raise the error: `does not name a type` when an Object is used outside of the main two blocks setup and loop
I have this:
class Person{
public:
    int age;
};

Person p;
p.age;

void setup() { ... }

void loop() { ... }

And I got this error:
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
MyProgram.ino:18:1: error: 'p' does not name a type
Error compiling

But is I use the Person instance inside setup or loop functions it compiles find.
void setup() {
    // initialize digital pin 13 as an output.
    Person p;
    p.age;
}

I got this:
Compiling 'MyProgram' for 'Arduino Mega w/ ATmega2560 (Mega 2560)'
Binary sketch size: 4,674 bytes (used 2% of a 253,952 byte maximum) (3.45 secs)
Minimum Memory Usage: 428 bytes (5% of a 8192 byte maximum)

What is the different? Why the instance only can be used into the blocks?
I also declared a file with a simple class and then create a instance of it class outside the blocks and I got the same error. If I put the instance inside the blocks it works. So, any tips?

As you have already noticed, you cannot call methods of a class, nor access its properties, outside a "block" (as you call it).  More specifically, you can only perform "programatical" operations from within a function.  Anything outside a function (known as the global scope) is purely for declaration and initialization of variables and types, etc.
Any class variables declared in the global scope have their constructor executed before the rest of the program (even before setup) gets run.  However, setup is not the first function to be called at startup.
Anything you put into a constructor has to take into account the fact that anything might be happening between the constructor being called and the object instance actually being used.  Things like pinMode and digitalWrite are unsafe to use in a constructor, since there is a chance they may be negated during the startup.  That is why the majority of Arduino classes have a .begin() method which is called from setup().
The proper method for using classes with pin control and similar operations is:

The constructor takes the pins to use
The constructor saves those pins in variables
The begin() method is called in setup()
The pins are configured appropriately.

For example:
class myClass {
    private:
        int _myPin;
    public:
        myClass(int pin) : _myPin(pin) {}

       void begin() {
            pinMode(_myPin, OUTPUT);
            digitalWrite(_myPin, HIGH);
        }
};

myClass p(4);

void setup() {
    p.begin();
}

void loop() {
}

The object instance p is in the global scope and can be referenced from any function. The pin is configured only when setup() is run.
The startup sequence, more specifically, is typically this:

The memory used by global and static variables is "zeroed".
Any pre-defined variable values (BSS) are copied from flash into RAM.
Any object constructors are called.
The main() function is called (main startup function).
The init() function is called which configures the Arduino platform.
The initVariant() function is called which performs any board specific setup routines.
USB is configured on the boards that have it
Your setup() function is called.
Your loop() function is called.
The serialEvent() system runs if defined.
Go to 10.

As you can see quite a lot happens between the constructor being called and setup() being called, and you cannot reliably predict what that might be.  Some boards may do nothing more than configure interrupts and enable timers (for things like delay and millis), but other boards may configure IO pins to default settings (especially more complex boards with multiple functions per IO pin), so really the only safe operations you can perform in a constructor are operations which act directly on the internals of the class itself.  Anything outside the scope of the class could be changed before you come to use it.

All code intended to be executed must be inside a function block in C++.

So, I can create an object instance but if I want to use it I have to invoke the functions inside the block? Is that correct? I am asking because right now I cannot test the arduino project.

That is correct. You can declare and initialize an object in the global scope, but you cannot call its methods or access its fields.

Having said that, it is possible to create additional memory segments that are executed prior to main(), but I don't know if the Arduino IDE will handle them appropriately.

I am trying to create a simple instance before the setup() and loop() blocks. Inside the instance I configure some pins to the output mode. But Arduino show a wrong behavior. But if I configure this pins into the setup blocks the Arduino show me the right behavior. I am really confuse. Because I want to use some class to reuse some functions.

Then put the code to configure the pins in the constructor block.

 pinMode(this->m_stepPin, OUTPUT);
 pinMode(this->m_direction, OUTPUT);``` I have this inside the constructor block but If does not run like I expect. When I create this configuration inside setup() function the problem is fixed. Then I am thinking that maybe Arduino is not handle this instance in the right way.

Let us continue this discussion in chat.


text:
Why did my pushbutton LED circuit work when my wiring was wrong?
I had a Coursera Arduino homewhere wherein you create a simple pushbutton-controlled LED circuit.
I used the example "button.ino" script that's builtin to the Arduino IDE, without modification. I'll reproduce it at the end of this question.
Here's what I did (wrong):
My circuit went from 5V Power to the top pin of a push button. The bottom of the pushbutton was (correctly) wired to Pin 2 on one side and a resistor was used to wire the other bottom pin to the anode of LED. The cathode of the LED was wired to ground.
The reason I think this is wrong is that I forgot that I was supposed to wire the LED to a pin corresponding to ledPin in the example script. The example script uses Pin 13, which has the builtin LED. I was using an external LED. Yet, the circuit worked perfectly.
Why did it work? Doesn't that mean the 5V power output was getting turned off (I'd guess you call that being set to LOW) when Pin 13 was set to LOW? Why would that be the case?
/*
  Button

 Turns on and off a light emitting diode(LED) connected to digital
 pin 13, when pressing a pushbutton attached to pin 2.

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached to pin 2 from +5V
 * 10K resistor attached to pin 2 from ground

 * Note: on most Arduinos there is already an LED on the board
 attached to pin 13.

 created 2005
 by DojoDave <http://www.0j0.org>
 modified 30 Aug 2011
 by Tom Igoe

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Button
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;     // the number of the pushbutton pin
const int ledPin =  13;      // the number of the LED pin

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

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

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

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

It worked because your button was controlling power to your led. The Arduino was doing nothing at all.

@Majenko Thanks. Yes, they did say that the Arduino was only supposed to supply power and ground for this homework, so I guess that was as it should be after all. Incidentally, the on-board LED seemed to read the state of the pin correctly, which was something I didn't even think to look at until just now. As simple as this was, I think it's a good beginner exercise.

The LED wired to the push button was turned ON by the push button closing the circuit, without any intervention from the micro controller.
That's a pretty simple circuit: a voltage source, a switch, an LED and a resistor, all in series. When you close the circuit the LED turns on. Simple.
The code on your microcontroller is watching the state change on the button and turning ON/OFF the on board LED: it has nothing to do with the LED in your circuit/breadboard.

Why did it work?

the button is shorting the led (turning it off) when it is closed. when the button is open, the led lights up from the resistor.
essentially your arduino is not involved with the led's operations.

Follow up question: what happens to the 5V when the button is open? It doesn't have a complete path so it just stays in the Arduino and the wire that leads up to the button?

The circuit you are describing seems to just have the button control whether the LED got the supply or not. Unless pin2 was grounded, you effectively supplied 5V to the resistor-LED as well as pin2 through the button.
This essentially gives you the standard LED circuit.
Have a great day!


text:
Can i use arduino code, without using arduino board but just using MCU included
I am developing a product, and to ease my job i am planning to use MCU inside the arduino with the library of Arduino.
Since all the registers are already defined inside the library, and all required things to registers of corresponding MCU are done to "make a pin input/output , enable interrupt , enable UART , enable I2C". I think that i can directly use the arduino coding enviroment even if i use MCU seperately.
Is it possible and how?  (can i use it in commertial product, i have already prototyped it with arduino)

Yes, you can. Once you have a .hex file for a specific MCU and environment you can use a programmer to upload it to a discrete MCU.

Does arduino coding enviroment generate Hex file? Normally i was Pic, Intel user however, i did not see the compiler generate hex file. Should i need to use just its library and insert into another coding environment and how?

Other questions on this site discuss both the .hex file and the use of alternate development environments.

Actually, i am not asking hex file issue, i am asking that if we use USB-serial circutry, and just burn bootloader to the MCU via this then just upload the code we wrote... doesn't it work for all arduino used MCU's ??

Why would you add the cost of a serial interface to your product instead of using the built-in ISP capability?

Yes actually, i can use my arduino to code the MCU...

to be direct... i wonder if i can use the method http://arduino.cc/en/Main/Standalone to programme ATmega2560 used in arduino mega?

There is no need for a bootloader if you stick with ISP.

Ignacio said everything is needed. Just search on google :) You can use programmer like khazama.
Also you can use arduino board to program atmel chips.
Using an Arduino as an AVR ISP
And now you need only .hex file to upload to your chip
How to find .HEX
I just want to point out one thing. Do not play with lock bits:)

@PeterR.Bloomfield :))

I know khazama. Such uploaders also used for PIC microcontrollers 16F877 etc. I have already used them, but i am planning to use the chip in arduino MEGA or Leonardo, which are surface mount...
Therefore, it seems that i need to use ISP...

Thats not right. You can use USB-TTL converter like it is done in Arduino. There are many schematics and tutorials how to write bootloader and so on. Surface mount you mean mega2560 TQFP package? I do not understand your argument.

You can program an AVR microcontroller easily with an existing Arduino as the programmer. AFAIK there's no easy way around SMD packages. The last time I've gotten them, I have to solder programming wires on them before placing it on the board. If you have space, you can also wire the ISP pins to a connector on the board.
In any case, here are the steps to program your chip, whether DIP or SMD.

Upload the Arduino ISP Sketch to your Arduino board's MCU.
Wire up the Vcc and GND, and the SPI pins (MOSI,MISO,SCL). (The wiring is actually described in the comment section of the sketch. As for the pin out on the ATmega328, go to page 3. You can find similar datasheets if you're using other MCUs.)
Write your code
Click "File>Upload using programmer" or just press Ctrl + Shift + U.
Done!

I think most AVR MCUs come with an internal calibrated resonator, but if you want to drive it at a higher speed (16MHz/20MHz...) you will need to connect the MCU to a crystal oscillator. As always, refer to the datasheet. ;-)
Here's another link you can refer to: link
Hope this helps.


text:
How to understand the "power economy" of a voltage up-converter (boost converter)?
My online video Arduino instructor makes use of various devices to amplify signals, currents, and voltages. This seems like magic to me.
For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.
I'm going to assume there must be some tradeoff here, because otherwise we can just use a giant string of these up-converters to give the world infinite energy from a single AA battery. I found the Wikipedia articles on this topic a little hard to understand, but basically gathered that if Voltage is boosted then it's at the expense of current. My questions are:

Is my understanding correct (higher voltage = lower current)?
If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?
What are the practical limits of this type of conversion?

I would appreciate a plain-language (easy to understand) answer. I'm also kind of curious how the conversion works, but I assume that will be highly technical.

yes.  2. there's still enough after division. 3. heat, space, economy, added up-front investment, DC-DC power (V*A) loss (~5-20%).

To explain the step up: imagine two batteries in series, the voltage is double the single cell's voltage. now replace the battery with a charged capacitor; same voltage doubling. now imagine you could disconnect the series chain and charge each cap in parallel, using only half the output volts. once charged, re-connect in series and drain. repeat 100,000 times a second and add a smoothing cap to the output to keep a steady double voltage. basically it, though most converters use caps and innductors and more complex cycles...

He is describing a boost converter which steps up voltage at the expense of current. To quote from the Wikipedia page on that subject:

A boost converter (step-up converter) is a DC-to-DC power converter that steps up voltage (while stepping down current) from its input (supply) to its output (load). It is a class of switched-mode power supply (SMPS) containing at least two semiconductors (a diode and a transistor) and at least one energy storage element: a capacitor, inductor, or the two in combination.

As an example, an Arduino Uno consumes around 50 mA from the power jack (at 9V) running a "do nothing" sketch like this:
void setup () {}
void loop () {}

You could say that this is consuming 450 mW of power.
9V * 0.050A = 0.450W

To run from a lower voltage the boost converter (say, 3V) you still need to get 450 mW of power, so therefore it will consume a higher current:
0.450w / 3V = 0.150A

In other words, we now need 150 mA (3 times the current) since we have 1/3 of the voltage.
Also, these converters are not 100% efficient. Say a particular converter is 90% efficient, that means it requires even more current (150mA / 0.9 in this case, being 166 mA).
The efficiency is not linear anyway. It varies somewhat depending on the input voltage and the load. There is a question and answer on Electronics Stack Exchange (Boost Converter Efficiency goes down as Duty Cycle goes up?) which discusses this.

Is my understanding correct (higher voltage = lower current)?

Yes - in the sense that the device consumes power. Thus a higher voltage requires a lower current to deliver the same power. Conversely, if you drop the voltage you need to increase the current to get the same power.

If the current decreased then why was this still an adequate power source for Arduino? Does current not matter?

Yes it matters. You need a certain voltage, with the capability of providing enough current. In this particular case if your batteries can supply 166 mA then the Arduino can still run.

What are the practical limits of this type of conversion?

You will eventually exceed the capacity of your battery to supply enough current. A more elaborate Arduino circuit may involve LEDs and motors. The higher current drain may exceed what the battery can supply, or possibly it will just be drained quickly.
Another factor is that batteries are less efficient when supplying higher current (the quoted mAh figure for a battery is usually for quite a low current). In other words, if you double the current drawn from a battery, the time the battery lasts is not half the time, it is less than half the time. One of the reasons for this is that batteries have an equivalent series resistance (ESR). At higher current drains there is a larger voltage drop over that resistance (some power gets turned into heat, in other words). Thus it isn't practical to try to get 10 amps from an AA battery. The battery will just get very hot.

For instance, he has 4 AA batteries with 1.2V each. He says "that's not going to be enough for Arduino" so he then passes the power through a voltage up-converter and increases it to 9V.

This is actually quite inefficient in the first place. The Arduino nominally can run from 5V (if sent directly to the 5V pin on the board) and 4 * 1.2V is 4.8V which should be close enough for practical purposes.
His idea is to step up the 4.8V using a boost converter to 9V (which in itself has some inefficiency) and then use the voltage regulator on the Arduino to drop the 9V back to 5V which is also inefficient because some power is now being dissipated as heat.

Thanks very much. In explanation of the prof's rationale for using the up converter, there was also a motor and motor shield involved, so I assume it used more power. I didn't want to over complicate the question with that detail though.

I presume he has field-tested this concept, so no doubt what he says is right. :) However with motors my comments about the higher current possibly not being available from the battery are even more relevant. Within reason this is a perfectly valid concept. For example, cordless mice which only have a single AA battery in them no doubt have a boost converter inside. You usually find though that mice with two batteries have a longer quoted life (less boosting required).


text:
ESP32 reset loop when using wifi.h
I have a strange behavior, using ESP32 devkit v.1 boards.
Everything works, I can upload blink sketch, serial works, led blinks.
However, once I upload any sketch which is using the wifi.h (and utilizing it for example calling WiFi.mode(WIFI_STA);), upon upload, the board keeps resetting the serial connection, stays up for not more then 1 second, resets again, and so on.
I could not debug the issue, since serial is unusable. Any ideas what is wrong? I did a fresh ArduinoIDE, ESP32 board manager install, etc. and normal sketches work flawlessly.

based on esp8266 experience. try to erase the flash with esptool.

Could be a power problem. WiFi needs a lot of power.

@Majenko, the devkit has USB connector. I assume Miro powers the board from USB.

Yes, but what from? An unpowered hub would be fatal...

Guys, Juraj was right, I had a too long usb cable, no idea that the power loss could be high enough not to run the esp. Sorry for an unnecesaary question. If anyone has reboots with wifi ON, try a shorter cable..

Majenko was right about powering issue, but the cable must be damaged somehow

The USB cable was too long, and hence power loss.
Sorry, I figured it out a day after I asked this question.

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


text:
Arduino 1.6.4 not showing any /tty/ options in Serial ports
hej guys,
recently I upgraded to Arduino's 1.6.4 IDE just to find out, that I can't seem to upload anything to my board. More specifically: The 1.6.4 IDE is not giving me the option to select the /tty/ board from the serial port list. I am avid Sublime Text 2 user, so obviously I tried to select the port in Stino and voilá: I was able to upload it to my boards.
Since I wanted to sort out if this is a software or hardware problem, I started to experiment with all my boards:
(all of them official boards, no clones)

2 x Arduino Micro
1 x Arduino Uno r3
1 x Arduino Duemillanove
1 x Arduino Mega 2560 r3
12 x Teensy 3.1
a bunch of different USB cables.

none of these boards were registered by the Arduino 1.6.4 IDE, even after restarting the software and the computer several times. i'd only get this in my port selection:

funny enough, my terminal told me the /tty/ device was there. here with the uno connected:
Dash:~ julianh$    ls /dev/tty.*
/dev/tty.Bluetooth-Incoming-Port
/dev/tty.Bluetooth-Modem
/dev/tty.usbmodemfa131

I also tried to re-install FTDI drivers, with no results.
only when I installed the old (trusty) 1.6.1 version, I was able to upload again.
all of the boards are also working fine. I just used my uno and mega another machine a few days ago for some side projects.
can someone confirm this problem with the new IDE 1.6.4 on OSX Yosemite 10.10.3? or is there any solution available online?
thanks!

What exactly happened when you tried to upload with the cu.* device?

I had the same problem when updated to 1.6.4, but with a Spark fun Pro micro.
Did a "reset to bootloader" on the pro micro, and hit upload, and it worked
 out nice and it still does!


text:
Send button press over RF
I'm trying to send a button press over RF (performing a closed circuit operation on the receiving end).
I have a controller with an UP and DOWN button. Unfortunately I am limited to the cable length, and would like to extend it with radio frequency. The controller has one cable for GND and one each for the corresponding UP and DOWN buttons.
The RF units is the typical 433mhz bought online (ebay).
Can I in someway send the signal over RF (directly on the data pin of the transmitter) without hooking it up to a microcontroller (Arduino)?

You could buy specialized an encoder/decoder IC pair like the HT12D and HT12E. They will serve as a bridge between your controller and the RF module; no need for an MCU. I've used them to control an RC car, so they should work just fine for sending 2 button presses.

No. You need a micro-controller at both the sending, and receiving sides.
eBay does set RF remotes with a few buttons. This might be easier and cheaper than making your own.

Here what might suit you http://www.ebay.com.au/itm/DC-5V-433mHz-2-Channel-Wireless-Delay-Relay-Remote-Controller-/281937100910

The reason you need a micro-controller at each end is the radio doesn't send data in a digital way.  It modulates the signal it sends to encode the data.  I'm afraid that's about as far a I got before I got lost and decided to give up.


text:
Seeeduino Motor Shield Power Supply
I'm looking to drive two DC motors (on a toy RC car) using a Seeeduino and Seeed Motor Shield V2, but can't manage to get the power scheme right. Right now, a 9V battery connected to the shield powers everything (i.e. LEDs are illuminated on the shield and seeeduino), but when I try running the motors everything flickers and the motors don't move (I assume this is because there isn't enough current). I've managed to get them working when plugging a USB and 9V battery (at the same time) into the seeeduino, as well as when plugging a 9V into the seeeduino and another into the shield (at the same time). Both of these configurations leave me feeling uneasy, as I'm not sure how the power sources will interact.
Further, there is a jumper (MB_EN) on the shield which, according to my research, should isolate the shield from the seeeduino when removed. The documentation (http://www.seeedstudio.com/wiki/Motor_Shield_V2.0) alludes to the fact that this jumper doesn't work, however. Indeed, when I try removing it, power is lost altogether.
I've found conflicting answers to this problem, none of which seems definitive. I've also found tutorials where people did exactly the same thing (with a proper arduino, mind you...) by plugging a single 9V battery to the shield. This should be possible.
I've exhausted just about every resource I can think of, and have spent innumerable hours searching up a solution -- nothing yet. Any help would be great.


text:
Having difficulty uploading sketch to an Arduino Pro Mini
Having developed and tested a project using an Arduino Uno, I would now like to upload it to an Arduino Pro Mini (5V, 328, 16MHz) for semi-permanent, long-term use, but I can't get any sign of life from the Pro Mini.
I'm using the latest Arduino IDE (v1.6.0 with Java 6, on Mac OS X Mavericks), and I've got a USB 2.0 to TTL UART 6PIN CP2102 Module Serial Converter to connect the Pro Mini to the Mac, and I've selected Tools —> Board —> Arduino Pro or Pro Mini (5V, 16MHz) w/ ATmega328.
The problem is that I don't see a suitable serial port in the list. When I plug in the Arduino Uno, "/dev/tty.usbmodem1421" immediately pops up in the Tools —> Serial Port menu, but I don't see anything similar with the Mini Pro.
The problem is probably in the connection between the USB/TTL converter and the Mini Pro, so my question is: which pins should connect to which?

FWIW the USB/TTL converter was supplied with a 5-core (not 6-core) cable to connect its 6 pins.
So do I connect Tx—>Tx and Rx->Rx, or should they be crossed over? It's fairly clear that "5V" connects to "Vcc" and "GND" goes to "GND", but what about CTS and DTR?
Also FWIW, I have googled this, and I have read a number of other posts and answers on StackExchange, but the fact that I'm here writing my question means that I'm still stuck. Any and all constructive suggestions will be appreciated. Thanks!

Forgot to mention: I've tried just plugging the six pins straight across into the six holes, and I've tried just using four connections as suggested here, but to no avail.

Linking a relevant post: https://arduino.stackexchange.com/a/95853/92185

You need to hook it up with the Arduino TX --> FTDI RX, and vise versa, so crossed over.  If you take the FTDI and hook it up to the Ardiono pin to pin as you have it pictured it should work, provided the FTDI works.
No to your note about not having a serial port, you should have that as soon as you plug the FTDI into your computer, the Arduino is not necessary for this.  First things first, check you drivers, and check your USB connection.  You won't get anywhere until that Serial port is recognized on your computer.

Thanks for your help. I think I expected to see the serial port as soon as the FTDI was present, but wasn't sure.
Now... drivers, you say? I'll go googling for those, unless someone has a helpful link...

@TimMorley Mine always install automatically, but I'm on Windows.  Who knows about you Mac guys :)  I would think it would be pretty similar to the Arduino drivers (Maybe even compatible) but I don't use that particular FTDI device.

Yay! With drivers I got the COM port to show up in the Arduino IDE; and the advice in the comment from @kontur helped me to find the split second when I had to press the RESET button; and I now have my sketch uploaded to my Arduino Mini Pro. Thank you, @Butters!

@TimMorley It looks like that FTDI is setup for the auto reset, so if you hook up all 6 pins, it should take care of the reset for you.  When I have pins like that on one of my boards, I put them in the arduino, and with just a little force forward on the FTDI, enough contact is made to flash the Arduino.

If you still have any issues, try connecting the vcc and gnd to raw and gnd near the pins. Mine worked this way


text:
gpio input read 0, but voltage is 3V3
I'm using GPIO api and configure it as input pull down. It reads value 0. However, when I use power meter, and connect this gpio and ground, it shows 3.3V. Is it normal or maybe some other peripheral module actually pull this gpio high? To reduce power consumption, should I connect this gpio to 3V3 and configure it as input pull high? Thanks.

What is your vref tied to?

How have you configured the pin as pull-down? Did you add an external resistor?

Please show your wiring and your code. Your description is not clear, on Arduino MCU, there is no notion of "input pulldown", it is either "input" (high impedence) or "input pullup".


text:
Books on Arduino development in C++
I will be using the Arduino platform with other data acquisition hardware for a school electronics project. I have limited knowledge of C++ syntax.
Are there good introductory to intermediate books that can bring a high school student with some programming experience to proficiency on Arduino?

IMHO the only way to learn it is to program it. So grab any arduino (UNO, Mega, Nano... I suggest you the mega 2560 because it'll be useful for more projects) and then go on the arduino website and follow the tutorials. Then choose a device (e.g. an LCD with Hitachi HD44780 controller) and search for "Arduino *", where * is the device; learn how to use it. Then move to the next one. The learning curve is not steep at all, and there are not many things to learn. Just, please, keep in mind that it is a MICROcontroller, not a PC. So avoid using complex structures. Keep it as simple as you can

I would start with a standard C++ introduction book to get an understanding for the language. After that I would read a book on object-oriented design and implementation.
There is a lack of books on how to systematically approach programming small scale embedded systems such as Arduino. Due to the restrictions on resources, both processing and memory, C++ has to be used "carefully". There is a need to understand some of the more difficult concepts such as volatile, virtual, ISR, etc.
Reading others code is also a very good way to learn. I would recommend looking at the source code and example sketches to Cosa. This is an OOP framework for Arduino/AVR.
Last but not least - learning by doing!
Cheers!

I'd recommend you go to cplusplus.com. Plenty of tutorial pages and topics to further your knowledge. However, be aware that Arduino uses a variant of C designed for microcontrollers (the exact flavour depends on the microcontroller type/family), rather than C++, so do be aware that some of the topics are not implementable on an Arduino. That said, I can't think why you'd be using some of the more elaborate C++ exclusive features in a fairly middle-of-road embedded system.
The only thing you need to ignore in C++ is memory allocation specifics - you're limited to the 'original' malloc() based functions rather than the all-singing-all-dancing operator new from C++. If you are in need of memory allocation functions, malloc is well-documented and a tutorial is only a quick Google away.
Of course I must also point you in the direction of the highly popular Stack Overflow site, part of this Stack Exchange network. While they don't have tutorials, there are plenty of great answers to common questions.

Only Intel's arduinoesque offerings use uClibc.

Most Arduinos (notably not the Due) run AVR microcontrollers. On these, the Arduino core library is based on AVR Libc.

@Ignacio Vazquez-Abrams: I thought "uClibc" was a generic term for a specific hardware-orientated C libraries, not a specific one; I stand corrected. Answer edited to remove direct reference.

Also, Arduino (at least for some of the boards) does use C++ the language proper; only some library support (notably the entire STL) is missing.

Recent versions of the IDE support new and delete. Thus you can instantiate classes on the heap without any trouble (excepting possible memory fragmentation). Plus what @IgnacioVazquez-Abrams said. You can basically program in C++. The STL can be installed if you want it. However exceptions are not supported as far as I am aware.

I found the Arduino examples a good reference for refreshing/learning C++.
Important Arduino C++ classes are:

String: https://www.arduino.cc/en/Reference/String
Arduino classes for components: https://www.arduino.cc/en/Reference/Libraries

To learn more about the syntax of the language, the inventor of C++ has also a couple of videos online.

There is a book called "C Programming for Arduino" by Julien Bayle that introduces it pretty well if you are just getting started at it. I think it's from Packt Publishing.
Another I found interesting is called "Practical AVR Microcontrollers" by Alan Trevennor that gives examples of programming using C without having to get an Arduino.
Otherwise, Stack Exchange is always really great to browse.

You don't actually need an Arduino to use Arduino libraries though. They work just fine with discrete MCUs.


text:
Arduino Uno R3 L(yellow) led stays on and error on upload
So I recently got an Arduino Uno R3. Installed the IDE and drivers under Windows 8.1 and everything seemed to work fine and received the 'Done uploading' message when goofing around with the Blink example(was in a hurry that day).
Next day when I connected the Uno, I noticed the L(yellow) led keeps staying on and I get the following error when trying to upload:
System wide configuration file is "/usr/share/arduino/hardware/tools/avrdude.conf"
         User configuration file is "/home/cy/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyS0
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: Send: 0 [30]   [20]

I tried on both Windows and Ubuntu and am really excited about learning things with Arduino. Thanks in advance for your help!

Have you got it working at all using Ubuntu, or was the goofing just in Windows? Each time you reboot your PC (at least for me) I have to select the correct COM port in the IDE from Tools -> Port. I think the same goes for my Linux setup (debian based), but I use that for a slightly different programming process, and I've never received an upload error using linux so I don't know what they look like. Could you add the error you get from Windows too? The current error message suggests that the IDE can't find your board.

The goofing around was only in Windows. I plugged the board now and I got "USB Device not recognised".


text:
Leonardo Serial1 enable internal pull-up for removable Bluetooth module
I would like to have a serial Bluetooth module thats completely removable, leaving nothing connected to the arduino.
My code would freeze up whenever the Bluetooth module was removed. I eventually tracked down the issue to an overwhelming amount of garbage being received from the disconnected serial pins.
I enabled the internal pull-up resistor on pin 0 (serial rx) in the setup() function which appears to have solved all my problems but is that correct? I found barely any information on removable serial devices, floating serial connections and pull-up resistors.
I suppose it's important to enable the pull up before calling serial1.begin() or maybe flushing the serial buffer once before reading any input to ensure there's no garbage?

Yes, what you have done is good.
It is important to tie all unused inputs to a stable state (normally low) to reduce current consumption from floating inputs.  When those inputs are actively used but not connected it is even more important to stop things happening that shouldn't.
As I mentioned, normally you'd use a pull-down, not a pull-up, but the UART is actually a special case where you would want to use a pull-up (as you have) not a pull-down.
UART is "Idle High", which means that when there is no data being transmitted on a line it is held high by the transmitter.  By adding a pull-up you are making it appear as if there is something connected but that something isn't actively transmitting at the moment.
The internal pullups aren't very strong, so in a noisy environment you may still get some spurious data on the UART.  If that happens then you want to add an external stronger (lower resistance) pull up.
Another thing to think about with your disconnected pins is to protect them from ESD.  You should have some TVS diodes on those pins to absorb spikes, and some small inline resistors to limit any overcurrent conditions.


text:
Is there such a thing as an "Always" loop?
I seem to remember somewhere somebody making an "Always" loop between Setup() and Loop().
But I can't find any documentation on it. Does such a thing exist, or am I imagining it?

There's nothing officially called an "always" loops as such. However, you can make a loop which goes on forever like this:
while (true)
{
    // this bit repeats forever
}

A while loop checks the condition before every iteration of the main body. If it detects that the condition equals boolean false then it will stop the loop and move on to the next bit of code.
Normally, the condition would be some kind of expression, like (x < 10). However, in the example above, the condition is hard-coded as true, meaning it will never be false so it will never stop.

Another variant - with exactly the same result - is for(;;){ ... }, which appeals to me for the simple reason that it reads almost like the word "forever". (Or maybe I just have an overactive imagination.... :-)

You might be thinking of the Serial Event system.
This is a specially defined function which runs whenever loop() finishes if there is anything to read from the serial port.

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

Basically it is implemented as a function call after loop() in the main() function, which looks like this:
setup();

for (;;) {
    loop();
    if (serialEventRun) serialEventRun();
}

As you can see there is only setup(), loop() and the serial event system.

@Spiked3 I beg to differ.  Yes, it is defined as weak, but there is a default one provided in HardwareSerial.cpp:190 which checks for serial data availability.  Yes, you can override it with your own, but if you don't (and few would) then it acts exactly as I described.


text:
How to calibrate MMC5603 magnetometer
I just got a MMC5603 magnetometer from Adafruit however the measurements are unreliable. For example when I convert it to a heading it goes from 200° to 180° and then back to 200° if I move it radially.

To calibrate a magnetometer you should perform hard-iron and soft-iron calibration. There's some guides online about how to do this but I found this digikey guide to be the most informative. Adafruit also has a guide here
I had some issues getting this to work however so here's some tricks
Using an M1 macbook
Both guides recommend to use MotionCal but it hasn't been updated in several years. If you downloaded the macOS version it might not show any available ports. To fix this you need to compile it from source – you can find details in this Github Issue but the TL;DR is:

git clone git@github.com:PaulStoffregen/MotionCal.git
brew install wxwidgets
Open the Makefile
Comment the line OS = LINUX
Uncomment the lineOS = MACOSX_CLANG
Under else ifeq ($(OS), MACOSX) add -arch arm64 to the CFLAGS
Run make and it should build

I had some issues with it not building after this which was resolved by deleting the directory and then redoing these steps
Using an Arduino UNO
Both guides say to use Adafruit Sensor Lab which is too large to fit onto an Arduino UNO's flash. Instead you can you use this code:
#include <Arduino.h>

#include <Adafruit_MMC56x3.h>

/* Assign a unique ID to this sensor at the same time */
Adafruit_MMC5603 mmc = Adafruit_MMC5603(12345);

int loopcount = 0;

// Hard-iron calibration settings
const float hard_iron[3] = {
    0, 0, 0
};

// Soft-iron calibration settings
const float soft_iron[3][3] = {
    { 1, 0, 0 },
    { 0, 1, 0 },
    { 0, 0, 1 }
};

void setup(void)
{
    Serial.begin(115200);
    while (!Serial)
        delay(10); // will pause Zero, Leonardo, etc until serial console opens

    Serial.println("Adafruit_MMC5603 Magnetometer Test");
    Serial.println("");

    /* Initialise the sensor */
    if (!mmc.begin(MMC56X3_DEFAULT_ADDRESS, &Wire)) { // I2C mode
        /* There was a problem detecting the MMC5603 ... check your connections */
        Serial.println("Ooops, no MMC5603 detected ... Check your wiring!");
        while (1)
            delay(10);
    }

    /* Display some basic information on this sensor */
    mmc.printSensorDetails();
}

void loop(void)
{
    static float hi_cal[3];
    // Get a new sensor event
    sensors_event_t event;
    mmc.getEvent(&event);

    // Put raw magnetometer readings into an array
    float mag_data[] = { event.magnetic.x,
        event.magnetic.y,
        event.magnetic.z };

    // Apply hard-iron offsets
    for (uint8_t i = 0; i < 3; i++) {
        hi_cal[i] = mag_data[i] - hard_iron[i];
    }

    // Apply soft-iron scaling
    for (uint8_t i = 0; i < 3; i++) {
        mag_data[i] = (soft_iron[i][0] * hi_cal[0]) + (soft_iron[i][1] * hi_cal[1]) + (soft_iron[i][2] * hi_cal[2]);
    }

    // 'Raw' values to match expectation of MOtionCal
    Serial.print("Raw:");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(int(mag_data[0] * 10));
    Serial.print(",");
    Serial.print(int(mag_data[1] * 10));
    Serial.print(",");
    Serial.print(int(mag_data[2] * 10));
    Serial.println("");

    // unified data
    Serial.print("Uni:");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(0);
    Serial.print(",");
    Serial.print(mag_data[0]);
    Serial.print(",");
    Serial.print(mag_data[1]);
    Serial.print(",");
    Serial.print(mag_data[2]);
    Serial.println("");

    delay(10);
}

which will output the magnetometer data correctly formatted at the correct baud rate. Then you just open up MotionCal, select the right port


text:
Analog pins all reading same value
I'm trying to read 5 analog inputs, but all the pins are reading the same as pin A0, plus or minus a couple points. I tried using pulldown resistors on all 5 pins and it made no difference. The board is a Leonardo. Thanks for any ideas/help!
void setup() {
    Serial.begin(115200);
    analogReference(EXTERNAL);
}

void loop() {
    int A0, A1,A2,A3,A4;
    delay(200);
    A0= analogRead(A0);
    A1= analogRead(A1);
    A2= analogRead(A2);
    A3= analogRead(A3);
    A4= analogRead(A4);

    Serial.print(A0);
    Serial.print(" ");
    Serial.print(A1);
    Serial.print(" ");
    Serial.print(A2);
    Serial.print(" ");
    Serial.print(A3);
    Serial.print(" ");
    Serial.print(A4);
    Serial.print("\n");
}

int A0, A1,A2,A3,A4;
delay(200);
A0= analogRead(A0);
A1= analogRead(A1);
A2= analogRead(A2);
A3= analogRead(A3);
A4= analogRead(A4);

Your local variables (A0 through A4) are shadowing the global variables for the pins (A0 through A4). Give your local variables different names.

Thank you! I knew it must be something stupid I'd overlooked.


text:
Determining which section of code uses the most flash
I'm running into the 32k flash ceiling of my 328p. The code is pretty compact but I need help making it smaller.
Is there an analysis tool (part of avr?) that can tell me which functions take up the most space?  Obviously looking at the source code won't help because I don't know how the compiler decides to reorganize things.
I've moved strings to PROGMEM, but I'm still hitting the ceiling.
What are some tips for space saving?
What are some ways of seeing what's taking up the most space?

For knowing which functions take the most space, I generally use
avr-nm. This command is intended to display the symbol table of a
compiled program. It is one of the tools that you get when you install
the Arduino environment, so you already have it. avr-nm provides the
same information as avr-objdump -t, but it can display it in a nicer
format.
As an example, I ran the following command on the basic blinky program:
avr-nm --size-sort -Crtd blink.elf

And this is the output:
00000148 T __vector_16
00000118 T init
00000114 T pinMode
00000108 T digitalWrite
00000082 t turnOffPWM
00000076 T delay
00000070 T micros
00000040 T loop
00000026 T main
00000020 T digital_pin_to_timer_PGM
00000020 T digital_pin_to_port_PGM
00000020 T digital_pin_to_bit_mask_PGM
00000016 T __do_clear_bss
00000010 T port_to_output_PGM
00000010 T port_to_mode_PGM
00000008 T setup
00000004 B timer0_overflow_count
00000004 B timer0_millis
00000001 b timer0_fract

The first column is the size of the object referenced by the symbol.
Second column is the type, where ‘t’ (upper or lower case) means “text”
(code and PROGMEM data), ‘d’ means “initialized data” (stored in flash
and copied to RAM at startup) and ‘b’ means “uninitialized data” (a.k.a.
“BSS”, occupies no flash, only RAM). The last column is the symbol's
name. In this example you can see that the biggest function is
__vector_16 (the ISR for timer 0 overflow), and it takes 148 bytes of
flash.
The options I passed to avr-nm are the following:

--size-sort, obviously, sorts the symbols by size. It also displays
the size, instead of the address, on the first column.
-C is for demangling the C++ symbols. For example, instead of
displaying “_ZN14HardwareSerial5beginEm”, it would display
“HardwareSerial::begin(unsigned long)”.
-r means “reverse sort”. This is for having the biggest functions at
the top, instead of at the bottom.
-td is for displaying the sizes in decimal instead of hexadecimal.

Since you are only interested in flash usage, you can ignore the symbols
in BSS. On a unixish OS, you could just pipe into grep -iv ' b '

Moving strings to PROGMEM will only exacerbate the problem, since PROGMEM is the 32k flash.
You can easily get your "symbol table" from the compiled .elf file by using avr-objdump -t <.elf file>.
It results in a list something like this:
... scrolls past ...
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
00800110 g       .bss   00000000 __bss_start
000008a2 g     F .text  00000022 main
00000126  w      .text  00000000 __vector_4
00000000  w      *ABS*  00000000 __heap_end
00000126  w      .text  00000000 __vector_9
000003ae g     F .text  000000d0 delay
00000126  w      .text  00000000 __vector_2
00000126  w      .text  00000000 __vector_21
00000126  w      .text  00000000 __vector_15
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
008001c3 g       .stab  00000000 __heap_start
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
000008ff  w      *ABS*  00000000 __stack
0000008d g     O .text  0000000a port_to_input_PGM
00800110 g       .data  00000000 _edata
008001c3 g       .stab  00000000 _end
00000126  w      .text  00000000 __vector_8
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000a08  w      .text  00000000 exit
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
00000126  w      .text  00000000 __vector_14
00000126  w      .text  00000000 __vector_10
000002a8 g     F .text  00000090 __vector_16
00800100 g       .data  00000000 __data_start
00000480 g     F .text  00000076 __vector_18
00000126  w      .text  00000000 __vector_20
00000108 g       .text  00000000 __do_global_ctors
... etc ...

The lines you are interested in are .text sections.  The first big number is the HEX location in memory.  The second one is the important one - that is the size.
You can see from that snippet that the function delay is located at address 0x3ae and is 0xd0 bytes in size.
If you're on Unix or OSX you can employ the more advanced searching tools that are at your disposal.  For instance, to just list the "global" .text entries:
$ avr-objdump -t <elf file> | grep '\.text' | grep ' g '

Which for my test program results in:
00000079 g     O .text  0000000a port_to_mode_PGM
00000918 g     F .text  00000040 _ZN5Print7printlnEv
00000a00 g       .text  00000000 __tablejump__
000006c2 g     F .text  00000040 _ZN14HardwareSerial4peekEv
000008c4 g     F .text  00000054 _ZN5Print5writeEPKhj
000000d4 g       .text  00000000 __trampolines_start
00000a0c g       .text  00000000 _etext
000006a0 g     F .text  00000022 _ZN14HardwareSerial9availableEv
0000012a g     F .text  0000002a loop
00000774 g     F .text  00000080 _ZN14HardwareSerial5writeEh
00000126 g       .text  00000000 __bad_interrupt
000000d4 g       .text  00000000 __trampolines_end
00000200 g     F .text  000000a8 digitalWrite
00000592 g     F .text  0000010e _ZN14HardwareSerial5beginEm
00000182 g     F .text  0000007e pinMode
00000097 g     O .text  00000014 digital_pin_to_port_PGM
000000d6 g       .text  00000000 __dtors_end
00000754 g     F .text  00000020 _ZN14HardwareSerial5flushEv
0000051c g     F .text  00000076 __vector_19
00000990 g     F .text  00000026 _ZN5Print7printlnEPKc
000000f8 g       .text  00000000 __do_clear_bss
000000ab g     O .text  00000014 digital_pin_to_bit_mask_PGM
00000000 g       .text  00000000 __vectors
000009fc g       .text  00000000 __tablejump2__
00000338 g     F .text  00000076 init
000000d4 g       .text  00000000 __ctors_start
000000e2 g       .text  00000000 __do_copy_data
000008a2 g     F .text  00000022 main
000003ae g     F .text  000000d0 delay
00000083 g     O .text  0000000a port_to_output_PGM
00000154 g     F .text  0000002e setup
000000d6 g       .text  00000000 __dtors_start
000000d6 g       .text  00000000 __ctors_end
0000008d g     O .text  0000000a port_to_input_PGM
000000bf g     O .text  00000014 digital_pin_to_timer_PGM
00000702 g     F .text  00000052 _ZN14HardwareSerial4readEv
000009b8 g       .text  00000000 __udivmodsi4
00000a08 g       .text  00000000 _exit
000002a8 g     F .text  00000090 __vector_16
00000480 g     F .text  00000076 __vector_18
00000108 g       .text  00000000 __do_global_ctors

From that I can see that the function _ZN14HardwareSerial5beginEm is the biggest and takes up 0x10e bytes.  That strange named function is a "C++ Munged" name.  It actually corresponds to HardwareSerial::begin() and is the parent class name for Serial.begin().

Nice answer! But two comments: 1) Moving strings to PROGMEM does not worsen the problem: whereas PROGMEM strings eat flash, non-PROGMEM strings eat both flash and RAM. 2) With avr-objdump you can use the options -t .text to list only the .text section, and -C to demangle the symbols.

A number of compilers I use put constant values in .rodata instead of .text, so it is useful to know how to do custom filtering with grep et al - that way you can filter it exactly to your needs.  Of course, if you're a wincan't user then you're pretty much screwed...


text:
Adafruit_GFX setRotation not working when called from within a class
Using an ILI9341. I'm trying to set the rotation from within a class, but it's not working.  The code is very straight forward.
If I rotate in the class, the setRotation code does not work but the text is still printed. The pointer is set properly and the text is still printed, it just doesn't get rotated.
Outside of the class, the rotation works fine.
Any help would be greatly appreciated!
#include "SPI.h"
#include "Adafruit_GFX.h"
#include "Adafruit_ILI9341.h"

#define TFT_DC 5
#define TFT_CS 3

Adafruit_ILI9341 *tft;
uint8_t newRotationAngle = 0;

void drawStuff() {
    tft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
    tft->fillRect(0, 0, tft->width(), tft->height(), ILI9341_BLACK);
    tft->setCursor(0, 0);

    tft->print(F("01234567890"));
    delay(250);
}

class test {
public:
    void init(Adafruit_GFX *_p) { ptrTft = _p; };

    void inClassRotation(int newRotation) {
        ptrTft->setRotation(newRotation);
        drawStuffInClass();
    };

    void drawStuffInClass() {
        ptrTft->setTextColor(map(rand(), 0, RAND_MAX, 0, 0xffff));
        ptrTft->fillRect(0, 0, ptrTft->width(), ptrTft->height(), ILI9341_BLACK);
        ptrTft->setCursor(0, 0);

        ptrTft->print(F("01234567890"));
        delay(250);
    }

    Adafruit_GFX *ptrTft;
};

test instance;

void setup() {
    tft = new Adafruit_ILI9341(TFT_CS, TFT_DC);

    tft->begin();
    tft->setTextSize(2);

    instance.init(tft);
}

void outsideClassRotation(Adafruit_GFX *passed) {
    passed->setRotation(newRotationAngle);
    drawStuff();
}

void loop(void) {
    newRotationAngle++;

    // This works. No problems.
//    outsideClassRotation(tft);

    // This does NOT rotate but still prints the text fine.
    instance.inClassRotation(newRotationAngle);

}

I would actually be quite surprised if outsideClassRotation() actually
worked. My guess is that it does not work as is. Maybe it did work at
some point, but then you made some subtle changes to your code and did
not check that it is still working.
Here is the deal: there are two setRotation() methods:

Adafruit_GFX::setRotation(unsigned char) does very little besides
storing the rotation angle... which is not used anyway.
Adafruit_ILI9341::setRotation(unsigned char) actually sends commands
to the LCD asking it to apply the rotation; this is the method you
want.

The problem is that these methods are not virtual, which means that
when you call them through a pointer, as in
some_pointer->setRotation(the_angle);, you get the method
corresponding to the type of the pointer, not the type of the actual
object. For example:
tft->setRotation(the_angle);     // calls Adafruit_ILI9341::setRotation()
ptrTft->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()
passed->setRotation(the_angle);  // calls Adafruit_GFX::setRotation()

I checked this by uncommenting your call to outsideClassRotation() and
disassembling the compiled binary: both times you are calling
Adafruit_GFX::setRotation().
Solution: change your Adafruit_GFX * pointers to be of
type Adafruit_ILI9341 *, or patch Adafruit_GFX.h to make
setRotation() virtual.

Actually, outsideClassRotation() works regardless, but you solved my mystery. I knew it was something simple.  I can only unlock bounty after 18 hours. Thanks!!!


text:
Reading values from the register of a slave
I am trying to interface MPU6050 with arduino. Found a simple code online, but having a bit of trouble in interpreting it.
// MPU-6050 Short Example Sketch
// By Arduino User JohnChi
// August 17, 2014
// Public Domain
#include<Wire.h>
const int MPU=0x68;  // I2C address of the MPU-6050
int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;
void setup(){
Wire.begin();
Wire.beginTransmission(MPU);
Wire.write(0x6B);  // PWR_MGMT_1 register
Wire.write(0);     // set to zero (wakes up the MPU-6050)
Wire.endTransmission(true);
Serial.begin(9600);
}
void loop(){
Wire.beginTransmission(MPU);
Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
Wire.endTransmission(false);
Wire.requestFrom(MPU,14,true);  // request a total of 14 registers
AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C     (ACCEL_XOUT_L)
AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
Serial.print("AcX = "); Serial.print(AcX);
Serial.print(" | AcY = "); Serial.print(AcY);
Serial.print(" | AcZ = "); Serial.print(AcZ);
Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for   temperature in degrees C from datasheet
Serial.print(" | GyX = "); Serial.print(GyX);
Serial.print(" | GyY = "); Serial.print(GyY);
Serial.print(" | GyZ = "); Serial.println(GyZ);
delay(3330);
}

Now there are a few things i want to ask regarding this code:
1. Here we have specified that the data from 3B register of the slave should be the first one and master will receive in total 14 bytes. In this case the 14 registers are continuous (see datasheet here) .Now how should i go about reading the values if i am interested in registers which are not continuous ,let us say alternative?
2.AcX=Wire.read()<<8|Wire.read();
This line is taking the first 8 bits and last 8 bits and forming a 16 bit number . But why do we need to shift the first 8-bits byte 8 places to left.Please explain how exactly this line works?

This code you found is very bad. Do not rely on it for your own developments. Specifically, there is no way to know which read() will be evaluated first in Wire.read()<<8|Wire.read().

So can you please tell me how should i go about doing the same in a better way?

Take a look at FreeIMU - it has all the code you could ever want.

For reading non-consecutive bytes, the “normal” way would be to do a
one-byte request and a one-byte read for each byte you want. However, if
the bytes you want are close enough (e.g. you want every other byte), it
would be faster to do a contiguous read and just ignore the bytes you do
not want. E.g.:
byte data1 = Wire.read();  // read first byte
Wire.read();               // read and ignore second byte
byte data3 = Wire.read();  // read third byte

For your question regarding the meaning of
Wire.read()<<8|Wire.read();:

Wire.read() return a 16-bit integer, where the 8 most significant
bits are zero and the 8 least-significant bits contain the actual
data. In binary, it's something like 00000000xxxxxxxx, where x
are the data bits.
<<8 means “shift left by eight positions”, where the missing bits
are replaced by zeros. Thus Wire.read()<<8 is xxxxxxxx00000000
in binary.
The second call to Wire.read() return another 16-bit integer in the
form 00000000yyyyyyyy.
The vertical bar | is the bitwise-or operator: each bit of the left
operand is or-ed with the corresponding bit of the right operand to
give one bit of the result: x or 0 is x, 0 or y is y.
Then, the whole expression gives xxxxxxxxyyyyyyyy, where xxxxxxxx
comes from the first Wire.read() and yyyyyyyy from the second.

The problem here is that the “first” and “second” Wire.read() in the
sentence above refer to the position of the call in the line, not to the
actual order in which the calls are performed. Thus you may be lucky and
get the the correct byte order... or not. You should instead do a single
read per statement if you want to control the byte order. For MSB first:
AcX = Wire.read() << 8;  // read most significant byte first
AcX |= Wire.read();      // then least significant byte

And for LSB first:
AcX = Wire.read();        // read least significant byte first
AcX |= Wire.read() << 8;  // then most significant byte


text:
Equivalent to POSIX mmap() in AVR-libc
Is there an similar function in AVR-libc/Arduino C++ to mmap()? I'm looking for a way to place machine code in memory at runtime and make it executable.

No.
First, mmap() makes almost no sense on an AVR, as there's no memory management unit or concept of process memory to configure.  Some related concepts like sbrk() are occasionally implemented in a minimalist fashion to let library functions designed for larger computers work, but they typically only update a tracking variable or fail.  For things that are physically realizable you can write your own mmap() if you really want, either allowing (assigning) or disallowing a region, and even if you really want automatically copying part of a file off an SD card or whatever...
But more importantly, your actual goal is entirely unachievable, as the AVR is a strict Harvard Architecture which can only execute instructions from flash, never from RAM.
If you want to execute from RAM, try one of the various small ARM Cortex M0/M4/M3 platforms (many of which have Arduino ports), or even consider a larger Embedded Linux system, which will not necessarily be any more expensive than an Arduino.


text:
How to use FTDI to program Lilypad Arduino?
I am trying to upload a basic Blink code from my computer to Arduino Lilypad contains Atmega 328. While my Blink codes are uploading, FTDI 1402-C CN480661 FT232RL module is not responding to the Arduino IDE at the end of the process. So I couldn't upload any codes with this uploading method, I mean using FTDI modules directly.
This is how I do the connections:

This is my Blink code:
void setup() { pinMode(13, OUTPUT);}

void loop() {
  digitalWrite(13, HIGH);     delay(1000);
  digitalWrite(13, LOW);      delay(1000);
}

I chose AVRISP mkII as a programmer. ATmega328 as a processor. Arduino Lilypad as a board on Arduino IDE v1.6.6
At this point, I got this error:

avrdude: ser_open(): can't open device "\.\COM4": Access is denied

Windows's device manager says: USB Serial Port is attached to COM4, also Arduino IDE saw that.

I downloaded FTDI driver for Windows, but still, I can't upload any code into my Lilypad Arduino.
How can I use FTDI to program my Lilypad Arduino?

"Access is denied" this looks like you should at least restart your computer after you installed the FTDI driver if you have not already.
Run Arduino IDE as Administrator and also make sure you are logged into an Administrator account in your windows login.
If all this fails this means another application is using that com port you will need to figure out what could be using that com port another instance of Arduino IDE opened? Etc
If all else fails restart your computer with the usb unplugged, login, open arduino IDE and plug in your usb and select the com port.
Edit: You can also try changing the USB port you are currently using for another one, this will also change your com port to a new number

I tried but still not working. Should I use JP3 pins on Lilypad board directly? But, how can I program directly ATmega 328 ? What I need?

“device "\.\COM4” looks like an odd name.  I don't have an MSWindows system, but perhaps you know if it's an ok name.

The error message

"avrdude: ser_open(): can't open device "\\.\COM4": Access is denied"

tells me that the error occurs when the Arduino IDE tries to open a connection to the FTDI adapter "serial port", long before the Arduino IDE actually sends anything through the FTDI adapter to the Arduino.
Have you read the Arduino Troubleshooting guide?
The Arduino Troubleshooting guide recommends

Access to the Serial Port

On Windows, if the software is slow to start or crashes on launch, or
  the Tools menu is slow to open, you may need to disable Bluetooth
  serial ports or other networked COM ports in the Device Manager. The
  Arduino software scans all the serial (COM) ports on your computer
  when it starts and when you open the Tools menu, and these networked
  ports can sometimes cause large delays or crashes.
Check that you're
  not running any programs that scan all serial ports, like USB Cellular
  Wifi Dongle software (e.g. from Sprint or Verizon), PDA sync
  applications, Bluetooth-USB drivers (e.g. BlueSoleil), virtual daemon
  tools, etc.
Make sure you don't have firewall software that blocks
  access to the serial port (e.g. ZoneAlarm).
You may need to quit
  Processing, PD, vvvv, etc. if you're using them to read data over the
  USB or serial connection to the Arduino board.

If I were you my next steps would be:

Unplug the USB cable from my computer, and check the "Tools >> Serial Port" option. Usually when the USB cable is unplugged, that option is greyed out (empty list), but sometimes there is a few things listed. Remember that list.
Plug the USB cable from the FTDI back in (preferably in a different socket of the computer this time), and check the "Tools >> Serial Port" option. Do you remember the list from the previous step? There should be a new item on the list, representing the FTDI adapter -- pick that one.
I would unplug the FTDI from the Arduino Lilypad, and then tell the Arduino IDE to upload the sketch. Obviously with the Arduino airgapped from your computer it won't be able to upload the sketch, but does it give a useful error message?
Reboot the computer with nothing plugged into its USB ports. Plug the FTDI adapter directly into the Arduino Lilypad ("BLK" to "B", "GRN" to "G"). Start the Arduino IDE in Administrator mode. Make sure the board type is set correctly. Try to plug in the USB cable, set the Serial Port, and upload a sketch before any other program has a chance to grab that COM port.


text:
I can't scroll Arduino IDE's example & scketch lists down
I have Arduino IDE 1.0.5 in win7 x64. I have so many library units. A pity that I can't scroll down to my other options. Is it Arduino.exe's problem or something else? How can I add triangle to scroll down and scroll up to see whole Sketchbook and Examples list? Thanks.

Try using 1.5.+. It has scroll arrows to allow larger lists of menus, bigger than the screen.
I find that most, if not all, sketches work equally well, if not better.
Up to 1.5.6r2 uses the same version of compiler as 1.0.+'s. 1.5.7 and newer uses a new compiler, that is more sctrict. All stock libraries work. And well written 3rd parties work. I personally use 1.5 and test backwards to 1.0.
There is a fork of 1.0 called ERW that has the scrolling. But 8t is becoming obsolete.

I downloaded this: http://forum.arduino.cc/index.php?topic=118440.435 And your answer is also good to me. Thanks.

You can get to the examples in Explorer. Just go to My Documents\ Arduino\ libraries\ <library-name>\ examples.
This one made me chuckle. Thank you for sharing.

Yes I know this way but I need two triangle to down the list. Thank you for your answer but I didn't want this.


text:
Powering a 6-12V motor using a lead acid 6V battery with 6Amps of current?
Hi I'm using a adafruit motor shield v2 and I need to power a DC motor 6-12V but I'm not sure if my battery will be okay for the shield. Will it burn the shield? I'm going to be using 6V so it should draw less current?

The 6Amps is the maximum current the battery can supply. It will only supply what it needed. You only need to look at the voltage, and 6v is fine for both the shield and the motors.

On the shield it says 1.2A/motor (3A max)

"1.2A per motor", so the battery doesn't really matter here, only the motors. What is the current rating of the motors at 6v?

Here's the link to the motor specs:  http://www.jaycar.com.au/Electromechanical-Components/Mechatronics/Motors-%26-Gearboxes/12V-DC-Reversible-Gearhead-Motors---55RPM/p/YG2738

14A full load (at 12 volt). 0.45A at no load (at 12V). So it depends on what is attached to it. You could try measuring the current by connecting the motor directly to the battery and see how much current it uses at 6v when attaching the maximum load.

Ohkay that sounds good but its just for an RC car project like move the wood car, do u think it will be a problem?

If you take the "full load" to be the "stall current", then you can work out the resistance of the winding.
R=V/I = 12/14 = 0.857Ω
From that you can then work out the stall current at 6V:
I=VR = 6×0.857 = 5.143A
That, being the stall current, is the maximum the motor will draw - the current drawn when it is trying to move an impossible amount of load and the rotor cannot move.  At that current you will melt the motor drivers (or they will go into thermal shutdown).
Of course, with a geared motor, that becomes a (comparatively) massive load and would be quite hard to achieve.  You have a 50:1 gear ratio, so the stall load is effectively 50x greater.
So there is going to be a limit to the load that you can drive with the motor before it becomes a problem for the driver.  There are ways of calculating it from the given torque, gear ratio, load/noload current ratings, etc, but I don't have all that at my fingertips right now.
So you can either "play it safe" and invest in a driver that can cope with the stall current, or experiment and measure what current is drawn by the motor with different loads and see if it stays below the 1.2A limit of the shield.


text:
Can I use an Arduino Due as a flash drive?
More specifically, can I use an Arduino Due to have an interface that can plug in/out of a USB port on a computer, connect it to an SD card or similar via a sd card logging shield, and have it present itself as a flash drive to the computer?
Why do I want this as opposed to a normal flash drive? I would like the Arduino to also have access to the contents of the sd card when the computer interface is not plugged in (or rather controllable via the Arduino which device has access to the card, the Arduino or the computer), without the need to remove/disconnect the cable

Possibly - you would have to implement USB mass storage mode.  And then you would have to implement a FAT filesystem when you want to access the card from a program on the due.   That is probably possible, but if you are willing to install a custom program on the PC there are simpler ways.

@ChrisStratton no easy way to pass the card access directly to the PC? (and thus let the PC format the file system as it would a flash drive)?

That's what USB mass storage does.  But you need filesystem code yourself if you want to access the contents of the result from the due.


text:
How can I add additional boards to Eclipse with the Arduino add-on with only a URL, not a zip file
I want to add the following boards:
https://redbearlab.github.io/arduino/package_redbearlab_index.json
Which I can add in the Arduino IDE by going to File -> Preferences -> Additional Boards Manager URLs and just pasting it there
Where is the equivalent function in Eclipse, or how do I configure Eclipse to allow me to develop for those boards?
From Eclipse, I have tried Window-> Properties -> Arduino and from there "Private Library Path" and "Private hardware path", and I have tried pointing them to "C:\Program Files (x86)\Arduino\hardware" and "C:\Program Files (x86)\Arduino\libraries", but that didn't seem to change anything (i.e. no new board options, even after running Eclipse as admin) - while the boards show up (examples and all) in the Arduino IDE

Until someone writes such a capability, there is none.

Read the JSON data, find the URLs, and download the zip files.  Then use your normal method of adding boards from zip files.

@Majenko so the zip files are all I need? I also see some .tar.gz stuff for the tools (i.e. gcc/etc.) - would I treat them the same way?

If you need tools they will also be in the JSON file.  Do the same with them as you do with the boards. I don't know Eclipse, so I don't know how you "install" things in there. You said you know how to do it with zip files, well the zip files (and all other forms of archive) are listed right there for you. The rest is up to you.

With arduino eclipse plugin 2.4 you simply install the boards with the arduino ide -like you described- and you can use then in the arduino eclipse plugin.
Version 3.0 (that is the nightly as 3.0 still needs to be released) contains it's own boards and library manager in windows->preferences->arduino.


text:
What happens if I try to draw power from the VIN port while under USB power on an Uno?
I would like to have a shield permanently attached that use the VIN (not 5v) for it's power - the problem comes in when I want to program the arduino (via the USB port), do I need to also have the barrel connector plugged in, or can I just expect the shield to not work (no, it won't be damaged from not getting enough/any power), but have the arduino itself be fine - or am I somehow damaging the power regulator by attempting to use it in reverse?

You do run the risk of damaging the 5V regulator, yes.
Power will attempt to flow from the 5V rail (USB port) through the voltage regulator (backwards) and into the shield to power it.
As your shield doesn't mind being under-powered from 5V while you're programming the Arduino you can add a diode between 5V (anode) and Vin (cathode). This will bypass the regulator when the voltage of the 5V rail is higher than the Vin rail, and your shield will be supplied with about 4.3V (slightly higher for a schottky diode).

So that would reduce the reverse voltage across the regulator to around .7v if I did it like this I think that would work, thanks

@user2813274 Yep, that's right.


text:
Can I power a 9g servo from an arduino nano with USB power only?
I want to run a 9g servo off of the pins from an arduino nano board, using only the 5v USB connection.
The servo specifically is a SG90, which I have measured a stall current of ~250mA - I don't intend to stall it, just have it run with almost no load
I am not sure which pins to power it off of from the arduino itself - do I use the VCC or the +5v? does it matter which ground I use? should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something? does the arduino nano negotiate to get more than the default of 100mA from a USB power connection?

The max current of the Arduino-Nano 5V Pin is 200mA. So if you draw more than that it might damage your Arduino.
Here is an interesting summary regarding the Maximum Ratings of the Arduino Nano: https://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

The 5V pin of the arduino is not connected through the
  microcontroller. As such, it can source significantly more power. When
  you are powering your arduino from USB, the USB interface limits your
  total power consumption to 500 mA.

So yes, it actually seems you can draw 250mA out of the 5V PIN.

do I use the VCC or the +5v?

You use +5V, because VCC is for powering your Arduino with an external Power Source. It allows you to use up to 7-12V (recommended), or up to 6-20V (limits).

does it matter which ground I use?

Doesn't matter

should I use a breadboard to help me place any other components that may be needed, i.e. a capacitor or something?

A breadboard makes it easier for you, to test your circuit. But you can do it without if you like. Then you possibly have to solder some connections
See also the offical Arduino Page for the Nano.

Thanks - might I ask a few more details - does the arduino negotiate for more than 100mA with the computer when connected to one, and also what would happen if more than 200mA are drawn - would it just lower the voltage and become temporarily unstable, or would something overheat? (does it even go through anything, or is it directly connected to the USB port?) - the breadboard was for if any extra components would be helpful, i.e. a capacitor or diode or something to keep the signal "clean" for the arduino

Isn't the 200mA limit only for when the board is power via VIN and not USB?

@Gerben Thank you. I researched it and you're right. Actually the USB-current-limit is much higher then 200mA. I have updated my answer. Source http://electronics.stackexchange.com/questions/67092/how-much-current-can-i-draw-from-the-arduinos-pins

authors: Дмитрий Грубский


text:
Where am I supposed to get an I2C BUFFER_LENGTH defined?
I am using a BLE nano - as soon as I try to include I2Cdev.h and compile, I get this error:
Arduino\libraries\I2Cdev\I2Cdev.cpp:276:62: error: 'BUFFER_LENGTH' was not declared in this scope

How should I fix this? I imagine I can hard-code it in and guess around as to the value (32 seems common), but I think I am missing something else as far as it using the right libraries for the hardware, so how can I check/fix that if it is indeed the case?

BUFFER_LENGTH is set in I2Cdev.h depending on the target. BLE nano is not directly supported (what I can see).
Cheers!


text:
Conver char value to variable?
I want to pass the preprocessor values(AT commands) to the Serial.println function. Im trying TCP connection using arduino-SIM900A. I've declared all AT commands to each preprocessor variables like below
#define A "AT\r"
#define B "AT+CPIN?\"
...

I've assigned all preprocessor variables in char array and pass it into Serial.print using for loop.
char varAT[12]={'A','B'....};
for(int i=0;i<=12;i++)
{
Serial.print(varAT[i]);
}

Its not printing AT, instead it print preprocessor variable name A. I searched the google how to convert char value to variable, in C there is a function called "eval". Using eval we can acheive, but it wont work in arduino lang. How to solve this?
Thanks.

Ok, first, char varAT[12] indicates an array of 12 characters.
Second, quotes indicate literals - 'A' means, literally, the character 'A'. Variables and constants are without quotes (same way you use  i).
I think you mean:
char *varAT[12]={A,B....};

Also, your constant B is invalid - I think you meant for it to end in \r", not \".

Thanks AMADANON. Its working. but i used char pointer char*. Once again thank you.


text:
Reading tiny voltage changes
I have an mpx12DP pressure sensor that I want to use to measure the depth of water in a 1m tall water tank.
But it only measures up to 55mV of voltage change, which the arduino can't really detect changes in. (The sensor measures 0 to 1.45psi- 1m of water should give me 1.4psi, so I should be able to get really good accuracy).
Is this as good sensor to use for this purpose? How do I amplify the signal from the sensor? I have tried an LM324 op-amp, but couldn't get it to work (this may be entirely the wrong thing to use! And I was utterly unsure of the kind of circuit to use it in). Any advice on parts.. schematics.. a suitable already-amplified sensor that reads only up to 1.45psi?
Thank you,
Pressure sensor datasheet: http://www.digikey.co.uk/product-detail/en/MPX12DP/MPX12DP-ND/684659
Op amp datasheet: http://www.ti.com/lit/ds/symlink/lm124-n.pdf

55 mV should be (barely) measurable by the Uno, as its analog resolution is ≈ 4.9 mV. The op-amp looks fine, how did you wire it? Did you try the non-inverting schematic on p. 13 of its datasheet?

I can just about measure it- but not good enough to tell you how full the tank is! I was hoping for much better accuracy! And I tried to wire it up like this: http://www.practicalarduino.com/projects/water-tank-depth-sensor but its awfully complex and I'm not sure I did it right... however I'm not really sure how to do it correctly!

So to try the non-inverting schematic as on the datasheet pg13.. pin 4 goes to 5v, pin 11 to gnd, then pin 9 to the -ve pin of my sensor, and pin 10 to the +ve pin of my sensor, then i should be able to read from pin 8.. this doesn't work so I have read it wrong somewhere!

Oops, sorry, didn't notice the sensor had differential output.

You could try using analogReference(INTERNAL);, to reduce the upper range of the ADC to 1.1volts, thus giving you better voltage resolution.

It is reasonable to use  analogReference(INTERNAL);, as suggested by Alexander M, to set the range of the ADC to 1.1 V.
Another alternative is to use two resistors to make a voltage divider, to make an external reference of 1 V (min.) at the AREF pin, and then use  analogReference(EXTERNAL);, but the Arduino's supply voltage is likely to be noisier than the internal reference.
Regarding tiggun's suggestion about grounding the V- pin, it isn't clear to me that the mpx12DP will function correctly with V- and ground connected together.
In any case, you can use two or three of the op amps in the four-op-amp LM324 package to make a differential amplifier or an instrumentation amplifier.  See figures 38 and 39 on page 20 of the LMx24 datasheet mentioned in the question.  Figure 38 shows a differential amplifier; you could, for example, replace R3 with a 50KΩ resistor and R4 with a 1MΩ resistor to get a voltage scaleup of about 21, via the formula shown: Vₒ = (1 + R4/R3)·(V₂-V₁).  Alternately, you can use a small variable resistor as in figure 39 to make a variable-gain instrumentation amplifier.

The reference voltage must be at least 1.0V.

Your sensor has differential output, with a voltage difference between the Vout+ and Vout- being the measurement. The span of this difference is 0 to 55mV. The reason the sensor is wired this way is to reduce noise. To amplify this type of output you would need a differential output amplifier which is more complicated than a single op amp.
However, you can also just wire the Vout- from the sensor to ground, and then use the sensor as a single-ended output from 0 to 55mV (noise might be a problem). If you do this, you can then amplify Vout+ with your LM324 op-amp as described on page 13 of the LM324 datasheet with a non-inverting amplifier. By setting the ratio of R2/R1 to 60, you would get up to 55mV*80 = 4.4V which is pretty good.
The op amp needs some voltage headroom, so if you are using 5V supply for it, don't set the amplified voltage max to 5V.
edit: I don't think you need much headroom and 4.4V will give you better resolution than 3.3V

I can't find anything in the ATmega328 datasheet describing differential capabilities of the ADC. I did find info in the ATtiny85 datasheet, however. It has built-in 1x or 20x gain.

Never mind, I must've been thinking of the Mega.