text:
Possible to store variables directly in EEPROM?
Is it possible to store a variable directly in EEPROM and retrieve it without needing to use a library?
I'm building a project that can change the colour of an RGB LED and I want to store the colour in a non-volatile memory space, but I was wondering if I could avoid using one of the EEPROM libraries and have a global variable stored in nonvolatile memory, but still accessed directly, without needing to call a function.

It is possible - but comes down to rewriting it yourself, as there is quite a complex requirement to write EPROM & the libraries are not doing it a long way round just for fun ; take a look at the source code in the library to see how to do it.

Also be aware that EEPROM access time is slower than SRAM. It is preferrable to not use an EEPROM memory cell as a variable in your program, and rather save the value to EEPROM from time to time, and read it at reset time only.

"Without needing to call a function" is a curious requirement -- what is the benefit of that? Even if you write the EEPROM access yourself, you would wrap it in a function to avoid code duplication. (Unless you need it only in one place, but still wrapping in a function would be good programming style.)

Just use <avr/eeprom.h>, instead of the arduino library, which is atrocious.

"Without using a library" is probably a better description. I'd attempted to use the Arduino EEPROM library and it appeared to crash the chip, seemingly regressing to a prior Pin13-flashing program instead of the program I'd spent hours writing.

Writing and reading EEPROM is possible to do without a library. Take a look at the datasheet of the ATmega328P to find an example: On page 25 / 26 there are example codes for reading and writing both in assembler and C. They do wrap it in a function but as I said in a comment if you only have place in your code where you would like to access EEPROM you can put the code there without duplication. These functions write and read one byte at a time, so if you want to store larger datatypes (a 16-bit integer for example) you already need to call the routines more than once.
Note that the EEPROM has a limited life cycle of at least 100,000 write/erase cycles (cells must be erased before they can be written, reads are unlimited) and it is considerably slower than SRAM (typ. 3.3 ms for writing a byte). You also need to make sure no interrupts interfere with the write process.
However, in the sense of the question it seems this is not what you want: You cannot just create a global variable and have it magically being written to EEPROM.

EEPROM can store one byte at a location. To store Integer variable, it requires two consecutive location. For Double, it requires four consecutive memory location. I have written function to store and read, int & double to and from built-in EEPROM. As per your question, you can modify it as per your need.

Actually this answer was copied from another thread.

/*
  StackExchange Question: "How to Store 2 analogRead values and read using EEPROM for Arduino uno?"
  Question Id: 15910 (https://arduino.stackexchange.com/questions/15910/how-to-store-2-analogread-values-and-read-using-eeprom-for-arduino-uno)
  Author: Anurag S. Vasanwala (AnuragVasanwala@gmail.com)

  Tested on Arduino Version 1.6.7

  Description:  This sketch helps to store and read, Integer & Double to and from built-in EEPROM.
  Objectives:
    + Write Integer @ Specified Address (Fn: EEPROM_Write_Int)
      + Conversion from Integer to Byte Array
      + Store Bytes
    + Read Integer from Specified Address (Fn: EEPROM_Read_Int)
      + Read Bytes
      + Conversion from Byte Array to Integer
    + Write Double @ Specified Address (Fn: EEPROM_Write_Double)
      + Conversion from Double to Byte Array
      + Store Bytes
    + Read Double from Specified Address (Fn: EEPROM_Read_Double)
      + Read Bytes
      + Conversion from Byte Array to Double
 */
#include <EEPROM.h>

// MACRO : Combines FROM_BYTES into TO_OBJECT of datatype "DATATYPE"
#define CombineBytes(FROM_BYTES, DATATYPE, TO_OBJECT) \
  TO_OBJECT = *((DATATYPE *)FROM_BYTES);

// MACRO : Splits FROM_DATA of DATATYPE into equivalent byte array TO_BYTES
#define GetBytes(FROM_DATA, DATATYPE, TO_BYTES) \
  *((DATATYPE *)TO_BYTES) = FROM_DATA;

// Writes Integer's equivalent bytes to Address and Address + 1
void EEPROM_Write_Int(unsigned int Address, int Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, int, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads two bytes from Address and Address + 1 and returns equivalent int
int EEPROM_Read_Int(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(int);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  int Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to int
  CombineBytes(Temp_Buffer, int, Result);

  return Result;
}

// Writes Double's equivalent bytes to Address, Address + 1, Address + 2 and Address + 3
void EEPROM_Write_Double(unsigned int Address, double Data)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  // Call macro to store byte array into Temp_Buffer from Data
  GetBytes(Data, double, Temp_Buffer);

  // Write number of bytes to memory location specified in Address and so on
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    EEPROM.write(Address + Index, Temp_Buffer[Index]);
  }
}

// Reads four bytes from Address, Address + 1, Address + 2 and Address + 3 and returns equivalent double
double EEPROM_Read_Double(unsigned int Address)
{
  // Get the size of datatype to write number of bytes
  const byte SizeOf_DataType = sizeof(double);

  // Create tem buffer to get Bytes of Datatype
  byte Temp_Buffer[SizeOf_DataType];

  double Result;

  // Read number of bytes from memory location
  for(byte Index = 0; Index < SizeOf_DataType; Index++)
  {
    Temp_Buffer[Index] = EEPROM.read(Address + Index);
  }

  // Call macro to combine bytes into equivalent to double
  CombineBytes(Temp_Buffer, double, Result);

  return Result;
}

void setup()
{
  // Initialize Serial @ 9600 baud
  Serial.begin(9600);

  // Print size of datatype just for reference
  /* Serial.print("Size of byte = ");
  Serial.println(sizeof(byte));
  Serial.print("Size of int = ");
  Serial.println(sizeof(int));
  Serial.print("Size of float = ");
  Serial.println(sizeof(float));
  Serial.print("Size of double = ");
  Serial.println(sizeof(double)); */

  int myInt1 = -290;
  int myInt2;
  double myDbl1 = 23.41;
  double myDbl2;

  // Write myInt1 @ 100 memory location; It requires 2 consequtive memory location to store integer
  EEPROM_Write_Int(100, myInt1);

  // Read integer located @ memory location 100 and assign it to myInt2
  myInt2 = EEPROM_Read_Int(100);
  Serial.println(myInt2);

  // Write myInt1 @ 200 memory location; it requires 4 consequtive memory location to store double
  EEPROM_Write_Double(200, myDbl1);

  // Read double located @ memory location 200 and assign it to myDbl2
  myDbl2 = EEPROM_Read_Double(200);
  Serial.println(myDbl2);
}

void loop()
{

}

This code is successfully tested on Arduino Version "1.6.7".

You can have a global variable in EEPROM if the EEPROM is memory
mapped. Memory-mapping
the EEPROM is possible on ATxmega
chips.
Notice that writes go to a temporary buffer, not the EEPROM itself,
until you explicitly issue a write command.
Most Arduinos, however, use ATmega chips, which do not have this
feature. I am not aware of any xmega-based Arduino or clone.


text:
Can at least one Arduino emulate a USB hub?
What I'd like to do is have some kind of compact (and preferably inexpensive) Arduino-compatible device emulate a USB hub, and simulates plugging in a USB keyboard, pressing a key, then simulates unplugging the keyboard.
The goal here being a USB-connected device with media-control buttons for an Android device, but since plugging in a device that acts as a keyboard disables the on-screen keyboard, the idea is that it only acts like a keyboard when a button is pressed, but keeps a connection going while it's plugged in.
Is this at all possible with any Arduino-compatible device, do I need to look for a different embedded architecture, or do I need a particular kind of USB converter chip?

Since an Arduino is "just" a microcontroller with some specific bootloader and commonly programmed via the Arduino IDE, you can also program it like any other microcontroller.
There are several projects offering USB functionality as a library, in the Arduino world or outside of it. Use your favorite web search engine to find them. With such a library you should be able to tackle your task.
However, this is not a beginner's task. Please note that you might need to learn a lot.
I'd say that even the simplest AVR based Arduino should suffice.

Given I don't have much experience with USB terminology, what should I be searching for? Would "USB composite library" be an accurate description of this set of features?

You could start with "avr usb library" and see what comes up. The interesting projects pop up quite early, and many of them link to other projects of the same subject. Use the keywords you find there to refine your search. -- But do I really have to tell you how to search?

source: Stack Exchange

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

sort: votes


text:
Simulation of Arduino Mega 2560 with GSM Module using Proteus
I have really been suffering with my simulation! Tried connecting my arduino mega 2560 to COMPIM (used as GSM Module) in my circuit and also loaded sample code but damn! In vain! I wanted to view the data sent in virtual terminal but am getting nothing! and its also complaining of excessive CPU usage.
This is the circuit as seen below in Proteus.

And thereafter, the log messages are displayed as shown below.

Someone please help me out. Am I making a mistake oh? Infact the arduino code for displaying in the simulation is also giving me hard time. The one am using is as shown below.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Leonardo only
  }

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  mySerial.println("Hello, world?");
}

void loop() // run over and over
{
  if (mySerial.available())
    mySerial.println("Hello, world?");
  if (Serial.available())
    mySerial.println("Hello, world?");
}

Will b every grateful for any help offered.

Generally speaking, circuit-driven simulation should be used when you have circuit details to work out; connecting two pieces of software is better done on the hardware itself, or by porting at least one piece to run on your PC.

You should download this GSM Library for Proteus . You can use this library to simulate your GSM module in Proteus software. You should also check this example where they have discussed Hoe to Send SMS with GSM module in Proteus ISIS. I hope it will help you out.
Thanks.

Hello I had the same problem as you, but I managed to solve it.
Use the TinyGSM library. Open the library folder, locate the Tinygsmcommon file.
Open the file, line 75 changes the value from Baud 9600 to 2400. That is the minimum speed of my module.
In proteus work with the same speed 2400.
It worked here. Proteus can not handle so much speed.
And do not forget to also change the speed of GSM, place 2400.

I'm sorry to say that answers need to be in English (see Quality Standards and [answer]). Please edit your answer to be in English otherwise it will be deleted.

I have used Google translate. Please edit it if there are any errors in translation.

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


