text:
How to blink LED's unsynchronized?
I'm new to Arduino. For my first project,  I want to make aviation strobe lights. My challenge is to use ONE Arduino to blink both sets of lights. My issue is,  I DON'T want them to be synchronized. I saved a sketch of the blink example from the Arduino IDE software after editing it to do what I want. But, the LED's are synchronized. One LED strobes twice,  while the other strobes once as I want them to. However, they begin their loops together currently and stay synchronized,  which isn't what I want.
So my question is: What is the code I need to write to make each LED blink unsynchronized from the other without having to use 2 Arduino units?
Code:
int led = 11;
int led2 = 12;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);
}

void loop() {
  digitalWrite(led, HIGH);
  delay(50);
  digitalWrite(led, LOW);
  delay(1000);
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(100) ;
  digitalWrite(led2,  HIGH);
  delay(50)
  digitalWrite(led2, LOW);
  delay(1000);
}

Could you post your current code?

That code is only for one led. You said you got things working for two LEDs.

OK,  I fixed it to reflect what I've got.

The Arduino Blink example uses delay() to pause the Arduino in a specific state, so that for a specific amount of milliseconds the device will keep the blinkPin HIGH or LOW.
Instead of using a delay(), you should use millis(). The main advantage of millis() over delay() is that it does not interrupt the code. When you call a delay() the whole code pauses, nothing can be done during those milliseconds. But millis() doesn't work that way. You also don't call it the same way as delay().
What millis() does is that it stores a timer value into an unsigned long. At a later point in time you can substract a new millis() from your previously stored millis in the unsigned long. The result is a difference in time between each millis() in milliseconds.
Now, instead of using only one unsigned long, we use two different ones: one for each LED. Now you can log a time interval, independently, for each LED. Furthermore, if you apply the logic of millis() for keeping the LEDs on or off, you don't have to interrupt the code with delay() functions. This means, that regardless of each LEDs state (HIGH or LOW), the timer keeps running, keeps logging and thus can control both LEDs simultaneously.
To give you a bit more information on millis(), below are some references that will get you started in how to implement. If you have more questions, just comment on this answer :)

millis() reference on the Arduino website
Blink without Delay example

Using the millis function call is generally always better than delay.  However it is more complex to use the millis functions as the developer needs to understand a different variable type (unsigned long) as well as consider what happens when the millis function wraps around (however infrequent). I think, in this case, using delays for the time base and counters that do not over flow for any variable type makes for an easy to explain and simple to implement answer to the question.

Although more complex, it allows for much more functionality on a device. Simply more than one thing can be done without completely disrupting the code. I never use delay() anymore, except when it is the only way to process some stuff (for example with a WiFi chip or Serial communications where short delays are sometimes needed to simplify the code). Anyway, millis() is amazing and delay() is not, haha.

It is not possible to escape the fact that both LEDs will be driven from a common clock.  However, it is possible to arrive at a convincing solution where the LEDs appear to be unsynchronized.  What is necessary is a rather fast event loop and rather large numbers which are not quite multiples of one another. As an example consider a loop with a delay of 10ms and two counter which will count up to 100 and 51 respectively.  Each time the counters reach their goal their respective LED is toggled and the counter is reset to zero.  One LED will appear to turn on off on with a period of about 2 second.  The other LED will turn on off on with a period of about 1 second.  However, over time,the second LED will start to trail the first.  Giving the appearance that they are not synchronized.
You can use any numbers you wish.  Edger suggested in the comments to use golden ratio numbers 144 and 89.
If you want to emulate the short burst of strobe lights you need to alter the suggested design (which provides a 50% duty cycle) to something that provides, say, a 10% duty cycle.
Let's adapt your code from above.  Add 2 counters one each for LED1 and LED2.  Define numbers for the period of LED1 and for LED2. Also define a number for the length of time the LEDs will be on for.  Notice that we only need one 10ms call to the delay method. All counters are incremented each time we enter the loop method.  Since our delay is 10ms we enter the loop method 100 times a second.  Inside the loop method we keep track and cap the counters at their predefined limits.  When we get close to those limits we turn on the appropriate LED.  When we hit the limit we turn off the appropriate LED and clear that LED's counter.
// What is the period of led 1 in 10s of milliseconds.
#define LED1_PERIOD_10MS 144
// What is the period of led 2 in 10s of milliseconds.
#define LED2_PERIOD_10MS 89
// How long to keep the LED on in 10s of milliseconds.
#define LED_ON_TIME_10MS 10

int led = 11;
int led2 = 12;
unsigned int count_led1;
unsigned int count_led2;

void setup() {
  pinMode(led, OUTPUT);
  pinMode(led2, OUTPUT);

  count_led1 = 0;
  count_led2 = 0;
}

void loop() {
  count_led1++;
  if(count_led1 == LED1_PERIOD_10MS - LED_ON_TIME_10MS)
  {
    digitalWrite(led, HIGH);
  }

  if(count_led1 > LED1_PERIOD_10MS)
  {
    count_led1 = 0;
    digitalWrite(led, LOW);
  }

  count_led2++;
  if(count_led2 == LED2_PERIOD_10MS - LED_ON_TIME_10MS)
  {
    digitalWrite(led2, HIGH);
  }

  if(count_led2 > LED2_PERIOD_10MS)
  {
    count_led2 = 0;
    digitalWrite(led2, LOW);
  }

  // Delay 10ms.
  delay(10);
}

I have only proof read the above code.  If you find any problems make a comment below and I will make the corrections.

So,  how would I write the code to achieve the counter reset? Basically,  what I've got is:

This answers your question.  However, it's worth noting LEDs lack the ability to simulate incandescent light bulbs as they have little thermal inertia. In order to simulate this you might consider programmable LED and slowly bringing up the down the brightness.  You can also use a normal LED and the Arduino's PWM feature to control the brightness.

The code isn't difficult.  In your Arduino loop method increment each number and test one for, say, greater than 100 & the other for, say, greater than 51.  If the test is true toggle the pin connected to the respective LED and zero out that counter.  Then you need to call a delay, say, 10ms.  The loop method will be called over and over again as this is part of the Arduino design.

Oh,  Ok.looks like it's gonna be a bit of tinkering to get the desired result. No problem,  as it helps me learn.

The strobes I'm making are based off the xenon high intensity strobes. 2 white wingtip strobes,  and 1 red belly strobe. LED's will do perfectly for what I'm doing.

Instead of 100 and 51, which is almost a factor 2, I would probably try something close to the golden ratio, like 144 and 89. The golden ratio being in some sense the “most irrational number”, it should provide a feeling of completely unrelated frequencies, instead of the “slowly drifting synchronization” you would get with 100/51.

Strobes?  Then using LEDs as is should get you the desired attack & decay.  I imagined you were trying for rotating beacons.  Then a slow attack and delay would look good.  Also, my solution creates a 50% duty cycle.  To emulate a strobe you need a much shorter duty cycle.  Say 10%.  Which would require the code to get a bit more complex.  For some reason, good answers for this question are getting down voted.  So, unless you ask for it, I'm not going to invest time to add an example of a 10% duty cycle to my answer.

@st2000, if I was shooting for a rotating Beacon,  I would just use fade in and out. Of which I did try with my wingtip blink code,  but the problem I run into with the fade in and out,  is that once the code initializes,  the led to fade fades in,  and stays on. Never fades back out. I tried changing pins to see if it was just the pins being too close... But the problem persisted. I would most definitely love to know your example. I have not been down voting anything. I am actually going to try all suggestions to see which one works the best.

The fade code example from here looks like it should work.  Make sure you are flipping the sign of the variable fadeAmount when you reach 255.  Copy and past the example so you know you didn't make a typing error.

You need to implement a pair of LFSRs, one for each LED. This will give a result that eventually repeats, but with registers of differing lengths and the correct polynomials it won't repeat quickly enough for it to matter.

But then OP would have to implement finite filed arithmetic for polynomials on an adruino for implementing an LFSR.

The article gives a couple of sample implementations in C that strictly use bit operations. It's not as complex as it sounds.


text:
Logging without IDE
Is there a way to log events on Arduino when developing using C / AVR toolchain, and not the Arduino IDE? Working on Ubuntu.

Do you want your host system to record stuff received from an Arduino?  Or do you want an Arduino to record data?  Either way, the answer is yes, it can be done.

First one, I would like to see on my host what Arduino is doing.

The IDE uses a plain serial console to communicate with the Arduino.  You can use any serial console application you like.

On Ubuntu, I usually simply do
stty -F /dev/ttyACM0 raw 9600
cat /dev/ttyACM0 > the.log.file

Replace 9600 with your baud rate of choice.

Ha, neato. No character encoding mangling woes?

@user400344: The command is encoding agnostic: it moves the data from the serial port to the file as a byte stream, not a character stream. It could well be binary data for that matter.

Thanks, it will replace my terrible hack completely. Do you use something similarly simplistic to send data to your MCUs?

@user400344: No, I use text-based protocols, like in this command line interpreter, and type the stuff directly at the keyboard, usually through screen. You could cat the.data.to.send > /dev/ttyACM0 but, since the Arduino resets when you open the port, your sketch will miss the beginning of the file. You can avoid this auto-reset feature by putting a cap between RESET and 5V.

pretty neat. what value should I use for the cap?

I just use tip, I never liked screen

@user400344: 10 µF is recommended by the ArduinoISP tutorial, 1 µF always worked for me.

Thanks. I have looked at microbox which is similar to your interpreter. I like the clarity of your str-fu better, though. +1

Any of these are straightforward: python (serial library) or processing (same type of user interface, will happily build portable java programs for linux/win/mac). I use an awful perl script for logging stuff, can't recommend it. If you don't prefer the two first options, have a look at IPC::Open2 or IPC::Open3 - I use a bidirectional connection so I can send stuff, but I rely on 'tip' to do the serial connection stuff. If I wanted to log more than a few things, I would probably use python, which is much easier to read (later), and it will require a small fraction of the memory a fullblown java applet.

source: Stack Exchange

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

sort: votes


text:
Cannot ping ESP8266's IP address from a computer on the same network
I have an ESP8266 module connected to my Arduino Mega 2560. I sketched a simple code to pass whatever command I typed from the Serial Monitor to ESP8266 and vice versa:
void setup() {
  Serial.begin(115200);
  Serial2.begin(115200);
}

