text:
Shield:FAIL problem in ESP8266-01 with Arduino UNO
I have been working on a Security System project wherein I should get an email if the PIR sensor detects any human presence.
I have used an Arduino UNO, ESP8266-01 WiFi module and a PIR sensor.
Power supply:
Arduino is powered through the USB connection of desktop and ESP8266-01 is powered through the 3.3V pin of Arduino UNO and I have not faced any problem with that 3.3V connection of Arduino.
The connection between Arduino UNO and ESP8266-01 are as follows:
Arduino UNO-ESP8266-01
Rx  -   Rx
Tx  -   Tx
3.3V - CH_PD & VCC
GND - GND
GPIO0 and GPIO2 left open.
After successfully uploading the 'BareMinimum' code as found in 'File>Examples>Basics' of Arduino IDE, the ESP8266 is able to communicate correctly i.e. connecting to a wifi network or serving as an access point via
SERIAL MONITOR.The ESP8266-01 displays '0018000902-AI03' as the firware version when I type AT+GMR in the serial monitor of Arduino IDE v1.6.8
Then I created an account on https://temboo.com/ and used the 'SendEmail' choreo as found under 'Google>Gmail>SendEmail'.
I selected the 'Arduino' option in one tab and 'Arduino Wifi' option in another tab.I then entered the required details including the 'App specific password' and I was able to successfully run the choreo.
Problem:
I was able to successfully upload the code  to my Arduino UNO that was generated by Temboo.
But after uploading the code, when I'm opening my SERIAL MONITOR window from Arduino IDE a message "Shield:FAIL" is being displayed.
I'm not able to communicate with the ESP8266 any further.
But if I upload the BareMinimum code again, then ESP8266 works normally.
After connecting Rx-Tx and Tx-Rx of Arduino UNO-ESP8266-01, the serial monitor still displays 'Shield:FAIL'.
I'm a newbie and dont know much about the programming of Arduino though some basics of C are clear.Please if anyone can help me with this, I would be very grateful.
The code is as below:
#include <SPI.h>
#include <WiFi.h>
#include <WiFiClient.h>
#include <Temboo.h>
#include "TembooAccount.h" // Contains Temboo account information

WiFiClient client;

// The number of times to trigger the action if the condition is met
// We limit this so you won't use all of your Temboo calls while testing
int maxCalls = 10;

// The number of times this Choreo has been run so far in this sketch
int calls = 0;

int inputPin = A0;

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

  // For debugging, wait until the serial console is connected
  delay(4000);
  while(!Serial);

  int wifiStatus = WL_IDLE_STATUS;

  // Determine if the WiFi Shield is present
  Serial.print("\n\nShield:");
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("FAIL");

    // If there's no WiFi shield, stop here
    while(true);
  }

  Serial.println("OK");

  // Try to connect to the local WiFi network
  while(wifiStatus != WL_CONNECTED) {
    Serial.print("WiFi:");
    wifiStatus = WiFi.begin(WIFI_SSID, WPA_PASSWORD);

    if (wifiStatus == WL_CONNECTED) {
      Serial.println("OK");
    } else {
      Serial.println("FAIL");
    }
    delay(5000);
  }

  // Initialize pins
  pinMode(inputPin, INPUT);

  Serial.println("Setup complete.\n");
}

void loop() {
  int sensorValue = analogRead(inputPin);
  Serial.println("Sensor: " + String(sensorValue));

  if (sensorValue >= 2) {
    if (calls < maxCalls) {
      Serial.println("\nTriggered! Calling SendEmail Choreo...");
      runSendEmail(sensorValue);
      calls++;
    } else {
      Serial.println("\nTriggered! Skipping to save Temboo calls. Adjust      maxCalls as required.");
    }
  }
  delay(250);
}

void runSendEmail(int sensorValue) {
  TembooChoreo SendEmailChoreo(client);

  // Set Temboo account credentials
  SendEmailChoreo.setAccountName(TEMBOO_ACCOUNT);
  SendEmailChoreo.setAppKeyName(TEMBOO_APP_KEY_NAME);
  SendEmailChoreo.setAppKey(TEMBOO_APP_KEY);

  // Set profile to use for execution
  SendEmailChoreo.setProfile("JigarFaria");
  // Identify the Choreo to run
  SendEmailChoreo.setChoreo("/Library/Google/Gmail/SendEmail");

  // Run the Choreo
  unsigned int returnCode = SendEmailChoreo.run();

  // Read and print the error message
  while (SendEmailChoreo.available()) {
    char c = SendEmailChoreo.read();
    Serial.print(c);
  }
Serial.println();
  SendEmailChoreo.close();
}

Before taking a look at the code, I see 2 major issues in your circuit. First, Arduino 3.3V supply pin won't be enough for the current required by ESP8266 for operations. Second, you should not directly connect Arduino RX/TX pins to ESP8266 RX/TX pins, you need a level adapter, otherwise you may just kill your ESP8266.

That code is for the Arduino WiFi shield, not the ESP8266.

@jfpoilpret What is a level adapter?

@Majenko Is there any way I can make the code work for esp8266 as I don't know much about programming?

Get the right library for your WiFi board. Examine the examples. Integrate your existing code with a suitable example.

Or: get a proper WIFi shield.

A level adapter (aka logical level converter) is a small circuit that helps you connect 2 digital pins that don't work at the voltage: 3.3V for ESP8266, 5V for Arduino. In your circuit, this is needed for TX and RX. Here is an example of such a circuit: https://www.sparkfun.com/products/12009

Sorry but I'm not sure if you change this  "wifiStatus = WiFi.begin(WIFI_SSID, WPA_PASSWORD);" with your own SSID and password?

You seem to have the ESP connected via serial, but aren't sending it anything.
The Rx of the ESP needs to be connected to the Tx of the Arduino (via a logic level shifter) and the Tx of the ESP needs to be connected to the Rx of the Arduino.
Do you know with a proper email sending library you could use any email server, not some service that you may have to pay for?
The ESP8366 is a much more capable device than the Arduino (IMO).  I suspect that you could directly connect your sensor to it, and program it (in Arduino C/C++) through the Arduino IDE and it would be much less hassle.
I think the problem with your code is that you haven't initialised the Wifi object, the first time you call it is to ask the status.  However I don't think you need this code because its not talking to the ESP8266 and you should be sending the data via the serial connection.

Both @CodeGorilla and @Majenko make valid points.
The shield esp will talk with the uno through Serial and your esp8266 has the AT firmware on it.
The BareMinimum reads input from serial and prints what the esp is sending .
the code you posted has code meant for the Uno and code meant for the shield esp.
That wont work.
Your should use the arduino library for esp8266 (https://github.com/esp8266/Arduino,) make a suitable code for it , connect your sensor to the shield and forget the uno.


text:
Forensic security of Arduino (SRAM)
Pardon the double post, but I'm not getting much traction with this question over at arduino.cc so I'm looking for answers here now.
Original post: http://forum.arduino.cc/index.php?topic=391698.0

I get the idea of uploading a "stop" sketch for the purpose of
  overriding a previously uploaded program in Flash memory space.
Then of course we have EEPROM for "long-term" storage.
However, let's say an Arduino: Read user input as secret key and store
  in memory (SRAM) Performed a signing operation with secret key
  Subsequently powered off
We know that computers introduce a wide range of complications to
  security because data can still be recovered, even after being erased
  or overwritten in some cases, variables stored in memory float around
  (unless pinned for decryption in SecureString contexts, etc.), etc.
To establish context for the following questions, let's [overly]
  simplify the attack vector in saying this would be a scenario where an
  Arduino used in a security application is physically disconnected,
  stolen, and then powered on sometime later.
Question 1: Obviously we're not talking about storing keys on disk
  necessarily (i.e. EEPROM). How likely (or difficult) would it be to
  analyze SRAM with the intent to recover keys that may have been
  previously stored in memory?
Question 2: Similarly, let's say sensitive information was in fact
  stored in EEPROM.  Does the same hold true of data previously stored
  in EEPROM that has since been overwritten with new (i.e. zero) data?

Any help would be greatly appreciated. Thanks!

As the others already said, if it is in RAM as soon as you power it off your key is gone. If you want to be really safe, overwrite the key as soon as you stop using it. If you store it in EEPROM, theoretically it is recoverable, but practically it isn't (it would require the "attacker" to tear apart the uC case, estract the silicon die, know where are the eeprom cells and read it with costy  equipment. But before doing this, probably they already guessed your password (or brute-forced it)

RAM can be retained for a while under certain circumstances. Read e.g. this article http://wp.josh.com/2014/03/03/the-mystery-of-the-zombie-ram/

Mystery of the zombie RAM, nice. I just read about this recently in an electronics book that LEDs not only give off light, but can produce a tiny current if light is shown onto it, "enough to sustain RAM indefinitely." So don't forget to bring a flashlight along with your liquid nitrogen (RE: Nick Gammon) :)

RAM memory looses its contents when it's powered off. However, this
natural erasure process is not instantaneous: it can take several
seconds, or even minutes. It has been demonstrated that cooling down a
memory chip can extend its data retention time to hours, which enables
a type of attack known as cold boot
attack.
This type of attack has been studied mostly on DRAM computer modules.
The Arduino memory, however, is based on SRAM, which is physically very
different from DRAM (a transistor feedback loop vs. a capacitor). There
seems to be very little research on cold boot attacks against SRAM. I
found nonetheless a technical report from the computer laboratory of the
University of Cambridge: Low temperature data remanence in static
RAM, by Sergei
Skorobogatov. Quoting from the conclusion:

Contrary to the established wisdom, there are several chips that
  retain data for dangerous periods of time at temperatures above −20°C.
  The temperature at which 80% of the data are retained for one minute
  varies widely between devices. Some require cooling to at least −50°C,
  while others retain data for this period at room temperature.
  Retention times can be significantly reduced by shorting VCC to ground
  rather than by leaving it floating.

From this perspective I would say that, although the attack seems non
obvious, your secret key is not completely safe even in SRAM. Since the
data retention time varies widely between devices, it could be worth
testing on your Arduino. If possible, I would suggest you overwrite the
key after the signing operation.

Update: I did a quick test on my Arduino Uno, at room temperature,
by just unplugging and plugging back the board. Here is my test code:
// This memory buffer will not be zeroed at startup by the C runtime.
uint8_t __attribute__((section(".noinit"))) buffer[1024];

void setup()
{
    Serial.begin(9600);
    Serial.println(F("Program started."));
}

void loop()
{
    switch (Serial.read()) {
        case 'i':  // Initialize the buffer with pseudo-random bits.
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++)
                buffer[i] = rand();
            Serial.println(F("Buffer initialized."));
            break;
        case 'f':  // Report number of flipped bits.
            int count = 0;
            srand(42);
            for (size_t i = 0; i < sizeof buffer; i++) {
                uint8_t mask = buffer[i] ^ rand();
                while (mask) {
                    count += mask & 1;
                    mask >>= 1;
                }
            }
            Serial.print(F("Flipped bits: "));
            Serial.print(count);
            Serial.print(F(" / "));
            Serial.println(8 * sizeof buffer);
    }
}