text:
Razor 9DOF SMD Capacitor replacing
I just bought This IMU a while ago, and when I reached the point where I wanna connect it, I noticed that one of the capacitors have been removed by accedint, and since it took too long to check the product, I won't get to replace it or get any refund, so my question, how can I replace that SMD capacitor?
P.S. I have some Ultrasonic sensors might have the same SMD capacitors that I can take off and replace with if anyone can help.

You are looking for C22,  0.1uF capacitor, connected to smooth the 3.3v from the regulator. If you are not using the battery connector, you can probably just leave it out.
You could just get a capacitor with leads and connect it somewhere between 3.3v and ground. You can use the ISP header (2x3 holes on the right) for this. I think it's the top-right and bottom-right pin.

Try using two soldering pencils, one in each hand. makes it easy to remove the capacitor from the donor board.

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


text:
Serial communication and Arduino program in C
When I flash this simple code (using Arduino-Makefile):
#include <avr/io.h>
#include <util/delay.h>
#include <Arduino.h>

void init_io(void) {

    // open serial port
    Serial.begin(9600);
    while (!Serial);
    Serial.println("Comm-link online");

}//END: init_io

int main(void) {

    init_io();

    while (1) {

        // send data only when you receive data:
        if (Serial.available() > 0) {

            // read the incoming byte:
            int incomingByte = Serial.read();

            // say what you got:
            Serial.print("I received: ");
            Serial.println(incomingByte, DEC);

        } else {

            //  Serial.println("No serial ");

        }

    }//END: loop

    return 0;
}//END: main

I only see first two chars printed in the serial output:

~$> Co

The input also does not work as intended - tested on two independent microcontrolers, Mega and Uno. I'm not sure what's the cause of this behaviour. Here's the Makefile:
BOARD_TAG    = uno # megaADK uno
MONITOR_PORT  = /dev/ttyACM0
ARDUINO_LIBS =

include $(ARDMK_DIR)/Arduino.mk

It's definitely not a hardware problem, I've used serial i/o before in other projects.

What program are you using to see the serial responses? How do you have the port configured on your end?

Usually screen, I tried also on Arduino IDEs built in Serial Monitor.

When using the Arduino core library, you normally do not write a
main() function. Instead, you write setup() and loop() and rely on
libcore's provided main() for calling them.
If you nevertheless want to provide your own main(), then you should
call init(); (with no arguments) before you try to use the library.
Adding this single call makes your program work on my Uno.
However, since it does not seem to be officially documented, this trick
may not be safe against upgrades in the core library. Writing setup()
and loop() should be more future-proof.

This solves the problem. An alternative is to use AVR libc implementations printf(), puts() and getchar().

Yes, but if you go along this path, you will have to initialize the UART yourself, and provide the put and get functions, and the ISRs. And since your program will not depend on libcore, you will probably use a Makefile simpler than Arduino.mk.

Yes,off course - I'm simply stating it here as another possibility, for future reference.


text:
Problem reading HMC5843 - Magnetometer in Simulink
I'm having a SparkFun 9 DoF sensor stick including the following components:

ADLX345 - Accelerometer
ITG3200 Gyroscope
HMC5843 - Magnetometer

Im currently working on a project in which I need to calculate the yaw angle, I tried using the gyroscope and the accelerometer for this and found out that it didn't work for the yaw angle but only for the roll and pitch angles.
Im trying to do my implmentation in Simulink where I read the sensors via I2C through an S-function. My sensor stick is connected to an Arduino Mega and it works well for both the accelerometer and the gyroscope but when I try to do the same thing for the magnetometer all the signals have a constant value of zero.
For doing this i include the two libraries wire.h, wire.cpp, twi.h and twi.c. This is the same libraries that are used in many Arduino sketches for reading I2C-devices.
I use the following code for the initialization:
    if (xD[0]!=1) {

  # ifndef MATLAB_MEX_FILE

  Wire.begin(); // start i2c bus

  Wire.beginTransmission(MAG_ADDRESS); // 0x3C
  Wire.write(MAG_MEASMODE);            // 0x02
  Wire.write(MAG_MEASMODEC);           // 0x00
  Wire.endTransmission();

  # endif
  // initialization done
  xD[0]=1;
}

For the output I use the following code
// wait until after initialization is done
if (xD[0]==1) {

# ifndef MATLAB_MEX_FILE

    unsigned int i = 0;         // counter var.

    unsigned char lb_mag[6] = {0};

    int temp_mag[6] = {0};

    Wire.beginTransmission(MAG_ADDRESS); //0x3C
    Wire.write(MAG_XMSB);                //0x03
    Wire.requestFrom(MAG_ADDRESS,6);     //requesting MSB,LSB of XYZ-component
    while (Wire.available()){
        lb_mag[i++] = Wire.read();
    }

    Wire.endTransmission();

    temp_mag[0] = (lb_mag[0] << 8) + lb_mag[1];  // convert x reading to int16
    temp_mag[1] = (lb_mag[2] << 8) + lb_mag[3];  // convert y reading to int16
    temp_mag[2] = (lb_mag[4] << 8) + lb_mag[5];  // convert z reading to int16

    for(i=0;i<3;i++){
       magnet[i] = temp_mag[i];
    }

# endif
}

Does anyone have any ideas on why this does not work? As I mentioned before it works for both the gyroscope and the accelerometer. Anyhow, all help is appreciated! Thanks in advance!


text:
Does upload using `ICSP`overwrite the bootloader?
If I compile a sketch then upload using ICSP does it overwrite the bootloader?
I am using Arduino program and Arduino Uno as ICSP.

The Arduino IDE creates an additional hex file that does also contain the bootloader. But you have to use to commandline to upload it.

Yes.
When you program using ISP you overwrite everything in the chips flash, even the bootloader.
This has some pro's and con's:

Pro: The program starts immediately, meaning it doesn't wait to check if there's any programming coming in before starting your sketch.
Con: You need to use ISP to program your Arduino again or to upload the bootloader again.

Normally there is not really any reason for not having the bootloader present but if you are programming bare Atmel chips without a serial interface this way might be preferable.

Thanks. I expected ths was the case, but I have a Nano which can't be powered/programmed by serial but works with ICSP. This seems to offer the opportunity to load a larger sketch.

Yes, it will overwrite the bootloader.
In addition to Hans Neve's list of Pros, it has the added benefit of gaining you a couple hundred bytes (0.5KB) that is otherwise used by the bootloader.

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


text:
Fritzing file for prototyping shield
I have a prototyping shield with mini breadboard similar to Adafruit Proto Shield for Arduino Kit - Stackable Version R3.
Is there a Fritzing file for this.

A quick google search turned up a solution in the very first result:
https://forums.adafruit.com/viewtopic.php?f=31&t=36560
It is a contribution from an Adafruit customer.
All credits go to them.
Source thread: https://forums.adafruit.com/viewtopic.php?f=31&t=36560


text:
Problem with serial driver for CH340G board
I bought a USB Nano V3.0 ATmega328 16M 5V Micro-controller CH340G board For Arduino and tried it with Arduino 1.6.6 on my MacBook Pro running OS X 10.11.1
The USB serial could not be seen. I searched on the web and found a few posts about this board, and downloaded http://www.wch.cn/download/CH341SER_MAC_ZIP.html
Most of the instructions were in Chinese, but the driver CH341SER_MAC.ZIP 资料类型：应用资料 资料大小：250KB 资料版本：1.1 更新时间：2013-12-25 seemed to install, but I cannot seem to find any /dev/tty and Arduino can't see any serial ports.
Has anyone had any success with this. (The seller has sold 18000 of these so someone may have got it working.)

I'm not sure if it's the answer, but your driver is for the CH341, not the CH340G

Well, that's what you get for buying cheap clones. Those chips are notoriously difficult to get working with OS X. Some have done it, some have failed miserably. Simplest just to cut your losses and buy a real Arduino.

I suggest you do not give overly great weight to (the great*) Majenko's advertising for "real" Arduino's. While there are indeed many substandard 'clones' the Arduino platform is, by the originator's intentions, open source, and it does much violence to their philosophy and intended open-ness of the design to disclaim "realness" for all products not made by one or two companies. The seller of the product should be able to provide drivers that work with any mainstream O/S. If the do not and cannot then by all means include them on Majenko's no-go list. I have had excellent results with ....

.... Baite electronics  Arduino compatible products. Great name ! :-). Also great price and rapid delivery (in my experience). I am not associated with the company in any way and gain nothing financially (or any other way) from recommending them. || * I consider Majenko to be very highly capable a superb source of technical advice. We may disagree on some unimportant secondary issues :-).

@FuaZe, the 340 and 341 are very similar, most drivers support both.

These cheap clones always give me a problem on a Mac, but when I have plugged them into a PC (of any age) they have always worked as expected. Don't get me wrong, I love Macs, but sometimes you have to use a PC...

Using different search criteria I found http://kiguino.moos.io/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html
This indicated a newer driver for OSX 10.9 and above at:-
http://kiguino.moos.io/downloads/CH34x_Install.zip
It is now working OK.
PS This was probably a Mac question, but I will answer as it is mainly of interest to Arduino users.
PPS The board worked on my Raspberry Pi which had the driver installed.
WARNING
The driver worked on OS X 10.11 but after upgrading to OS X 10.11.2 when I plug the USB cable into the Mac it causes a crash. This may or may not be related to the upgrade but after this happened twice I gave up.

I think you should mark your answer as correct

This worked for me: http://kig.re/2014/12/31/how-to-use-arduino-nano-mini-pro-with-CH340G-on-mac-osx-yosemite.html

On MacOS Sierra it kept crashing the OS,  but version 1.3 works on MacOS Sierra.
Found here:  https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver

Yep. That works. :-)

The CH340 is a chip with notoriously iffy driver support, definitely for OS X, and reportedly also for Windows. Some driver authors are not very fond of it, as evidenced by this affectionate comment
/*
 * driver for WinChipHead CH341/340, the worst USB-serial chip in the world.
 */

On the upside, the chip costs an order of magnitude less than the commonly used FTDI chips.
I've seen drivers from 3 sources:

The manufacturer drivers work off and on. The ones on the official site are not signed, and at some point, they started causing kernel panics for me.
The Codebender team is including free CH340 drivers in their installer, and I've had some success running those, although I'm having some difficulties with the latest version. YMMV.
So far, the drivers developed by Repleo have been rock solid for me. These are commercial, but, at less than $10, a pretty good deal in my opinion.