void loop() {
  if (Serial.available())
  {
    Serial2.write(Serial.read());
  }

  if (Serial2.available())
  {
    Serial.write(Serial2.read());
  }
}

So from here on I just type my AT commands inside Serial Monitor and receive the output also inside Serial Monitor. Managed to connect into a wifi network using the command:
AT+CWJAP="SSID","password"

And obtain my ESP8266 module's IP address using the command:
AT+CIFSR

+CIFSR:APIP,"192.168.4.1"
+CIFSR:APMAC,"5e:cf:7f:c2:ce:30"
+CIFSR:STAIP,"192.168.1.103"
+CIFSR:STAMAC,"5c:cf:7f:c2:ce:30"

OK

Problem is, whenever I run CMD and "ping 192.168.4.1" or "ping 192.168.1.103" from my PC which is connected to the same network, I will get "request timed out". Pinging my own PC's IP gets me a reply. What is wrong here? Totally clueless... :-/
EDIT My PC's IP address is 192.168.56.1

And are those IP addresses actually on the same subnet as your computer?

What is your computers IP address.  You will not be able to ping one of the addresses unless you have set the subnet mast to 16(ish) bits (255.255.0.0)

The IP address 192.168.4.1 is the default IP address used by the ESP8266 when it is running as an access point. You can ignore that, it doesn't actually exist.
You need to make sure that you are actually connected to the access point by issuing AT+CWJAP? which should respond with the access point name an OK if it is connected.
Secondly you need to make sure that you are on the same network segment as your ESP8266 - that is, the same subnet.  If your computer isn't on an address in the range 192.168.1.1 to 192.168.1.254, and your subnet mask is set to (what is usually the default) 255.255.255.0, then you won't be able to communicate unless there is an appropriate route between the subnets.
Also some wireless routers impose client separation on the WiFi channel, which means that WiFi devices cannot talk to each other, and LAN devices cannot talk to the WiFi devices. This is usually something that can be disabled in the router's configuration.

First, you need to confirm that your PC's wireless connection is on the same IP subnet as the ESP8266. At the CMD prompt, type:
ipconfig /a

and look for the wireless adapter. Hopefully the IP address will start with 192.168.1.... It should but there's no harm in checking!
Second, check that your WiFi router hasn't disabled pinging between its clients - some do (mine did, until I threw it out...). Do you have a smartphone or other WiFi device? If so, find out its IP address (hopefully also 192.168.1....) and confirm that you can ping it.
Pinging your own address isn't very useful. Normally it detects the fact that it's its own address, and replies with no attempt at sending over the air.

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


text:
How to read Arduino voltage
I am trying to do voltage measurement using Arduino. I am using a voltage divider circuit to reduce the voltage to less than 5V. I measured the voltage on the 5V pin of Arduino and found out that its 4.279 V (I am powering through USB).  So, I am doing following calculations for voltage measurement:
int data1   = analogRead(A0);
float data2 = data1 * (4.279/1023.0);
float volts = data2 * (10 + 2.2)/2.2;  //R1=10k , R2=2.2k
Serial.println(volts);

if(volts > 12.00)
{
  digitalWrite(6,HIGH);
}
if(volts < 12.00)
{
  digitalWrite(6,LOW);
}

So I am getting exact values of voltage. Now I have put a condition like if volt is greater than 12V, turn on an output, else turn off the output. For output, I have a transistor and mosfet connected. As soon as the voltage increases above 12V, output get on but the problem is that when the output is on, Arduino displays wrong values. Like if the voltage is 12.3, it shows 13.6.
I looked it into more and found out that the voltage at 5V pin of Arduino (4.279) gets reduced to 3.865 and due to which calculation goes wrong and it displays wrong values of voltage.
Is there anything which I am doing wrong? Is there any function or keyword in Arduino libraries which can tell us the voltage or is there any way through which we can measure it? I tried putting the 5V pin to analog pins to read it and convert it into volts but again for this we need a reference voltage.
I hope I have explained the question clearly.
Schematic

A0 is the analog pin and PIN6 is digital output of arduino

Full schematic and code please.

@Majenko I have updated the code and schematic.

I thought so. You have no base resistor on your BJT. That's causing a brownout.

@Majenko base resistor. I didn't get you. Do you mean resistor on base. Can you please describe it

A small resistor between pin 6 and the base of the resistor to limit the current that can flow through the base. Since you are only switching a MOSFET with it the actual value doesn't matter that much - maybe around 1KΩ should be OK.

The brownout that @Majenko referred to happens because the voltage across the base and emitter of your 2N3904 will limit at about 0.6V.  So your pin 6, when driven high would be pulling the VCC supply down.

@Majenko you should convert your comment into an answer

@Majenko Thanks. I used 1.8k resistance and the voltage is seems to be ok now.

@Majenko I am facing problem regarding the reference voltage for reading the voltage. As I already mentioned, I am using 4.279 but now that voltage has increased to 4.8. Why.? why this voltage is not constant.

USB has quite a wide range that the 5V can be. You can't rely on it being 5V. Read this: https://hackingmajenkoblog.wordpress.com/2016/02/01/making-accurate-adc-readings-on-the-arduino/

It would appear that the wrong A/D reading is due to the reduced +5V output. The A/D reference is powered by the input to the computer chip. The big question is what is causing the voltage drop. Are you powering something else
from the USB supply when the FET is turned on? Bottom line is that you cannot
expect the A/D to read the same voltage when the voltage input to the computer chip is changed.

I have connected my arduino using USB and when nothing is connected and blinky program is running, it shows 4.279v instead of 5v. In my project I am planning to use only ATMEGA328P instead of the complete arduino so in that case I will giving it the full 5v power, so may be at that time it will show 5v.


text:
AnalogRead(0) always returns 0 on RFduino
I'm using RFduino to do analogRead at pin 2 and pin 0. Pin 2 works perfectly, and I got the result. However, for pin 0 it returns all zero.
#include <RFduinoBLE.h>

static const int topPin = 2;
static const int bottomPin = 1;

int top;
int bottom;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(topPin, INPUT);
  pinMode(bottomPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
    RFduino_ULPDelay( SECONDS(0.01) );

    bottom = analogRead(bottomPin);
    top = analogRead(topPin);

    Serial.print(top);
    Serial.print(" ");
    Serial.print(bottom);
    Serial.print("\n");
}

I double checked the wires and it's OK. I measured the voltage across pin 0 and it's 3.3V. How do I fix this problem? There's no shortage between pin 0 and 3.3V.

I don't see any pin 0 read.. Also IIRC the analog pins on Arduino are aliased by A0, A1... rather than the number.

It's RFduino, a variation of Arduino. And yes, there's a typo in the code

Soo.. shouldn't it be A0, A2 rather than 0 and 2?

No. Pin 2 works perfectly. If it's A0, A2 it would be a compilation problem.

You don't have to set them as inputs with pinMode. It's my understanding that pinMode is for digital pins only. Comment out those pinMode lines and see if it works.

Analog pin numbers do not start at 0. Arduino pin 0 is a digital pin. Analog pin A0 is an alias for the first analog pin. A0 is a predefined constant.

Yes they do. You can use analogRead (0) to read from pin A0. You also don't need to do a pinMode for it. The notation A0 is for when you want to use an analog pin for digitalRead or digitalWrite (which you are allowed to do).

@DzungNguyen if there is a typo in the code than please fix it by editing your question so to make it clear what you are doing. Also a wiring diagram would help along with the description of any shield/module attached (if any).
Also note RFduino is not ATmega328 based, but ARM Cortex M0...

Without RFDuino specs handy, I'm guessing - but I think it's likely - that the A/D converter gets shut down in an ultra low power sleep and requires some amount of time to wake up. The mis-reading pin, pin 0, is the one your sketch reads immediately on waking. That read call probably takes long enough that the A/D wakes up by the time your read pin 2 so it gives a better reading.
Try switching the order in which you read the pins and see if pin 2 mis-reads if you try to read it immediately after waking. If it does, the cure may be as simple as a 10-100 uSec delay between waking and trying to read any analog data. I just pulled that number out of the air; you might start with a couple of milliseconds and see how low you can make it before you start to see errors, then double that amount.

Thanks for your confidence, but unless this actually worked, I think @edgar nailed this one.

I couldn't find an usable datasheet for the RFduino, seems like a very
poorly documented board. But I found an enlightening comment in the
source code of the RFduino library:

Only pins 1-6 is avaliable [sic] for using as ADC inputs

If you read the source, it is clear that calling analogRead() on an
inappropriate pin is supposed to return 0.


text:
Debugging my created Library - Error - request for member ... which is of non-class type
This seems to be a very common error, I am struggling to understand what exactly the solution to this is.  I am attaching everything, library files, code, and errors.  If you have a moment, I need help with these two errors which appear to be caused by the same problem.  Fixing these errors may however not be the end of my problems so if you notice something else please point it out!!  I recognize my own incompetence regarding this topic any help will be appreciated.
This is a Morse Code Encoder, my goal is to transform the original functional code into a library so that I can insert it into another code more easily.
The Following is the Morse.h Library File (I created this with the Arduino Library Tutorial)
/* Morse.h - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#ifndef Morse_h
#define Morse_h

#include "Arduino.h"

class Morse
{
public:
Morse(int LED, int BEEP, int delayTime, char tmpChar);

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

private:
int _LED;
int _BEEP;
int _delayTime;
char _tmpChar;
int _note;
int _dotLen;
int _dashLen;
int _elemPause;
int _Spaces;
int _wordPause;
};

#endif

The following is the Morse.cpp Library (I created this with the Arduino Library Tutorial)
/* Morse.cpp - Library for flashing Morse code.
Created by Young on Sept. 1, 2016 */

#include "Arduino.h"
#include "Morse.h"

Morse::Morse(int LED);
{
pinMode(LED, OUTPUT);
_LED = LED;
}
Morse::Morse(int BEEP);
{
pinMode(BEEP, OUTPUT);
_BEEP = BEEP;
}

_note = 587;

_dotLen = 75;

_dashLen = dotLen * 7;

_elemPause = dotLen * 4;

_Spaces = dotLen * 10;

_wordPause = dotLen * 14;

void MorseDot();
void MorseDash();
void LightsOff(int delayTime);
void GetChar(char tmpChar);

void Morse::MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);     // start playing a tone
delay(dotLen);                // hold in this position
}