And this is the output, with my comments on the right:
Program started.            ← fresh boot
Buffer initialized.         ← pressed 'i'
Program started.            ← pressed the reset button
Flipped bits: 0 / 8192      ← pressed 'f'
Program started.            ← unplugged and plugged back
Flipped bits: 4166 / 8192   ← pressed 'f'

It appears the RAM is preserved across a warm reboot (pressing the reset
button), but it is completely lost after a power cycle: half the bits
flipped is a total loss of information. I tried to do this as fast as I
could, which is slightly less than one second. It would seem the SRAM in
the ATmega chips decays pretty fast, at least at room temperature.

Update 2: I found an enlightening story about an unpowered AVR
keeping data in RAM for more than 10 minutes, but only on mornings:
The mystery of the Zombie
RAM.

Sounds good, but if I was going to burst into a room with liquid nitrogen to cool down the chip, I would arrive a minute earlier, and make sure that the chip wasn't powered down in the first place.

+1 for conducting your own separate tests to validate existing research :)

Uploading a new sketch using the IDE does "page erases" which means that a small sketch will not completely replace a larger one. However using a ICSP programmer starts with a complete flash erase, so that would be more secure. Or you could probably (and it would be better to) upload a new sketch containing mostly random data (eg. a large array in PROGMEM).
Rewriting EEPROM should be pretty secure, especially if you replace the EEPROM with random data, and preferably do it a number of times.
As for SRAM, I would be surprised if you could recover much after a power-off. If the attacker manages to keep the power on that would be different. If possible, write over sensitive data with random bytes as soon as you don't need it any more.
If the data has to stay in RAM, I could envisage a scenario where if I got access to the processor (still powered on) I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.
I think the AVR processors at least would be comparatively safe. After all they don't have disks, virtual memory, or fancy remapping of sectors like a USB stick might.

Read user input as secret key and store in memory (SRAM) Performed a signing operation with secret key. Subsequently powered off.

Sounds pretty safe once you specify "powered off".

https://xkcd.com/538/

“I would upload a small sketch which would simply dump RAM to (say) the serial port a byte at a time, to avoid needing much RAM to do the dumping.” I bet you would write the program in such a way that it uses zero RAM.

Yes, quite possibly. :) It might depend on how much money changed hands. :P

+1 for covering EEPROM details and pointing out complete flash erase as added safety measure. Thanks!

source: Stack Exchange

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

sort: votes


text:
Run 'Serial.begin(9600)' before loop()
My sketch looks somehow like this:
ClassA classA;

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

    classA = ClassA();
    Serial.println("Bar")

    ...
}

void loop() {
    classA.functionFoo();
}

The constructor of ClassA however calls some internal methods that perform a Serial.println().
My problem is, that the first (implicit) call of the constructor of ClassA comes in the first line of the sketch with
ClassA classA;

This is before the Serial interface has been initialized (with Serial.begin(9600)). Therefore the Serial.monitor cannot interpret the first messages coming from the serial interface.
How can I either suppress any Serial.writes before the setup function or otherwise make sure that the Serial interface is initialized before the setup function?

Make classA a pointer and create the new object with new.

You can make your current object a pointer so it isn't instantiated:
ClassA *classA;

Then create an object with new:
classA = new ClassA();

The constructor is then only called when the object is made.
Note that you will have to change your accessors to ->:
classA->myFunction();

Adding the classA = new ClassA(); in the setup() function just after calling  Serial.begin(9600); will be a quite good solution, but as for the use of bool bSerialReady solution, the rework will be important (replacing classA.<function()> by classA-><function()>.

In order to be sure that your classA object doesn't use the Serial.println() function before the baudrate is defined, it is necessary to add functions in your class ClassA and to inform from setup() your classA object.
The simplest way is to add:

a boolean bool bSerialReadyto keep the status of the Serial object,
in all ClassA constructors, initialize that bSerialReady = false;,
add a function void SetSerialReady() to switch the status bSerialReady = true;. The function should be called in the setup()function just after Serial.begin(9600);,
and in all functions of ClassA, add a if-condition if (bSerialReady) before calling the Serial.println().

Your class ClassA will become:
class ClassA
{
private:
    bool bSerialReady;
public:
    ClassA() {
        // ...
        // Initialize bSerialReady
        bSerialReady = false;
    };
    void SetSerialReady() {
        bSerialReady = true;
    };
};

Your setup() function becomes:
void setup() {
    Serial.begin(9600);
    classA.SetSerialReady();
    ...
}

And in functions of ClassA, it looks like:
if (bSerialReady) {
    Serial.println("Bar");
}

Plus, you'll probably want some logic to store and re-issue the messages that would have been issued before bSerialReady became set.

not a bad solution, however, it is only about debug messages. I wouldn't want to change my code too much for them...

@speendo, could you provide an example of your class ClassA source code using the Serial.println() function to display debug message ? Did you have used the same template in the rest of the source code ?

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


text:
Shrink array to save memory
In my project I need three arrays to store data inside.
I define a maximal number of elements as a macro variable. However, at a certain point in the setup function, the program could determine, that the arrays would actually store a smaller number of elements. In other words, it is possible (and even likely) that there is more memory reserved for the arrays than actually necessary.
As I think that memory might be a critical factor on a micro controller like the Arduino, I would like to set the excess memory free.
Is there a way to dynamically resize and shrink the arrays at runtime?
Something like this (pseudocode)
#define maxSize 50
int theArray[maxSize];

int actualSize = getActualArraySize();
// sets actualSize to a value <= 50, let's assume actualSize = 20
shrinkArray(theArray, actualSize);
// shrinkArray doesn't exist :) I need something like that.

Arrays can not be resized, but if you know the required size of the array before any data is written into it, you can declare theArray as a pointer instead of array: int *theArray; and then later allocate the required amount of memory: theArray = malloc(requredArrayLength * sizeof(int)); - Would that solve your problem?

However, if it is not the case that you somewhere else use an inversely proportional amount of memory to the size of these arrays, it might not be necessary to save bytes here. E.g. if you conditionally reduce an array of ints from 50 to 30 elements, you will save 40 bytes of memory only if the condition is met and you can not rely on this memory always being available for other purposes.

thank you jarnbjo! malloc() could be a way to go. Actually it would be three arrays reduced from 50 to 30 elements. So 40 bytes * 3 = 120 bytes. I don't know enough about memory allocation on a micro controller but I thought it might be significant? If you could share your opinion and some more information about the "malloc solution" this would help me a lot!

... to clarify: in my project I need to match a user input against a password. The input is stored (and translated) in the arrays. The password is stored in the eeprom and can only be changed in the setup function. But at compile time I don't know the exact length of the password. However, it is very likely that the password is much shorter than the maximal possible length.

I am not sure if you understood what I wrote in my second comment. What are you intending to use the 120 bytes for, which you may save, as long as you won't be sure if the memory is actually available. Do you have any other parts of your code, which will need more memory if a short password is configured? If not, spare yourself the effort and forget about those 120 bytes, since you won't have any situation, in which you can use them.

In fact I really didn't (and maybe still don't) understand what you wrote in this comment. If I get it right, you state that if there is the possibility that the arrays reach the length of maxSize, I might just as well allocate the memory fitting to maxSize. My idea is that the mc might run faster if it has more memory available - therefore the arrays shouldn't use more memory than necessary. However, my view might come from my lack of knowledge about the function of an mc. On a desktop computer, saving RAM would be advantageous, but is this also true for an mc?

and to answer your question: no, if the password is short there are no other parts of the code that need more memory.

The amount of memory available has no bearing on the speed the MCU runs at all. You are thinking of a phenomenon on PCs where when there is not enough memory available some memory is "swapped" to hard disk, which slows it down. Since there is no hard disk, no swapping, no memory management, none of that applies. So speed can never be affected by lack of RAM in the way you are supposing.

Neither a microcontroller, nor a desktop computer will magically run faster if you use less RAM. On a desktop computer, your software is usually running in a multitasking environment and it might be advantageous to save RAM to leave resources for other processes, but on the microcontroller you are 'on your own' and can manage the resources as you need them and not worry about other processes.

I see. In this case the only restriction is that all variables I define will fit inside the SRAM - no need to reduce memory usage as long as this condition holds... Thank you. Would anybody want to formulate an answer so that I can accept it?

Do the elements of the array really need to be ints? If the values you store in it are between 0 and 255, you could use a array of bytes, halving the amount of RAM required.

You could also consider hashing the password into a much smaller value, if memory consumption is a problem.

As a matter of fact, not all arrays are ints - this was just for illustration.

This is a common question when designing software. The simple answer (rule of thumb) is statically allocate the maximum size of the array. In this case the maximum size of the arrays. This simple rule will keep you out of trouble and make testing etc much simpler.
Using dynamic allocation (adjusting array size etc) especially for small scale embedded systems such as the Arduino opens a "can of worms" with possible memory (heap) fragmentation and hidden concurrency and performance issues.
If the required maximum size of the array is 32 elements the application has to allow that and there is no memory to save. Statically allocating will make the sketch simpler and easier to test.
Cheers!