text:
Push-Pull tone code
I wanted to use a piezo sounder to sound an alarm in an application. Testing indicated that tone() was not very loud.
I could use some external circuitry to swing the pins ±5V but as I have plenty of spare pins, it seemed feasible to use 2 pins driven in anti-phase to increase the power by 4.
I looked at the source Tone.cpp but the code is somewhat intimidating. Before I start to modify it I was wondering if anyone else has already done something like this.

Wouldn't you still end up with the total voltage difference across the two pins being at most 5V?

@dlu No The swing is 10V. Think about it - this is a standard technique.

-1. No, the swing is 5V, unless you generate 10V with a boost converter or generate a -5V rail. Fundamental flaws in your plan aside, yes it's possible to add an anti-phase pin to the mix a few edits to the Tone library.

@CharlieHanson No, the swing is 10V. At any moment in time the instantaneous voltage between the two outputs is 5V, but into an inductive load (speaker, moving coil) the displacement is double since you are inverting the polarity all the time, and first pushing the coil with +5V and then pulling the coil with -5V giving the equivalent drive displacement of 10V with a -5V offset.

Yes, Tim Eckel has already published a library "toneAC" on the Arduino website at http://playground.arduino.cc/Code/ToneAC
All of the syntax is there too.


text:
Arduino Leonardo model differences
I was thinking of buying another Arduino, and the Leonardo looks appropriate.
However I am confused! The Comparative Tables seems to show 2 different Leonardos. (This table is very difficult to read with tiny black text on a grey background, and no key to the column headings.)
There appear to be different models "R3" and "R4" from different retailers and Element14 seems to have a "U4". Can anyone clarify the differences?
I assume I can use the Uno Prototyping shield on the Leonardo.

Wow! I'll have to talk to them about that. :) I think you can take that as a typo.

I think the pin-outs are the same on both boards (the pin spacings) so the shield should work on the Leonardo. The signals will differ a bit from the Uno to the Leonardo.

Personally I wouldn't buy the Leonardo unless I specifically needed the USB interface stuff (eg. mouse/keyboard emulation). There are more sketches for the Uno than for the Leonardo. However if you want to make something that simulates a keyboard, then the Leonardo is the way to go!

Personally I wouldn't buy either. I'd buy the chipKIT Lenny, but then I made it :P Not such good USB support yet though, so it depends what you want from it...

At the end of the day the Leonardo is just a chip (ATMega32U4) on a board with a voltage regulator, a couple of LEDs and USB socket / shield headers. There's not much else to it.
Different revisions may change some of the support components - maybe a component went EOL and they needed to change it, or a better / cheaper one came along that they switched to - but the basic design of it - a chip on a board with minor support components - can't really change.
The reason it's hard to find the differences between the different revisions is because those differences are so inconsequential to the end user that knowing them is irrelevant. The only real way you'd find the differences would be to compare the schematics of each revision to find the components that have changed. In some cases it may even just be a change to the silk screening in re-branding from Arduino to Genuino, or just a slightly more modern logo, etc.
It's still the same chip, and still connected up in the same way.

In fact I decided to buy a Pro Mini instead, as I don't need USB.


text:
Differences between Arduino IDE versions
I run Arduino IDE on both my Mac and under Raspbian on a Raspberry Pi, both running the latest version of OS.
The Raspberry Pi has Arduino 2:1.0.5+dfsg2-4.1 and I am running the latest 1.8.4 on macOS.
Debian is always somewhat behind the latest software, and this has not concerned me before, as I have never had issues before. (I know I could download the latest ARM32 build or compile from source, but this would probably generate a lot of dependencies.)
I have recently run into a couple of problems.
Compiling a script which has #include <SdFat.h> generates an error, although the library is present in ~/sketchbook/libraries/SdFat/src/SdFat.h. This does not seem to be an issue on macOS.
I was also trying to program an Atmega using a Uno as ISP as in "Using an Arduino as an AVR ISP". I have done this in the past, but the instructions and the Arduino program seem to have changed; there is no longer "Upload Using Programmer" menu, but suggests the "Burn Bootloader" command. Does this upload both the Bootloader and Sketch?

Debian is always somewhat behind the latest software

No, when it comes to the Arduino IDE Debian is frozen on an ancient version.
1.0.5 is considered to be too old to use. Many many things have changed since then - bug fixes, optimisations, new API components. And not least the implementation of the Board Manager for installing support for more boards, both by Arduino and other makers, and support for multi-arch libraries (which your SdFat library is with a src folder in it).
You should never install the Arduino IDE from the Debian repositories. Instead you should download the current version of the Arduino website (http://arduino.cc/download) as a tar.\z file and extract it into a folder and run it from there.

Majenko answered why my sketch did not compile.
I decided to give it a try and downloaded arduino-1.8.4-linux32.tar.xz.
I was somewhat concerned that there seemed to be no indication whether the Linux ARM supported ARM6, or ARM7.
The download itself contained absolutely no information, not even a README. I ran install.sh as outlined in  https://www.arduino.cc/en/Guide/Linux and Arduino IDE installed alongside the existing Arduino IDE, and worked (at least on the PI3).
I also solved my issue using a Uno as ISP. The documentation on the Arduino site now describes "Use the Burn Bootloader command". I found the missing "Upload Using Programmer" menu under the Sketch menu.


text:
'TCCR0B' undeclared
I am trying to compile the function in http://playground.arduino.cc/Code/PwmFrequency
This produces a couple of errors
sketch/setPwmFrequency.c:34:3: error: unknown type name 'byte'
   byte mode;
   ^
sketch/setPwmFrequency.c:45:7: error: 'TCCR0B' undeclared (first use in this function)
       TCCR0B = TCCR0B & 0b11111000 | mode;

byte is trivial, but I can't seem to find TCCR0B et al I assume it should be defined somewhere.

@LookAlterno How can a verbatim download of the code from the link to the Arduino site be insufficient?

Your chip doesn't have that register. Find out what the original code does and implement the same functionality on the target chip.

Both errors can be solved by adding the following line to your setPwmFrequency.c:
#include <Arduino.h>

This will include the files that contain the byte typedef and also the register definitions.
You may notice that is not necessary in an .ino file. The reason is that the Arduino IDE automatically adds the Arduino.h include to .ino files during sketch preprocessing before compilation.

The #include partially solved the problem, but still didn't link. Maybe I could have solved with a .h file. I gave in to the dark side, and renamed it .ino. Life would be so much easier if Arduino didn't try to redefine c/c++ - particularly when the language seems to have changed since I last used it.

I assumed you would have a .h file to go with your .c file. I did my testing with that setup and it did indeed compile. The Arduino IDE really doesn't mess with the language much. Pretty much the only thing other than the automatic Arduino.h include in .ino files is it generates function prototypes in .ino files where necessary but you can manually declare them if you like. main() is hidden away in the core library but that's still standard c++.


text:
How to configure location of preferences
I had been using Arduino 1.0.5 on my Pi, and in September last year downloaded arduino-1.8.4-linux32.tar.xz (which I have since updated).
I have been successfully using 1.8.5, but just noticed it seems to have been /home/pi/.arduino15 for preferences and packages.
I probably did this inadvertently when I was briefly running both 1.8.4 and 1.0.5 (which is long gone). I have /home/pi/.arduino but this only contains preferences.txt and has not been used since September.
There seems to be no  way of changing this to the normal directory; where is this configured?

That is the normal directory.

they can be in a couple places, grep is your friend.

Since the introduction of many enhancements in the IDE, such as the Boards Manager, and the Arduino Builder system, it was decided that this would break backwards compatibility with older versions of the IDE.  In version 1.5.0 of the IDE it was therefore decided that the location of all the Arduino data files (of which there are now many, not just a preferences.txt file) should be moved to a new location, and .arduino15 was chosen to reflect the current version.
Since then a version number war broke out between the two Arduino factions, which was then subsequently resolved, and we ended up with the 1.8.x group of versions. These, since they haven't introduced anything drastic to the underlying system since 1.5.x, haven't needed to change the location of the data files (indeed, to do so would be undesirable), so it has remained as .arduino15.
I don't believe it's possible to change the preferences location, since the only place would be in preferences, and it would need to load the preferences to know where to load the preferences from.
If you really need to access the preferences.txt file yourself as ~/.arduino/preferences.txt (why would you?) then you can just delete the old .arduino directory and create a link to the new one:
$ rm -rf .arduino
$ ln -s /home/pi/.arduino15 .arduino

Update:
There is a command-line argument to the Arduino IDE that lets you set the location of the preferences.txt file (detailed here):
$ arduino --preferences-file /home/pi/.arduino/preferences.txt

However what that will do with an old preferences.txt file is anyone's guess.

Thanks for the explanation. I probably jumped to the conclusion that this was related to the older 1.0.5. The question now becomes do I need .arduino and where did it come from? It seems to date from the installation of 1.8.4

.arduino was created by 1.0.5.


text:
Serial source code
Serial is documented on the Reference pages, but seems to receive special treatment (no need to include header), and there does not seem to be any file with the Source code.
Stream is the base class for Serial and inherits from the Print class.
There is source for Stream.h
LiquidCrystal_I2C also inherits from the Print class, and I was planning to write code which outputs to either LiquidCrystal_I2C or Serial; there are many options, but I was looking for Serial to explore its inner workings.

The HardwareSerial.cpp file is located in ...hardware/arduino/avr/cores/arduino, if that is what you are looking for

@Fauzan There is no Serial class in the location above, which is where I found the other source.

Serial is an instance of class HardwareSerial.

@Majenko Where is it defined? I cannot even find the symbol Serial anywhere?

https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/HardwareSerial.h#L143 is where Serial is defined. On AVR MCUs with built-in USB it is defined here https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/cores/arduino/USBAPI.h#L152.

Serial is an instance of the HardwareSerial class.  It is defined in HardwareSerial0.cpp:
#if defined(UBRRH) && defined(UBRRL)
  HardwareSerial Serial(&UBRRH, &UBRRL, &UCSRA, &UCSRB, &UCSRC, &UDR);
#else
  HardwareSerial Serial(&UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);
#endif

HardwareSerial is a child of Stream as defined in HardwareSerial.h:
class HardwareSerial : public Stream
{
    ....
};

Stream is a child of Print as defined in Stream.h:
class Stream : public Print
{
    ....
};

Print is a top-level class with no inheritance.
Serial is not a class. It is an instance of a class. That is, it's an object that has been constructed from the class definition. Anything you access member functions of using a . is an instance of a class (aka an object) not a class itself. Anything you access member functions with :: is a class using static member functions.
Examples:
Serial.println(); // Call the println() function in the Serial object
Wire.beginTransmission(0x34); // Call the beginTransmission function in the Wire object
Foo::bar(); // Call the static function bar() in the Foo class.


text:
Using Arduino to show images in Serial Monitor
Some time ago I came across a Vedic in which a person has hacked an optical mouse's camera and displayed the image in the Serial Monitors.
My question:
How to use Serial Monitor to display an image captured by the Arduino

Based on this guide, he doesn't actually display the images on the serial monitor, only the image data for each pixel.
Then another program (Javascript and some HTML) on the PC side collects the data and converts it to a greyscale image.

If you happen to know, could you tell me how those  programs work


text:
Sensing horizontal tilt
I'm building a digital gear shift knob, which would display current gear (1-5, R) and based on readings from OBD-II change color when gear shifting is required, to save on fuel consumption.
I need a way to detect the current gear - PID 0D (current gear) is not availiable in this car. I was thinking about doing it based on the horizontal tilt of the gear stick, since there are 6 positions plus a neutral gear:
    1   3   5
     \  |  /
      --0--
    /   |  \
   2    4   R

Is there a sensor I could use? Or perhaps it'd be possible to build one, e.g. using 6 of these ball switches: https://www.adafruit.com/products/173
There is however a space constraint since everything needs to fit inside a gear knob, therefore I'd prefer a nice single package.

My first thought was accelerometer, but you'd have a hell of a job filtering out the acceleration/deceleration/turning g-force and the general vibration of the car.  Maybe a gyroscope may work.  Tough one this...

That's funny. I had the same thought too, use an accelerometer. I think you could do it with just a three axis accelerometer , but like Majenko said, you'd have to filter out the noise. However, my thought is that shifting gears has a distinct motion pattern, so you might be able to implement a state machine. Otherwise, you can "beef" up your accelerometer and go for an IMU. This would allow you to create internal frame of reference for tracking the position of the shift knob.

Many vehicles with manual transmission use two push rods or cables to transmit gear selection to the gearbox. It may be easier to detect the position of those rods/cables than to attempt to filter out the g-forces involved in a moving vehicle.
Alternatively, you could use the ratio of vehicle speed to engine revs (if you can retrieve these from OBDII in your vehicle). Given that these two are directly related when a specific gear is selected and the clutch is engaged, a simple division should give you a ratio you could use to decide which gear is selected.

You could also sense the position of the stick where it enters the floor with hall sensors... 1-5 and reverse would have sensors, neutral would be when none of the other gears are detected.

Your stick goes into the chassis at some point.
Why not detect the position down there?
But to be sure to save fuel, you'd need to know the rpm/speed and especially the load of the engine. If you are going at a high gear and low speed you won't save fuel either, so the knob is not the right place to detect the gear in question.
Go for OBD, get the ratio of speed and rpm and get the load or injection quantities. If you go up the hill and select too high a gear, you won't be happy either.


text:
Galileo - servo motor moves only in one direction and it doesn't turn back
I have an Intel Galileo (1st gen) and a servo motor (Tower Pro SG90).
My problem: my servo moves only in one direction and it doesn't turn back.
I want to perform a movement from 0° to 90° and then from 90° to 0° again.
At the moment, I have just tried the official arduino snippet for servo motor that should perform a similar movement. But, as said before, the servo doesn't turn back.
Here the code
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // a maximum of eight servo objects can be created

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos < 180; pos += 1)  // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=1; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