void Morse::MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);    // start playing a tone
delay(dashLen);               // hold in this position
}

void Morse::LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position
}

digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

void Morse::GetChar(char tmpChar)
{
// Take the passed character and use a switch to find the morse code for that character
switch (tmpChar) {
    case 'a':
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        break;
    case 'b':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
    case 'c':
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        MorseDash();
        LightsOff(elemPause);
        MorseDot();
        LightsOff(elemPause);
        break;
//This continues through z and then 0-9, I have shortened it hear for ease of
//reading.  Each break statement functions fine in the original code.

The following is the test code
#include <Morse.h>

int delayTime;
int tmpChar;

Morse dot();
Morse dash();
Morse dark(int delayTime);
Morse set(char tmpChar);

char stringToMorseCode[] = "String to be converted to morse code";

// Create variable to define the output pins
int LED = 13;      // blink an led on output 12
int BEEP = 14;      // output audio on pin 8
int i;

void setup()
{

}

void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++);
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
set.GetChar(tmpChar);
}

// At the end of the string long pledause before looping and starting again

dark.LightsOff(8000);            // hold in this position

}

These are the errors I get when I run this code.
/Users/Young1/Documents/Arduino/Morse_Library_Test/Morse_Library_Test.ino: In function 'void loop()':
Morse_Library_Test:31: error: request for member 'GetChar' in 'set', which is of non-class type 'Morse()'
set.GetChar(tmpChar);
    ^
Morse_Library_Test:36: error: request for member 'LightsOff' in 'dark', which is of non-class type 'Morse()'
dark.LightsOff(delayTime);            // hold in this position
     ^
exit status 1
request for member 'GetChar' in 'set', which is of non-class type 'Morse()'

This is an exercise for me in improving my own skills.  I have spent a day since my last issue (trying to call a class function without an object) researching my problems, however I have been unable to relate the variety of similar questions and answers to my own code.  It seems that most of them deal with a misplaced ().  If you find something that is wrong, please assume that I know nothing.  Post as though you are trying to teach a child how to use Arduino.
I am adding the original code which I am trying to transform into a library for the purpose of inserting it into another code without inserting all 453 lines.
/*
Morse Code Project

This code will loop through a string of characters and convert these to morse code.
It will blink two LED lights and play audio on a speaker.
*/

char stringToMorseCode[] = "String to convert to Morse";

// Create variable to define the output pins
int led13 = 1;      // blink an led on output 12
//int led6 = 0;        // blink an led on output 6
int BEEP = 0;      // output audio on pin 8
int note = 587;      // music note/pitch

/*
Set the speed of your morse code
Adjust the 'dotlen' length to speed up or slow down your morse code
(all of the other lengths are based on the dotlen)

Here are the ratios code elements:
Dash length = Dot length x 3
Pause between elements = Dot length
(pause between dots and dashes within the character)
Pause between characters = Dot length x 3
Pause between words = Dot length x 7
*/
int dotLen = 75;     // length of the morse code 'dot'
int dashLen = dotLen * 7;    // length of the morse code 'dash'
int elemPause = dotLen * 4;  // length of the pause between elements of a character
int Spaces = dotLen * 10;     // length of the spaces between characters
int wordPause = dotLen * 14;  // length of the pause between words

// the setup routine runs once when you press reset:
void setup() {
// initialize the digital pin as an output for LED lights.
pinMode(led13, OUTPUT);
pinMode(BEEP, OUTPUT);

}

// Create a loop of the letters/words you want to output in morse code (defined in string at top of code)
void loop()
{
// Loop through the string and get each character one at a time until the end is reached
for (int i = 0; i < sizeof(stringToMorseCode) - 1; i++)
{
// Get the character in the current position
char tmpChar = stringToMorseCode[i];
// Set the case to lower case
tmpChar = toLowerCase(tmpChar);
// Call the subroutine to get the morse code equivalent for this character
GetChar(tmpChar);
}

// At the end of the string long pause before looping and starting again
LightsOff(8000);
}

// DOT
void MorseDot()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dotLen);   // start playing a tone
delay(dotLen);              // hold in this position
}

// DASH
void MorseDash()
{
digitalWrite(led13, HIGH);    // turn the LED on
tone(BEEP, note, dashLen);   // start playing a tone
delay(dashLen);               // hold in this position
}

// Turn Off
void LightsOff(int delayTime)
{
digitalWrite(led13, LOW);     // turn the LED off
digitalWrite(BEEP, LOW);      // Silence the Beep
delay(delayTime);             // hold in this position

}