To elaborate a little, while you CAN allocate the arrays smaller, there's really no point leaving some memory free: the program has to work even in the worst case, with the arrays as big as they'll ever be, and it won't work any better if you sometimes have some memory left over.


text:
I need help purchasing materials for a arduino fpv quadcopter
I am an absolute noob in FPV quadcopters and quads in general. My aim is to create a simple quadcopter with a live video transmission. Based on my research I need:

4 rotors
4 Props
4 Electronic Speed Controllers
Camera Kit
Lipo battery
Power Distribution Board
Accel. and Gyro
Arduino UNO
Receiver Kit

Am I missing anything? and how would you wire it?

I'm sorry but I can't see what this has to do with Arduino's so I have voted to close it.  To be honest if you have to ask what parts you need then maybe you should consider if it would be safe for you to build one.  Maybe you should look at kits to get more familiar with the subject.

Transmitter, battery charger, display, a smaller arduino that the UNO (e.g. Pro Mini), wire-connectors (especially for connecting to the battery).

This is not a practical approach.  If you want to experiment with applications such as FPV, you should be using on off-the-shelf flight stabilization computer and radio link, the engineering of both of which has moved far beyond Arduino experiments.  If your goal is instead to build the flight computer, for safety reasons you should be experimenting on a platform far smaller and lighter than one that can lift an Uno.  There was a point a few years ago when Arduino based flight computers almost made sense, but today they are so crude and limited compared to the options actually in use.

I wanted to create one from scratch

These are my suggestions.
You don't need the following:

Accel. (a gyro is enough)

You are missing the following:

You need 2 sets of receiver/transmitter. One of them is for the controller, the other one, for video.
You also need a screen or PFV goggles to display the received video.
You need a frame.

Here is my suggestions for a couple of your parts.

Buy a DIY Flame Wheel Kit. They should include : motors, ESCs, props and the frame itself.
Get a GoPro Hero (original) for your camera. They're cheap and should give you good enough quality for a DIY quadcopter build.
Use and Arduino Pro Mini, they are smaller. Note that you need an external FTDI programmer for it.
Use at least a 3S lipo.

A MEMS gyro is not enough. They drift over time (derivative), so you need an accelerometer, to know which way is down.

@Gerben - actually that is untrue.  The goal of the gyro is not to consistently orient the vehicle, but to slow its uncommanded rotation (or in this case multi-axis tumbling) to the point where a human pilot can achieve desired oritentation by command inputs based on visual observation.  Systems which also include accelerometers are more friendly to beginner pilots as they can also be self orienting, but that is only a feature that became common in the past few years.

I am using a display instead of goggles. The receiver kit comes with a transmitter and remote controller (a.k.a transmitter). The frame I was planning to use wood.


text:
String use in arduino IDE (this question for understanding)
I'm using arduino several month now, And i don't understand when i can use the arduino object of String. I'll explain, I read a lot and the it's look like that this object is a good way to read/write and use strings, But everywhere they say that this object take a lot of RAM. So i made some project, And almost in all of them the String object not work as i expected. When i check the RAM in my projects i see that when my usage of RAM is greater then 65% the string object start to do problems. Because of this i stop use the string object and use only char arrays.
So my question is:

How can i know when i can use String from the beginning?
there is a way to change from char array to string or vase versa easily (i know this is completely different logic)?
How can i avoid the memory problems with the String object?

All this questions come from that the String object is very effective and easy to use and i want to use it, But i'm fear from RAM problems so i'm not using it.
Thank you very much for reading all this, Hope you can help me!

I recommend looking at thsi question: http://arduino.stackexchange.com/questions/19294/what-is-the-memory-expense-of-creating-a-string-from-a-char-array and this answer http://arduino.stackexchange.com/a/19295/84 with which I fully agree: DO NOT use String. The linked answer provides all (good) reasons for that.

@jfpoilpret this is not a duplicate, I'm trying to understand how can i use string sometime, in all my project i'm using char array and it's very sad there is such a good object for this and i don't know if i can use it at all.

For me the answer to your question is the answer to the above question, then I don't see the point having the same answer here. If you read the answer I linked to, then you shall understand that String usage is generally bad, except if you do simplistic projects and only for fun. I NEVER use String (and never will).

I read the answer, And this is a very good one, thank you for that. According to that, i now sure that is no usage with this object.

I've added an answer to the cited question, which will be relevant here as well, with the understanding that Uno's memory size is borderline to use String objects any more than trivially.

String objects are simple to use. There is a trade-off for simplicity. Strings work by using dynamic memory allocation. Something like this for example:
String foo;
...
foo += 'a';

By adding one character to a string the class has to allocate new memory for the slightly longer string. If you keep doing this you get memory fragmentation.
You are probably better off deciding what your maximum size string is and making that a static array of characters.

So should I use the String objects?
For occasional use they are fine (for example, holding the name of something). They tend to fall down once you start with a small String and keep adding to it, because the code has to dynamically allocate memory, allocating (say) 5 bytes, then 6 bytes, then 7 bytes, and in the process freeing up the original 5 bytes, then 6 bytes and so on. This allocating/freeing process can leave holes in the "heap" causing a thing known as memory fragmentation.
Done to excess you can run out of memory. That is, you might need 100 bytes but have 10 lots of 10 bytes free, with stuff in-between that isn't free.
You don't have lots of memory to start with, so it is probably better, faster and more efficient to decide the largest amount you need for some string, and just make that a character array.

so, you said not use the String object?

See amended answer.


text:
Arduino ModBus RTU master communication with Power Meter problem
i have an arduino UNO with RS485 module.
I have made this connection:
And i have an problem with communication of this module with power meter
"InePro PRO-1Mod"
(datasheet) over ModBus protocol. I want for example read an L1 Voltage value, which i know from the manual (page 24 & 25) that this value is stored in "read holding register" with adrress 5002. I should communicate with these paramaters:

Baud rate 9600
8 data bits
even parity
1 stop bit

There is also mention about 120 ohms resistor placed by the power meter (but it is 15cm long cable, and even with the resistor there is no change)
I have tried using many of ModBus libraries and for now none of them doesn't work. I have tried "Modbus-Master-Slave-for-Arduino" , "ModbusMaster and now at last i am using this "simple-modbus".
I think that with that simple modbus library i went far as i can, but it is still doesn't working, but i see on the display of power meter that there is some try to communication (i see a black dot which shows modbus communication)
but i don't receive any useful data.
I am using this code:
    #include <SimpleModbusMaster.h>
#include <AltSoftSerial.h>

#define TxEnablePin 2                    // RS485 modbus direction control pin:
#define baud 9600                           // modbus port speed:
#define timeout 1000                        // modbus timeout in mSec:
#define polling 500                         // modbus scan rate in mSec:
#define retry_count 15

#define TOTAL_NO_OF_REGISTERS 1// number of registers to poll for:

AltSoftSerial altSerial;

enum
{
 PACKET1,
 TOTAL_NO_OF_PACKETS                       // leave this last entry
};

Packet packets[TOTAL_NO_OF_PACKETS];        // array of Packets to be configured

//struct packetPointer packet1 = &packets[PACKET1];
unsigned int regs[TOTAL_NO_OF_REGISTERS];   // master register array
long previousMillis = 0;
long interval = 1200;
unsigned long currentMillis;

void setup() {
 Serial.begin(9600);
 altSerial.begin(9600);
 altSerial.println("Hello World");
 modbus_construct(&packets[PACKET1], 5, READ_HOLDING_REGISTERS, 5000, 2, 0);  //initialize packet
 modbus_configure(&Serial, baud, SERIAL_8E1, timeout, polling, retry_count, TxEnablePin, packets, TOTAL_NO_OF_PACKETS, regs);
}

void loop() {
 modbus_update();

 float Power;
 unsigned long temp = (unsigned long)regs[1] << 16 | regs[0];
 Power = *(float*)&temp;

  currentMillis = millis();
 if (currentMillis - previousMillis >= interval)
 {
   altSerial.print("Exception errors: ");
   altSerial.println(packets[PACKET1].exception_errors);

   altSerial.print("Failed requests: ");
   altSerial.println(packets[PACKET1].failed_requests);

   altSerial.print("Successful requests: ");
   altSerial.println(packets[PACKET1].successful_requests);
   altSerial.print("Low byte: ");
   altSerial.println(regs[0]);
   altSerial.print("High byte: ");
   altSerial.println(regs[1]);
   altSerial.print("Power ");
   altSerial.println(Power);
   altSerial.println("----------");

   previousMillis = currentMillis;
 }

}

And i have got only this output in the pc (its repeating of course):
----------
Exception errors: 0
Failed requests: 5
Successful requests: 0
Low byte: 0
High byte: 260
Power 0.00
----------

Altserial library i am using together with USB2TTL convertor on pins 8 & 9,
to see output.
I should mention that there is only A and B screw terminals on power meter, so i have no option to make common ground connection. I also using an 15cm twisted pair cable UTP.
Can someone help me to make it work ?
I have tried to change adrress of holding register to 0x5000 or 5002, tried changing number of registers.
I have tried to connect rs485 module with USB2TTL to pc and run software called "qModMaster" and it works, but with arduino it doesn't work.
Slave ID (power meter) is 5.
Thank you, for your help.

Can u help me,, i have a same problem. i try to read value from pulse meter autonics and display to serial monitor arduino. my pulse meter setting is : baud rate 9600
address 02 with your code above, can i solve my problem? or any code have to change...
thankyou...

This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. You can also add a bounty to draw more attention to this question once you have enough reputation. - From Review

I don't know which type of "pulse meter autonics" you use but i found manual for these types: MP5S_MP5Y_MP5W_MP5M and in manual they said that they are NOT using PARITY BIT. So you should change "SERIAL_8E1" to "SERIAL_8N1"

I edited my answer, for more help look at it.

My reference is this vidio link. in that video show that pulse meter Mp5Y can communicate with other system (mkrokontroller/arduino) and the measurement result/ PV can display on 7 segmen