Obviously I have made the attachments like on arduino tutorial.
Every help will be greatly appreciated! :)
Thanks in advance

How are you testing this? Do you manually push the servo back to the 0° position? What happens if you swap the 2 for loops? Or increase the delay to something like delay(300)? Very odd problem you have there.


text:
Sample code for using adafruit servo shield?
I would like to control 16 motors with a servo shield, however, I have found scant to nothing sample code online. The one I was able to find is...strange to say the least
https://github.com/kachok/arduino-libraries/blob/master/Adafruit_PWMServoDriver/examples/servo/servo.pde
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

#define SERVOMIN  150 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  600 // this is the 'maximum' pulse length count (out of 4096)

uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("16 channel Servo test!");

  pwm.begin();

  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
}

void loop() {
  // Drive each servo one at a time
  Serial.println(servonum);
  for (uint16_t pulselen = SERVOMIN; pulselen < SERVOMAX; pulselen++) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);
  for (uint16_t pulselen = SERVOMAX; pulselen > SERVOMIN; pulselen--) {
    pwm.setPWM(servonum, 0, pulselen);
  }
  delay(500);

  servonum ++;
  if (servonum > 15) servonum = 0;
}

Im used to controlling motors using servo.write, but with the shield, it doesn't seem very intuitive as to how I should control the motors. How does Servomin and Servomax map to 0 degree and 180 degree?
Someone please elucidate!

The 2 values SERVOMIN and SERVOMAX define the pulse length, which tells the servo what angle to go to.  The example uses 150 for SERVOMIN and 600 for SERVOMAX.  When running the code, the servos travel 180 deg.  I changed the code to read:
#define SERVOMIN  262 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  488 // this is the 'maximum' pulse length count (out of 4096)

and the servo now moved only 90 deg. centered at the same place as the original code.
the tutorial provided by Adafruit describes a way to define the movement by angle:
pulselength = map(degrees, 0, 180, SERVOMIN, SERVOMAX);

found here:  https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library
hope this helps

Adafruit's guide for the shield is here:
https://learn.adafruit.com/adafruit-16-channel-pwm-slash-servo-shield/using-the-adafruit-library
I'm not sure how much the library you linked and the official one differ. They seem to be used the same way, but you should probably stick with the official one.
You are going to have to use setPWM(pin, on, off) since the arduino is not generating the signals like it would with servo.write(), the arduino is sending commands to a chip on the shield that generates the signals for you.
Adafruit recommends calibrating SERVOMIN and SERVOMAX yourself with whatever brand of servo you plan on using, but those default values should be pretty close.


text:
Curious: What would happen if you connect 5V and GND port directly with a wire
Has anyone ever accidentally or inadvertently connected connected the supply port with the ground port with a wire?
Does Arduino provide internal safety to prevent the circuit board from shorting out?

There is some protection.
When powered from the USB port, the UNO has a 0.5 A fuse.  This is a self resetting fuse that will trip when the current is high, and reset when it cools back down.  These fuses are great for peripherals that might be exposed to occasional "oops".  See the data sheet for more details of the part on the UNO.
When powered from the PWRIN plug, the voltage regulator provides some protection.  The device on the UNO contains over current and over temperature protection, which is common for regulators such as this.  The device will get very hot, and the protection will activate to limit the current (see datasheet for details).  By design, the regulator chip should protect itself from being destroyed.
So to first order, if you by mistake connect the +5 on the header to GND, all that will happen is Vcc will be reduced to near zero Volts.
The caveat is that a small spark can be generated when you make this short to ground, especially if you have a bunch of capacitors on Vcc.  That spark may cause a voltage transient that could damage a pin.


text:
Arduino + simple DC motors? (4WD kit)
I am trying to connect 4 small DC motors to Arduino, like those in the following image:

The specification for each of them is:

Suggested Voltage: 3V DC;
  No Load Speed: 65 ± 10rpm;
  No Load Current: 125mA (170mA MAX).

But I have no useful knowledge in electronics to do so...
I would be really thankful if anyone could explain me why it is so difficult to connect DC motors to Arduino (I've heard about problems with the magnetic field, but I don't really understand why); and possible point me to an easy (and cheap) solution. I am, of course, willing to study (not expecting a complete solution).
I'm aware there are some shields for doing this kind of connection, but they are really expensive, and I've seen some people using only transistors or components like SN754410.
Thank you in advance! :-)

It's not really the no-load current you need to know, but rather the load current.  Those look suspiciously like the type of low-voltage, high-current motor which is hard to drive, such that many people replace the actual motors in the gearboxes with others.  But if you want to try, consider an FET H-bridge like the TB6612FNG, probably already on a PC board.

@ChrisStratton, thanks! I am planning on using a L298N driver motor; wiring the two left motors together and the two right motors together (being able to use a single dual H-Bridge). Would you happen to know if this configuration would suffice? :-)

may i ask where you got that kit ?

I would not use the L298 in a battery powered application - the losses are a bit high, in particular you will drop more than a volt across the two transistors.

Thank you, guys! I have used the L298 and it was perfect. :-)

@Magic-Mouse, I have bought them with a reseller in Brazil. But they are easily found on Google (try googling the image itself on google images).

First you make 4 parallel H-Bridges, http://en.wikipedia.org/wiki/H_bridge then you attach it to an external powersource ( or attach directly to the battery to prevent burning your arduino )
Attach every up to a pin, making it high makes the motor running, you need 8 pins for this, eg pin 1 makes motor 1 go forward, pin 2 makes motor 1 go back and so.
This is by far the most practical solution, but it is the easiest, and can be done with 8 PNP and 8 NPN transistors.
If you don't know how transistors work i suggest https://www.youtube.com/watch?v=-td7YT-Pums collins lab, it is both educational and entertaining.

Making your own H bridges from discrete transistors is probably not the best solution here, especially for a poster facing this for the first time.

Just wire 2 motors to turn forwards, and 2 to turn backwards. That way you don't need an H-bridge (which in theory is easy to make, but in practice can be difficult to do right, I'm told).

@Gerben true true, but this is 4 motors attached, i was just afraid that the current going through them would be more than the arduino could handle, thats all. (Besides it is fun to play with H-Bridges, since it is the first step for a stepper motor. No pun intended)

@Gerben The Arduino does not handle more than 40mA on an IO pin (according to documentation) and 200mA on the Vcc pin meaning he could only run 1 motor or risc frying the board.