// *** Characters to Morse Code Conversion *** //
void GetChar(char tmpChar)
{
// Take the passed character and use a switch case to find the morse code for that character
switch (tmpChar) {
case 'a':
MorseDot();
LightsOff(elemPause);
MorseDash();
LightsOff(elemPause);
break;
case 'b':
MorseDash();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
MorseDot();
LightsOff(elemPause);
break;

//This continues through z and then 0-9, but it adds a few hundred lines we
//don't need to read here.

The problem lies with your object instantiation. I will explain shortly - I am eating right now.

That's fine, I am not in a rush, after all I can't figure it out on my own!!

The main problem lies with your object instatiation:
int delayTime;
int tmpChar;

Morse dot();
Morse dash();
Morse dark(int delayTime);
Morse set(char tmpChar);

Morse has a constructor format thus:
Morse(int LED, int BEEP, int delayTime, char tmpChar);

When you instantiate an object from a class and call the constructor you have to pass all the parameters to the constructor (unless they have been given a default value, in which case you can leave them out from the right-most only).
You never provide () if there are no parameters needed for the constructor - this is a little idiom of C++ that I have never understood.  To break it down:
Morse dot();
Morse dash();

These have no parameters being passed. Lose the () if that  is intentional (and you have a matching constructor with no parameters) or add the four parameters for the constructor.
Morse dark(int delayTime);
Morse set(char tmpChar);

In these two you are trying to pass one parameter only, and for some reason you are also trying to give it a type at the same time. I can only think that it may be to try and indicate which parameter you mean. That is not right. You must provide all the parameters. Also you are passing values from variables that haven't been given a value yet, so it is actually completely meaningless.
I am not entirely sure what you are hoping to achieve with those last two there...
A further issue, digging into your actual class, is these odd constructors:
Morse::Morse(int LED);
{
pinMode(LED, OUTPUT);
_LED = LED;
}
Morse::Morse(int BEEP);
{
pinMode(BEEP, OUTPUT);
_BEEP = BEEP;
}

They have no matching prototype in the class header, and even if they did, the compiler will have no way of differentiating between them. They both have the same type (int). Overloading operates on the type, not the name of the variable.
Oh, and the one constructor you do have a prototype for just plain doesn't exist in your code.

I have no idea what I am doing, I have just tried to compare this to the Library tutorial, and well, my ignorance is obvious, thank you for the help.  If you don't mind, could you explain to me how to use parameters?  I understand I can pass a value, but not much more than that.  I will upload the original code, but essentially, it takes a string, assigns a temporary character to each value incrementally, then calls each switch break command that corresponds with the character in the string thus outputting an encoded morse string which represents the original string.

@user26383 http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

Wish I had stumbled upon this yesterday!!


text:
Is my atmega2560 schematic correct?
I'm designing a custom board with an atmega2560. It will be programmed using ArduinoISP. I want to be sure that i have made no mistakes on my schematic design before I order it. I folloud the schematic for the arduino mega 2560 from the arduino website. For the basic function of uploading a sketch is my design correct?
I can upload the full schematic on pdf if you need it but it just contains some ICs for the final board.
This is the pcb design as asked in the comments!

You want us to evaluate a board you've designed but won't show us the gerbers? How are we supposed to be able to answer that?

I would be happy to show you the "gerbers" if I knew what they are!

They're what you send to the board house in order to have them actually make the board. Load them into a viewer and post the images here.

Oh you mean the pcb design. I dont find a reason to post it because its just the schematic on a board but if you need it I will...

You need to read AVR042.

I don't have much time but from a quick look on the example layout maybe i have a problem on decoupling my gnd/vcc pairs but i think its covered by the 3 caps in series. Although its not a big mistake to correct.

Atmel recommends to have one decoupling cap per VCC/GND pair, and to place it as close to the pair as possible.

Your ground paths leave a lot to be desired.  Flip C1 and use a ground pour.

for the basic function of uploading a sketch your board schematics is indeed correct and going to work.
I can't say much on the PCB as what you have posted is a partial design, in particular it doesn't show the solder mask expansion and other details which might greatly influence the final result.
Please also note you don't need a reset button, a voltage regulator nor an external oscillator for the basic function of uploading a sketch, but I believe you also want to have the ability to run the sketch without the programmer being attached...

Thank you very much. I actually do want it to run without the programer and the PCB is indeed partial as the final design will have lots of junk stuck on it. But thanks anyway, really helpful!

You don't need the crystal on the very first upload. However, once you have programmed the fuses to have the AVR clocked off the crystal, you will need it for any subsequent upload.

@EdgarBonet you are right, but he might also decide to program the fuses so the internal 8MHz oscillator is used... It really depends on what he wants to do with it.
I have my own designs running at 3.3V 8MHz internal in order to trim down costs.

See the schematic and the PCB design in the question: there is a crystal with matching caps connected to XTAL1/XTAL2. I would make little sense have that crystal and program the fuses to use the internal RC oscillator.

@EdgarBonet I am saying the crystal is not mandatory.... you say the cristal is needed with certain fuses, I say the fuses can be changed and you get back to the presence of the crystal?!?
I am saying the crystal is OPTIONAL and I agreed with you it would than require a proper setting on the fuses. Going back to the schematics makes no sense whatsoever to me.

@FrankF. then if your design involves specific analog stuff than there is space for improvement: a proper analog reference and separating the decoupling capacitors for digital and analog lines would improve the quality of your analog readings.

@RobertoLoGiacco I'm going to use the external oscilator and I'm going to use a bunch of analog lines. I'm actually attaching 3 CD4051B analog multiplexers for 24 analog lines but i don't actually need perfect quality. Although, connecting a single decoupling capacitor on each gnd/vcc pair instead of 3 to all of them would improve anything?

To improve your analogRead you should decouple AVCC-AGND separately from VCC-GND, so, depending on your requirements, 220nF capacitance on each of the two separate lines might do.
A big boost in analogRead quality would also come using an external precision reference voltage rather than using the internal reference.
I haven't read the CD4051B datasheet though, so take my comment as a general advice rather than a specific solution.

Well thank you but I'm not going to change anything. I really don't need all this presition as my project is a dj controller. Here are my complete schematics and grebers.


text:
Avoid global variables with classes
I want to avoid global variables when using my own classes in Arduino. Here is a example.
void setup(){
/* setup here */
  classA objectA;
}

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

I know that my compiler will complain about it (out of scope, etc) but is it possible to do that or just forget it and use globally?
Thanks in advance!

Use globals. They're the recommended way. There are other ways, but global static declaration is the right way of doing it.

@Majenko even if my classes getting bigger? I don't have to worry about that?

Even if your classes getting bigger. By declaring it as a global with static declaration (MyClass foo;) you are reserving the RAM at compilation time. All other ways of doing it involve dynamic RAM allocation and that is bad on a microcontroller.

@majenko Are you familiar with any patterns to help organize larger, non-trivial programs?  Polluting the global space is frowned upon in most other problem domains.

A program small enough to fit in the Arduino Uno is probably too small for global name space pollution to be a very serious concern. By using objects, you are already in a sense organizing the name space. If you do worry about your global name space, you could put all your globals in their own name space, or inside a big “app” object.

If you want a variable to be available within more than one function it has to be global. There is no other possible way of doing it.
If you are only using the variable in the loop() function and nowhere else you can declare it static in loop(), which has the same effect of making it global, but it is only possible to see it within loop().
You can make a pointer global, then create a new object in setup() (using new...) and assign it to the pointer, but that has the potential of making a mess of your heap and should be avoided unless absolutely necessary. Also it's pointless, because you don't gain anything over having the object statically created in the global scope.

Seems enough for me. You convinced me! :)

I read to avoid new and delete when coding for arduino. It is not my priority. I am just curious if is possible to do what I asked.

You still end up with a global variable, just a different type of variable.

This answer isn't satisfying.  There has to be a way to balance programmer efficiency (e.g. organize logical bits of code in classes) with memory constraints.  Is there not a compiler that can optimize the end-product in the global namespace way you suggest, but also provide the developer-friendly code organization that @marquesm91 is asking for?

It is worth noting that the global constructors get called before the initializations done by the Arduino core and setup(). That's why many standard objects have a begin() method to do any initialization that needs to be deferred until the core is ready.

@AndrewAllbright: The C++ compilers have a namespace keyword.

You could completely ignore the global space and the setup() function and just treat loop() like main(). Stick a while(1) at the end of loop() to stop it looping, define all your variables as local to loop(), then pass them all as parameters to where they are going. What do you end up with? You end up with global now inside loop() and allocated on the stack instead of the BSS. Big deal. Just stick with global, it's easier.


text:
How can I move these global variables to be
I'm taking a sample I found on the web about how to get ROS and arduino to communicated together over serial. I have the sample working and now I'm moving the idea of the sample into my OOP project and am running into some trouble.
My sketch works but when I move a certain global variable to a protected member it breaks my sketch.
How do I declare this global variable
ros::Publisher chatter("chatter", &str_msg);

as a protected variable
protected:
  ros::Publisher chatter("chatter", &str_msg);

without getting this error
expected identifier before string constant

sample .ino
/*
 * rosserial Publisher Example
 * Prints "hello world!"
 */

#include <ros.h>
#include <std_msgs/String.h>

ros::NodeHandle nh;

std_msgs::String str_msg;
ros::Publisher chatter("chatter", &str_msg);

char hello[13] = "hello world!";

void setup()
{
  nh.initNode();
  nh.advertise(chatter);
}

void loop()
{
  str_msg.data = hello;
  chatter.publish( &str_msg );
  nh.spinOnce();
  delay(1000);
}

ROSController class
#include <ros.h>
#include <std_msgs/String.h>

class ROSController {
  protected:
    ros::NodeHandle _nh;
    std_msgs::String str_msg;
//    ros::Publisher chatter("chatter", &str_msg);
    int _throttle;
    bool _is_on = false;
  public:
    void loop();
    ROSController();
    double* getAttitude();
    bool isOn() {
      return this->_is_on;
    }
    int getThrottlePerc() {
      return this->_throttle / ROSController::THR_MAX;
    }

    static const int THR_MAX;
};

const int ROSController::THR_MAX = 100;

ROSController::ROSController() {
  this->_nh.initNode();
//  this->_nh.advertise(chatter);
}

double* ROSController::getAttitude() {
  return new double[3]{0, 0, 0};
}

void ROSController::loop() {
//  str_msg.data = new char[] {"hello"};
//  chatter.publish( str_msg );
  this->_nh.spinOnce();
  delay(1000);
}

I don't understand what you are trying to do there. Some context would be nice - ideally some actual code that demonstrates just what you are trying to do (before and after maybe?)

I added my sample .ino and a little more of the backstory. It's really such a small issue so I was hoping I could keep the question just as simple but I suppose to be thorough you'll have to see the bigger picture.

And where are you trying to move that global variable to?

I've added my ROSController class to the bottom of the question

There's no such thing as a "protected" global variable. Protected variables belong inside classes.

The problem you are having is you are trying to both define and declare a class member variable at the same time. You can't. Instead you need to split it:
protected:
    ros::Publisher chatter;

ROSController::ROSController() : chatter("chatter", &str_msg)
{
    this->_nh.initNode();
//  this->_nh.advertise(chatter);
}

That is, set up the variable as a protected member, then have the constructor call the constructor for you with the right parameters.
(I think that is the right syntax off the top of my head).

Then your Publisher class has no default constructor. Add one.

Hey, that worked! I don't understand what you did on line 4. What is that called? I want to research it and find out more about it.

It's called an initialization list - you can read a little more about it here: http://www.tutorialspoint.com/cplusplus/cpp_constructor_destructor.htm

You can't call the constructor in the class definition. Example:
class foo
  {
  protected:
    String bar ("fubar");
  };

void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

That gives this error:
sketch_sep08b:4: error: expected identifier before string constant
     String bar ("fubar");
                 ^
sketch_sep08b:4: error: expected ',' or '...' before string constant
exit status 1
expected identifier before string constant

Instead declare the class (without the constructor) and call the constructor in the constructor for the parent class, like this:
class foo
  {
  protected:
    String bar;
  public:

    foo () : bar ("fubar") {};  // constructor
  };

void setup ()
  {
  }  // end of setup

void loop ()
  {
  }  // end of loop

authors: ปิยพงษ์ จันทร์ขาว


text:
code for automatic door
I want it running as a normal automatic door so both sensors work as a separate activate. The only problem I've seen is that the servo remains active waiting for another high read and you can hear the buzz of it trying to keep position.
It didn't used to do this before the code change. While its open, if it reads another high it will remember and rerun the open wait close after it closes.
Eg. The door activates and while open 3 people walk thru so when the door closes it will then run 3 more times with out anyone being there.
Edit: Code changed
    #include <Servo.h>

  Servo myservo;

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

  //amount of time we give the sensor to calibrate(10-60 secs according to       the datasheet)

  int calibrationTime = 30;

  int pirPin = 12; //digital pin connected to the PIR's output
  int pirPos = 13; //connects to the PIR's 5V pin
  int pirPin2 = 6; //digital pin connected to the PIR's output
  int pirPos2 = 10; //connects to the PIR's 5V pin
  const int position_closed = 0;      // door closed position [deg]
  const int position_open = 90;      // door open position [deg]
  const uint32_t delay_step = 15;     // delay between servo steps [ms]
  const uint32_t delay_open = 60000;  // how long the door stays open [ms]

  void setup()

  {
      myservo.attach(4); //attaches servo to pin 4
Serial.begin(9600); //begins serial communication
pinMode(pirPin, INPUT);
pinMode(pirPos, OUTPUT);
digitalWrite(pirPos, HIGH);
pinMode(pirPin2, INPUT);
pinMode(pirPos2, OUTPUT);
digitalWrite(pirPos2, HIGH);

//give the sensor time to calibrate
Serial.println("calibrating sensor ");
for(int i = 0; i < calibrationTime; i++)
{
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
}
Serial.println();
Serial.println("done");
  }

  void loop()
  {
static enum { CLOSED, OPENING, OPEN, CLOSING } state;
static int position;          // door position
static uint32_t last_change;  // last time state or position changed
uint32_t now = millis();

// When presence is detected, switch to the OPENING state.
if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
        && state != OPENING) {
    state = OPENING;
    last_change = now;
}
else switch (state) {
    case CLOSED:
        break;
    case OPENING:
        if (position == position_open) {
            state = OPEN;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(++position);
            last_change = now;
        }
        break;
    case OPEN:
        if (now - last_change >= delay_open) {
            state = CLOSING;
            last_change = now;
        }
        break;
    case CLOSING:
        if (position == position_closed) {
            state = CLOSED;
            last_change = now;
        } else if (now - last_change >= delay_step) {
            myservo.write(--position);
            last_change = now;
        }
        break;
      }
  }

Please edit your question to include what behaviour you DO see when it the code runs. e.g. Do you see the serial output expected during setup (calibrating sensor and SENSOR ACTIVE) ?

Are you trying to go from 0 to 180, delay, go from 180 to 90, delay, go from 90 to 0 ?   (i.e. 3 stages :- open, close partway, close fully, with delays between) ?

On top of what @KennetRunner said we need to know the expected behaviour: do you want any PIR to open the door or do you want both PIRs to detect something in order to open the door? Because you are in the second condition from the code above....

KennetRunner already explained what is wrong with your code. Here I will
try to give advice on the proper way to implement the automatic door.
First thing is to get rid of delay(). While your program is inside a
call to delay(), it can do nothing but wait until the delay is over.
This is acceptable if the program has only one single task to perform,
like blinking an LED. As soon as you have two tasks, delay() is a
nuisance because it blocks all the tasks.
Case in hand: after keeping the door open for one minute, your program
would close it, irrespective of whether there is someone in the way. It
could not see the person come because it was busy delaying the closing
of the door.
The standard way to get rid of delay() is to never wait inside
loop(). Instead, if there is something to do right now, do it; if
not, just don't do it, but do not wait. Pseudo-code:
void loop()
{
    if (it_is_time_to_do_foo()) {
        do_foo();
    }
    if (it_is_time_to_do_bar()) {
        do_bar();
    }
    /// etc...
}