I have made it. Now it is working. I only checks A & B cables (tried a new one) and change address of register from 5000 to 0x5000 and now it works. I thought that this library already give 0x before address, because i didn't see it anywhere with 0x before.
An advice for people with the same problems:
Most of the devices which is using RS485 and ModBus protocol (and have an some kind of display) shows an communication (over 485 & modbus) on display by some kind of mark, for example in my case it was an "dot" which blinks when there's an communication. When this mark is shown, it is sign of that the communication settings is right, so data, parity bit, stop bit & baudrate is OK (data has successfully reached the dest. device).
After that, these devices send you an error message back on its line. So if you have problems with getting data, you should send your message (ask) from the arduino to that device, over an Transmit pin from arduino (of course trough an converter, for example max485) and the Receiving pin (side) connect to your PC through again some kind of converter from UART to USB. (Warning: you should have the same ground potential, so wire all grounds together)
Install some software to communication for modBus on PC (i am using this soft: https://www.simplymodbus.ca/ | you can use demo ) After that let arduino sent an message and receive it by PC. (in simplymodbus look at the "response") read that code and look to the manual for the device you using, where there should be an description of error codes, if not look at this doc.: http://www.simplymodbus.ca/exceptions.htm or THIS).After that you will have an better look on what is going on and where there is a problem.

Using the solution i write above, i figured out that there was a problem with "Illegal Data Address", received "02" exception response code.

I'm using a mp5w pulse meter, the settings:

Baud rate : 9600
Address : 02
Parity : none
Stop bit : 1

Modbus memory map table for measurement value /(PV) :

Modebus : 31002
Address  : 03E9
Size    : 5

As i look into the manual, there is NO sign that these pulse meters uses an ModBus protocol, only an RS485. In this manual link on page M-26 (M-27 is last page) so the first before last page. There is this text: "The comunication control ordering of MP5 series is a private protocol (not compatible with other system)" and then the description of this private protocol follows.

Then you can't use this library, it will not work at any settings.

My reference is this vidio link. in that video show that pulse meter Mp5Y can communicate with other system (mkrokontroller/arduino) and the measurement result/ PV can display on 7 segmen.

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


text:
Arduino write to memory and self shut down (over MOSFET) - An idea help
i would like to ask you for help with design of an circuit.
I have and atmega328p, with detection for voltage on its Vin (Vcc).
I have made and voltage divider and its output i connected to Analog Pin. And i would like to, if an voltage decrease under an certain level (4.5V), to shutdown itself (atmega328p).
As i said the voltage detection is no problem (there is an voltage divider), programing it is as well no problem, but i though that i program it like this:

Detect voltage on analog pin A0, if the voltage is less than certain
  level (4.5V), write to memory and send to digital pin 3 an "LOW" (0)
  logical state.

This will turn the mosfet off and the atmega will loose its ground (GND) and its shuts down, but i have there an pull-up resistor which when the atmega shutsdown takes its lead an set Gate at MOSFET to high (transistor will turn on) and atmega turns on, then it shuts down and this will do the infinite cycling until there's no power to turn on atmega.
I want to use an Supercapacitor (2.2F 5.5V) to power it when the main input is lost and to give an atmega a time to write to memory and steadily turns off.
I am adding an schematics to better look at the problem.

I know that there is no crystal and capacitors and the other things to make it reliable and fully functional, but this is not a subject of this question.Its an first sketch, which is not completed.
I know some ICs that can detect Voltage and turn its output to some logical state (1 or 0), like an MAX809 (803 or 810) and so on and of course this is my backup plan, but i want to ask you, if you have any great idea to make this without any special ICs and more easily? I also thought about some OPamp or thyristor maybe, i don't know......
Can you help me with an idea or better with an schematics how to do it ? Thanks.

You should be using a p channel MOSFET and switching the power not the ground. When I get home I'll draw you a schematic

@Majenko Thank you, i appreciate that, but i have already thought about that and i think it will be the same situation but with all logic states reversed. If i think right then at the p channel mosfet, when there is high state on base the fet is OFF and vice versa. So if i during the running of atmega send LOW to base, the transistor is ON a everything is good, but when i want to shutdown atmega, atmega will send HIGH to base, transistor is OFF and the pull up resistor will stick it HIGH (until cap will discharge), but when the power is recovered resistor keeps it HIGH and atmega wont start.

if i use the pull-down instead of pull up, then when there is a power transistor is pulled down by resistor and its ON (good). When i want to turn transistor OFF, atmega will send HIGH to base of transistor and transistor will turn OFF (good), but when atmega dies, there will be no more HIGH at transistor base and the pull down resistor will turn transistor ON, and we have the same cycle as with the current schematics.
Sorry i use BASE, i know that MOSFET has a GATE, not BASE....

The trick is to have the arduino keep the system on, not tell it to turn off.

Just a question: are you using the arduino with a stable voltage reference or with VCC? if you use VCC as reference, and use a voltage divider to detect VCC, you will never see any change...

@frarugi87 yeah i know that, i forgot to mention it. I will be using internal analog reference 1.1V.

You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

simulate this circuit – Schematic created using CircuitLab
In this schematic M1 is normally off.  You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on.  When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.
This arrangement means:

You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
You get a soft-power switch to turn the power on
Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
You are switching VCC, not GND (switching GND can cause all sorts of problems).

thanks, i got it, this works fine but i want to turn on arduino automaticaly (without switch) when the power is recovered. If we use a power supply (instead of battery).
When there is a power cut to the power supply, its all meant to be automatically saved the data to memory (for powering atmega for this time, there is an supercapacitor), power down atmega and when the power is recovered, automatically power up atmega again and read the data and so on .......

Sounds like you want a proper PMIC (or create one with a small MCU).  Maybe thrown in a little 8 pin ATTiny to manage the power...

Personally I usually use a PIC10F200-I/OT in this situation. Really small, really low power, really cheap, really hard to program for with only 256 words of instructions and 16 bytes of RAM. Ideal for something like a simple PMIC though...

i think that i can't avoid it (using PMIC or any other special IC). I thought if it can be possible to create it with simple design, but i am worried that i really need to use special IC to do this thing.

It is perfectly possible to create a circuit to do it, but that circuit would be considerably more complex with the addition of auto power on - and likely cost more than a PMIC or small low-power MCU. That's why PMICs exist - because they're cheaper and more convenient than trying to roll your own circuit.

OK, so i will stay at my backup plan, i will use MAX809 to switch ON/OFF the transistor, but as i look into it, i can use your schematic, that i will connect output of MAX809 to Gate of M1 Transistor. Then i will have the advantages you wrote, but in this situation i have to use MAX810 (which has output inverted compare to 809)

It would be easier to simply to power down the CPU using software once you're ready to shut down:
set_sleep_mode(SLEEP_MODE_PWR_DOWN);
cli();
sleep_enable();
sleep_bod_disable();
sei();
sleep_cpu();

Thank you, i know, but i don't want to sleep it, i want to completely turn off supply.
I know that, you may ask why, but please just accept, that it will have to be like that.

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


text:
Is it possible to measure the velocity of a Unmanned Aerial Vehicle using only accelerometer?
Our project is about dropping a payload from a UAV on the specified area. We are using an accelerometer (connected to the Arduino board) to measure the velocity of the plane (assuming the initial velocity to be zero). Is it possible to accurately measure the velocity of a plane moving in the air for a time t? Will this method be feasible?

Is there a reason why you can't use a GPS system?

Not with any measure of accuracy, no.
You're basically asking about Dead Reckoning which is problematical at best - and when doing it with just a low-grade accelerometer it can't be anything more than a rough "It's moving quick" or "it's moving slower now" accuracy.

I'm a little interrested in this, what happens if we remove the high accuracy contraint, is it possible, with something like an MPU6050, mesure a the velocity to, maybe an accuracy of +- 10km/h?

@DatHa: No; this won't work reliably without a source you can use to fix your position or velocity. An accelerometer can only measure acceleration. Measuring velocity requires continuously integrating the accelerometer over time, but because you can only sample finitely many times per second, you will gradually accrue errors in your estimation until it becomes completely useless.

It's even worse than that: to get position requires double-integrating the velocity over time. It works on paper, but in the real world, physical disturbances and electrical noise soon dominate the sums, rendering them useless very quickly.


text:
How come the console prints error `avrdude: usbdev_open(): did not find any USB device "usb"`?
How come when I try to push a sketch to my Arduino I see this error on the console? The subsequent sketch does not work.

avrdude: usbdev_open(): did not find any USB device "usb"

I've already added myself to the dialout group,

sudo usermod -aG dialout $USER

And, I did that after I confirmed the dialout group owns the device (in my case /dev/ttyACM0:
$ ls /dev/ttyACM0 -l
crw-rw---- 1 root dialout 166, 0 Oct 12 03:15 /dev/ttyACM0

This is because in the IDE I was using

Sketch → Upload Using Programmer [Ctrl + Shift + U]

However, I should have been using

Sketch → Upload [Ctrl + U]

Try "Tools> Port:> then select your board"
Make sure your pc hasn't assigned new com port to the attached usb (Arduino)


text:
Powering an Arduino UNO through 5V
I have a bench supply which I can use to power a breadboard at 5 V. Is it a bad idea to power the the Arduino by going directly to the 5 V pin? It sounds like both this method, and the USB are unregulated, so there would be no difference. Is it safe? Are there any caveats to this?

5V.This pin outputs a regulated 5V from the regulator on the board. The board can be supplied with power either from the DC power jack (7 - 12V), the USB connector (5V), or the VIN pin of the board (7-12V). Supplying voltage via the 5V or 3.3V pins bypasses the regulator, and can damage your board. We don't advise it.

They say they "don't advise it", but why?

Possible duplicate of On the Uno, why does VIN require 7-12 volts and the USB only 5 volts?

They wouldn't advise it because they provide on board regulation. By feeding it directly you're circumventing their own protection. If however, you're providing your own regulated supply there is no reason why you can't supply it directly.
In a perfect environment, USB should already be regulated. However given the cheap imported USB hubs and plug packs that are available on the market, I would certainly argue that a good bench power supply is no problems in this regards.

How precise does the regulation needs to be? What can I figure out the tolerance?


text:
Ideal settings for regulated power using Arduino Uno VIN?
Is there a downside to providing a lot of amps to Arduino UNO's VIN? Is there any advantage to only supplying a limited amount of amps? I have a regulated power supply and I'm curious what I should set it to when going through the 5v port?
Also, should I stick with 5 volts? I've seen some tutorials say if powering the board through VIN it should ideally be much more than that?
Is there a spec sheet of sort that tells you this?

https://www.arduino.cc/en/Main/ArduinoBoardUno Input Voltage (recommended)  7-12V

@Gerben so you can put you 12 V in through the 5 V, VIN pin?

You can put 12V only in the Vin pin. Putting it in the 5v pin will probably make smoke.

Honestly, it doesn't matter how much power (amps) you make available, it will only draw what it needs.
However, there is definitely something to be said for limiting how much power you provide.  If something in your circuit is miswired or otherwise shorts out, limiting the circuit to something reasonable (wisely including a fuse in your design as well) means that you won't have some enormous current suddenly passing through burning stuff out and possibly injuring someone. :)
As far as what to provide in terms of volts and amps, the data sheet for your particular arduino is the place to go.  As long as you are providing that you are in good shape.

From https://www.arduino.cc/en/Reference/Board :

The input voltage to the Arduino board when it's using an external power source (as opposed to 5 volts from the USB connection or other regulated power source). You can supply voltage through this pin, or, if supplying voltage via the power jack, access it through this pin. Note that different boards accept different input voltages ranges, please see the documentation for your board.

For specific values, visit https://www.arduino.cc/en/Main/Products?from=Main.Hardware and select your board, and look down to where it says "Input voltage" - there's a "recommended" and "limit", each being a range. Note that some power sources will fluctuate (e.g. 4 AA batteries are 6 volts, possible slightly higher when brand new, but will drop down if there is a high drain, or as they get used up. 4 AA batteries will not provide 6v for long).
As for current (measured in amps or milliamps), if the power supply cannot supply what is used by the board, it will overheat; if it provides more than is required, then it will work 100% perfectly well (so long as you don't have a short circuit). The current an Arduino on it's own will draw will vary depending on the board, Nick Gammon measured an Arduino Uno Rev 3 board at 50 milliamps, but LEDs will typically draw around 20mA each; motors will draw a lot more. 1000mA = 1 amp, so Nick's Uno would draw 0.050 amps. Power supplies typically say on them how many amps (or in some cases, milliamps) they can (safely) provide.

Right, but is there any danger to supplying to many amps to the arduino if the load demands and it's available will that damage the controller in a fashion that limiting the amps from the power source wouldn't?

As I indicated in my answer, not directly.  There is no risk to your circuit if everything is designed properly and connected properly.  The only risk is if a part fails as a short or something is not correctly wired or something else happens that creates a short circuit to ground.

Also, you don't say how much is the idea to power the board though VIN?

It varies from board to board - that's why I say "for specific values, vist...."


text:
Detect USB activity from a host
I am testing a WinCE device that loses all USB communication infrequently. I need to detect when the USB fails on this device. When it fails, the power is intact at the port, just no data at all on D+ and D- (I verified this with an oscilloscope). This host device is basically a black box to me so I can't do anything to it but check it's state.
My proposed solution:  Use an arduino of some type (preferably an UNO since I have one already) programmed to detect USB activity to let me know when USB is failing on the host device I am testing.
Is this possible? The arduino seems like a good solution for me because I assume it is a USB client, which I need in this scenario.  Any example or pointing me in the right direction would be of great help.  Thanks!

If you choose to use an Uno you probably need to reprogram the ATMega16u2 on the board, that does the usb-to-serial. I think it would be easier to have a arduino in which the main chip support USB, like the Leonardo or Micro. But I haven't done anything with USB myself.

If you modify the firmware of the USB interface chip, implement software USB, or use a native-USB board like the Arduino Leonardo,  it would be fairly trivial to run a time-out timer on USB traffic and thus see if the normally periodic polling of this slave ceases.

Did you manage to figure this out? If so can you please share the code?

If all you are interested in is the voltages on the D+ and D- lines you could wire those direct into two ADC inputs on the Arduino and wire +5V and GND into the +5V and GND pin.  The Arduino can then sample the voltages and compare them to valid or invalid ranges.

This is a great idea.  So glad I asked; I can't believe it didn't even cross my mind.

No, that's really not going to work well.  The USB signalling is outside the bandwidth of the arduino ADC.  You need to look for transitions, not levels.


text:
Software PWM implementation on ATTiny44 screws up timing functions
I've came up with a poor man's implementation of software-based PWM for the ATTINY44 and I'm kinda stuck now. It works but it screws up the timing functions badly (delay, delayMicroseconds) no matter what timer I use for the ISR (timer 1 or 0). The delay in my example is more like 1 second than 100ms. Can somebody point out what I'm doing wrong? :)
uint8_t pwmled[11] = {0};
volatile uint8_t currentStep = 0;
uint8_t p[11] = {PORTA0, PORTA1, PORTA2, PORTA3, PORTA4, PORTA5, PORTA6, PORTA7, PORTB0, PORTB1, PORTB2};

void initTimer1() {
  cli();
  TCCR1B = (1 << WGM12) | (1 << CS10);
  OCR1A = 64;
  TIMSK1 = (1 << OCIE1A);
  sei();
}

ISR(TIM1_COMPA_vect) {
  if (currentStep < 100)
    currentStep += 1;
  else
    currentStep = 0;
  for (uint8_t x = 0; x <= 10; x++)
    (currentStep < pwmled[x]) ? (x < 8 ? PORTA |= (1 << p[x]) : PORTB |= (1 << p[x])) : (x < 8 ? PORTA &= ~(1 << p[x]) : PORTB &= ~(1 << p[x]));
}

void setup() {
  initTimer1();
  for (int i = 0; i <= 10; i++) {
    pinMode(i, OUTPUT);
    pwmled[i] = 1;
  }
}

void loop() {
  pwmled[random() % 11] = random() % 100;
  delay(100);
}

What speed is your ATTiny44 clocked at? Any way to confirm this?

I've solved the issue, look in the comments below :) The attiny is clocked @8MHz using the internal oscillator.

What you are doing wrong is:
The problem is your interrupt handling routine lasts too long. Since inside ISR() interrupt flag is automatically cleared, timer0 interrupts are being missed and delay() depends upon timer0 interrupts.
To confirm the problem is ISR, remove the for loop and just toggle one pin instead. I bet the delay will then be as it should.
Try to put sei() at the beginning of your ISR to see what is going to happen with the timming of the delay - but that is not the right way.
Instead of using delay() (based on timer0) you can count the number of timer1 interrupts but ISR routine must not last longer than the time between two interrupts and your ISR spends quite a few T-states inside the for loop. A rule of a thumb is ISR has to be very short (fast) - unless you really know what you are doing. For example, in one of my devices I am using a very long ISR routine (in fact the firmware consists of only the ISR - there is only sleep_mode(); in main) for which I know it sometimes lasts longer than the time window between interrupts and I know some of the interrupts are occasionally being missed. However, these few missed interrupts are not critical to that particular application and I am sure the interrupts are being missed rarely.
You could change OCR1A value to increase the time between interrupts but then you would have lower PWM frequency.

Thanks a lot for the clarification and help! I've come to a solution that works well enough for my needs (driving a bunch of LEDs). I have no idea how one's supposed to reply with a block of code but there's the link, now the timing functions work as usual. Indeed, the first code was more shitty than this one, the ISR overlapped with itself causing either timing to go nuts or a substantial amount of flicker (depending on what timer I've set to trigger the interrupt).
Again, thanks a lot :D

I usually just set a flag in the interrupt routine (or use the interrupt flag itself) and handle it in my loop. If the interrupt has a substantial amount of code/looping/calculations.


text:
Tracking Device Using Arduino UNO, GSM and GPS
I'm using SIM900A and GY NEO6MV2. I'm supposed to receive device location continuously after sending "Staff" to GSM and will stop receiving the location if I send "Stop" to GSM. This work on Serial monitor but not on my cellphone.
    #include <SoftwareSerial.h>
    #include <TinyGPS.h>

    float flat, flon; // create variable for latitude and longitude object
    int temp=0,i;

    SoftwareSerial mySerial(10, 11); // create gps sensor connection
    TinyGPS gps; // create gps object

    void setup(){
       Serial.begin(9600); // connect serial
       mySerial.begin(9600); // connect gps sensor
       delay(2000);
       Serial.println("AT+CNMI=2,2,0,0,0");
       temp=0;
     }

     void loop()
     {
        while(Serial.available())
        {
           if(Serial.find("Staff"))
           {
              get_gps();
           }
           if(Serial.find("Stop"))
           {
               loop();
            }
         }
      }

     void get_gps() // run over and over
      {
        unsigned long start = millis();

        while (millis() - start < 10000) {
        if (mySerial.available()) {
             char c = mySerial.read();
             if (gps.encode(c)) {
                 gpsdump(gps);;
             }
            }
          }
        }

     void gpsdump(TinyGPS &gps)
     {
         init_sms();
         gps.f_get_position(&flat,&flon);
         Serial.print("Location?\nRight here:\n");
         Serial.print("Google Maps: https://google.com/maps/place//@");
         printFloat(flat, 5); Serial.print(",");
         printFloat(flon, 5); Serial.print('\n');
         Serial.print("Location as metioned above\nTQVM");
         Serial.write(0x1A);
         delay(2000);
       }

      void init_sms()
     {
       Serial.println("AT+CMGF=1");
       delay(400);
       Serial.println("AT+CMGS=\"+60134484868\"");
       delay(400);
     }

    void printFloat(double number, int digits)
    {
     // Handle negative numbers
     if (number < 0.0) {
     Serial.print('-');
     number = -number;
    }

      // Round correctly so that print(1.999, 2) prints as "2.00"
      double rounding = 0.5;
      for (uint8_t i=0; i<digits; ++i)
      rounding /= 10.0;

      number += rounding;

    // Extract the integer part of the number and print it
     unsigned long int_part = (unsigned long)number;
     double remainder = number - (double)int_part;
     Serial.print(int_part);

    // Print the decimal point, but only if there are digits beyond
    if (digits > 0)
    Serial.print(".");

     // Extract digits from the remainder one at a time
     while (digits-- > 0) {
     remainder *= 10.0;
     int toPrint = int(remainder);
     Serial.print(toPrint);
     remainder -= toPrint;
    }
   }

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

That's an instant death warrant right there. You can kiss your stack goodbye as it crashes mercilessly into your heap. Never ever ever call loop() from anywhere.
Your decision as to whether or not to get the GPS data is completely flawed. It will run the function once when it finds "Staff" and never again (unless it sees "Staff" again on serial). It doesn't keep finding the same thing over and over again unless you keep sending it over and over again.
And come to that - how exactly are you sending "Staff" and "Stop" through GSM? I assume by SMS message, however I see no code there to actively retrieve the SMS messages from the SIM. So you'll never see anything anyway.
You need to completely re-think your whole program methodology:

Look for new SMS messages
If any exist then read one and delete it.
If the message contained "Staff" then enable sending mode. If the message contained "Stop" then disable sending mode.
If sending mode is enabled and enough time has passed since the last sending then get the GPS data and send it.

You notice the sending of the GPS data is separated from the SMS reception. It's not the reception of the SMS that controls the GSM but the "mode" your program is running in. The SMS just controls that mode.
This is a crude form of Finite State Machine.


text:
How to read data using Arduino SPI
in the datasheet, it's stated that I should apply 32 serial clocks to get the 32 bits of data. How can I program this is Arduino?

I suggest you to open the examples of the SPI library and check them. Anyway, the code should be byte result[4]; for (i = 0; i < 4; i++) result[i] = SPI.transfer(0x00); and you will find in result the 32 bits you need

I already did that. but the energy chip I am using is STPM10 and it suggests that I should use simplex synchronous SPI where the MOSI is not connected. there is just a timing diagram to switch from reading bytes and writing bytes. When I used SPI.transfer(), The data is not stable and I think not reliable

How do you say it is not reliable? The peripheral is full duplex, and according to the way it works the only way to receive data is by sending dummy data. If MOSI is not connected, well, it doesn't matter; note however that you can't use the MOSI pin for other tasks. By the way, did you remember to correctly set the slave select pin of the other peripheral? Did you use the SS pin on the arduino board or another one?

You call SPI.transfer() four times, each time saving the returned value to a variable after proper bit shifting.
uint32_t val;
val = SPI.transfer(0xff);  //0xff is a dummy
val |= (uint32_t)SPI.transfer(0xff) << 8;
val |= (uint32_t)SPI.transfer(0xff) << 16;
val |= (uint32_t)SPI.transfer(0xff) << 24;

I assume the least significant byte is received first. Make sure the SPI mode is the right one, as indicated in your datasheet.
If the slave can't handle being deasserted between bytes (which is what SPI.transfer() will do at the end of the transaction), then you can either try st2000's hardware SPI approach or use bitbanged SPI with shiftIn().

Not sure this will work.  We really need to know how the SPI slave works before we can assume how it will react.  Also, if the Chip Select line is asserted and de-asserted with each 8 bit SPI transaction, how well is the SPI slave designed?  That is, such a SPI slave could easily get out of sync with the SPI master.  Specifically, how are you assured which 8 bit byte you are actually reading?

@st2000 The OP saw fit to not give enough details; nothing but assumptions can be made till that changes.

All the examples I've seen use SPI,transfer(0) to read data rather than SPI.transfer(0xff). They also use SPI.transfer for writing data, too. I still haven't figured out what SPI does with the 0 or 0xff when you are actually reading data. Is this sent to the slave?

@S.Imp They're dummy bytes. You can send whatever you want to send, the device at the other end will still discard them, if it even pays the data any mind. SPI.transfer() is always used partly because of the intrinsic full-duplex nature of SPI and (as a result of the first factor) then partly because of the way most MCUs implement their SPI peripherals. Once the clock starts running, there is always "data" on the MOSI and MISO lines, it's just up to each participant on the bus to read it or not, deciding based on whatever predefined higher-layer protocol if the "data" is meaningful or not.

It wouldn't be totally incorrect to say you can't truly read without writing on an SPI bus and vice versa as well. So it makes sense to simply design a peripheral that takes a byte in one register and, 8 cycles later, returns a byte in another (or even the same) register, just to generalize usecases. Then it's up to the user's application to decide if they're only interested in the byte that was written out in the first place (TX) or the one that was read back (RX) or both (TX and RX). Also, hence the ambiguous name transfer() since it serves both reading and writing roles.

Sparkfun has a good explaination of what SPI is:
https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi
The Arduino IDE has a SPI library that comes with the IDE.
http://www.arduino.cc/en/Reference/SPI
The library comes with two examples:
Using SPI to read a Barometric Pressure Sensor
Controlling a Digital Potentiometer Using SPI

Objective is to read 32 bits using the (unknown) device's SPI port.
If the device will tolerate the SPI Chip Select line activity (going from inactive to active to inactive for each 8 bit byte read) you should be able to get the desired 32 bits of data by performing 4 consecutive 8 bit SPI reads.
However, if the device will not tolerate the above SPI Chip Select line activity (that is, if the device requires the SPI Chip Select to be active for the entire 32 bit SPI transaction), you can not separate the 32 bit transaction into 4 individual 8 bit SPI transactions with out controlling the SPI Chip Select line.  The following code example illustrates how this is done:
void loop(){
//transfer 0x0F to the device on pin 10, keep the chip selected
SPI.transfer(10, 0xF0, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, keep the chip selected
SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response1, keep the chip selected
byte response1 = SPI.transfer(10, 0×00, SPI_CONTINUE);
//transfer 0x00 to the device on pin 10, store byte received in response2, deselect the chip
byte response2 = SPI.transfer(10, 0×00);
}

The above example comes from the Arduino SPI library web page and is a 16 bit (not 32 bit) transfer.  To code up a 32 bit transfer, continue to call the SPI.transfer method using the SPI_CONTINUE parameter.
added later...
It appears people are discouraging use of the DueExtendedSPI methods. And SPISettings and SPI.beginTransaction() are to be used? If so this page show example code where the code is explicitly controlling the SPI Chip Select line (look for slaveAPin & slaveBPin).  Note how the code is reading 24 bits from slave A and writing 8 bits to slave B. To read 32 instead of 24 bits, we need to alter a segment of the code (along with a few other supporting changes) in this fashion:
...
  SPI.beginTransaction(settingsA);
  digitalWrite (slaveAPin, LOW);
  // reading only, so data sent does not matter
  val0 = SPI.transfer(0);
  val1 = SPI.transfer(0);
  val2 = SPI.transfer(0);
  val3 = SPI.transfer(0);
  digitalWrite (slaveAPin, HIGH);
  SPI.endTransaction();
...

We really need to see the specifications of the slave SPI device to compose a more specific answer.

I use STPM10 evaluation board. The connection is a simplex synchronous SPI, and the MOSI of the Arduino is not connected to anything. There is a timing diagram to switch from read only and write only. My problems is to how to read the data from the registers of the chip. I used SPI.transfer but I don't think the data is reliable.

The STPM10 timing diagram found on page 11 of it's spec does not look like a standard SPI transaction. I am inclined to say you can not use the Arduino SPI library. Instead, you may need to bit-bang this out totally in software. For instance, I do not believe there is a "SYN" line in the standard SPI bus. And I don't believe the Chip Select line should go high before the end of the SPI transaction.


text:
Creating an Arduino Tic Tac Toe game
I'm trying to create a Tic Tac Toe game using the Arduino Uno. Since the Uno has a limited amount of pins to use, I am trying to see if there is a configuration that would make the project possible.
For the button detection circuit I am using a simple voltage divider and an analog pin. I made the following in a circuit simulator:

Now for the LEDs, since the Uno only hosts 9 pins, and we need 18, we need some sort of wizardry to get something working. I came up with the following design using the circuit simulator:

I would use 9 of these, one connected per Arduino pin. Since only one of the LEDs in each of the 9 sets should be on, this type of circuit should allow the Arduino to control all of the 18 LEDs. In the simulation I get about 5mA draw from each side (with 5v and GND).
However my problem is that the LED setup doesn't work. The lights are extremely dim. At first I simply thought that 5mA was not enough for the LED. I decided to measure the current going through the LED and found that it was about 0.8mA. What happened to my 5mA calculation? After all, isn't Arduino pin able to handle about 40mA? Am I asking for too much current?
Where have I gone wrong with this? Thanks in advance for any help.
tommis15

Worth mentioning, what are the specifications, or the make of your LEDs bring used

I bought them through Tayda Electronics. The spec sheet says 20mA forward, but they work when I use the GND or 5v pins on the Arduino. It just doesn't when I use the digital ones.

yes, those are pretty normal specs, also I wouldn't put the LED straight across 5V and GND. What I would like yo know is the voltage drop across the LED. Could you also clarify the reason why you have 3.3V on the one LED anode?

No, I am using the circuit above, but instead of a digital pin I am using the 5v and GND pin.

yes but why the 3.3V supply??

can you connect one LED and resistor to a digital PIN and toggle it with some code. First use your 330ohm resistor and then try with a 220ohm. And reply with the observation

I use the 3.3v supply because current flows without it and both LEDs turn on at all times.

This question is similar to Increasing the numbers of I/O pins on Arduino Uno.

I was working with it more and I found that my mistake was that I was using pin 0 and 1 to test (serial) and switching to pin 2 and above works.

Please accept it by clicking on the "tick" icon next to the answer. This indicates to other users that you found the solution, and it also stops Stack Exchange from periodically "bumping" your question in the hope of getting an accepted answer. Thanks for your understanding and cooperation!

You should really provide more info:
- your program
- what exactly you are trying to achieve (you seem to be driving two leds per 'board position'. What do they represent?) and schematics.
It would also help if you measured the voltage level at the pin in both the ON and OFF state and mentioned it here.
However, one thing that should be noted (hopefully before it is too late) is that your 40mA/pin assumption is wrong. First of all, 40mA is the absolute maximum rating for one pin (i.e. the value you should stay clear of). Secondly, although one isolated pin can source or sink close to 40mA, the total of all GPIO pins should stay below 200 mA. See also http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations .

"The total of all GPIO pins should stay below 200 mA", yes. This is why I wanted to draw only 5mA from each pin (which would result in way under the limit).
As far as my program, I have not written it because I want to hardware to work before I write. (I am using digitalWrite to test if the led will turn on).

How do you expect to test the hardware without running a program? And what is the voltage level of the pins? And what exactly is the meaning of each LED pair (I would expect one to represent an X and the other an O, but I can't see how your circuit would have them both off (to represent an empty position).


text:
Why can't I use an optocoupler to drive an AC circuit using the arduino digital pins?
So, when I searched for ways to drive AC circuits from Arduino, everyone suggested relays with a transistor switching circuit to channel an external 5V. I was wondering what would happen if I used an optocoupler like 4n35 to drive an AC circuit. Will the phototransistor inside the chip burn out?

Which AC voltage?

220 V AC mains I meant

Maximum current is 50mA, so not that useful in most cases.

From what you are typing, I guess you are neither an electrician or somehow experienced in this matter. Dealing with mains voltage, in particular building circuitry working with mains voltage requires substantial knowlede to avoid deadly risks as accidental electrocution and fire hazards. In fact in most countries you sail close to the wind doing so without. You face administrative fines up to imprisonment in case of injury to persons. I strongly recommend you fetch some basics about electrical safety and your local regulatory legislation before continuing with what you had in mind.

@Gerben: at least 11 W :) (and the thermal energy of the burning plastic housing).

Thanks for the advice. I want intending to try this. Just needed a theoretical explanation.

Use it with Triac.  I use MOC3020 + BT138 + 330 and 510 Ohm resistors.
It works good as relay and in dimmer scheme.
Scheme is here
http://cyber-place.ru/attachment.php?attachmentid=1030&d=1370462030

Normally Opto couplers like a 4N35 were not designed to drive an application load.  Typically they are used to trigger another device such as a SCR or Triac.  There is a vidio I would recommend you watch, it gives some information and the comments are good.  Give this a try:
https://www.youtube.com/watch?v=FVef6f2_Si8
Gil

No. A 4N35 will switch 150mA at 30V DC. See http://elinux.org/RPi_GPIO_Interface_Circuits for more detail. If you are proposing to switch 110/240V AC there are safety issues. You should look at available commercial modules.

SSR's typically have a arduino friendly 3v + dc input, and can switch 10+ amps of up to 330vac.


text:
How to change the baud rate of ESP8266 (12E) using an Arduino Uno?
I have with me an Arduino UNO and an ESP8266 (12E) WiFi Module. I need to make a webserver using the two. I read that the default baud rate for ESP8266 is 115200, and that the software serial pins can't handle such high speeds. I dont have an USB-UART converter at hand. Is there a way to use my Arduino as one to change the baud rate, so that I can interface with the chip using the software serial pins of the Arduino later.

if you have an uno you don't need a usb-uart; just rx-tx, tx-rx, g-g, uno's rst-gnd

@dandavis Okay. In that case on which pin should I connect the voltage divider to reduce the logic levels to 3.3V?

you don't actually need one just to flash an ESP, but you would "stepdown" the uno's TX pin for long-term connectivity, the 5v-tolerant ESP's pins put out enough for the uno w/o modification. using a red LED instead of a wire for the uno's TX to the esp's RX suffices.

You can use this block of code in Arduino to set baud rate...
void setup()
{
  Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
}

void loop() {}

Change value in serial.begin() as per your value.

Use SoftwareSerial library for your module and define your own tx and rx pins like this and then you can define baud rate for your specified serial pins.
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9); // RX, TX for your module
void setup(){
   mySerial.begin(115200);
}

for more details visit https://www.arduino.cc/en/Reference/SoftwareSerialBegin

But from what I heard, SoftwareSerial doesn't support such high baud rates.

go to this link https://www.arduino.cc/en/Reference/SoftwareSerialBegin

Yeah, okay. It says it's supported. Thanks. It seems there's a lot of misinformation on the internet.

SoftwareSerial can't receive reliably at higher than 9600 baud, but it can transmit reliably enough for you to command the ESP board to change its baud rate to 9600. From then on, use SoftwareSerial at 9600 baud.

You can use the SoftwareSerial library and define your own tx and rx pin and set baud rate according to your requirement.
#include <SoftwareSerial.h>   // SoftwareSerial library
SoftwareSerial mySerial(2,3); // RX, TX for your module

void setup()
{
   mySerial.begin(9600);      // Set your buad rate
}

And you can also do without this library.
void setup()
{
  Serial.begin(9600);        // Set your baud rate
}


text:
Can I port a project built on Arduino Uno to a standalone ATmega328 using the exact same code?
I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?

Yes you can.  There shouldn't be any difference.

most code should run the same. try it and work through the compiler errors.

Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.
If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.
Update:

There's a bit more required, for example, the clock rate needs to
  match or the timing will be off ...

I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.
If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed without modifying the code for those differences.

There's a bit more required, for example, the clock rate needs to match or the timing will be off, and the clock source and supply voltage need to match or the fuses may make the system unbootable or unstable.

You can run any code on an ATMEGA328P that you can run on an Arduino Uno. For maximum compatibility, you would configure the ATMEGA328P with a 16Mhz crystal/resonator.
There are instructions for using an Arduino Uno as an ISP for programming other devices, many of which require a Uno with a DIP version of the ATMEGA chip which can be removed.
What you cannot do is directly run code for an ESP8266 on an ATMEGA328P.

fun fact: shorting reset to ground does the same thing as removing the DIP...

An Arduino with the processor removed or held in reset is not likely to be helpful for ISP operations, rather it could be borrowed as a serial interface for bootloader or test ones.  BEWARE that an ATmega with its reset grounded is susceptible to corruption (loosing the bootloader, etc) if it sees ISP-like traffic on the SPI pins.

Yes, it might work. But as a minimum you should check that the following is mapped between the two in a compatible way:

Pinout and configuration of pins. ESP8266 allows INPUT_PULLDOWN in some pins, whereas ATmega328 doesn't.
Use of timers and interrupts. ESP8266 accepts "true" interrupts on all I/O pins, whereas ATmega328 only accepts them in 2 pins (although you can use Pin Change Interrupts (PCIx), which are far less powerful than "true" External Interrupts (INTx)). Also, ESP8266 accepts HIGH level interrupts, whereas ATmega328 doesn't (even on INT-capable pins).
Use of specific ESP8266 libraries which won't work at all on an ATmega328

The Arduino library ports for ESP8266 may work as expected out of the box, it may require minor tweaks, or it may require a major revamp of key code fragments. It's difficult to say without seeing the code.

he's not switching to an ESP, he's switching to a bare chip and still wants to connect the ESP as a module. (not sure why; the ESP is faster, cheaper, etc...)


text:
Power Supply for 30 Servos
I am now constructing something with 30 servos (each one will control an individual joint separately, so I guess I can't get away from this), how can I determine how much current do I need, I have a 5V 6A power supply, will that be working just fine? Many thanks in advance!

Get one of the servo's working at full load & measure the current flowing through it, multiply that by 30.
That's a lot of servos :D

You'll need to look up for your particular model of servo what it is rated for.
From this random datasheet I got values of about 5mA while idle and 150mA while running. Your 6A supply will be fine (if your servos don't draw significantly more than these) even if you run them all at once (which in practice, you might not).
Note that if you stall the servos they will draw more current, but it seems unlikely that you'd stall all of them at once.


text:
Raspberry Pi, Teensy and Arduino's on i2c
I just got into an interesting mess.
I have 3 Arduino's (Pro Mini's) and 2x Teensy's (3.1's) connected via I2C to a Raspberry Pi Master. The 2x Teensy's I2C data lines are connected via OctoBoards but that doesn't really matter since the OctoBoard maps the I2C Pin's of the Teensy to itself. I have 4k7 pullup resistors for SDA/SLC close to the master (also tried on the end - with no effect).
The Arduino's alone are super solid - no issues other than the occasionally I2C lockup when writing data.

The I2C interface has been running for over 3h with no problems.
Now as soon I add a Teensy to it, the bus locks-up and I need to completely shut down everything. Only thing I got to work was direct connection from RPI -> Teensy and even then there were sporadic detection issues.
I tried the Wire lib as well the IC2_T3 lib with no difference. Also tried with 4 different Teensy's with no difference.
Are the Teensy's not compatible with RPI?

That is a lot of antenna hanging around.  Consider using a method that keeps the Microprocessor wires from going from computer to computer.  Ground references could cause a lot of problems and would explain the problems but it is not the only possibility.  Different processors have different reactions to transients.  Be sure the grounds from each unit are connected together.  I would expect each combination to act differently.

I do not have experience with your exact setup, but I once had a similar problem. I had a pi as I2C master, a battery module that used I2C to communicate battery status and two servo controllers attached. The servo controllers alone worked and the battery module alone worked, but all three attached to the pi didn't work and there was no collision in I2C addresses (have you checked that btw?). It turns out, that both servomodules and the battery module had I2C pullup resistors attached, so the end result was 3x4k7 in parallel, which is around 1566 ohm. The solution was to remove the pullup resistors from the servo controllers.
So the question is, have you by any chance enabled pullup resistors on any of the arduinos/teensys/pi in addition to your own resistors, resulting in wrong pullup resistor value?


text:
USB detect on Arduino DUE
I want to know when something is connected to USB port by blinking an LED.
I suppose have to check PB10 UOTGVBOF, but how to do this ?

What I'm going to say is probably not the most efficient way to do it, but it should work: if your DUE is used as gadget and you wnat to detect the presence of a master, connect a GPIO to the +Vcc line of the usb port and either poll or program an edge triggered interrupt to detect when the line goes high.

Got it working by testing some internal registers state. Thanks for the reoly though

@Siddharth Would you care to put your solution as an answer.  It'll help others who come by later with the same question.  Regards,

authors: Сергей Мартикян


text:
Can I place bootloader directly onto Atmega2560 and have USB?
I am working on a prototype device which I am now on my 2nd board iteration and moving away from it being a shield and wired to an arduino mega2560 board.
I have used the freely available Arduino mega 2560 schematic and incorporated this into my project.
I notice that there are 2 µcontrollers on this schematic, (Atmega2560 & Atmega16U2)
I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.
On the searching I have done I'm getting myself terribly confused.
Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)
However, I was intending to flash a boot loader that would make the device appear to a computer (over usb) as a midi controller device.
I am unclear if I can indeed interface a usb port directly to the ATmega2560,  and upload my sketch code AND a midi-over-usb boot loader..
I doubt the advice because the ATmega16U2 (i think) has a built in UART to communicate via usb and that the 2560 does not...
Sorry If this all sounds vague, I'm searched out and confused...
thanks.