@Gerben and Magic-Mouse, Thanks! I am planning on using a L298N driver motor; wiring the two left motors together and the two right motors together (being able to use a single dual H-Bridge to control left or right). Would you happen to know if this configuration would work? :-)

Yes the L298N is perfect for that since it supports up to 4 amps of current so you could serial couple about 23 of those motors without frying it.

@Magic-Mouse - the Arduino would not be able to run even one of these motors.

@user282723 grad you choose to use a dedicated H-bridge chip. The L298N should work. You can just connect the two motors in parallel.

Thank you, guys! I have used the L298 and it was perfect. :-)


text:
Basic usage of Nick Gammon's Regexp library
I am using the following code modified from the examples. I get the count of matches but the actual value is not displayed
#include <Regexp.h>

void setup() {
    Serial.begin(115200);
    MatchState ms;
    char buf [100];
    char buf2 [100] = "The quick brown fox jumps over the lazy wolf";
    ms.Target (buf2);
    unsigned int count = ms.MatchCount ("[aeiou]");

    Serial.print ("Found ");
    Serial.print (count);
    Serial.println (" matches.");
    for (int j = 0; j < count; j++)
    {
          Serial.print ("Capture number: ");
          Serial.println (j, DEC);
          Serial.print ("Text: '");
          Serial.print (ms.GetCapture (buf, j));
          Serial.println ("'");
    }
}
void loop(){}

Could you add the output you are getting, to your question?

You haven't defined any capture groups in your regexp.
The regexp [aeiou] will match any of those characters, but it won't capture them.  To capture you need to define a capture group which is a sequence of tokens surrounded by parenthesis.  For instance:
([aeiou])

In your test phrase "The quick brown fox jumps over the lazy wolf" that should match 11 times and capture each match, resulting in captures of e u i o o u o e e a o.
The reason why matching and capturing are two completely different things is so you can do things like [aeiou]([aeiou]) which would capture the second vowel in a two vowel sequence. In your example it would match the ui of quick and capture just the i.


text:
invalid conversion from 'char' to 'const char*'
My intention was to overload a function to handle optional parameters. My code looks like
void functionA(const char *errorMsg) {
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg) {
    ...
}

The line functionA('0',... generates the error
invalid conversion from 'char' to 'const char*'

How do I fix that?

The compiler needs the prototypes of the functions before the body containing the call to the overloaded function otherwise if starts complaining that the parameters does not match the known function (at this point in the source code).
// The function prototypes
void functionA(const char *errorMsg);
void functionA(char errorCode, const char *errorMsg);
...
void functionA(const char *errorMsg)
{
  functionA('0', errorMsg);
}

void functionA(char errorCode, const char *errorMsg)
{
  ...
}

Cheers!

What do your prototypes look like? I suspect that the compiler thinks that it is calling the first instance of functionA() and is trying to cast '0' to a 'const char *` and that isn't going to work…
If you don't have prototypes for both signatures, then adding the second one may solve your problem. If you do, I'm puzzled.


text:
serialEvents within a class
My .ino looks roughly like this
#include "command.h"

Command command;
void setup() {
}

void loop() {
}

command.h
class Command
{
    public:
        Command();
};

command.cpp
#include <Arduino.h>
#include "command.h"

Command::Command() {
  Serial.begin(9600);
}

void serialEvent() {
  while (Serial.available() > 0) {
    char inChar = (char)Serial.read();
    Serial.print(inChar);
  }
}

The serial events don't seem to be happening. It works normally if I move the code out of the class.

Does it work when you move serialEvent() back to the sketch? This might be a build/link issue.

When you put the Serial.begin in the constructor and declare the Command object at file scope, the Serial.begin will occur before setup().  Not recommended, perhaps not allowed.
If you do that, the compiler has to figure out that the Serial instance must be constructed before the Command instance is constructed.  It can't always figure out the correct order.
In general, this is why you see many classes with a begin or init method.  This allows the construction of file-scope instances to take place in any order, before setup.  Then setup does the Command.begin(), which finally calls Serial.begin, long after Serial has been constructed.
Also, using SerialEvent is no better than doing the polling in loop().  If you're busy doing something else, SerialEvent does not get called.  If you need to handle characters in the background, in the RX interrupt, you might want to take a look at a modified version for the Serial object(s) I posted, NeoHWSerial.  You can attach a routine to be called whenever a character is received.

Yes by putting an init method in the Command class and calling it from setup() the problem was fixed.

@user316182, Yes, I am sure that SerialEvent is not called from the RX char interrupt.  It is called from main, which just calls loop and then serialEventRun in the never-ending for loop.  You may as well just call your serialEvent code from loop.  Sadly enough, there was a time when SerialEvent was dispatched from the IRQ, but it was later moved to main. See this commit.  :-(

@slash-dev "...Also, using SerialEvent is no better than doing the polling in loop()." Are you sure about that? SerialEvent (and especially the ones on Teensy3) use hardware interrupts which can be handled in the midst of other operations; even delay() does not block interrupts (http://playground.arduino.cc/Code/AvoidDelay). It's hard to imagine multiple serial streams running at 100 kbaud or better (test reported in PJRC forum) and handling each character in the main loop even if that was all your program did. And why would you want to? There are good reasons interrupts exist.
Update: I'm not allowed to "comment" without 50 reputation. Thanks for the commit link... I can't imagine why HardwareSerial would not use interrupts... that is the default on all other platforms we've used for years.

Uhh... did you notice you were pressing the "Add Another Answer" button?  There is an "add a comment" button below my answer that you should have used.  I have replied above, in a comment to my answer.


text:
Class is not tracking changes to a private field
I have a program where a device registers itself with a command object. The command object is losing track of the registrations. The following program repeats "0 devices registered" even though when it initializes it displays "Devices registered 1". My guess is that I am accidentally creating 2 copies of the command object.
This is the main sketch
#include "command.h"
#include "widget.h"

Command command;
Widget widget;
void setup() {
  command.init();
  widget.init(command);
}

void loop() {
  command.update();
}

command.h
#include "Arduino.h"

#ifndef Command_h
#define Command_h

typedef struct  {
  char id;
  char name[20];
} Device;

class Command
{
  public:
    Command();
    void init();
    void registerDevice(Device _cmd);
    void update();
  private:
    Device Devices[20];
    byte DevicesPtr = 0;
};

#endif

command.cpp
#include <Arduino.h>
#include "command.h"

#define DEVICES_MAX 9

Command::Command() {
  DevicesPtr = 0;
  Device Devices[DEVICES_MAX];
}

void Command::init() {
  Serial.begin(9600);
}

void Command::update(){
  Serial.print( DevicesPtr );
  Serial.println( " devices registered" );
  delay(500);
}
void Command::registerDevice(Device _cmd) {
  _cmd.id = '0' + (++DevicesPtr);
  Devices[DevicesPtr] = _cmd;
  Serial.print("Devices registered ");
  Serial.println(DevicesPtr);
}

widget.h
#include "Arduino.h"
#include "command.h"

class Widget
{
  public:
    static void init(Command _command);

  private:
};

widget.cpp
#include "widget.h"
#include "command.h"

void Widget::init(Command _command) {
  Device device;
  strcpy(device.name, "Widget #1");
  _command.registerDevice(device);
}

It is all about calling conventions and argument binding. The code is using call-by-value when it should be call-by-reference.
This is call-by-value (the incoming command is not updated, a copy is passed as parameter):
void Widget::init(Command _command)
...
widget.init(command);

This is call-by-reference (a pointer to command is passed as parameter):
void Widget::init(Command* _command)
{
   __command->registerDevice(...);
}
...
widget.init(&command);

Alternative syntax is:
void Widget::init(Command& _command)
{
   _command.registerDevice(...);
}
...
widget.init(command)

Cheers!

Thank you so much, great Christmas present! The compiler complained about "widget.init(&command)" when I changed it to "widget.init(command)" it worked.

Typical cut-paste-error :). Thanks!


text:
How does arduino fetch instruction string from sms and execute?
I am working on a project in which i have to send commands using sms (GSM shield) to the arduino uno to control dc motor. What i want to know is that how can i define the instruction strings that i can send in form of sms and arduino uno reads it and executes it.
P.S. I am a total beginner at arduino coding so please help me out.

You can define them in any way you want - they are strings, they just contain text.  It's up to you to decide what you want that text to say and how you want the Arduino to act when it gets that text.,

Your GSM shield will receive the SMS which your Arduino code can retrieve as a string of characters (that description hides a mountain of detail, most of which you won't need to know). It doesn't care what the content of the SMS message is.
Your Arduino code will have to translate from the message text to motor-control commands so you want some text commands that will be easy to parse, but not so trivial that any random message might wrongly be interpreted as legitimate commands.
The digit pair "15" might command motor 1 to speed 5. But you wouldn't want any message with a couple of digits in it to change a motor. (You didn't say you had multiple motors, and if not you can leave that part out).
Let's make the message distinctive enough that it's unlikely to appear in some other context, yet simple enough to distinguish as legitimate. It would be nice if it's simple to thumb-type, too!
"motor,1,5" could convey the same information as the "15" in our first example, doesn't limit you one-digit values, isn't likely to appear in a "Hey Dude, lunch at 12:15?" type of conversation, is easy to parse and isn't too long to type on a tiny keyboard. You could extend it later, so "motor,1,+2" could mean to increase motor 1's speed by two units, "motor,1,off" could mean power it down (not just zero speed), and "motor,all,off", well, that's probably obvious.
Look up the function sscanf() [oops: not sprintf()] for one way to parse the incoming strings and collect their data.
Update: sscanf() does the reverse of sprintf(): It reads a string, collects values from it, and assigns them to variables. Search sscanf on the web for a description of its use.
Here is a sample program that reads a few possible SMS messages, checks whether they are motor commands (according to my simple example SMS above), and if it is, assigns the contained values to some variables in your program. You can see by the return values of sscanf() whether and how many conversions it made from each message, thus your code can tell whether a received SMS looks like a motor command, as well as what the command values are:
/*
 * sscanf example - Uses sscanf to test and collect data from a
 * a command string.
 */

#include <WProgram.h>

void test_sscanf(const char *sms);

// Sample of SMS messages to test whether our sscanf() format string
// can recognize good ones and reject bad ones. Experiment by adding
// ones of your own:
const char *SMS[] =
{
   "motor,1,5",
   "Hello World,3,2",
   "motor 123 456",
   "moto, 7, 13",
   "motorized, 4, 11"
};

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

   delay(1000);     // delay for user to launch a terminal (if you're quick)

   // Test each SMS example in the SMS array
   for( uint8_t s = 0; s < sizeof(SMS)/sizeof(char *); ++s ){
      test_sscanf(SMS[s]);  // test one SMS string
   }
}

void loop() {
   ;            // nothing to do here
}

// Tests a sample SMS, prints the number of variables it assigned, and what
// their values were. '0' means it didn't assign any, probably because the
// command-word failed to match.
void test_sscanf(const char *sms)
{
   int16_t assigned, values[2];

   // Print the SMS and convert it.
   Serial.print("\nSMS: \""); Serial.print(sms); Serial.println("\"");
   assigned = sscanf(sms, "motor,%d,%d", &values[0], &values[1]);

   // Display the results
   Serial.print(assigned);  Serial.println(" values assigned"); // How many values? A good command has 2.
   if( assigned > 0 ){
      for( uint8_t i = 0; i < assigned; ++i){
     Serial.print("value["); Serial.print(i+1); Serial.print("] = "); // print each assigned value
     Serial.println(values[i]);
      }
   }
}

So basically i have to define a variable with datatype 'char' then in the if-while-else loop we match the sms with the predefined value of the variable.

You would first match "motor," (in my example) to decide whether this string is really a motor command. Then you would convert the two following numeric values and use them to control your motor.

how do i do that?

and i forgot to mention i am using single 24v dc motor with driver ic ofcourse.

I am unable to understand >sscanf()

Ok got that i just have to do it myself now. And appreciate your help man. Thanks a ton


text:
Arduino Power - DC adapter
I have a 12V 2.5 ampere Dc adapter.Can i use it to power arduino uno board?
It says on the arduino website that i can use 9-12V and upto 1 ampere. I am concerned with current limit here..

Note that the higher the voltage, the hotter the voltage regulator on the Arduino will get.  Arduino requires 5V, so anything above must be regulated to 5V with the linear regulator on board (LM7805?).

If you go in through the barrel jack the power will be regulated.

Don't worry about the current limit. The board will only draw what it needs. The spec is telling you that the board can draw as much as 1 amp, so in general the power supply should be able to supply that – more is no problem, but less could be if you have a lot of devices attached to the board that are drawing power as well.
As is pointed out in the comment above the higher the input voltage the more power the on-board regulator will need to dissipate (as heat). If you are using the barrel jack (which you should if you aren't providing power through an external regulator or other stable source) there is a diode (D1 in the reference design) in the input path and the MC33269D-5.0 regulator is spec'd with a max dropout voltage of 1.25 V so you will need an input voltage of at least 6.95 V (assuming a 0.7 V drop across the diode).

So i shouldn't worry about 2.5 amperes? everything else is ok.

Not at all. The 2.5 A is a capability of the power supply. I can provide up to 2.5 A if you need it, but it will not "force" more current into the load than the load is asking for. Think about it as being like a water pipe – a larger pipe has the capability of moving more water than a smaller one, but the amount of water that flows is determined by the valve at the end. All other things being equal (which they never are :-)) a larger supply is a good thing, it gives you excess capacity for driving loads (for example if you wanted to attach a string of LEDs or some motors to your project).

Make sure that the adapter you have is the correct polarity for the arduino or it won't work.
The barrel jack is centre positive, so look for this symbol on your adapter:

The barrel jack should have reverse voltage protection so it won't work if it's the wrong way around. The Vin pin doesn't have this protection, so be extra careful connecting things there.

If you're not sure and have a meter of some sort (or even an LED and a resistor where you know the polarity), check to confirm it. That said, it looks like the input is protected against reverse polarity (see the diode D1 in the upper right hand corner of the reference design). It looks like the board will not work if you have the polarity revised (the power LED should not come on).

Yep, you're right, sorry. The barrel jack does have reverse voltage protection, it's the Vin pin that doesn't have it.

No problem. I had to look at at the schematic and it is way better to be safe than sorry :-) Good to add the point about the Vin pin, that's worth noting.