You would use the millis() function to know when the time has
come to do some task, as explained in the Blink Without Delay
Arduino tutorial. This is really the second tutorial every Arduino user
should read, right after learning how to blink an LED.
Next, you have to learn how to implement a finite state machine. I
recommend the Finite State Machine tutorial by Majenko,
a regular contributor to this site.
Your problem can be very naturally mapped into a machine with four
states: CLOSED, OPENING, OPEN and CLOSING. You then write the rules
about what to do in each state, and when to transition to another state.
For example:

when the door is CLOSED

if the sensors detect someone, transition to the OPENING state

when the door is OPENING

if it's time to move the servo by one step, do it
if we have already moved all the way to the open position, we can
say the door is OPEN now

when the door is OPEN

if it's time to close it, transition to the CLOSING state
if the sensors detect someone, reset the timer <<<< note this!

when the door is CLOSING

if the sensors detect someone, transition to the OPENING state
if it's time to move the servo by one step, do it
if we have already moved all the way to the closed position, we say
the door is now CLOSED

A few things to note here:

See the line marked by “<<<<”: this will prevent the aforementioned
problem of the door closing into someone.
The first rule for the CLOSING state follows from a similar rationale.
I made up some of these rules, as the job of your program was not
completely specified in your question. Feel free to change those rules
to your taste.

And here is my proposed implementation. Warning: not tested. As
usual with FSMs, it is based on a big switch/case statement going
through all the possible states. However, to avoid repeating rules, I
factored the “if there is someone, start OPENING” rule out of the
switch. I also folded “if there is someone, reset the timer” into the
same rule.
const int position_closed = 0;      // door closed position [deg]
const int position_open = 180;      // door open position [deg]
const uint32_t delay_step = 15;     // delay between servo steps [ms]
const uint32_t delay_open = 60000;  // how long the door stays open [ms]

void loop()
{
    static enum { CLOSED, OPENING, OPEN, CLOSING } state;
    static int position;          // door position
    static uint32_t last_change;  // last time state or position changed
    uint32_t now = millis();

    // When presence is detected, switch to the OPENING state.
    if ((digitalRead(pirPin) == HIGH || digitalRead(pirPin2) == HIGH)
            && state != OPENING) {
        state = OPENING;
        last_change = now;
    }
    else switch (state) {
        case CLOSED:
            break;
        case OPENING:
            if (position == position_open) {
                state = OPEN;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(++position);
                last_change = now;
            }
            break;
        case OPEN:
            if (now - last_change >= delay_open) {
                state = CLOSING;
                last_change = now;
            }
            break;
        case CLOSING:
            if (position == position_closed) {
                state = CLOSED;
                last_change = now;
            } else if (now - last_change >= delay_step) {
                myservo.write(--position);
                last_change = now;
            }
            break;
    }
}

thanks for the code ive included it over what i had the only problem ive seen is that the servo remains active waiting for another high read and u can hear the buzz of it trying to keep position and while its open if it reads another high it will remember and rerun the open wait close after it closes

@ANDREW: I couldn't quite make a sense of your last comment. “the servo remains active [...] trying to keep position”: this is normal, and it's exactly what a servo is meant to do when you do not ask it to move elsewhere. “it will remember and rerun the open wait close”: I could not replicate the behavior you describe.

U can hear the constant buzzing noise it creates when running. the last code I used only made a noise when moving not when waiting for next high. I was thinking of adding detach at the end and attach at the start that might help

You expect the servo to be noisy when it's moving or when, in a static position, it is fighting some load. If static and unloaded, it shouldn't make much noise.

Your code is looping 180 times, EACH TIME it :

Sets the servo to 180
Delays for 2 seconds
Sweeps the servo from 180 to 90 in single steps
Sets the servo to 90
Delays for 60 seconds
Sweeps the servo from 90 to 180 in single steps

So you code will take more than 3 hours to complete.
I think you would be better pulling the code that moves the servo out into its own function: Something like:
void moveServo(servoStart, servoEnd, servoStep, servoInterval)
{
  for(int servoPos = servoStart; servoStart < servoEnd; servoStep)
  {
     myservo.write(servoPos);
     delay(servoInterval);
  }
}

then simply call it from your main loop, like this:
void loop()
{

    if((digitalRead(pirPin) == HIGH) && (digitalRead(pirPin2) == HIGH))
    {
      moveServo(0, 180, 1, 15);
      delay(2000);
      moveServo(180, 90, -1, 15);
      delay(60000);
      moveServo(90, 0, -1, 15);
    }
}


text:
Arduino is freezing during Serial.Print() while passing a char array
This problem is on an Arduino Due.
I am trying to populate a char array buffer that is receiving information over a serial port. I am reading the information off of the serial port and storing it into a buffer array and passing it back to the original function call.
First is the code that initializes the buffer and writes the data that the Serial requires in order to issue a response. This function compares many types of expected responses (uint32_t expect) and returns a confirmation as an int.
//Receive a cmd to send over serial and expect a certain response
int SendCommand(char * cmd, uint32_t expect){
  int cmdSuccess = 0, j=0;
  char buffer[500];
  memset(&buffer,0,sizeof(buffer)); //0 out the buffer
  Serial3.print(F(cmd));
  delay(500);

  Response(buffer);

  if (expect == EXPECT_OK){
    for(int i=0;i<sizeof(RESP_OK);i++){
      if(buffer[i]==RESP_OK[i]){ //RESP_OK is an example of a response of length 6
        j++;
    }
  }
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }
  else{return 0;}
  delete [] buffer;
}

void Response(char buffer[500])
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Data will be coming across serial3
  {
    char data = Serial3.read();
    buffer[index]=data;
    index++;
  }
    count++;
    delay(100);
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
  }

}

Edit: fixed the braces.
Right now, this code is hanging at the last part of Response right before break;. Am I having memory issues by the time it reaches the println at the end?
That last println was actually working until I began passing the buffer as a pointer and not returning it a char* and declaring void Response as char* Response. But the problem with this approach was that the buffer would reduce to sizeof(buffer) = 4 and would strip off the rest of the information when returned.
Edit: As Matt suggested down below, I declared a static const size_t bufferSize and pass it into the Response() call as well as passing in buffer as char*. Then I reset the buffer size by buffer = (char*)malloc(bufferSize).
What I still don't understand curious is the sizeof(buffer) after Response which is returning 4. However, 6 characters are stored into the array during Response. I've changed the pointer call to Response(char* buffer, const int size) with the following:
  if(index<size){
  buffer[index]=data;
  index++;
  }
  else{Serial.print(F("Buffer length exceeded!"));}

Thanks so much for your time!

What is that delete command for? 1) delete is c not c++ and should only be used to free something allocated with new and 2) that line is unreachable. Secondly you never check whether you're going past the end of your buffer (not an issue right now because of the incorrect } meaning you only ever get 1 byte) What if 501 bytes arrive before you time out?

Also when you pass a char* sizeof will always return 4 (or 8 on 64 bit systems) rather than the size of the buffer, you're asking it for the size of the pointer not the size of the buffer it's pointing to. The normal way to cope with this is to pass a pointer and also pass an integer value of the buffer size. That makes the buffer size known to the function without having to hard code it as part of the function parameters.

The 500 in the function's argument is meaningless and ignored by the compiler. If your timeout is supposed to be an inter-character timeout, then you're doing it wrong. You should clear 'count' in the IF block, if that is your intention.

I tried putting it in as @Andrew mentioned, by passing the buffer as a pointer separate to its buffer size. However, it's still only returning with a sizeof = 4, leaving off some of the chars that are being read into it.

Of course it's still returning a sizeof of 4, I said it will always do that. That's why you pass the size as a second parameter. Use that within the function and don't use sizeof.

Sorry, but there are quite a few issues with your code any of which may be contributing to your problem.