USB really needs specialized hardware to handle the low-level signalling and timing requirements.  1.1 can be bit-banged if you have the resources (https://www.obdev.at/products/vusb/index.html for example), but anything better than that pretty much requires the dedicated hardware.  A common UART won't even come close.

I understand that the arduino bootloader resides on the 16u2 and it connect to the usb connector. the 16u2 then programs the 2560 with the code you send it.

That is a misunderstanding.
The bootloader is on the 2560.  The 16U2 contains its own custom firmware which acts as a USB CDC/ACM interface to connect the USB to the 2560 as a TTL UART connection.
The same can be done using any number of other similar devices, such as the FT232R etc.
You cannot directly connect the USB to the 2560 since the 2560 has no concept of what USB is.  The 16U2 has that knowledge, but doesn't have as many IO pins as the 2560, so combining the two gives you a total system that both understands USB and has lots of IO.

thank you for this useful reply. If I am understanding you correctly then, I could use an FT232R to give the 2560 usb communication capability, and also flash the code (in addition to my program code) to enable the device to be seen as a midi controller (HID Device) on connection to a computer?

@BradHolland: No. The FT232R is strictly for serial communications. You will need to use a MCU with native USB support (such as the '16U2 on the Mega 2560).

Someone suggested to me that I could in fact do away with the Atmega16u2 all together (this would drastically reduce my component count and free up valuable board space)

I recommend that you keep the '16U2 and ditch the '2560. Since the '16U2 is both native USB capable and has sufficient I/O for a MIDI controller then you should use that one for your project.
Of course, since there's no Arduino core for the '16U2 you may want to consider either learning AVR programming without Arduino (when will there be a better time to do so?), or switching to the (overpowered) 'U4, which uses the Leonardo core.

thank you. This isn't just a simple midi controller I'm confident the 16u2 wont work for the application. we're already using a lot of i/o including a large array of leds, analog inputs and an oled screen..

Then you'll need to find some sort of protocol you can use to talk between the '16U2 and the '2560.

if I can indeed interface a usb port directly to the ATmega2560

You cannot interface USB directly to the ATMega2560, because that µC has no USB support build into (and VUSB is probably no solution either).
If your program is simple enough, then it could fit onto the ATMega16U2 on its own, eliminating the 2560.


text:
Arduino Uno and I2C
How does the arduino uno talk with i2c? i saw the circuit and it use analog input pins but as far as i know you cant use them as output. How does he send data over those pins?

Most pins on the Arduino are multi-function and can be switched into different modes. Analog is just one of those modes. I2C is one of the available modes for the pins that A4 and A5 are connected to.

But i cant change it using pinMode(Output), or can i?

pinMode(OUTPUT) will put the pin into digital IO mode and set it to output - just like every other pin.

but i give it the index of the io pin (to the function), what values i give for the analog pins?

Either the name (A3 for example) or 14 - 19 following on from the highest numbered digital pin D13.

Wow didnt know that, thank you. And then its just a regular output io?

Yep, just like using D0 to D13.

So e.g. pinMode(A3, OUTPUT) and digitalWrite(A3, HIGH).


text:
How to add more inputs on Arduino?
I'm building an instrument that has 72 buttons that can be pressed. Now I'm planning on using Arduino to send data to computer via USB cable about which buttons are pressed. So I figured I'd need 72 different input pins, one for each button(the button is connected to the Arduino via a wire). But, the Arduino doesn't have 72 input pins, so this seems kind of impossible. So what I'm looking for is a way to somehow extend the number of pins on the Arduino or another way to solve my problem. Maybe it would be better to use another micro-controller? Maybe using analog inputs for this is better?
If it makes any difference, the max number of buttons that can be pressed at once is 10.

Look into multiplexing. Create a grid of 8x9 buttons. Energize only one row at a time, and measure all the columns. The energize the next row, and repeat. To reduce the number of pins you could use a shift-register to drive the rows.

There is a whole concept you need to learn:
Matrix
By using a matrix arrangement you can, using (8 + 9 = ) 17 IO pins you can create a grid of 8 × 9 buttons, which is 72 buttons.
This method is used all the time for keypads, and you can read more here: http://playground.arduino.cc/Main/KeypadTutorial
To further reduce the number of IO pins used you can replace the 8 IO pins for one dimension of the matrix with a 3-to-8 decoder, since only one pin is ever active at a time.  That reduces it down to just 12 IO pins for the whole shebang.

Thank you very much! This was very helpful and I'm going to use the concept of matrix to solve my problem.

There are quite a few GPIO expanders available that you could use to increase IO lines in your circuit, mostly running off I2C. Just search "I2C GPIO" on your favorite electronics site/google/ebay
Examples:
https://www.sparkfun.com/products/8130
[No affiliation]
If every sensed key has to be on a GPIO, then this is the way to go.
Having said that, with IO expanders, you will find that sensing large number of keys still takes lots of code on your uC. With some extra software effort, you could eliminate expanders, and rather scan a key matrix as suggested by Majenko

I'm going to stick with key matrix as it seems much easier than any other way. But thanks for suggesting GPIO expanders, I'm sure I'll run out of input pins some day and knowing this beforehand will save me a lot of time.

You may try making something like a button grid, Like the ways Leds are connected in a Led cube, For example - In a 4*4*4 led cube, u don't need 64 pins, but a smart connection of all on x and y axis,
what i mean to say is,
you need to make rows and columns of button, But i don't think this idea would work cause buttons are totally different from leds, But then also try searching for led cube circuit, let it spark a new idea in your mind.


text:
Does lowering arduino analog reference increase precision in measuring low voltage?
The definition for Analog Reference is as follows: The reference voltage used for analog input (i.e. the value used as the top of the input range).
By default you have analog reference of 5V. So the precision of analogRead is 5 / 1023 = 0.0048875.
Now what happens if I lower the analog reference to let's say 1V. Does that mean that the precision now is 1 / 1023 (and the arduino can't measure voltages higher than 1V) or it is the same precision as before with the only difference being the fact that the arduino can't measure voltages higher than 1V anymore?

"Does that mean that the precision now is 1 / 1023?" - that is correct.

Bear in mind the minimum for Vref is 1V, so don't start planning on dropping it to 0.5V.

The former, i.e precision would now be 1/1023 but the accuracy of the AD converter is 4 / 1024 or 1 part in 256  i.e. 0.25%.
Also be aware that the internal reference voltages themselves are not very accurate :
DEFAULT: depends on your computer power supply USB2  Vbus = 4.4V - 5.25V, Vint 1 = 1.1V  actually 1.0 -- 1.2V, Vint 2 = 2.56V  actually 2.4 -- 2.8V

Thanks for the fast and very helpful response! So the best precision you can get out of arduino analog pins is 4 / 1024 due to the accuracy of the ADC, right?

Precision and accuracy are related but different. With 1 in 1024 converter, the precision is .000977, but lack of accuracy may make the last few bits meaningless. If we had a rubber ruler marked in millimeters, and we stretch it, the precision wouldn't change but the accuracy would.

You could measure a know voltage, and use that to calibrate the ADC. Or you could measure the 1.1v internal reference, by measuring the voltage at Aref using a multimeter.

The A/D simply gives a binary value between 0 and 1023. That value is evenly divided between reference and ground. Since it is a successive approximation register that starts counting at zero and counts up in consistent steps until the reference voltage is reached, that count is saved and presented as the reading. If your input voltage is in that range you will get a reading on the number of steps from zero where it matched (0 to 1023). If measuring higher voltages you simply use a resistor divider and multiply the reading by that ration.


text:
Arduino communicate between 2 different router in different location
I am on my final year project in I.T. my project is that i want to create a helicopter or quadcopter with a camera attached to it. And i want to control the copter via wifi from an android phone in another location. e.g, the copter is at home and i am somewhere else (work, university etc..). so i wanted to know if i can connect both via 2 different routers and control it and get the live video the camera is actually recording (the idea is to monitor your house when you are away). if that is possible, which arduino hardware will enable me to do that.
Thank you.

It's not the Arduino that has anything to do with this but the routing, port forwarding and/or VPN that you set up between your routers.
I'd have thought, since you're in your final year of IT, you'd at least have some rudimentary knowledge of routing, port forwarding and VPNs...


text:
What is the purpose of the howMany integer in the wire.onReceive() function from the example code?
In the master write/ slave read example for the wire library, there is an integer declared howMany that is never used.
 void setup() {
   Wire.begin(8);                // join i2c bus with address #8
   Wire.onReceive(receiveEvent); // register event
   Serial.begin(9600);           // start serial for output
}

void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
   char c = Wire.read(); // receive byte as a character
   Serial.print(c);         // print the character
}
 int x = Wire.read();    // receive byte as an integer
 Serial.println(x);
}

As the function does not work without it, i would like to know what is its exact purpose.I would imagine that is something regarding the buffer size.

The description of the wire commands are extremly poor. For me there is also a lot of guessing involved. Without example codes from foren for me it is not possible to generate a running code.
For that reason the question for the sense of how many is very valid.

It tells you how many bytes have been received, and consequently how many you can read with Wire.read().
Before you have read anything with Wire.read() Wire.available() will return the same value.  As you read from the buffer Wire.available() will decrease, but howMany will stay the same.

The reference page https://www.arduino.cc/en/Reference/WireOnReceive states:

Parameters
handler: the function to be called when the slave receives data; this should take a single int parameter (the number of bytes read from the master) and return nothing, e.g.: void myHandler(int numBytes)

I suggest you look at the reference pages for the functions in future before asking what they do.