Polarity is not the issue..i just wanted to know if 2.5 amps of adapter will kill my board or not.

Can anyone tell me what the DC “barrel” adapter size is? I can’t find anything about this adapter on the Circuit layout (actually the Reference design only seems to show the USB in - I can’t figure out which component is the DC plug!)


text:
Inherent delay running EEPROM.read()
I'm using EEPROM to store long term data for use in sketches (thanks to DarthRubik for the guidance).  I store stuff like a location ("Garden") and a device name ("Greenhouse Monitor 02") plus whatever else I'd need to store to help filter through data.
When this information is stored in the sketch itself it is recalled quickly and accurately, is passed via wifi to my PHP, that then posts the data to the relevant fields in my AWS db.  Piece o' cake!  When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.
My question is actually simple (I think):
Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?
I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.
I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier.  If I can't figure it out I'll post the code for more direct answers.

I don't play a lot with EEPROM but your description of "extra time" making the whole stuff fail, looks weird to me. I guess we are talking about a few ms here only. Have you measured that time?

No.  I haven't.  Can you point me to a sketch timer (or whatever it's called)?

I would say your assumption that 'it is slow so it is corrupting the data' is wrong. Do you know that the data is correct? Do you know that you are really storing and retrieving the right things?

I just measured it: a single call to EEPROM.read() takes about 1.8 µs (microseconds, yes, not milliseconds).

Please post the code you currently use to get your data from EEPROM. Without viewing it, it will be very hard to point you into the right direction.

I plan to post it.  I haven't gotten around to it yet.

When I store it in the EEPROM, the extra time required to find it in EEPROM, pull it through the sketch, and then push it through to the db corrupts the data sourced from EEPROM and posts a jumbled mess of characters...if it even makes it to the db at all.

Are you certain of that? It is incredibly unlikely that mere time will corrupt characters and data as they are read and sent - especially the minuscule amounts of time we are talking here.

Is it possible to "stage" strings from EEPROM in flash or SRAM vs. pulling cold from EEPROM?

Yes, and you are already doing so, since you can't send direct from EEPROM to WiFi - you have to go via SRAM. You read from EEPROM into SRAM then send from SRAM through WiFi. You just won't be doing it an entire string at once.

I think PROGMEM plays a role here and I'm looking at examples oh how other sketched employ PROGMEM to better understand how to use it.

No, it doesn't. PROGMEM is for storing strings and other data within your sketch. It has nothing at all to do with EEPROM.

I am withholding the code for now because I want to try to implement concepts people may describe before I am just shown the solution...although that would be easier. If I can't figure it out I'll post the code for more direct answers.

Without seeing your code no one is really going to be able to help you. I suspect (although I am stabbing wildly in the dark) that your EEPROM reading/writing code is completely wrong and you aren't actually storing the data you expect in the EEPROM, nor reading it back properly. Unless we see your code we can't know what is going on, and so we don't have a cat's hope in hell of diagnosing your problem.


text:
Tmp36 spike and dip
I'm measuring two temperatures  and powering both tmp36 sensors off of the 5v pin.  For some reason pin A0 (t0) will periodically spike or dip 100°f over actual ambient and pin A1 (t1) will spike or dip but only by about 30°f at the same time but not necessarily in the same direction at A0.
I'm using about 4' of 24ga solid wire to each sensor.
This began with a wall adapter putting out 5v 850ma connected to the barrel connector
Previous adapter of 5.3v 2a worked fine connected via USB.
I don't think it's SW because the arduino is doing exactly what I want it to do: measure t0 and t1 and write them to a database table via wifi.  I'm thinking that I need a 5.3v 2a barrel connector.  Am I right?

You should read the specifications of the Arduino board. It states that you need at least 6V on the barrel jack, preferably 7V minimum.

Well...there ya' go.  User error.


text:
Modify SSID and Passwords in WiFi sktechs
This is a question about modifying sketches other than through the IDE.
I'm using an Arduino Uno r3 + Arduino WiFi Shield (not the 101).  Up to now I've been using the IDE to manually change the ssids and passwords to connect to wireless networks.  As a next step, I'd like to create something that will let update the ssid and password from a source other than an IDE, preferably a batch or bash file.  Over the air updates are out of the question (way too advanced) so it is safe to assume that all updates will be done via the USB cable.  Based on my limited knowledge of what I think needs to happen, I need to solve the following high-level problems:

Get the computer to recognize that a gateway is plugged into a USB port
Prompt the user to enter the new ssid and network password
Write to the ssid and password fields
Compile the code and save it (equivalent compile/upload in the IDE)
Run the sketch to find and connect to the network

I'd like this to look like two blank fields and a "submit" button to the user.
My imaginary use case is that I'm installing a clone of my gateway/sensor network at a technically-illiterate grandparent's house.  I have no idea where to begin or even if such a thing is possible!Assuming that it is possible, how can I make it easy for them to configure the gateway for use on their home network without resorting to the IDE?