memset(&buffer,0,sizeof(buffer)); //0 out the buffer you are taking the address of a pointer and passing it to memset().  buffer is already a pointer of type char*.  Its working, because address of the pointer is the same address as buffer[0], but it is wrong and won't always work.
Serial3.print(F(cmd)); I have never used the F macro, but my understanding is it tells the compiler to store the string in flash memory.  cmd is a variable on the stack, a parameter to the function, so my guess would be the compiler is ignoring the F macro.
500 using a literal value in more than one place is opening you up to problems.  I think you should declare static const size_t BufferSize = 500;
void Response(char buffer[500]) It would be better to pass in a pointer to a char and the size as the parameter, (const char* pBuffer, const int& size) you can treat it the same within your function or you could pass a pointer to the next available item and then return the updated pointer.
1for(int i=0;i strlen(buffer))` then buffer can't contain RESP_OK (its quicker too).

Also the Response function won't compile, because you have too many closing braces (I assume its a copy and paste error).  This is the cause of you code hanging if(Serial3.available()) is inside a while(1) and there is no way of breaking out.  So if you just fix that you code will run.

About point 1: buffer is not a pointer, it's an array. The & does not make the array identifier decay to a pointer, thus &buffer is not the address of a pointer, it's the address of the array.

Yes, these are all good points. First, you are right about the copy-paste error and the hanging bracket, otherwise I'm sure the code wouldn't compile.
So it no longer freezes, and I modifies the buffer call to Response by passing it in as 'char*' (not a pointer) and 'size'. However, I'm still getting the problem when I call 'sizeof(buffer)' right after the call to response. It is reading in 6 characters into the array during 'Response', and when it resumes 'SendCommand' buffer has only a length of 4!

@EdgarBonet In c the name of an array without an index specifier is a pointer to the start of the array not the entire array. That's why sizeof(array) doesn't work within a function if the array is passed as a parameter, all that gets passed is a pointer.

@Andrew sizeof(buffer) will NEVER tell you how many bytes of data are in the buffer. Depending upon the scope it will either tell you the number of bytes allocated to buffer when it was created  (500 in this case) or it will tell you the size of a pointer. If you want to know how many bytes you've written to that buffer then you need to track the maximum index you have used to write data.

@Andrew (user 24459, not the OP) wrote: “In c the name of an array without an index specifier is a pointer to the start of the array”. This is incorrect. An array identifier represents the whole array. However, when you use the identifier in an expression, it does decay to a pointer to the first element, save for three exceptions. Taking the address of the array is one of these exceptions: there is no decay and you get the address of the array. C.f. the C FAQ about the equivalence of pointers and arrays.

I thought sizeof(buffer) was wrong but apparently it is correct.  It tells you the size of buffer in relation to the size of c single char.  However I looked this up as C++ and I don't think the same applies to C, but which language is this in?

The Arduino IDE compiles your program as C++, but whether it's C or C++ makes no difference for this array/pointer/sizeof issue.

I am having difficulties to follow your code due to indentation and additional braces which don't pair up correctly, but to me you are breaking out of the if(count == 50) statement through to the whole function as the while(1) statement was already closed.

Ok, thanks to the responses in this thread, I believe I have the solved the problem. There is a problem using sizeof(char*) when passing through arrays, so I used strlen(char*) instead. This code properly stores the messages of various sizes coming off of Serial3 and correctly compares them to the expected responses. The F() macro in Arduino is very useful in keeping the buffer free and, in general, I use it to print constants during debugging.
int SendCommand(char * cmd, bool resp_type, uint32_t expect){
delay(500);
  int cmdSuccess = 0, j=0, msgSize = 0;
  char * buffer;
  Serial3.print(F(cmd));
  Serial.print(F(cmd)); //Print to serial for debug purposes only
  delay(500);
  buffer = (char *)malloc(bufferSize);
  msgSize = Response(buffer, bufferSize);

  Serial.println("Buffer is: ");
  if (expect == EXPECT_OK){
    for(int i=0;i<msgSize;i++){
      if(buffer[i]==RESP_OK[i]){
        Serial.print(buffer[i],HEX);
        j++;
      }
    }
    Serial.print("\n");
    if(j==sizeof(expect)-1){Serial.print(F("\nGOOD RESPONSE!\n")); return 1;}
  }

  return cmdSuccess;
}

int Response(char* buffer, const int size)
{
  int index = 0; //message index;
  int count = 0; //used for timeouts
  while(1)
  {
  if(Serial3.available()) //Message will be coming across serial3
  {
    char data = Serial3.read();
      if(index<size){
        buffer[index]=data;
        index++;
      }
      else{Serial.print(F("Buffer length exceeded!"));}
  }
    count++;
    if(count == 50){
    Serial.println(F("\nEnd of Response"));
    break;
    }
  } return index;
}


text:
Using VMA-02 / KA-02 Sound Shield to get line-in input on arduino
I bought this VMA-02 audio shield: http://www.velleman.co.uk/contents/en-uk/p623_vma02.html
I want it to get the data from line-in to line-out but with reading it in my arduino scetch first (e.g. for analysis later).
There's a example project to download here: http://www.apogeekits.com/Zip_Files/ka02-sample-code.zip
But I don't know whether it's possible to get the sound input anyway and if yes, with which pins I can read the input / write the output?


text:
How to count the number of button presses then play a sequence?

When I press the button once, sequence s1() plays.
When I press the button twice, sequence s2() plays.
When I press the button thrice, sequence s3() plays.
When I press the button 4 times, sequence s4() plays.

const int buttonPin = 10;
int buttonState = 0;

void setup(){
  Serial.begin(9600);
  //initialize pin 2 - 9 as output
  for(int i=2;i<=9;i++){
    pinMode(i,OUTPUT);
  }
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    s1();
    s2();
    s3();
    s4();
  }
}

void s1() {
  int i = 2 ;
  for(int z=0;z<=1;z++) {
    for(int x=i;x<=9;x++) {
      digitalWrite(i,HIGH);
      digitalWrite(x-1,LOW);
      delay(500);
      i = i + 1;
    }
    i = 2;
    if(i = 2) {
      digitalWrite(9,LOW);
    }
  }
}

void s2(){
  int y = 9;
  for(int i=0;i<=1;i++) {
    for(int x=2;x<=5;x++) {
      if(y>=1) {
        digitalWrite(x,HIGH);
        digitalWrite(y,HIGH);
        delay(500);
        y = y - 1;
      }
    }
    off();
    y = 9;
    delay(500);
  }
}

void s3() {
  for(int i=0;i<=2;i++) {
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 == 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,HIGH);
      }
    }
    delay(500);
    for(int z=2; z<=9;z++) {
      if(z % 2 != 0) {
        digitalWrite(z,LOW);
      }
    }
    delay(500);
  }
}

void s4() {
  for(int i=0;i<=2;i++) {
    for(int x=2;x<=9;x++) {
      digitalWrite(x,HIGH);
      delay(500);
    }
    off();
    delay(500);
  }
}

void off() {
  for(int i=2;i<=9;i++) {
    digitalWrite(i,LOW);
  }
}

You should tell us the preblem you are having.

You didn't like my solution on [so] so you have to crosspost this question here?

Someone suggested on his question http://stackoverflow.com/questions/39388020/arduino-count-the-number-of-button-press-then-play-sequence/ that he take it here. However cross-posting is normally discouraged.

That's not that complex, please have a look at the following code: not the most elegant solution ever, but should be working (I didn't compile it as I'm currently on launch break in the office)
#define LONGEST_PAUSE 1000
unsigned long lastClick;
unsigned int counter;

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    // button is pressed
    while(digitalRead(buttonPin) == HIGH)) {
      delay(1); // wait until button released
    }
    lastClick = millis();
    counter++;
  }
  if (counter > 0 && (millis() - lastClick) >= LONGEST_PAUSE) { // 1s passed since last click: let's play!
    switch(counter) {
      case 1:
        s1(); break;
      case 2:
        s2(); break;
      case 3:
        s3(); break;
      case 4:
        s4(); break;
      default:
        // what if I keep clicking?!?
    }
    counter = 0; // reset the counter
  }
}

is there a way to break the loop when i press the button when the loop is running?

The OP apparently wishes to (and I'm quoting him) "break the loop when I press the button the the loop is running"
While this might be a question on it's own...
NO, if you exit the loop() function then (by default) your Arduino stops doing anything and just sits there dissipating energy into heat, not much though. With some little effort you can instruct it to reboot.

If my answer solved the problem stated into your question you should accept it and create a new question accordingly to your updated needs.

I prefer you to use pinchange interrupt or simple INT0 interrupt for the buttons to count the press.
Check this link.
on ISR, you can count the press.
int count=0;

void setup() {
  pinMode(interruptPin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(interruptPin), countFn, CHANGE);
}

void loop() {
  switch(count){
      // all cases here
  }
  count=0;
  delay(2000); // this delay is important to give enough time for a number of presses for the user
}

void countFn() {
  count++;
}


text:
Coin Acceptor CH-925 Pulse
I got a problem where pulse voltage from acceptor is about 20mV. How can I solve my problem? and I can't detect the pulse using arduino uno.
please any one can help ?

Output seems kind of low... Are you powering it with +12 volts?

yes I power it with +12v adapter and 1 A , it is a big problem to me since that this module doesn't exist in my country , and I wait 1 month to got it .Is their any solution?

I don't know- it just seems odd that the output voltage is 20mv. I think you've either miswired it or you have a defective unit. Check the documentation to see what output voltage you should expect.

I'm now trying to amplify this value to 5V Is this right ? or I must buy another one ?

From this Amazon review:

There are 'live' (12V), 'ground' and 'signal' wires coming out of the
  back. Live and ground are pretty self-explanatory, and need to be
  connected to a 12V supply - I bought a simple 1A DC one. The final
  wire says 'signal', and needs to be connected to your circuit as input
  into a GPIO pin in the case of a raspberry pi. It produces a pulsing
  5V signal (Why not tell us it will be 5V somewhere in the
  documentation? Luckily I have a multimeter) as a way of encoding which
  type of coin it has encountered. However, raspberry pi's only want
  3.3V signals as inputs, so you'll be wanting to make a voltage divider (With a couple of resistors - I used 33k and 18k) to safely bring that
  5V pulse down to 3.3V. (http://en.wikipedia.org/wiki/Voltage_divider)
  You'll also want to connect the ground from the device to a ground on
  your Raspberry Pi, or the signal won't work. I did this by splicing
  the ground cable from the power supply so that it has 2 ends - 1 for
  the power supply to the unit, and one for the unit to the Raspberry Pi
  Circuit.

It seems that a 5v pulse is the expected output. How are you measuring the output? You'll need a 'scope rather than a multimeter measuring voltage...
Anyway, I would not try to 'amplify' the signal, I would look to check the connections are correct and if that's not the issue, I would return the unit as defective.

I wonder if the output is actually an "open collector" type that needs a pull up resistor to 5V before you see a proper pulse. Pull-ups can be configured on the AVR input pins - which the Amazon reviewer may have done on his GPIO pin - or an external resistor could be used. Regards,

good point @Michael Vincent +1

I connected the signal to an arduino and programmed the unit  just like the videos in YouTube, the arduino cant read the signal, then I tried to detect the signal using oscilloscope, I spent 1 week on trying many solutions all of them failed, then the last thing I'm going to do is to amplify the value to 5 V, I'm wondering if their is any possible solution !

what do you mean with "scope"  You'll need a 'scope rather than a multimeter measuring voltage... ?

and the big problem is that this unit isn't available in my country and I waited about one month to get it form outside!! and bringing anther one will be time consuming .

Make sure you're looking at the signal reference the power supply ground. If your ground is floating then you won't see anything (or 20mv). If you have three wires- 12v, Gnd, and Signal, then you also need to connect the power supply ground to the arduino in order to see any signal out of the coin acceptor. Check this by connecting your meter ground to the power supply ground, and your meter + to the signal out.

Correction... Use your scope, not a meter. The coin value encoding is a pulse train (I gather) and you may not see it correctly with a meter.

I checked all connections and they are as you said, I connected the signal wire (white wire ) to analog input 0 (A0) and I read the value , it is about 7 when nothing is inserted and it's 27 when a coin is inserted ! I tried to fix the problem in code , but unfortunately all this doesn't seem to work !  what to do in this case ? Is it good option to amplify the value to 5v ?

authors: محمود عبد الكريم


text:
Can't upload to Arduino UNO (kuman UNO)
I am trying to upload my code to my new Arduino (Just got one today, so im very new).
I can compile my code with no problems, but uploading it gives me:
[Arduino: 1.6.11 (Mac OS X), Board: "Arduino/Genuino Uno"

Sketch uses 1,186 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
chmod: Unable to change file mode on /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Read-only file system
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: Permission denied
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0
/private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude: line 6: exec: /private/var/folders/md/s6pczlkd6gq8ylyh13z_3z8r0000gn/T/AppTranslocation/0D981E7A-E386-4AFD-9AEC-35E9ED8DA180/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude_bin: cannot execute: Undefined error: 0

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

It doesn't matter what i upload (tried to upload some of the examples).
As said i am very new, so if you need any more information to help me just ask.
Thanks in advance!

Please format your question appropriately. In this case the big block you copy-pasted here should be contained within a code block (the button with two curly brackets {})

Drag Arduino.app out of your ~/Downloads folder to /Applications or anywhere else that isn't where you downloads it to. The app is being subjected to Gatekeeper Path Randomization which means it is running on a read-only file system. The app is trying to chmod something inside the app bundle and thats not possible on a read-only file system.

Thank you! I didn't know that this was a thing ;)

Check your port to which your arduino is connected. The port name can be checked from Arduino IDE. Click Tools -> Port -> There you can find the port name.
Open Terminal and type the following command.
sudo chmod 777 /dev/port_name

After this try to Recompile/Upload the code again.

i ran sudo chmod 777 /dev/cu.usbmodem1411. Still same problem.

Are you sure? You are using correct port name?Try dmesg | grep tty
to list all Serial Device Converter

Try to run your Arduino IDE with super user privileges,  because the  compilation log shows most of the errors are related to inadequate rights of writing/executing on files.

I ran sudo /Users/madsankernielsen/Downloads/Arduino.app/Contents/MacOS/Arduino and now it won't even compile it. Am i doing it right?


text:
Trying to Serial.write RAW code properly
I have a SIM800L Module connected to my arduino Nano. I want to open a TCP connection from the sim800l module to my own server and send a text string. The connection is working however I am not able to send text, because there is an issue with the arduino write() function I think... Below is the code I am trying to execute. Right after the message is sent, I need to send the stop value 0x1A (byte 26) to tell the sim800l module that the message end is reached and to send out the message.
My problem is, that it is not working in the arduino IDE and I don't know why.
My arduino code:
#include <SoftwareSerial.h>

#define SIM800_TX_PIN 8
#define SIM800_RX_PIN 7

SoftwareSerial serialSIM800(SIM800_TX_PIN, SIM800_RX_PIN);

void setup() {

serialSIM800.println("AT");
delay(500);

serialSIM800.println("AT+CIPSTART=\"TCP\",\"IP-ADRESS-HERE\",\"9999\""); //connection works
delay(500);

serialSIM800.println("AT+CIPSEND");
delay(500);

serialSIM800.print("TEXT MESSAGE HERE");
delay(500);

serialSIM800.write(26);
delay(500);

serialSIM800.println("AT+CIPCLOSE");
delay(500);
}

void loop() {
  //Empty
}

On my server I am running this python script that opens a socket:
import socket
import sys

HOST = ''   # all available interfaces
PORT = 9999 # Arbitrary non-privileged port

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#Bind socket to local host and port
try:
  s.bind((HOST, PORT))
except socket.error as msg:
  print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
  sys.exit()

print 'Socket bind complete'

#Start listening on socket
s.listen(10)
print 'Socket now listening'

#now keep talking with the client
while 1:
  #wait to accept a connection - blocking call
  conn, addr = s.accept()
  print 'Connected with ' + addr[0] + ':' + str(addr[1])
  data = conn.recv(1024)
  print len(data)
  print data
s.close()

Once I execute this, I see the connection is working because "Connected with IP:PORT" is printed on my console. However right after that "len(data)" is printed (0) and "data" is an empty string. I even upped the delay from 500 to 5000, still same result.
However, if I leave the arduino IDE and send the message using the program "HTerm", it is working! In HTerm I typed in the text message and hit enter. After that I switched from ascii to hex mode (there is a checkbox) and I just typed 1A and sent it. That way it worked. Anybody can help me? Why is it not working @arduino?

After typing 1A into HTerm hex mode, did you hit ENTER?

Yes I hit Enter and it worked in HTerm.

Replace serialSIM800.write(26); with serialSIM800.write(0x1A);, also  change serialSIM800.print("TEXT MESSAGE HERE"); with a println or add a carriage return \n.

good idea. I already tested this. serialSIM800.write(0x1A) didn't help and I even replaced all println with print and added a \n to the end of each string. That all didnt work... even with \r\n it didnt work.


text:
Performance tuning PORTB manipulation - mask
I have the following snippet that seems to be taking a total of 6 CPU cycles per invocation.
Can I speed this up somehow? x  is a byte with the 3 lowest bits set.
#define SET_COLOR(x) PORTB = (PORTB & ~(7)) | x

@TisteAndii: Interesting suggestion, but it ends up using an identical amount of instructions. I assume the compiler is smart enough.

@tisteandii compilers are smart enough to do this for you.

@Gerben So I gathered. Dont know much about the optimizations they perform.

4 cycles:
IN Rd,PORTB
CBR Rd,7
ORI Rd,x
OUT PORTB,Rd

Translation into proper GCC inline assembly syntax is left as an exercise for the reader.

Thanks. In the end (with some proper analysis) it showed the original code was resulting in exactly 4 instructions, as well.


text:
Voltage increasing when charging a battery using arduino
I am making a solar charge controller using Arduino. So for starting, I thought I should calibrate the voltage so that I am able to read the exact voltage of battery and solar charger. For testing purposes, I do not have any solar panel, so I used a 12V power supply and set its output voltage to 13.56. I used the following calculations for getting exact voltage:
float solarData = 0;
float batData = 0;
float batScale = 0;
float solarScale = 0;
float batPinVolt = 0;
float solPinVolt = 0;
float batVolt = 0;
float solVolt = 0;

Vcc = readVcc()/1000.00;    //getting the exact voltage of arduino
Serial.print(Vcc);
solarScale = analogRead(A0);  //reading solar analog data
batScale = analogRead(A1);    //reading battery analog data
solPinVolt = (solarScale/1024.0) * Vcc;
solVolt = solPinVolt * (9.80 + 2.168)/2.168;    //I used 10k & 2.2k so entered their exact value
batPinVolt = (batScale/1024.0) * Vcc;
batVolt = batPinVolt * (9.80 + 2.168)/2.168;

Initially, I faced few problem regarding the exact voltage of the Arduino which I used as a reference voltage to calculate voltage. But then I found a solution here. So below is the code which calculate the voltage of Arduino
long readVcc()
{
  long result;
  // Read 1.1V reference against AVcc
  ADMUX = _BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1);
  delay(2); // Wait for Vref to settle
  ADCSRA |= _BV(ADSC); // Convert
  while (bit_is_set(ADCSRA,ADSC));
  result = ADCL;
  result |= ADCH<<8;
  result = 1125300L / result; // Back-calculate AVcc in mV
  return result;
 }

Now when I uploaded the code, I got the exact values of the voltages.
Now I wrote a logic where if the battery voltage is less than 12V then start charging until it is above 13V. Following is the code:
if((solVolt > batVolt)&& ( batVolt <= 12.00 ))
{
digitalWrite(chargePin,HIGH);  //enable charging
digitalWrite(loadPin,LOW);     //load off
}
else if((solVolt > batVolt)&&(batVolt > 12.00)&& (batVolt <= 13.00 ))
{
 digitalWrite(chargePin,HIGH);   //enable chargin
 digitalWrite(loadPin,LOW);      //load off
}
// // shut down when battery is fully charged or when sunlight is not enough
else if ((batVolt > 13.00) or (solVolt < batVolt))
{
 digitalWrite(chargePin,LOW);    //disable charging
 digitalWrite(loadPin,HIGH);     //load on
}

But when I uploaded the code, the Arduino started showing wrong values of the voltages. Power supply was set to 13.5, but it showed 13.15 and battery voltage was 11.8, but it showed 12.7.
Now due to this what exactly happened was it started charging so the value of battery voltage 12.7 (which is wrong) started increasing. When it was above 13V, Arduino turned off the chargePin. So when the chargePin is low, it shows the exact battery voltage which is low so it again started charging it and this loop keeps on going. This is all because of the wrong values of voltages. Following is the schematic:

I am following the article I found on Instructables. (cannot post more links due to reputation). I want to know why there is change in voltage. Can anyone please help me on what I am doing wrong.

And now you know why you need to stop charging when reading the voltage.

@IgnacioVazquez-Abrams I am trying to stop the charging by setting the chargePin to low which will turn off the transistor. But when the charging stops it shows the exact value of battery voltage which is lower than what arduino shows. So it again charging it rather than cut off. I want to know why it shows wrong values.

What tolerance are the resistors in the voltage divider?

What are those variable data types? Float?

@IgnacioVazquez-Abrams Resistor values are R1=10k R2=2.2k.

@NickGammon Yes all the variables are float. I have edited the code

Not the values, the tolerance.

@IgnacioVazquez-Abrams I guess the tolerance is 10% as the last color in the resistor is silver.

Now that you know the tolerance you can figure out just how terrible your voltage divider is.

@IgnacioVazquez-Abrams yes you are right. I never thought about this. So I should use resistance with 1% or 2% tolerance which might give correct values. Am I right.?

You need to use resistors with equal or better tolerance than the voltage you need to maintain. You also need to determine the exact value of the bandgap reference in the chip itself.

@IgnacioVazquez-Abrams I didnt get you by bandgap reference. Please explain.

There may be a voltage drop acros the wires (and fuse) running to and from the battery. One solution to this is to have separate wires going directly to the battery for measuring the voltage.

In order to charge a battery you have to apply a voltage to the battery terminals that is higher than the batteries own internal voltage. That's pretty much the definition of charging a battery.
Basically you're trying to do the impossible, you can't measure the batteries off charge voltage while charging it because as soon as you start charging the voltage at that point changes.
When charging your supply is 3.5V and your supply measurement is 13.15. That means you're loosing 0.35V in battery cables and F1.
The battery voltage is 12.7V so that's 0.45V loss in D1 and Q1.
That first loss seems too high and the second one too low, D1 should drop typically drop 0.58V, so you may have some resistor tolerance or noisy reading issues. The total voltage drop seems reasonable but the split looks wrong.
The best solution to what your are trying to do is to measure the charge current.
Move D1 to the other side of R1 so there is no diode drop between your two voltage measurements and add a small resistor in series where D1 used to be. The difference between the two measured voltages and the resistance between those points now tells you the charge current. Stop charging when the current drops below a certain threshold. Larger resistors make it easier to measure accurately but have an obvious efficiency hit, make sure you check the resistors power rating.
You may be able to avoid adding the resistor and simply use the on resistance of Q1 as your resistor. This will be a little variable between devices so it's not suitable for mass production but for a one off it should be good enough as long as it's not too small for you to measure the current accurately.
One further note: With a supply of 13.5V you will never get the battery to 13V. You have a diode in there with a 0.6V drop so the highest you could get is 12.9V. On the plus side this means you can keep charging until the current drops to 0 with no risk of overcharging.
Or alternatively switch D1 for a schottky diode with a drop of around 0.2V

I made my circuit according to the schematic which I have posted but there were few things which I was doing wrong. After your suggestions I have made few changes. Now at least I am getting accurate voltage. I want to know how to measure the actual voltage when the battery is charging. As you said, when we connect battery to solar/power supply, its voltage increase, if it was 11 v, then it started showing 12v. So in code also it will consider it as 12v. Then how can we measure the actual battery voltage while charging..? I need this because I also need to protect the battery....

...the battery from overcharging. If it will show voltage other than actual voltage, then I guess its impossible to measure its voltage. Is there any way of protecting the battery from overcharging.??

You can't charge unless you apply a voltage greater than the batteries voltage to its terminals. Which means it is impossible to know for sure the voltage you will measure when you remove the charge voltage. It may be possible to estimate what it will be as a function of charge voltage and charge current but that won't be perfect. If you want to prevent overcharging then limit the charge voltage to the maximum battery voltage and charge until the charge current is almost zero.

Lets say I have set max voltage to be 13v. Current battery volt is 11v. So as soon as I start charging, MOSFET conducts and battery volts increases to 12v(lets say). So it will charge till 13v and stop charging. When no charge voltage, actual battery volt has increase from 11v to 12v so it will again start charging. How to handle this condition.

If you charge to the point where there is no charge current flowing then the voltage you are measuring will be the batteries at rest voltage. If there is still a charge current then the amount the battery voltage will drop will be roughly proportional to the charge current.  You need to stop thinking purely about voltages, you need to take the current into account.


text:
How to make PCA9685 work with Arduino Due?
I have Arduino Due and PCA9685.
I use this library:
https://github.com/adafruit/Adafruit-PWM-Servo-Driver-Library
The board does not do anything with servo connected. I tried to use SDA/SCL pins and SDA1/SCL1 pins, I tried to use or not use pullup resistors. The board does not react in any case.
The PCA9685 is 100% working, because it operates properly when I connect it to my Arduino Mega using the same library, it works without pullups.
Also I noticed the following indicium, when I tried to use  this scanner
http://playground.arduino.cc/Main/I2cScanner I have no detected devices on SCL1/SDA1 but have detected 2 devices at 0x40 and 0x70 when I connect the board SDA/SCL pins.

I made it working by this way: despite PCA9685 datasheet recommendations, we do not need to connect OE pin to VCC. Also we do not need to connect OE to ground as it recommended in some instructions related to other Arduinos.
So we should leave OE pin unconnected.
Also we should use 4,7K pull-up resistors to connect SDA and SCL to VCC.
The board can be used without level converters.
No special program/libraries changes needed. So it was a hardware problem.


text:
7-segment display code
What is the meaning of BitSet = bitRead(numeral[number], segment);?
const byte numeral[10] = {
  //ABCDEFG /dp
  B11111100,  // 0
  B01100000,  // 1
  B11011010,  // 2
  B11110010,  // 3
  B01100110,  // 4
  B10110110,  // 5
  B00111110,  // 6
  B11100000,  // 7
  B11111110,  // 8
  B11100110,  // 9
};

// pins for decimal point and each segment
//                          dp,G,F,E,D,C,B,A
const int segmentPins[8] = { 5,9,8,7,6,4,3,2};

void setup()
{
  for(int i=0; i < 8; i++)
  {
    pinMode(segmentPins[i], OUTPUT); // set segment and DP pins to output
  }
}

void loop()
{
  for(int i=0; i <= 10; i++)
  {
    showDigit(i);
    delay(1000);
  }
  // the last value if i is 10 and this will turn the display off
  delay(2000);  // pause two seconds with the display off
}

// Displays a number from 0 through 9 on a 7-segment display
// any value not within the range of 0-9 turns the display off
void showDigit( int number)
{
  boolean isBitSet;

  for(int segment = 1; segment < 8; segment++)
  {
    if( number < 0 || number > 9){
      isBitSet = 0;   // turn off all segments
    }
    else{
      // isBitSet will be true if given bit is 1
      isBitSet = bitRead(numeral[number], segment);
    }
    isBitSet = ! isBitSet; // remove this line if common cathode display
    digitalWrite( segmentPins[segment], isBitSet);
  }
}

Do you now about chips like the Max7219?  It will help you handle a number of 7 segment displays (up to 8).

bitRead(x, y) takes a value x, and looks at bit number y.
So, if:

y is the number 2;
x is 53 (binary number 0 0 1 1 0 1 0 1)

                                       ^

it looks at bit #2. Bits are counted from the right starting at 0 - I have indicated the bit in question above.
So, bitRead(53, 2) would return 1, since bit #2 in 53 is a 1.
In the above program, the clever programmer has coded whether to light or not light the LED for each segment of the display in a single byte for each possible number to display. The digit 8 has all seven of its LEDs lit up, so you'd expect the encoding for 8 to have lots of binary 1s in it - and sure enough, it does (B11111110)! And the digit 7 has only three segments lit up, so you'd expect only 3 bits to be set. Sure enough, B11100000.
The comment at the top describes what each of the bits represent - the last bit is the decimal point, which is never set...


text:
Nano resets or freezes on calling a function
I'm controlling a light bulb with my Arduino Nano from serial or RF (via nRF24L01+) and I'm passing the commands as a string. After I get all the variables (3 ints) I try calling the function execOrder but no matter what I put in there, the Arduino just hangs or resets. Code is as follows:
#define SSR 3
#define SW 4
#define nanoID 1
bool isPWM = false;
int value;

// Módulo RF
#include <SPI.h>
#include "nRF24L01.h"
#include "RF24.h"
#include "printf.h"
RF24 radio(9,10);
const uint64_t pipes[2] = { 0xF0F0F0F0E1LL, 0xF0F0F0F0D2LL };
#define PayLoad 20

#include <MemoryFree.h>

void setup() {
  pinMode(SSR, OUTPUT);
  pinMode(SW, INPUT_PULLUP);
  digitalWrite(SSR, LOW);
  value = 0;
  Serial.begin(9600);
  Serial.println("------ CEACI SAS -- Controller Module ------");
  Serial.println("Module No: " + String(nanoID));
  // Inicializar RF
  Serial.println("Inicializando RF");
  radio.begin();
  radio.setRetries(15,15);
  radio.setPayloadSize(PayLoad);
  radio.setPALevel(RF24_PA_MIN);
  radio.setDataRate(RF24_250KBPS);
  radio.setCRCLength(RF24_CRC_16);
  delay(100);
  radio.openWritingPipe(pipes[1]);
  radio.openReadingPipe(1,pipes[0]);
  radio.startListening();
  //radio.printDetails(); //RF Debug
  Serial.println("RF listo!");
  Serial.print("freeMemory()=");
  Serial.println(freeMemory());
}

void loop() {
  if (Serial.available()) {
    Serial.println("Rcvd Serial!");
    String msgRcvd = Serial.readString();
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    String msgRcvd(msgBuff);
    int ID = msgRcvd.substring(4,5).toInt();
    int cmdCode = msgRcvd.substring(10,11).toInt();
    int cmdVal = msgRcvd.substring(16).toInt();
    //Serial.println("ID: "+String(ID)+", CMD: "+String(cmdCode)+", VAL: "+String(cmdVal));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    //execOrder(ID,cmdCode,cmdVal);
  } else {
    chkSwitch();
  }
}

void execOrder(int ID, int CMD, int VAL){
  if (ID == nanoID || ID == 0){
    switch(CMD){
      case 0:
        State();
        break;
      case 1:
        value = VAL;
        OnOff();
        break;
      case 2:
        value = VAL;
        PWM();
        break;
    }
  }
}

I wanted to process the incoming string in a function, but it resets as well.
By the way, I'm using MemoryFree library to check if I'm out of memory, and there's plenty of it, so I don't really know where's the problem. Any help would be greatly appreciated!
EDIT:
For the serial part I can do the following (my original code):
if (Serial.find("MOD=")) {
  int ID = Serial.parseInt();
  if (ID == nanoID || ID == 0) {
    Serial.find("CMD=");
    int command = Serial.parseInt();
    int cmdVal = 0;
    if (command != 0){
      Serial.find("VAL=");
      cmdVal = Serial.parseInt();
    }
    Serial.println("MOD: "+String(ID)+", CMD: "+String(command) + ", VAL: " + String(value));
    Serial.print("freeMemory()=");
    Serial.println(freeMemory());
    execOrder(ID,command,cmdVal);
  }
}

And it works flawlessly. But I don't know how to achieve the same results with the RF input. The problem seems to be with using so many strings.

Your problem is not due to memory shortage, but because you are erroneously using pointers.
Even with your fix you are doing the same mistake, you are just not incurring into the same problem by luck as you are not addressing anything new after the bad definition of your variable msgBuff.
Putting all that into simple terms, you should change your code and probably read some articles on C pointers as it looks like you have a Java background (like me).
Your issue is in the char msgBuff[]=""; statement which should be moved after the the call to obtain the payload size and turned into char msgBuff[RFlen];:
int RFlen=radio.getDynamicPayloadSize();
char msgBuff[RFlen];
delay(10);
radio.read(&msgBuff, RFlen);

Ok, I solved it like this:
if (radio.available()){
    int RFlen=0;
    char msgBuff[]="";
    RFlen = radio.getDynamicPayloadSize();
    delay(10);
    radio.read(&msgBuff, RFlen);
    int ID = msgBuff[4] - '0';
    int cmdCode = msgBuff[10] - '0';
    int cmdVal = msgBuff[16] - '0';
    if (cmdCode == 2){
      cmdVal *= 100;
      cmdVal += 10*(msgBuff[17]-'0');
      cmdVal += (msgBuff[18]-'0');
    }
    execOrder(ID,cmdCode,cmdVal);
}

The problem is with using strings, but I don't know why since there's plenty of memory. Anyway, I hope this helps anyone else with the same issue.