Yes, this is possible. However, you need to have some programming skills (Java, C, C++, anything really that can cope with serial comms) to write the computer-side program.
Forget 'automatic' running of a program without installing a service on the target computer to constantly monitor incoming serial comms. That said, there's nothing to stop you doing that but to me it's an unnecessary extra step. If the End User can handle connecting the Arduino to the computer without having a breakdown, then they can probably cope with launching the input program themselves.
Hence, write a program for the target computer that analyses COM ports for active connections. For each connection, listen for some kind of identification sequence. Perform a basic 'handshake' to verify that it's found the Arduino. Once it has, allow the User to enter the WiFi details, which are then passed on to the Arduino via serial. If you're feeling slightly adventurous (the necessary code is provided with the Arduino IDE as an Example, so it's no real challenge) you could have the Arduino scan for networks and offer the User a list to choose from.
On the Arduino, include within the sketch a method of opening serial comms with the target computer. This can be either:

Within loop(), at regular intervals, which becomes redundant after you've performed the setup correctly; or
A one-time affair within setup(). Each time the Arduino is powered on it attempts to establish comms with the computer, but times out after 30 seconds of 'silence', thus the User has to launch the program on the computer within a reasonable time.

Whichever approach you choose, the code in the sketch follows a similar essence - send a unique message to whatever is listening (if anything at all!) and wait for a specific response. If the computer is connected and the program is running, it should answer. Provided the answer received by the Arduino is expected (thus 'handshake' mentioned earlier), it should then wait for the SSID/pass to be entered by the User and sent by the computer. From there, connecting the Arduino to the network is a trivial process.

You could also make use of the Arduino serialEvent() function. Behind the scenes, every time the loop() function returns, this function (if you define it) is automatically run by the Arduino if the Serial buffer contains data. So all you have to do is define the serialEvent() function and have it read from the serial port and compare what it gets against some pre-defined handshake value. If the read data is a valid handshake, the Arduino should respond with a unique value too and then await the SSID, password and other stuff you wish to set.
This means your can run your PC program anytime and simply have it send the handshake and wait for the Arduino's response before sending the wifi details. You can use serialEvent() like this:
    void serialEvent(){
        if (Serial.read() == 'Z'){ //if 'Z' is your handshake value
            Serial.write('X');   // if 'X' is the response expected by the PC
            getWifiDetails();   // the handler that gets the needed data
        }
        while (Serial.read() != -1);  // flush to get rid of any garbage
    }

The handshake value could be more than 1 byte to increase chances of uniqueness. This method assumes you aren't doing anything else with the serial port, since that could bring garbage to the forefront of Serial.read() calls and cause false triggering of serialEvent() and its IF condition. You could implement a timeout in your handler to handle such events though.


text:
User-Agent question
I've seen a few different User-Agents used in demo sketches and am curious as to what the various User-Agent options are and how to determine which one to use.
For example...
User-Agent: Mozilla/4.0
User-Agent: Arduino/1.0
User-Agent: ESP8266
User-Agent: ArduinoWiFi/1.1
I've used Arduino/1.0 successfully with an Uno/WiFi101 but want to use an ESP8266 now.  Do I continue using Arduino/1.0 or switch to ESP8266 (Arduino IDE 1.6.5)?
When would someone use Mozilla?
Any guidance is appreciated.

You can use anything you like. It's used by the remote server to (try and) determine what browser you're using in order to give you the best visual experience. On an Arduino you really don't care about the visual experience. You don't even need to provide a User-Agent field, but it is courteous to do so.


text:
3.3v inductive proximity sensors
I'm using an ESP8266 so I'm limited to 3.3v.  I've found a number of inductive proximity sensors but they require 5v or more.  Does a 3.3v sensor exist?
I recently dropped some tiny screws on dark carpeting and would like to find them instead of just vacuuming them up.  Stupid project?  Maybe.  But a good excuse to buy another sensor.

Have you tried using a magnet?

i've not had many problems w/ 5v sensors w/ESPs. If its a digital output, that's easy enough to use a transistor or dropper diode on (or nada). w/analog output, it's easy enough to use a voltage divider...

Why use a magnet when I could build something?

if you want really cheap, try some of these ideas: https://www.newark.com/pdfs/techarticles/microchip/3_3vto5vAnalogTipsnTricksBrchr.pdf if none of the doezen or so ideas work, bite the bullet and get some 2-way level shifters on ebay like these: http://www.ebay.com/itm/132091293479

An inductive sensor may not see "tiny" screws very well, and if it does it may well also see things you don't care about, like nails in the underlying flooring.   In contrast a magnet will pick up the screws.  Then you can use them to make a more suitable project.

I don't know what voltages inductive proximity sensors use, but in general it's inexpensive to use  3.3V–5V logic level converter modules.  These typically are bi-directional interfaces that use an N-FET and pullups to the two supply voltages to interface different-voltage logics.
See the "Bi-directional level shifters" section of the TAKING IT TO ANOTHER LEVEL: MAKING 3.3V SPEAK WITH 5V article at hackaday.com for a circuit explanation.  See gearbest.com and sparkfun.com and Adafruit for inexpensive modules.
Note, for finding small screws in carpet, a search coil as used in a metal detector might be a better choice than a proximity sensor.  The coil is part of a tuned LC circuit; metal near the loop detunes the circuit slightly, producing a tone by heterodyning.

Those "inexpensive" devices cost more than an ESP8266 MCU...

@dandavis, can you give a link to an ESP8266 MCU that costs less than $1.21, the gearbest module cost delivered?

I wish! haha ;) tbh, I didn't see that one, just the paytafruit and the other...

You could probably just use a resistive divider to bring the 5V down to 3.3V.


text:
Wifi101 ad-hoc network
I've reviewed the WiFi101 library but have found no way to make the 101 an ad-hoc network.  Am I missing something?  I'd like to be able to emulate the RedFly example:
http://notebook.kulchenko.com/embedded/storing-wifi-configuration-in-eeprom-on-arduino
Can the 101 become an ad-hoc network?  I understand the security problem with the ad-hoc capability so it would make sense that Arduino prohibits it.

Apparently you can have an ad-hoc network, you can see the example on the github here:
https://github.com/arduino-libraries/WiFi101/blob/master/examples/AP_SimpleWebServer/AP_SimpleWebServer.ino
It shows how to create an open ad-hoc network, for a secured one, you might need to check the datasheet + the method implement "beginAP".

It does not need to be secured.  Thank you!


text:
Basic Question - ESP8266 Board Pins
I have an embarrassingly simple question.
My experience to date has been limited to Arduino Uno + Wifi101.  I bought an ESP8266 and noticed that the GPIO pins don't match the printed numbers on the board.
When programming and defining pins, does #define <pin name> 16 call the pin with the printed designation D0?
I can't find a straight answer to this anywhere.
Image credit: http://crufti.com/content/images/2015/11/nodemcudevkit_v1-0_io.jpg

When you use it with what libraries?

The Arduino IDE: ESP8266WiFi.h, SPI.h

Looks like you're using https://github.com/esp8266/Arduino, in which case - yes, 16 is GPIO16, which on the NodeMCU board you have is labeled D0.
I am not entirely sure why the NodeMCU guys had to do this "pin remapping", but the end result is inconvenience when using the module with anything but their Lua.

It looks like they are using a similar system to the Arduino pin mappings, for example:

(Image credit: https://www.arduino.cc/en/Hacking/PinMapping168)
There, for example, pin 2 on the chip, is D0 (digital pin 0) on the board.
Their board will use their own mappings, but the concept is the same.

does #define  16 call the pin with the printed designation D0?

That doesn't "call" anything. It would depend on the code. If the code in question addresses the actual chip pins, then it is chip pin 16. If it goes through a library and the library maps the chip pins to the board pins, that it will refer to board pin 16. I notice BTW that the board doesn't have a pin 16.

Pardon my ignorance.  By pin 16 I meant GPIO 16.

I know what you meant. I'm just saying that a line #define foo 16 can only be read when you see what is done with foo. On its own it could mean anything.

Well based on my experience with NodeMcu and Arduino, in Arduino you use the GPIO by reffering its pin number (like 0-13), whereas in NodeMcu you will have to use D0-D8.
It's better to use D0 to use GPIO 16.


text:
Yun - replaced uhttpd with lighttpd - luci works but not /data access..?
Ok, utthpd is running on port 80 and lighttpd on port 81...both give access to the luci control panel...all well and good.
However the /data access to the yun data store only works from uhttpd.
Lighttpd returns error 404 (page not found).
Any idea what the solution might be..?


text:
Bridge */arduino/analog/2 returns a blank page
Had some start up difficulties. But updated the YUN and IDE to the latest version.
Using  * "/arduino/digital/13/1" works as supposed (turns on the LED) - it's just a bit slow. But I can't see why the analogs shouldn't work. I tried to connect it to 5V or GND, so it wasn't floating. But it still returns no reading.
Don't know if this is the cause. But when I connect to my router I can't the the YUN in the list of DHCP Clients...


text:
Servo Issues with Arduino
I am trying to execute the sweep program but all the servo does is go back and forth in one step. When I tried changing the delay, It behaves erratically.
Servo Specs:
Required Pulse: 3-5 Volt Peak to Peak Square Wave
Operating Voltage: 4.8-7.2 Volts
Operating Temperature Range: -10 to +60 Degree C
Operating Speed (4.8V): 0.18sec/60 degrees at no load
Operating Speed (6V): 0.16sec/60 degrees at no load
Operating Speed (7.2V): 0.14sec/60 degrees at no load
Stall Torque (4.8V): 11kg/cm
Stall Torque (6V): 13.5kg/cm
Stall Torque (7.2V): 16kg/cm
360 Modifiable: Yes
Potentiometer Drive: Indirect Drive
Bearing Type: Double Ball Bearing
Gear Type: All Metal Gears
Connector Wire Length: 12"
Dimensions: 1.6" x 0.8"x 1.4" (41 x 20 x 36mm)
Weight: 56gm

Sweep Code:
#include <Servo.h>

Servo myservo;  // create servo object to control a servo
                // twelve servo objects can be created on most boards

int pos = 0;    // variable to store the servo position

void setup()
{
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
}

void loop()
{
  for(pos = 0; pos <= 180; pos += 1) // goes from 0 degrees to 180 degrees
  {                                  // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
  for(pos = 180; pos>=0; pos-=1)     // goes from 180 degrees to 0 degrees
  {
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                       // waits 15ms for the servo to reach the position
  }
}

I tried both powering up internally and externally. Internally it responds but externally, arduino's L LED is high all the time and servo does not respond. May I know what is actually going wrong here.

Without code or a schematic it is difficult to help you.

Do you have a common ground when you're powering it externally?

@Comintern & sherrellbc By externally I meant, voltage being supplied from a different source and yes, the grounds were tied.


text:
Find external router IP from Arduino Yun inside router network
I want two Arduino Yuns in different private networks to communicate, i.e., behind two distinct routers of which at least one does not have dynamic DNS, so its external IP may change from time to time.
To be reachable, this Yun could forward its router's external IP to the other Yun which has a fixed DNS name. But for this to work, it must be able to determine its router's external IP.

How can the Yun find out that the external IP of the router has changed? The Yun will be runnning all the time.
If the external router IP has changed (i.e., my Fritz.Box disconnects in the night and may receive a different IP when it reconnects), how can the Yun determine the new external IP?

If this is not the right place to ask, I'm happy for pointers to somewhere else (Server Fault SE forum?).

See this, pretty much what you want:
http://stackoverflow.com/questions/3097589/getting-my-public-ip-via-api

@Devrope This looks promising, but I can't try right now. Thanks a lot!

You could use Dyndns Service like noip.com (free for basic service) and do the publishing of the new IP within the FritzBox. On the Arduino use just the hostname you specify at the dyndns service.

You can write a program that updates its own external IP every couple of minutes/hours, or when it doesn't get a response from another Yún/PC/server.
You can use this link (or find another site of the web that gives you your external IP address): http://www.realip.info/api/p/realip.php
This link has a beautifully formatted information that you can easily extract. I have a similar solution on one of my servers that have a dynamic IP...


text:
trying to delay between sequences
I am trying to build a set of four stars using an Arduino, potentiometer and a four channel relay to control how fast it speeds across the stars. My question is how can I delay the process, say for 20 or 30 seconds before it starts again?

Use Delay(  ).
Or this code
long previousMillis;

void setup(){
  previousMillis = millis();//in void setup
  bool lS=LOW;//in void setup
}

void loop(){
  long currentMillis= millis();//in void loop

  if(currentMillis-previousMillis>=20000){
     if (lS==LOW){
       digitalWrite(pinNo,HIGH);
       lS=HIGH;
     }
     else
     {
       digitalWrite(pinNo,LOW);
       lS=LOW;
     }
     previousMillis= millis();
  }
  delay(1);
}

While this does not serve your purpose, it shows you an how to switch on and off and LED after every 20 sec without keeping the Arduino idle for 20 sec.You could improve on it and make your own code.

Thanks FuaZe , for the edit.It looks a lot more easy to understand now , though the whole code is exactly the same to the Arduino.

If you want to just provide a delay use this function
delay(ms) -> where the argument is an integer value that represents the time in milliseconds.

For example, 1s = 1000ms
If you wanna stop everything and wait 1s, just use like that:
delay(1000);

Note that the atmega controller will stop everything it is doing and wait the amount of time. If you need to count or wait for something while other things are occurring, use timer interrupts. So the counting process is done in background and your main loop continues to do its jobs.

delay():
delay(20000); // wait for 20 seconds


text:
Adafruit Music Maker Shield - Retrieve song names from SD Card
I am currently working on a project that plays music for you. My question for this thread is, is it possible to retrieve the names of the songs within the micro SD card that is inserted into the shield?
Currently I am renaming the song files to track001, track002, track003, etc. As can be seen in the following code:
const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

That is how am I currently playing music with this shield. I am not too happy with this as I would like to be able to insert different micro SD cards into the shield without having to rename them to track00X or without having to change the code every time to match the song names.
So, is it possible to code it to retrieve the song names from the SD card instead of having to specify their name in the code?
Below you can see my full code:
#include <SPI.h>
#include <Adafruit_VS1053.h>
#include <SD.h>

#define BREAKOUT_RESET  9      // VS1053 reset pin (output)
#define BREAKOUT_CS     10     // VS1053 chip select pin (output)
#define BREAKOUT_DCS    8      // VS1053 Data/command select pin (output)

#define SHIELD_CS     7      // VS1053 chip select pin (output)
#define SHIELD_DCS    6      // VS1053 Data/command select pin (output)

#define CARDCS 4     // Card chip select pin
#define DREQ 3       // VS1053 Data request, ideally an Interrupt pin

Adafruit_VS1053_FilePlayer musicPlayer = Adafruit_VS1053_FilePlayer(SHIELD_CS, SHIELD_DCS, DREQ, CARDCS);

int volume = 20;
const int arraySize = 5;
char songs[arraySize][15] =
{
  {"track001.mp3"},
  {"track002.mp3"},
  {"track003.mp3"},
  {"track004.mp3"},
  {"track005.mp3"}
};

int songNumber = 0;

void setup()
{
  Serial.begin(9600);
  musicPlayer.begin();
  SD.begin(CARDCS);
  musicPlayer.setVolume(volume, volume);
  musicPlayer.useInterrupt(VS1053_FILEPLAYER_PIN_INT);
}

void loop()
{
  // Lower Volume
  if (musicPlayer.GPIO_digitalRead(7) == HIGH)
  {
    if (volume < 70)
    {
      volume = volume + 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Increase Volume
  if (musicPlayer.GPIO_digitalRead(6) == HIGH)
  {
    if (volume > 0)
    {
      volume = volume - 1;
      musicPlayer.setVolume(volume, volume);
      delay(50);
    }
  }

  // Start Music Player
  if (musicPlayer.GPIO_digitalRead(5) == HIGH)
  {
    if (! musicPlayer.playingMusic)
    {
      musicPlayer.startPlayingFile(songs[songNumber]);
    }
  }

  // Pause / Resume
  if (musicPlayer.GPIO_digitalRead(4) == HIGH)
  {
    if (! musicPlayer.paused())
    {
      musicPlayer.pausePlaying(true);
    }
    else
    {
      musicPlayer.pausePlaying(false);
    }
    delay(500);
  }

  // Prev Song
  if (musicPlayer.GPIO_digitalRead(3) == HIGH)
  {
    if (songNumber - 1 >= 0)
    {
      songNumber = songNumber - 1;
    }
    else
    {
      songNumber = arraySize - 1;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);

    delay(500);
  }

  // Next Song
  if (musicPlayer.GPIO_digitalRead(2) == HIGH)
  {
    if (songNumber + 1 < arraySize)
    {
      songNumber = songNumber + 1;
    }
    else
    {
      songNumber = 0;
    }
    Serial.println(songNumber);
    musicPlayer.startPlayingFile(songs[songNumber]);
    delay(500);
  }
}

If this is possible and someone reading this knows how to do so, I would truly appreciate it if you explained it to me and even provided an example or even edit my own code if you want. Thank you! :)

The adafruit library was is similar to the prior SFEMP3shield library (disclosure I am the main author of that). That said either library can work on either Adafruit or SFE shield or breakout board. AdaFruit's library is cleaner re-write. But in doing so it is minimal in its functions. The SFE library demonstrates many more features of the VS1053 chip.
That said; the ./Example/fileplayer.ino does exactly what you are asking. The directory command lists out the files with an enumerating number. Entering 0[number] plays that file. This is how I broke away from "track###.mp3", without having to implement a command prompt parser. And it also allows other file formats.
The bulk of this feature is in the LOOP() and not in the constrained to the library. So one can cut and paste it into a sketch using the Adafruit library in place of the SFEMP3 or any sketch with an SdCard. That said it would actually be easier to replace the play file calls and include in the FilePlayer.ino example. Or just use it straight up.
The SFEmp3 library is bit overwhelming because it supports so many features of the VS1053. And uses a different SdCard library, which is more upto date than the IDE's SD". While the Adafruit library is a very nice re-write and cleans much hte confusing #define's making it much easier code to read, it is not as feature rich. But most feature beyond play and stop are not really needed.
Good luck.


text:
I am looking for the source and/or proper definition for the int() function
I am looking for the source and/or proper definition for the int() function.
I have searched through the source in Arduino.app, without much success.
The reference gives a terse explanation
int(x)
 x: a value of any type
 Converts a value to the int data type

Passing 1, '1' or 49 returns the int 1. I haven't tested other types.
This seems to be an Arduino specific function - it doesn't seem to be in any c/c++ library.

int(x) is not a function but another way to perform an explicit cast of x to an int. It is part of the C++ language itself, that is why you could not find it in a library.
This is not Arduino-specific.
In C and C++ you can cast a value to an int by doing this:
int y = (int) x;

C++ has extended this notation by allowing to do it this way, which is equivalent:
int y = int(x);

You can find this in more details in C++ language reference.

to clear things i think add long x; above int y = int(x); in my opinion this would be better?

Thanks. I could not find this in any of my (admittedly old) c++ books, or in Xcode documentation.


text:
NodeMCU Light Sensor
I'm using a -12E with three light sensors and a sketch I've successfully used with an Uno.  I cannot get the -12E to print anything but 0 or 1023 for a light level (0 when I connect the grounds, 1023 without grounds).
I've successfully printed from a single light sensor but now I'd like to try three.
I'm curious to know what I'm missing.  Any guidance would be appreciated.
Code is as follows:
const int photocellPin_0 = 16; // D0
const int photocellPin_1 = 5; // D1
const int photocellPin_2 = 4; // D2
int photocellReading_0;
int photocellReading_1;
int photocellReading_2;

void setup() {
  delay(4900);
  Serial.begin(115200);
  Serial.println("Startup");
  delay(100);
  pinMode(photocellPin_0, INPUT);
  pinMode(photocellPin_1, INPUT);
  pinMode(photocellPin_2, INPUT);
}

void loop() {
  delay(1000);
  photocellReading_0 = analogRead(photocellPin_0);
  photocellReading_1 = analogRead(photocellPin_1);
  photocellReading_2 = analogRead(photocellPin_2);
  Serial.println("-----NEW ON READING-----");
  Serial.print("Photo Sensor #1 = ");
  Serial.println(photocellReading_0); // the raw analog reading
  Serial.print("Photo Sensor #2 = ");
  Serial.println(photocellReading_1);
  Serial.print("Photo Sensor #3 = ");
  Serial.println(photocellReading_2);
  delay(5000);
}

This is based on an adafruit sketch I pulled off of some website (modified for three photo sensors) and I'd credit it if I could recall exactly where I got it from.

you can only use analogRead on pin A0 on the ESP8266. you can multiplex or even use a relay to switch out sensors, or use a cheap and precise I2C ADC, like the 16-bit ads1115 ($2.5), which gives you four hi-res analog inputs. you could also use a cheap pro mini or nano to expand IO, but they don't have the best ADCs...

The ESP8266 ESP-12E has only one analog input, that is A0 (which tolerates a range 0-1 volt).
digitalRead() statements are not appropriate for a photocell within a potential divider since you will simply get a boolean result 0 or 1 from the connected pin.
You can read one photocell connected on A0 by analogRead( A0 ) assuming it is so connected within a potential divider that a maximum of 1 volt is presented to pin A0.
The Arduino Uno by contrast has 6 Analog inputs which tolerate up to 5 volts