text:
Random output on decoding time from LTC audio using arduino UNO
I am a newbie in Arduino and I am trying to decode time from ltc audio. For this I got Arduino UNO.
I got a sample code from here.. Here my code:
#define icpPin 8        // ICP input pin on arduino
#define one_time_max          588 // these values are setup for NTSC video
#define one_time_min          422 // PAL would be around 1000 for 0 and 500 for 1
#define zero_time_max          1080 // 80bits times 29.97 frames per sec
#define zero_time_min          922 // equals 833 (divide by 8 clock pulses)

#define end_data_position      63
#define end_sync_position      77
#define end_smpte_position     80

volatile unsigned int bit_time;
volatile boolean valid_tc_word;
volatile boolean ones_bit_count;
volatile boolean tc_sync;
volatile boolean write_tc_out;
volatile boolean drop_frame_flag;

volatile byte total_bits;
volatile byte current_bit;
volatile byte sync_count;

volatile byte tc[8];
volatile char timeCode[11];

/* ICR interrupt vector */
ISR(TIMER1_CAPT_vect)
{
 //toggleCaptureEdge
 TCCR1B ^= _BV(ICES1);
  //Serial.println("Inter");
 bit_time = ICR1;

 //resetTimer1
 TCNT1 = 0;

if ((bit_time < one_time_min) || (bit_time > zero_time_max)) // get rid of anything way outside the norm
 {
   //Serial.println(bit_time, DEC);
   total_bits = 0;
 }
 else
 {
   if (ones_bit_count == true) // only count the second ones pluse
     ones_bit_count = false;
   else
   {
     if (bit_time > zero_time_min)
     {
       current_bit = 0;
       sync_count = 0;
     }
     else //if (bit_time < one_time_max)
     {
       ones_bit_count = true;
       current_bit = 1;
       sync_count++;
       if (sync_count == 12) // part of the last two bytes of a timecode word
       {
         sync_count = 0;
         tc_sync = true;
         total_bits = end_sync_position;
       }
     }

     if (total_bits <= end_data_position) // timecode runs least to most so we need
     {                                    // to shift things around
       tc[0] = tc[0] >> 1;

       for(int n=1;n<8;n++)
       {
         if(tc[n] & 1)
           tc[n-1] |= 0x80;

         tc[n] = tc[n] >> 1;
       }

       if(current_bit == 1)
         tc[7] |= 0x80;
     }
     total_bits++;
   }

   if (total_bits == end_smpte_position) // we have the 80th bit
   {
     total_bits = 0;
     if (tc_sync)
     {
       tc_sync = false;
       valid_tc_word = true;
     }
   }

   if (valid_tc_word)
   {
     valid_tc_word = false;
/*
     timeCode[10] = (tc[0]&0x0F)+0x30;      // frames
     timeCode[9] = (tc[1]&0x03)+0x30;      // 10's of frames
     timeCode[8] =  '.';
     timeCode[7] = (tc[2]&0x0F)+0x30;      // seconds
     timeCode[6] = (tc[3]&0x07)+0x30;      // 10's of seconds
     timeCode[5] =  ':';
     timeCode[4] = (tc[4]&0x0F)+0x30;      // minutes
     timeCode[3] = (tc[5]&0x07)+0x30;      // 10's of minutes
     timeCode[2] = ':';
     timeCode[1] = (tc[6]&0x0F)+0x30;      // hours
     timeCode[0] = (tc[7]&0x03)+0x30;      // 10's of hours
*/

         timeCode[9] = ((tc[0]&0xF0)>>4)+0x30; // user bits 8
       timeCode[8] = ((tc[1]&0xF0)>>4)+0x30; // user bits 7
       timeCode[7] = ((tc[2]&0xF0)>>4)+0x30; // user bits 6
       timeCode[6] = ((tc[3]&0xF0)>>4)+0x30; // user bits 5
       timeCode[5] = '-';
       timeCode[4] = ((tc[4]&0xF0)>>4)+0x30; // user bits 4
       timeCode[3] = ((tc[5]&0xF0)>>4)+0x30; // user bits 3
       timeCode[2] = '-';
       timeCode[1] = ((tc[6]&0xF0)>>4)+0x30; // user bits 2
       timeCode[0] = ((tc[7]&0xF0)>>4)+0x30; // user bits 1

       drop_frame_flag = bit_is_set(tc[1], 2);

     write_tc_out = true;
   }
 }
}

void setup()
{
 Serial.begin(9600);
 pinMode(8, INPUT);                  // ICP pin (digital pin 8 on arduino) as input

 bit_time = 0;
 valid_tc_word = false;
 ones_bit_count = false;
 tc_sync = false;
 write_tc_out = false;
 drop_frame_flag = false;
 total_bits =  0;
 current_bit =  0;
 sync_count =  0;

 Serial.println("Finished setup ");
 delay (1000);

 TCCR1A = B00000000; // clear all
 TCCR1B = B11000010; // ICNC1 noise reduction + ICES1 start on rising edge + CS11 divide by 8
 TCCR1C = B00000000; // clear all
 TIMSK1 = B00100000; // ICIE1 enable the icp

 TCNT1 = 0; // clear timer1
}

void loop()
{
  if (write_tc_out)
   {
     write_tc_out = false;
     //if (drop_frame_flag)
       //Serial.print("TC-[df] ");
     //else
       //Serial.print("TC-[nd] ");
     Serial.print((char*)timeCode);
     //Serial.print("\r");
   }
}

I am generating LTC audio from this link. On running my code I am getting this output:-
Finished setup
?>-00-0000??-??-77=??>-??-;?????-??-?>???>-:?-=????>-??-?=???>-;=-??5>?>-;=-??=7?>-?;-??=>?>-?:-??=7?>-;=-??>??>-;;-??=7??-?=-=7?>?>->7-?????>-;;-??=7?>-;>->??:??-?=-7????>-;?-??5>?>-;?-?=?>??-?=-?7>??>-7:-?67=?>-;?-???5?>-;=-7?==?>-;;-??=7?>-7=-??>>?>-:?-7????>-;=-?;;=??-?=->?=5?>-;=-???=?>-;?-?=5>??-?;->=???>-?>-7>;???-?;->????>-;?-?7=??>-;>-??>;?>-;=-;?5>?>-??-=7;7?>-;=-;?=??>-;=-??=7?>-;=-??:??>->7-=?????-?7-=?>>?>-?6-??;>?>-7;-???=?>-??-;=???>-;=-?7=7?>-?=-??>;?>-:?->??

So, can anyone one tell me where is mistake.

((tc[0]&0xF0)>>4)+0x30

Will generate values in the range x30 to x3F, which are 0 to 9 :;<=>?
This is what you are seeing in you output (because you are adding in x2D '-')
I'm not sure what you are expecting to see, but as far as I can tell there are no mistakes and your code is working fine.
If you are trying to turn tc[0] into a hex digit then I would use this function
char ToHex (const char input)
{
    char output = '0';
    if (input > 9)
    {
        output = (input - 10) + 'A';
    }
    else
    {
        output = input + '0';
    }
    return output;
}
char TCToHex (const char input)
{
    return ToHex(((input & 0xF0) >> 4));
}
char* CharToHex(const char input, char buffer[3])
{
    buffer[0] = ToHex((input & 0xF0) >> 4);
    buffer[1] = ToHex((input & 0x0F));
    buffer[2] = '\0'; // Always null terminate a string
    return buffer;
}

So what you will get if you call the functions is
    char buffer[3];
printf("CharToHex 0x%s\n", CharToHex('A', buffer));  //0x41 65 in decimal, ASCII A
printf("TCToHex = 0x%c \n", TCToHex(0x50)); // 5, because this function only takes the high nibble.
printf("ToHex = 0x%c \n", ToHex(0x0f)); // F

Hope that helps.

I am trying to send time stamp on serial port. But your code is not working. Any idea?

Unless your timestamp is in the same format as the TC array then no it won't.  I'll edit the answer to provide you with a more generic solution too.


text:
how to send large strings (> 100 characters) from arduino serial monitor
I am a newbie to arduino programming. I wish to send big strings which are in range of 100 to 1000 characters to my arduino uno. I saw that arduino cannot read more than 63 characters at a time.

The strings can be received in parts (~40 characters) which will be processed by my program and few minutes later they will get deleted. Then another ~40 characters will be received and the process continues till all the characters are received.

Can you please help me with this. If the question is not clear, you're free to ask in the comments. Thanks in advance :-)

Running 1000 bytes through the serial port will take quite some time: the bytes are sent one after the other. Your Arduino should just process each byte as it receives it.

Do you have any code yet?

@EdgarBonet The bytes are commands to be executed by the machine. So processing might take long

@DaveX Do you mean the code for serial communication?

@dark32 I mean have you got any semi-working code to show what issue you are having.  From the Q, it seems you can process about 40 bytes per few minutes, and you seek to buffer 2-25 commands worth of data within the Arduino.    There's code in 3D printers that processes megabytes worth of serial commands on-the-fly at command-execution speed by using buffering and handshaking on the sending end.  They rely on a state machine to assemble a command and its parameters from a serial stream, and don't pull data out of the the buffer until they are ready for it.

Sorry, no code that was able to read more than 63 characters. I am newbie so i simply used Serial.read() to fetch the strings.

I saw that arduino cannot read more than 63 characters at a time.

Not strictly true. The Arduino core HardwareSerial library has a 64 byte buffer, so it can only buffer up to 64 characters. If your sketch is reading the characters from the buffer whilst you are sending the characters from your PC then that limit is irrelevant. As long as you are reading the characters as fast as they are coming in.
Serial is actually quite slow (on the scale of things) and unless you're doing silly things like using delay() or long blocking loops, then reading the data fast enough is not that big a problem.  If you do need more time the simplest way is just to slow down the serial data somewhat - i.e., use a lower baud rate. The slower you send the data the longer you get between each character arrives to do things.
For strings the size you are on about you are probably best off processing the data on the fly rather than storing it all then post-processing it - simply because the Arduino doesn't have much RAM, so storing large strings isn't always an option.

I do believe that it's possible to change the size of the buffer though. Which may be neccesary if only a high baudrate is possible, on a device where the execution of the messages takes longer than the receiving. In all other cases, your answer will do (:

@Paul Yes, you can always hack the core to increase the SERIAL_BUFFER_SIZE from 64 to something bigger - at the cost of more wasted RAM...

But you'll avoid having to copy it from one buffer to another, in order to be able to receive one message at once. But indeed, if possible, another way of fixing it may be preferable

@Paul: For that, you would have to make the RX buffer public, and you would need to be ready to deal with the message not being contiguous, because it's a ring buffer.

source: Stack Exchange

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

sort: votes


text:
How to convert String to Double?
I found the .toFloat() but that's not accurate enough.
String StrEx = "57.10598";
float FloatEx = StrEx.toFloat();

Serial.println(String(FloatEx)); //outputs 57.11
Serial.println(StrEx);           //outputs 57.10598

There is no double.

What does Serial.println(FloatEx, 5); give you?

@Majenko gives me 57.10598. Thanks!!!

It is a common misconception that, because when you print a float you only get 2 decimal places, that the float only has 2 decimal places.
That is not true. A float doesn't have a number of decimal places - that is how it gets its name - floating point: the decimal point floats around as needed.
The problem is actually that, by default, all the Arduino print and string conversion functions are set to 2 decimal places. Unless you specify the number of decimal places you want to print (or convert to) you get 2 decimal places.
By specifying 5 decimal places when you print or convert to a string you get 5 decimal places.  It still won't always give you exactly the same number, but that is because a 32-bit float cannot store all possible numbers, so some are only an approximation. It's still a whole lot more accurate than 57.10598 -> 57.11 though.

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


text:
Arduino Data to Cloud without shield []
I am performing basic analogue read like temperature and LDR, reading the data serially, but I would like to deploy it online to cloud platforms like (Plotly, Xively, ThingSpeak, or DataSparkFun). Is that feasible? Thank you in advance.

Without a shield? Yes, it's possible.
You send it serially to your computer as you are doing now. Then you write some software for your computer to read that data serially and send it on to your chosen web service.
Can the Arduino magically send data to the internet by itself without you investing in a network connection of some form (WiFi shield, Ethernet Shield, etc)? No, of course not. If it could there would be no market for the network shields, and so they wouldn't exist.

Thanks @Majenko, any recommended software to deploy the data online? like Python, Node.JS? C#..

@BadreddineZebbiche Whatever you feel most comfortable programming in.

Would it be okay to provide any links? I am more into hardware. Not familiar with both..

Links to what? Just choose a language already. I can't tell you what you are best at programming in. Just pick one and try it. If you don't like it, try another. If you're on Windows you're probably best off using one that is included with something like Visual Studio since that makes it "simple" to program. Personally I program mostly in C or C++ on Linux, but that takes more experience than programming in, say, Python (which I loathe, but some beginners really love).


text:
Is there a way to set an interrupt to go off after a certain period of time?
I'm trying to save power by putting my device to sleep once it has run through the code once and turn it back on every 33 milliseconds. So basically, if the code finishes executing in 20 milliseconds the device can go to sleep for the remaining 13 milliseconds and it will be turned on by the interupt which is set to go off every 33 milliseocnds.
According to the documentation an interrupt is based on a change to the pin state, but I'm sure there must be a way to base it on time. If there isn't then is there a way to set the total time that a device sleeps? The sleep function seemed to just turn the device off, but can it be given a parameter to just turn off for a certain amount of time?

See for example this answer for an example of setting a timer to periodically wake-up the Arduino Mega.

I saw the sleep function, but where are they setting the actual interrupt?

The line TIMSK1 = _BV(OCIE1A);  // enable TIMER1_COMPA interrupt, as the comment says, enables the interrupt.

Follow up question, is this code Arduino? I see a main method but no setup() or loop().

It's plain avr-libc, but it works under the Arduino environment.

The easiest way to achieve your purpose seems to be to configure a
timer to fire every 33 ms, and use this interrupt to wake up the
MCU. For this, you first have to choose what timer to use. On the Mega, I
would rather use the 16-bit timer, but the ATtiny85 only has 8-bit
timers. Next you have to choose a prescaler value (clock frequency
division) among those available for that timer. The prescaler should be
large enough to avoid overflowing your timer, but smaller prescaler
values give better time resolution.
Then you configure the timer to run in “CTC mode” (clear timer on
compare match). In this mode, it counts from zero to the value that you
programmed in the OCRxA register (where x is the number identifying
the timer), and then goes back to zero. This way you can get an
interrupt every OCRxA + 1 timer cycles.
In the example code below, you have to replace x with the appropriate
timer number, and check the datasheet for the bits to set in the control
registers TCCR*:
#include <avr/interrupt.h>

// Interrupt period, in prescaled clock cycles.
const uint16_t PERIOD = ...;  // or uint8_t for an 8-bit timer.

// The timer interrupt is used ONLY to wake the CPU, so there is no job
// to be done inside the interrupt service routine.
EMPTY_INTERRUPT(TIMERx_COMPA_vect);

void setup()
{
    // Disable Timer 0 interrupts.
    // Warning: this will prevent the Arduino from keeping time.
    TIMSK0 = 0;

    // Configure Timer x.
    TCCRxA = 0;            // undo the timer config done...
    TCCRxB = 0;            // ...by the Arduino core library
    TCNTx = 0;             // reset the timer
    OCRxA = PERIOD - 1;    // set the period
    TIMSKx = _BV(OCIExA);  // enable TIMERx_COMPA interrupt
    TCCRxA = ...;          // set the counting mode to CTC...
    TCCRxB = ...;          // ...and set the prescaler
}

void loop()
{
    // Sleep while waiting for the timer interrupt.
    sleep_mode();

    // Now that we have been waken up...
    do_the_job();
}

Edit: As noticed by Gerben, the Arduino core library configures
Timer 0 to send periodic interrupts (one every 1024 µs), which
are used for timekeeping (millis(), delay() and co.). This
interrupts will wake up the MCU and prevent it from sleeping as long as
you want. The simplest solution, which is implemented in the code above,
is to disable the Timer 0 interrupts. The drawback is that the
Arduino timekeeping functions will not work anymore.
If you need those timekeeping functions, then the proper solution is the
one sketched by Gerben in his comment: set a boolean in the interrupt
that can be checked in the main loop. Here is the naive implementation
of this idea: EMPTY_INTERRUPT(TIMERx_COMPA_vect); is replaced by
volatile bool time_elapsed;

ISR(TIMERx_COMPA_vect)
{
    time_elapsed = true;
}

Then, in the main loop you sleep repeatedly until the ISR sets the flag:
void loop()
{
    // Warning: race condition here!
    while (!time_elapsed)
        sleep_mode();
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

As stated in the comment, this naive implementation suffers from what is
known as a race condition. The problem is in the following scenario:

The main loop reads the value of time_elapsed and it turns out to
be false
At this point the interrupt fires and the ISR sets that boolean to
true
Returning from the ISR, the main loop does not test the flag again
(since it just did it) and goes straight to sleep_mode();.

At this point the MCU ends up sleeping although it should be performing
the job which is due now.
This race condition may not a be a big deal to you: The MCU will be
eventually woken up by the Timer 0 interrupt no more than 1024 µs
later. In some cases it is an issue, but fortunately there is a proper
solution. It is described in the page about sleeping of the avr-libc
documentation. It relies on the fact that when interrupts are
disabled, then enabled again with sei(), the machine instruction right
after the sei() is guaranteed to be executed before any interrupt is
serviced. Then the proper way to test the flag and sleep is:
void loop()
{
    while (!time_elapsed) {
        cli();
        if (!time_elapsed) {
            sleep_enable();
            sei();          // interrupts enabled
            sleep_cpu();    // this will be executed before any ISR
            sleep_disable();
        }
        sei();
    }
    time_elapsed = false;

    // Now that we have been waken up...
    do_the_job();
}

With this version, if the interrupt fires right after the test
if (!time_elapsed), it will be serviced after sleep_cpu(), which
will have the effect of waking the MCU right away.

Wow that helps a lot, but why do you subtract 1 from PERIOD? That other example did that too. Also, PERIOD is supposed to be the duration between interrupts, correct? So for my project I'd set it equal to the number of clock cycles that will equal 33 milliseconds. Right?

The counter counts from 0 to OCRxA inclusive, so the period is OCRxA+1. The period is in prescaled clock cycles, see the prescaler setting.

Timer0 (used for millis and delay) will also wake up the device. You probably need to set Boolean inside the interrupt, so the main loop can check if it needs to go back to sleep or not

Thanks @Gerben for noticing. You are absolutely right. I've amended the answer to account for this issue.

Nice solution for the race condition.

There are many many kinds of interrupt. External interrupts (of the kind you use with attachInterrupt()) are but one.
Almost every internal peripheral in the AVR chip can generate an interrupt (or multiple interrupts in some cases). One of the most useful is the timer interrupt which is triggered by one of the timers when its timer has overflowed.
I am not familiar with the AVR's sleep mechanisms, but I would assume a timer interrupt can wake it from sleep - assuming the timer can run while sleeping.
You should check the documentation for the chip on your Arduino rather than relying on the (somewhat scant and basic, and often misleading) documentation on the Arduino website when it comes to doing anything low-level like this.

You are right: the timer interrupt can wake up the MCU, but only if it's sleeping in the so called “IDLE” mode... which is the default sleep mode anyway.

Does the setting of a timer interrupt vary from microcontroller to microcontroller? I'm trying to write this code on the Arduino Mega first and then port it to an ATtiny.

Yes. You should read the documentation for both your target microcontrollers and program accordingly - probably with copious usage of #ifdef ... #endif

@AngelLockhart: It's often not that different. You could probably use the same code for the 16-bit timers of the ATmega2560 and the ATtiny84A. What ATtiny are you targeting? At what clock frequency?

The principle of operation will be almost the same between them. Numbers will change though (calculations for time vs clock frequency), and register names may change (depending on number of timers available, etc). In general, though, there will be a lot of copy-and-paste of logic blocks like these when it comes to designing chips in the same broad family.

@EdgarBonet I'm using the ATtiny85, also can you explain why the number would change? My plan was to calculate the time the program ran with millis() and then subtract that from 33 milliseconds. Will that not work?

Timers operate on clock ticks. You need to calculate how many clock ticks make up the time you need it to run for, and of course that changes depending on the speed the clock is running at.


text:
Why is there already text in the serial monitor before the Arduino initializes?
I have encountered this several times before and I would like it if someone was able to give an explanation. In almost any sketch that I've ever created with Serial communication involved, I notice that I will get text that seemingly appears before the void setup() function has run. For example, I have the simplest sketch below where this occurs.
void setup(){
// put your setup code here, to run once:
Serial.begin(9600);
Serial.println("Welcome");
}

void loop(){
// put your main code here, to run repeatedly:
}

If I upload this to one of my Arduino Megas, I will often get the output in the serial monitor:
WelcWelcome

When I open the serial monitor to view the output, the "Welc" is already written and then the rest of the "Welcome" come in a few moments later. If I close and re-open the serial monitor or reselect the baudrate setting within the serial monitor, the serial monitor clears, restarting the Arduino, and printing only "Welcome" to the screen without the "Welc", as I would expect.
However, if I upload the sketch, then disconnect-reconnect the Arduino-USB cable from the computer, and open the serial monitor, there is no leftover bytes printed to the screen like before.
The exact bytes leftover that appear before the void setup() function is called varies from upload to upload. Can anyone give me an explanation and is there a way to avoid the leftover bytes ? Thank you.

It's because the Arduino has started running the sketch and placed data into the USB chip's buffer. You then open the serial monitor which then opens the serial port thus resetting the Arduino. So the sketch runs again.
It only resets the Arduino, not the USB interface chip, so you get what was in there from the first execution plus the new text from the second (post-opening) execution.
You cannot "avoid" the extra bytes, that's just the way things are. The Arduino resets. There are buffers in various places. You have no control over those buffers.
As a side note: the serial monitor is completely disgusting. If you want to do things properly use a proper terminal emulator, then you can use ANSI control codes to do things like clear the screen, move the cursor around, apply colour, etc.

Because as soon as you start the serial monitor, it picks whats on the serial buffers and  then resets the arduino connected and also it would reset again when you try to upload code but luckily serial monitor is cleared in this instance;


text:
How to detect the pulse width from microphone as Input?
I'm working on a project that detects the pulse width of an audio signal, which uses a microphone as an input. The user gives 2 different types of sounds one last less 0.3 seconds and other lasting less than 0.7 seconds. I've attached the audio visualisation of the signal pic in the attachment.
All want to detect is their pulse widths.
I tried Pulsein() - but as you can see that it has a variable until 0.3 or 0.7 seconds it only detect the first and most peak and returns the value which is almost zero.
But all I need is the total time taken for the pulse to rise from 0 and to variate and then become 0 this total time period is what I require.
would duty cycle help ? or any other functions available to detect two different sounds in arduino ?

pulse width

@Egar Bonet I even tied setting up an threshold upto which the unwanted signals are removed but after that would it possible to recover the pulse width of it !

It is better to include the images in the question rather than a link to some offsite drive. I've done one for you, the other I can't open (which is why you should do it yourself in the first place).

If you are just detecting Morse code (which it looks a bit like you are from the file name you used (ditandddat.jpg)) then a simple on/off test should do it.

You will need some sort of interface circuit between your mic and your
Arduino. Best would probably be to have some kind of external peak
detection. This way the Arduino reads instantaneous wave amplitude. The
other option is to only shift and scale the signal so that it fits the
Arduino ADC, acquire the signal at a high enough sampling rate, and
compute the instantaneous amplitude in software.
I suggest you take a look at this sound-meter program. You could use
it as a basis for your own processing.
Then you just have to define a threshold and time how long the amplitude
remains above that threshold.


text:
Why does this not put my Arduino Mega to sleep?
I have the following program which is supposed to print the words "Program is on" once and then go to sleep. However it doesn't go to sleep and continues to print "Program is on" over and over again.
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_IDLE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

Because any interrupt will wake it up from Idle, including those used by the Arduino libraries.

So what is waking up my Arduino in the code I have above? I don't have anything there besides the the sleepNow() function.

What is waking it up is what you don't see in the code above nonetheless exists.

In idle sleep, the timer interrupts will wake the processor, as  Ignacio Vazquez-Abrams said in his comment.
A "higher" sleep mode works, however I had to add Serial.flush () otherwise it only printed "P" because the processor goes to sleep before the serial output buffer has been emptied.
#include <avr/sleep.h>

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

void loop()
{
  Serial.println("Program is on");
  Serial.flush ();
  sleepNow();
}

void sleepNow()
{
  // Choose our preferred sleep mode:
  set_sleep_mode(SLEEP_MODE_PWR_SAVE);
  // Set sleep enable (SE) bit:
  sleep_enable();
  // Put the device to sleep:
  sleep_mode();
  // Upon waking up, sketch continues from this point.
  sleep_disable();
}

See my page about power savings.

Do you know if there is anyway to wake it up with you are using the SLEEP_MODE_PWR_SAVE mode?

@CrystalPritzker: There are a few. See the "Power-save" row in the "Sleep Modes" section of the datasheet.

See my page about power savings. Pin-change and external interrupts wake the processor from any sleep state. I think a serial interrupt will too. Also a watchdog timer interrupt can be used.


text:
Building a Vector class in Arduino
I'm struggling with this issue that I can seem to get around of.
 When defining a vector class, I'm seeming to get some issues when deleting the allocated pointer.
Oddly enough, this only happens after I "read" the memory. What I mean by this is that if I push back a series of values to the vector, they seem to stay there. But once I read the values, the data pointer seems to become invalid of some sort so I crash when trying to deallocate it.
Code:
#ifndef VECTOR_H
#define VECTOR_H

#include <string.h>     /* memcpy */

#define min(a,b) (a < b) ? a : b

template <typename T>
class vector {
public:
    vector() : __capacity(0), __count(0), __data(0) {} //empty constructor
    vector(T obj, int count = 1) {

        if (this->__data) { // free data ptr if used
            delete this->__data;
        }

        this->__data = new T[count];
        this->__count = count;
        this->__capacity = count;

        for (int i = 0; i < count; i++) //populate array with given object
            this->__data[i] = obj;

    }

    ~vector() {

        if (this->__data) { // free data ptr if used
            delete [] this->__data;
        }

        this->__count = this->__capacity = 0;
    }

    T const & operator[] (unsigned int idx) const {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

    T& operator[] (unsigned int idx) {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

    void resize_to_fit() {
        resize(this->__count);
    }

    T& pop_back(){
        return this->__data[--this->__count];
    }

    void push_back(T obj) {

        if (this->__capacity == this->__count) {
            resize(this->__capacity + 1);
        }

        this->__data[this->__count++] = obj;
    }

    bool isempty() {
        return !this->__data ||
            !this->capacity ||
            !this->size;
    }

    void clear() {
        this->~vector();
    }

    T* data() {
        return this->__data;
    }

    int size() {
        return this->__count;
    }

    int capacity() {
        return this->__capacity;
    }
private:
    void resize(int capacity) {
        if (this->__data == nullptr) {
            this->__data = new T[capacity];

            this->__count = 0;
            this->__capacity = capacity;
        }
        else if (capacity != this->__capacity) { //else do nothing

            T* data = new T[capacity];

            this->__count = min(this->__count, capacity);
            this->__capacity = capacity;

            memcpy(data, this->__data, sizeof(T) * this->__count);

            delete this->__data; //program crashes here, but the pointer is already broken...
            this->__data = data;
        }
    }
protected:

        int __capacity;
        int __count;
        T* __data;

};
#endif//VECTOR_H

I was using this code in my Arduino, not sure if it helps
void print_vec(vector<int> v){
  Serial.println("Printing new vec!");
  for( int i = 0; i < v.size(); i++){
    Serial.println(v[i]);
  }
}

void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600); // Open serial connection to report values to host

  while(!Serial); //Waiting for serial to open

  vector<int> i = vector<int>();

  i.push_back(10);
  i.push_back(2);
  print_vec(i); //prints 10 and 2, perfect so far
  i.push_back(3);

  while(true){
    print_vec(i);
    i.pop_back();
    delay(2000);
  }
}

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

}

This code outputs:
Printing new vec!
10
2
Printing new vec!
0
2
3
Printing new vec!
0
2
Printing new vec!
0
(...)
What could be causing this? I'm stonewalled for a while now, any insight on how to solve this is appreciated. Thanks!

At the end of what you say the code outputs, is “(...)” part of the output that you see, or not?  If it isn't, how does the output differ from what you expected to see?  If there are four items in a vector, four i.pop_back() calls should empty the vector.

delete this->__data; //program crashes here ... should use delete[] right? Also there is no platform code in your class so you could debug on pc where there are much better debugging tools available.

You had a lot of problems with your code so it's hard to know where to start. :)
I agree with what John Burger said.
I took your code onto my PC to save mucking around uploading it each time, and also so I could use valgrind on it. Certainly valgrind reported an error after you printed the vector. The reason for that is simple. You passed a copy of the class to print_vec which meant that the destructor got called when print_vec exited, thus deallocating the memory. You should have had a copy constructor. Without it the compiler makes a bitwise copy of the class, which means you now have two objects sharing the same allocated memory.
A quick and dirty fix is to call print_vec by reference:
void print_vec(vector<int> & v){

However that leaves the bug lurking around for the future.
I implemented the copy constructor in my example below, however calling print_vec by reference saves the class having to be copied, reducing the number of new/deletes you are doing, thereby possibly reducing memory fragmentation.

As John Burger said: do not call the destructor yourself! You can't do that. If you want to do the same thing in the destructor and the clear function, just get the destructor to call clear().

The use of leading double-underscores in variables is contrary to the C++ Standard. Don't do that. Use a trailing underscore if you want to indicate a member variable. Lose all the this-> references. They just clutter things up.

Since you allocate an array you should use delete [] - you did that in one place but not the other.

Why do this? It's an unnecessary assignment:
  vector<int> i = vector<int>();

Just do:
  vector<int> i;

If you are going to assign the class for some reason you should also implement an operator= or you will have the same problems as you had with the copy constructor. (See my example).

Here you are testing functions (capacity and size) without calling them:
bool isempty() {
    return !this->__data ||
        !this->capacity ||
        !this->size;
}

You can't really do this:
  T const & operator[] (unsigned int idx) const {
        if (idx < this->__count) {
            return this->__data[idx];
        }
        else {
            // throw exception or handle error to be implemented
        }
    }

If you take the "else" path then the function is returning no value (you get a compiler warning if you turn warnings on).

My reworked example, with my suggestions in it. It compiles without warnings or errors and runs without crashing (on a PC):
//      g++ -std=c++11 -g3 test.cpp -o test
// OR:  clang -std=c++11 -g3 -Wall test.cpp -lstdc++ -o test
//
// valgrind --leak-check=yes ./test

#include <stdio.h>      // printf
#include <string.h>     /* memcpy */

#define min(a,b) (a < b) ? a : b

template <typename T>
class vector {
public:
    //empty constructor
    vector() : capacity_(0), count_(0), data_(nullptr) {}

    // copy constructor
    vector (const vector & rhs) : capacity_(0), count_(0), data_(nullptr)
      {
      data_ = new T [rhs.capacity_];
      capacity_ = rhs.capacity_;
      count_ = rhs.count_;
      memcpy (data_, rhs.data_, sizeof (T) * count_);
      }  // end of copy constructor

    // operator=
    vector & operator= (const vector & rhs)
      {
      // gracefully handle self-assignment (eg. a = a;)
      if (this == &rhs )
        return *this;

      data_ = new T [rhs.capacity_];
      capacity_ = rhs.capacity_;
      count_ = rhs.count_;
      memcpy (data_, rhs.data_, sizeof (T) * count_);
      return *this;
      }  // end of operator=

    // destructor
    ~vector()
      {
        clear ();
      }  // end of destructor

    T const & operator[] (unsigned int idx) const {
       return data_[idx];
    }

    T& operator[] (unsigned int idx) {
       return data_[idx];
    }

    void resize_to_fit() {
        resize(count_);
    }

    T& pop_back(){
        return data_[--count_];
    }

    void push_back(T obj)
        {
        if (capacity_ == count_) {
            resize(capacity_ + 1);
        }

        data_[count_++] = obj;
    }

    bool isempty() {
        return count_ == 0;
    }

    void clear() {
      delete [] data_;
      data_ = nullptr;
      count_ = capacity_ = 0;
    }

    T* data() {
        return data_;
    }

    int size() {
        return count_;
    }

    int capacity() {
        return capacity_;
    }
private:
    void resize(int capacity) {
        if (data_ == nullptr) {
            data_ = new T[capacity];
            count_ = 0;
            capacity_ = capacity;
        }
        else if (capacity > capacity_) { //else do nothing

            // allocate new memory
            T* data = new T[capacity];
            // count can't be higher than capacity
            count_ = min(count_, capacity);
            capacity_ = capacity;
            // copy data across to new pointer
            memcpy(data, data_, sizeof(T) * count_);
            // delete old pointer
            delete [] data_;
            // now remember the new pointer
            data_ = data;
        }
    }
protected:

        int capacity_;
        int count_;
        T* data_;
};

void print_vec(vector<int> v){
  printf("%s\n", "Printing new vec!");
  for( int i = 0; i < v.size(); i++){
    printf("%i\n", v[i]);
  }
}

int main() {

  vector<int> i;

  i.push_back(10);
  i.push_back(2);
  print_vec(i);
  i.push_back(3);

  vector<int> j;

  // test assignment
  j = i;
  print_vec(j);
  print_vec(i);

  while(i.size () > 0){
    print_vec(i);
    i.pop_back();
  }

}

Alright, thanks a lot! A lot of the issues were just plain distraction on my end, I was trying focus on fixing the memory problems I was facing at first.

In your second constructor you start with the following code:
if (this->__data) { // free data ptr if used
    delete this->__data;
} // if

This is deadly! You've not initialised __data, so it could hold any value under the Sun. And there is no way that it could possibly be a valid pointer to existing data - it's a brand-new uninitialized object. Returning this garbage pointer to the heap is simply asking for trouble.
Remove those lines - or even better, use an initialiser list like you did with the first constructor:
vector(T obj, int count = 1) :
       __data(new T[count]),
       __count(count),
       __capacity(count)
{
    for (int i = 0; i < count; i++) //populate array with given object
        __data[i] = obj;
} // vector(T, count)

Another problem: In your clear() member you wrote:
void clear() {
    this->~vector();
}

You should never, never, never directly call a destructor like this. The compiler can put all sorts of other code in the destructor code, since it "knows" that it's the only one that will ever call it. For example, some compilers pre-push a flag to say whether to delete the object from the heap after doing the destruction. You haven't done that, so the above can corrupt all sorts of things.
Instead, move the code that is in the destructor into clear(), and then simply call clear() from the destructor.
Another one, this one picked up by @Nick Gammon:
bool isempty() {
    return !this->__data ||
           !this->capacity ||
           !this->size;
}

This is testing whether the __data member is false, and whether the capacity and size functions have been defined. Don't worry: the latter two have been... you missed the prefix __...

[Also, stop it with the this-> everywhere. You've used a __ before all your member variables (which is itself against convention); you don't need to hammer home the fact that they are member variables: the compiler already knows.]

I deleted the entire vector(T obj, int count = 1) constructor and it compiled without errors, so that wasn't the issue in this case, but you are right that __data was not initialized.

should never have compiled - it tested the functions rather than calling them. capacity is a member function, not a variable. I picked that up when I tried compiling it under clang.

Hee hee! I missed that - and you're right!

a bit of advice: Your code is practically unreadable. Use a better coding style: https://google.github.io/styleguide/cppguide.html

I also fail to see why you are doing this. While full-blown STL is not supported, there are several well-debugged implementations that you can find with a simple google search.
If you are doing it to learn C++, the arduino environment is probably the worst way of doing it!

You are quite right - for example see Maniacbug's StandardCplusplus. However in this case I wanted to make the answer a bit of a tutorial on writing classes.

I wasn't familiarized with a lot of the info, you're right. I should have started elsewhere. Anyway thanks a lot of pointing out those mistakes, it would have taken ages to find them by myself.

There is something I would like to add.
Others have already pointed out numerous errors in the code. And I could point many more, but that is not the point.
IMO, the biggest mistake is - implementing a Vector class for the Arduino!
Even if it works, it is just a bad idea. Keep in mind, that the Arduino has VERY limited amount of memory. Dynamic memory allocation in such a constrained space just sounds like a bad idea - you are wasting memory, you're fragmenting the heap and you gain almost nothing, except some coding convenience.
I have yet to see a case where one really needs dynamic memory allocation in an Arduino project. And even if you do, there are many other tools you can use (like stack-allocated temp buffers, arena allocators, pool allocators and whatnot). But again, probably the code and memory cost of these "generic" solutions will be unfeasible on the Arduino.
Most of the time it's fine to use vectors, maps and whatever you like on platforms like PC (I work as a PC games programmer, so I often encounter situations where extras like these are big "no-no", but for most applications it's fine).
But, on a "tight" platform like the Arduino, I think you should stay "close to the metal" and be in total control of what is going on (memory and CPU cycles wise). Ideally, you should only afford "luxuries" like these when you know what is going on "underneath" and you know you can get away with it. Which is rarely the case on "tight" platforms like the Arduino.

You have a point here. In particular the push_back idea which incrementally allocates more memory (which is normally fine on a PC with 4 Gb of RAM) is likely to introduce memory fragmentation. I think even normal STL implementations allocate vector memory (capacity in this case) in batches (eg. 10 at a time) to reduce this issue.


text:
Servos Do Not Move to Specified Position
This code receives sine wave parameters from a serial connection, then formats and writes the sine wave positions to 8 servo motors.
The positions are successfully written to 6 of the 8 motors.
Of the two that don't work, I tried changing the motors to see if they were faulty; they are not. I changed the output pins to see if they were damaged; they are not.
I changed the order the equations are solved, and the positions are written to ensure there wasn't some bizarre timing issue. I saved a full cycle of the written positions and they output the correct numbers (i.e. the correct amplitude). You can see them here (format is "servo #" : "position"):
0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1779 1:1337 2:1750 3:1480 4:1357 5:1438 6:1452 7:1490

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1846 1:1404 2:1704 3:1434 4:1403 5:1484 6:1385 7:1423

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1880 1:1438 2:1630 3:1360 4:1477 5:1558 6:1351 7:1389

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1870 1:1428 2:1549 3:1279 4:1558 5:1639 6:1361 7:1399

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1819 1:1377 2:1485 3:1215 4:1621 5:1702 6:1412 7:1450

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1742 1:1300 2:1458 3:1188 4:1649 5:1730 6:1489 7:1527

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1662 1:1220 2:1474 3:1204 4:1633 5:1714 6:1569 7:1607

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1603 1:1161 2:1530 3:1260 4:1577 5:1658 6:1628 7:1666

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1582 1:1140 2:1609 3:1339 4:1498 5:1579 6:1649 7:1687

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1604 1:1162 2:1687 3:1417 4:1420 5:1501 6:1627 7:1665

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1665 1:1223 2:1742 3:1472 4:1365 5:1446 6:1567 7:1605

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1745 1:1303 2:1757 3:1487 4:1350 5:1431 6:1486 7:1524

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1821 1:1379 2:1728 3:1458 4:1379 5:1460 6:1410 7:1448

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

0:1871 1:1429 2:1663 3:1393 4:1443 5:1524 6:1360 7:1398

The entire code is below. The relevant section begins after if (Afreq > 0) near the bottom. The positions that do not write correctly are pos[6] and pos[7]:
/*
This is a program that recieves sine wave parameters from a serial connection in a single string.
The string is parsed and converted into numbers, which are plugged into 8 sine equations to generate
positions for each joint of the robot.
*/

#include <Servo.h>

Servo SB, SF, HB, HF, EB, EF, KB, KF;
int iAmp, iF_offset, iB_offset, iFk_offset, iBk_offset, pos[] = {0,1,2,3,4,5,6,7};
unsigned int t = 0;
unsigned long previousMillis = 0;
float fKnee_amp, fAfreq, fPhase, fGait;

void setup(){
  //Start serial stream at 115200 baud
  Serial.begin(115200);

  //Connect servos to Arduino
  HB.attach(2);
  KF.attach(3);
  SB.attach(4);
  EB.attach(10);
  HF.attach(6);
  KB.attach(7);
  SF.attach(8);
  EF.attach(11);

  delay(3000);
}

void loop(){
  char c, buffer[10];
  String readString, amp, knee_amp, afreq, gait, phase, f_offset, b_offset, fk_offset, bk_offset;
  unsigned int sine_time = 50;

  while (Serial.available() && readString.length() < 37){
    //delay to allow buffer to fill
    delayMicroseconds(100);
    if (Serial.available() > 0){
      //get one byte from serial buffer
      char c = Serial.read();
      //creates the string "readString"
      readString += c;
    }
  }

  if (readString.length() > 36){
    //see what was received
    Serial.println("The string is: " + readString);
    Serial.println(readString.length());

    //parse serial string into separate parameters
    amp = readString.substring(0, 3);
    knee_amp = readString.substring(3, 7);
    afreq = readString.substring(7, 11);
    phase = readString.substring(11, 15);
    gait = readString.substring(15, 20);
    f_offset = readString.substring(20, 24);
    b_offset = readString.substring(24, 28);
    fk_offset = readString.substring(28, 32);
    bk_offset = readString.substring(32, 36);

    //convert string values to numbers
    iAmp = amp.toInt();

    knee_amp.toCharArray(buffer, 10);
    fKnee_amp = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    afreq.toCharArray(buffer, 10);
    fAfreq = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    phase.toCharArray(buffer, 10);
    fPhase = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    gait.toCharArray(buffer, 10);
    fGait = atof(buffer);
    memset(buffer, 0, sizeof(buffer));

    iF_offset = f_offset.toInt();
    iB_offset = b_offset.toInt();
    iFk_offset = fk_offset.toInt();
    iBk_offset = bk_offset.toInt();

    //clear strings
    readString="";
    amp="";
    knee_amp="";
    afreq="";
    gait="";
    phase="";
    f_offset="";
    b_offset="";
    fk_offset="";
    bk_offset="";
  }

  //if the joints should be oscillating
  if (fAfreq > 0){
    //determine joint positions
    pos[0] = iAmp * sin(fAfreq*t) + 1500 + iF_offset;
    pos[1] = iAmp * sin(fAfreq*t) + 1522 - iF_offset;
    pos[2] = iAmp * sin(fAfreq*t + fGait) + 1500 + iB_offset;
    pos[3] = iAmp * sin(fAfreq*t + fGait) + 1446 - iB_offset;

    pos[4] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1500 + iFk_offset;
    pos[5] = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase) + 1581 - iFk_offset;
    pos[6] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1500 + iBk_offset;
    pos[7] = iAmp*fKnee_amp * sin(fAfreq*t + fPhase) + 1538 - iBk_offset;

    //get time in milliseconds
    unsigned long currentMillis = millis();

    //if the time threshold has been passed
    if(currentMillis - previousMillis >= sine_time){
      previousMillis = currentMillis;

      //write servo positions

      SB.writeMicroseconds(pos[0]);
      SF.writeMicroseconds(pos[1]);
      HB.writeMicroseconds(pos[2]);
      HF.writeMicroseconds(pos[3]);
      EB.writeMicroseconds(pos[4]);
      EF.writeMicroseconds(pos[5]);
      KF.writeMicroseconds(pos[6]);
      KB.writeMicroseconds(pos[7]);

      //increment time parameter
      t+=1;
    }
  }
}

I don't know what to try next.

Given that it's the last two that aren't working, perhaps you've got a timing problem. Now I don't know how good the compiler is about detecting common code, but you might want to make it easier for it, and perhaps speed things up by making some temporary variables:
//determine joint positions
int pos01 = iAmp * sin(fAfreq*t);
pos[0] = pos01 + 1500 + iF_offset;
pos[1] = pos01 + 1522 - iF_offset;

int pos23 = iAmp * sin(fAfreq*t + fGait);
pos[2] = pos23 + 1500 + iB_offset;
pos[3] = pos23 + 1446 - iB_offset;

int pos45 = iAmp*fKnee_amp * sin(fAfreq*t + fGait + fPhase);
pos[4] =  pos45 + 1500 + iFk_offset;
pos[5] = pos45 + 1581 - iFk_offset;

int pos67 = iAmp*fKnee_amp * sin(fAfreq*t + fPhase);
pos[6] = pos67 + 1500 + iBk_offset;
pos[7] = pos67 + 1538 - iBk_offset;


text:
The L LED Keeps Itself On
I am using a Arduino Uno 3 for line follower robot. However when I power the Arduino Uno, the L led is turned on and is never turned off. After a bit of searching I found out that the L LED is connected to pin 13. So I set the pin 13 to low but still the led is on. Is there a problem with the arduino? Or there's something that I am unaware about? (Amongst a lot of other things that I don't know.)

You need to tell us more about your line follower robot.  Specifically, where to find the schematic and code.  The way you worded your question is similar to asking: "Where is the headlight switch in my car?"

same problem here please cousld any one help!!
i used arduino uno its L led is not turning off it used to turn of but now no it is not it stays on .and blink code works but i am trying to make balancing robot but no it doesnt work i started uploading code for it this morning then after 3 hours i dont know how it worked for about 30 mins i was tuning the pid values while that 30 mins also the led was on though.but after that 30 mins i am trying but it is not working.Please help!

This is a “feature” introduced in the revision 3 of the Uno board. Up to
Rev 2, the “L” LED was connected to pin 13, through a 1 kΩ
resistor. On Rev 3, the same LED+resistor combination is driven by pin
13 through an op-amp. Thus, when pin 13 is in high impedance mode (i.e.
INPUT mode, the default mode when the program starts), the input of
the op-amp is floating. The voltage at this input (and thus at the
output) is not controlled and depends only on the parasitic conductances
and on leakage currents.
If you want to turn the LED off, you not only need to write LOW to it,
you also (and most importantly) should set the pin to OUTPUT.

Its possible its the Power LED you are looking at - that will always be on.
Simplest test is to load up the Blink Example that's included in the Arduino IDE - and the LED should blink once a second. That will show you if your Pin13 LED is working ok.

The power LED is the green one, and the L led is the yellow one. I am looking at the yellow one

Now first check IC on your arduino UNO. if it is atmega328p, set the board to arduino nano in the software and set the processor th atmega328p. that makes it work.  :)

I guess the arduino is burnt cus it happens with me in the same way. The usb port of my PC is writing device not recognize, and the atmega328p on the arduino temperature is getting high. To save my time I bought another new one I think that should help.

An LED lights up when in forward bias.  That is, when the voltage on the anode is greater then that on the cathode.  If the anode is connected to an Arduino GPIO pin (and the cathode is connected to ground and an appropriate limiting resistor is used), the LED will light up when the pin has positive voltage.  This is when it is set to 1 in the code.  If the cathode is connected to an Arduino GPIO pin (and the anode is connected to positive voltage and an appropriate limiting resistor is used), the LED will light up when the pin has zero voltage. This is when it is set to 0 in the code.

authors: Сергей Романов

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


text:
How to wake up Arduino Mega when in Power Saving Sleep Mode?
I'm using sleep mode to turn off my device after the routine has finished executing and want to use interrupts to wake it up every 33 milliseconds. Basically, the idea is that if the routine completes in less than 33 milliseconds the processor can shutdown and save power for whatever remaining time, which will hopefully translate to reduced power consumption. I've currenlty managed to turn off my device with the sleepNow() function you see below, but the interrupt I have programmed in doesn't seem to work. The program simply goes to sleep and never wakes up. What am I doing wrong?
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>

const uint16_t PERIOD = 2150;

void setup()
{
  noInterrupts();
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B |= (1 << CS12); // ...and set the prescaler
  interrupts();

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  Serial.println(millis());
}

void loop()
{
  Serial.println("Program is on");
  Serial.flush();
  sleepNow();
}

void sleepNow()
{

    // Choose our preferred sleep mode:
    set_sleep_mode(SLEEP_MODE_PWR_SAVE);

    // Set sleep enable (SE) bit:
    sleep_enable();

    // Put the device to sleep:
    sleep_mode();

    // Upon waking up, sketch continues from this point.
    sleep_disable();

}

Timer 1 cannot wake you up because... it's sleeping! Only Timer 2 is awake in SLEEP_MODE_PWR_SAVE.

Problem is that when I do that it never leaves the ISR and re-enters the loop. It just infinently prints out the time. It didn't use to do that before when I used IDLE and Timer 1.

What's strange is that when I move the print statement outside of the ISR function the program runs just fine.

Printing from within an ISR should be avoided, as the serial port relies on interrupts to send the data, and they are blocked inside the ISR.

Okay that makes sense, but I just have a quick housekeeping question. When I tried to move the interrupt setup into a separate method and then call it from the setup method the interrupts stop working. Is that because you NEED to setup your interrupt in the setup method?

No, you can setup the interrupts wherever you want. You probably introduced an unrelated bug while doing that.

It is certainly tempting to go into a very deep sleep in order to save
power, but you still need to keep awake whatever peripheral you want to
use as a wakeup source. If you want to use a 16 bit timer, there is no
other choice than SLEEP_MODE_IDLE.
But it may not be that bad. In IDLE mode you can selectively disable the
clock (and hence put to sleep) the peripherals you do not use. Or maybe
put them all to sleep, and then wake up the few ones you do need. This
is achieved with the power_*_disable() and power_*_enable() family
of functions.
In the edited code below: all peripherals but the Timer 1 are disabled
while the CPU sleeps. The USART is enabled only for the time it needs to
send its message:
#include <avr/interrupt.h>
#include <avr/power.h>
#include <avr/sleep.h>
#include <util/delay.h>

const uint16_t PERIOD = 2150;  // 34.4 ms

void setup()
{
  // Disable all but the needed peripherals.
  power_all_disable();
  power_timer1_enable();

  // This is for debug pulses.
  pinMode(22, OUTPUT);

  // Configure Timer 1 to wake us up every 34.4 ms.
  TCCR1A = 0;            // undo the timer config done...
  TCCR1B = 0;            // ...by the Arduino core library
  TCNT1 = 0;             // reset the timer
  OCR1A = PERIOD - 1;    // set the period
  TIMSK1 = _BV(OCIE1A);  // enable TIMERx_COMPA interrupt
  TCCR1B = _BV(WGM12)    // CTC mode, TOP = OCR1A
         | _BV(CS12);    // ...and set the prescaler /256

  Serial.begin(9600);
}

ISR(TIMER1_COMPA_vect)
{
  // Send a debug pulse.
  digitalWrite(22, HIGH);
  _delay_ms(2);
  digitalWrite(22, LOW);
}

void loop()
{
  // Enable the USART only while needed.
  power_usart0_enable();
  Serial.println("Program is on");
  Serial.flush();
  power_usart0_disable();

  // And go to sleep in IDLE mode.
  sleep_mode();
}

Notice also that the ISR does not print to the serial port: it just
sends a debug pulse to watch with the scope. This should be removed from
production code. The delay is achieved with the avr-libc function
_delay_ms() because the standard Arduino delay() would not work: it
relies on Timer 0, which has been disabled.

But wouldn't this affect the functionality of the program since you are disabling the peripherals in the start of the program with power_all_disable(); since I'm not an expert on Arduino couldn't this introduce a whole bunch of new bugs? Lastly, if I am able to use very deep sleep and wake it up with the code I have above what would be the advantage of switching to the less power saving option of IDLE mode?

Also why would using a 16 bit timer force me to use IDLE?

@AngelLockhart: If you want to be on the safe side, you can disable only the peripherals you do not use. The nice thing about the IDLE mode is that you can wake up out of it. ;-) The datasheet has, on section 11.1, a table with the wakeup sources available in each sleep mode. You can see that most peripherals (“Other I/O”), including all the 16-bit timers, are only available in IDLE mode.


text:
Why doesn't the time update?
I am making an arduino clock/alarm. I use an LCD screen to display the time.
void loop(){
    static unsigned long timing=micros();
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);
        writeTime(minutes, hours);//display time
  }
}
  unsigned long countTime(unsigned long timing){
            if (micros() - timing >= 59946970) {
              return timing += 59946970;//more precise because Arduino timing is not perfect
              minutes++;

    }
        else{

         return timing;
        }

      }

    void writeTime(int minute, int hour) {
      lcd.setCursor(6, 1);
      if (minute >= 60) {
        minute = 0;
        hour++;
      }
      if (hour >= 24) {
        hour = 0;
      }
      if (minute < 10) {

        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + "0" + minute);
        }
        else {
          lcd.print(hour + String(":") + "0" + minute);
        }
      }
      else {
        if (hour < 10) {
          lcd.print(String("0") + hour + ":" + minute);
        }
        else {
          lcd.print(hour + String(":") + minute); //possibly split if problems arise
        }

      }

  }

I used to do all this within the loop, but decided to make it separate. Why isn't this code working?

This statement:
static unsigned long timing=micros();

...only gives it an initial value.  It is not executed during loop.  These kinds of variables should be assigned an initial value in an executable section, perhaps when the alarm time is set.
This requires the definition to be pulled out, to the file scope:
static unsigned long timing;

void loop(){
    if (mode == 0) {//mode 0 is when the time should show
        timing=countTime(timing);

Here, the static keyword has a different meaning, although I usually use it to reduce the chances of colliding with other global variable names.
Make sure to give it an initial value in executable code somewhere:
void setup()
{
  ...
  timing = millis();  // Just once?  When the alarm is set?
}

... and update it as you do in countTime.

UPDATE  It's not clear from your snippet as to when the timing variable should be initialized, so I originally avoided addressing that.  If it is really initialized just once, at program startup, you can set it in setup.  Otherwise, it should be set when the initial timing value is finally known.

Why have it static if you assign every loop? Also, as a matter of form, you should always assign a static variable with a default value.

LOL, that should be inside the if statement, and initialized in setup.


text:
How can you determine the duration of a timer interrupt?
So I understand that when setting a timer interrupt you don't use nanoseconds or milliseconds, but the actual number of clock cycles. However, I don't understand how you would be able to setup a specific time this way. If I wanted my interrupt to go off every 20 milliseconds would I have to divide that by the duration of each clock cycle?

The timer takes its time from the system clock. That may be, typically, 16MHz. We call this F_clk_io for the Frequency of the IO CLocK.
Every time that clock ticks the timer counts. Or, depending on settings, every time that clock ticks the prescaler counts, and eventually the output of the prescaler ticks and then the timer counts.
So first you need to divide the F_clk_io by the prescaler. That may be 1:1, 1:2, 1:4, 1:8, etc, depending on settings. No prescaler is the same as a prescaler of 1:1.
So say you have selected a 1:4 prescaler.  The timer's frequency is then F_clk_io / 4, or if it's 16MHz you're running at, then the timer's frequency is 16/4 = 4MHz.
So at 4MHz each tick lasts for 1/4000000 = 250ns.
If you want 20ms you need to know how many ticks that would be.
20ms in nanoseconds would be 20000000. 20000000 / 250 = 80000 ticks.
Now, there's a problem there. 80000 won't fit into the 16-bit registers of a 16-bit timer. The maximum you can have is 65535. So we're going to need to slow things down a bit.
Set the prescaler to 1:8 and see what happens...
16/8 = 2MHz. 1/2000000 = 500ns. 20000000 / 500 = 40000 ticks.
That fits.  See how doubling the prescaler has simply halved the number of ticks you get in the same time?
So setting it to a prescaler of 1:8 and letting it tick 40000 times should give you 20ms.
Except it doesn't.
It gives you 20.0005ms.
Why? Because the interrupt triggers and the counter resets when it reaches the target count, not when it passes the target count.  And since it starts counting at 0, there's actually 40001 ticks there. So you have to subtract 1 from the number of ticks.
So the finished formula is:
ticks = ((F_clk_io ÷ Prescale) × time) - 1

Things get more tricky when you are working with a smaller chip though and only have an 8-bit timer to use. With that the maximum ticks you can have is a mere 255. So you will have to use a much bigger prescale to get it to fit in. If that's even possible.  If it's not, then there are other tricks you can use.  My favourite is a manual pre-scale:

Run the timer at a multiple of your target frequency (10x is easy)
Count the number of times the interrupt triggers
When the interrupt has triggered 10 times (if using a 10x faster timer) then reset the count to 0 and trigger your real ISR code.

10x is simple to program and visualize, but it's not very programatically efficient. Better is to use a "power of two" multiple since you can examine a single bit in your counter to see if it's reached the target count.  Only minimal differences though, and not really worth worrying about unless you are having a very fast timer interrupt.

My goal is to set a 33 second delay on the ATtiny85 which is supposed to have 8 bit register. Will it even be possible for me to get that kind of a delay?

@FortunaIwasaki: If you clock your ATtiny at 8 kHz, yes.

Or if you use the method I mentioned - have a shorter delay and count those to know when 33 seconds have elapsed.


text:
How to Implement Simple, Quick HMAC on Arduino
Hi I am a research student working on securing the communications in Controlled Area Networks (CANs), and I am using Arduinos to simulate one of these CANs.
My goal is to use HMAC to implement message authentication of packets, and the algorithm must be very fast (I was originally thinking of using FNV1a). However, there are no Arduino libraries for this (I found one, but it uses SHA which will most likely be too slow for CAN). I don't have a lot of practice with cryptography and hash algorithms, only usage of them.
So basically, I need help writing a FNV or FNV1a function in C. The message for input will be a key (obviously) concatenated with a string (char array). Also, I need the hash to be between 128 and 256 bits for sufficient security.
Just as a side note: A CAN message/packet looks like 7df#02010d and the actual data part, 010d (two bytes) is the char array I will be using. For example, as integers, the array for 010d would be {1, 13}.
--
I also know this message applies more to cryptography than Arduino, but I figured someone from this community might have more experience with my particular task, or even have/know of a library I can use that I hadn't found.
-Thanks

EDIT: I found this FNV1a implementation in C/C++ that might work. But I have not tested it yet.

HMAC = Hash-based Message Authentication Code

I ended finding a Arduino library called Spritz which can be found here:
https://github.com/abderraouf-adjal/ArduinoSpritzCipher
Also, for anyone else who comes across this task, here is a very simple Hashed Message Authentication Code (HMAC) example I scrapped together:
https://github.com/zach-king/ArduinoStash/blob/master/src/Spritz_HMAC/Spritz_HMAC.ino
This library supports encryption as well, which is nice, but not needed in my case.
--EDIT--
The SpritzCipher library was actually too slow (about a 50% reduction in network speed) so I must try a different approach. I have found a MD5 library for Arduino which I will try next:
https://github.com/tzikis/ArduinoMD5

How did ArduinoMD5 implementation go?

@mixdev It's been a couple of years now so I don't remember the exact details of the performance, but I believe I did end up going with the MD5 implementation. MD5 was sufficient for speed and bit-length security for my purposes.


text:
Upload code on Arduino Leonardo using command line
I'm trying to upload a compiled .hex file on an Arduino Leonardo, using the terminal. Uploading a sample code using the Arduino IDE works well, and from the Arduino IDE I got the upload command
avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

But executing it I got the following error
Connecting to programmer: .avrdude: Send: . [1b]
avrdude: Send: S [53]
avrdude: Recv: . [15]

avrdude: ser_recv(): programmer is not responding
avrdude: butterfly_recv(): programmer is not responding

What's wrong?

The problem with the Leonardo is it doesn't automatically reset when you open the serial port like boards such as the Uno do.
The Arduino IDE contains code to manually reset the board (by opening the serial port at 1200 baud and closing it again) which avrdude doesn't have.
Basically you need a different way to reset the board so it enters the bootloader. That may be as simple as just pressing the reset button at the right time (the LED fades in and out when it's in bootloader mode) or using some command line utility to open the serial port at 1200 baud and close it again just before running avrdude.
I don't have my Leonardo to hand right now, but you might have some luck running:
stty -F /dev/ttyACM0 ispeed 1200 ospeed 1200 && avrdude -C/etc/avrdude.conf -patmega32u4 -cavr109 -v -v -v -v -P/dev/ttyACM0 -b57600 -D -Uflash:w:[file.hex]:i

This doesn't work for me.

After try some trial and error I have built a simple binary to upload into the Leonardo bootloader. This binary opens serial at 1200 baud then closes it, and wraps the avrdude binary to write .hex into flash.
In Arduino core CDC.cpp we can see that CDC not only waiting baudrate 1200, but CDC checking DTR value. If DTR goes high, CDC cancels to jump into the bootloader. That's why I cleared DTR value. I tried this in Ubuntu 16.04.
https://github.com/vanbwodonk/leonardoUploader
Only use this simple command:
leonardoUploader /dev/ttyACM0 Blink.ino.hex

I hope it helps other people searching for this.

For a Windows solution look here: How can I force a Leonardo to reset with avrdude?. I made simple bat file wrapper that automates avrdude invocation.
It identifies Leonardo COM port with WMI, resets this COM port to 1200 baud with mode command, then identifies bootloader COM port and invokes avrdude.
Firmware is supposed to be placed to firmware.hex, but bat file can be changed to be supplied from command line.
I've put the code to GitHub repo: Simple wrapper for avrdude to allow firmware upload to Arduino Leonardo from command line.

This is a link only answer and should be revised or deleted.

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


text:
Why are pull-up resistors needed?
Please tell me why is it necessary to access pull-up resistors and how can we access them in arduino?

Pull-up resistors are used to define the state of an otherwise "floating" input by pulling the voltage at the pin to a set voltage.
The most typical example is a switch - let's say you have some signal, which is connected to your input through a switch. If the switch is open, the state of your input is "floating". If you try to digitalRead or analogRead that input, the value will be pretty much just noise.
But, if you have a resistor connected from your input to ground (pull-down) or VCC (pull-up) your reading will be consistent (HIGH or LOW, depending on where the resistor goes) while the switch is open.
When the switch is closed, the voltage at the pin will be pulled to the voltage at the other end of the switch.  Because of the lower resistance of the switch relative to your pull-up resistor, this is the input level that will be read by the microcontroller. Pull-up resistors are usually pretty big value (5k-100k) in order to be much higher resistance than the switch and to decrease the current that is used by the switch to produce a signal.
If, for example, you have a pull-up resistor and a switch that connects your input to the ground, when the switch is open you will read HIGH and when it is closed you will read low.
Note that many components act similar to switches, for example transistors, open-drain / open-collector devices and many more, so the switch was just an example.
You can use external pull resistors (just add a resistor from your pin to ground or VCC) or use the internal pull resistors of your MCU.
The Arduino only has internal pull-up resistors (no internal pull-downs) - their value depends on the model, but usually is between 20K-150K.
To activate the internal pull-up resistor for a given pin on Arduino, use the following code:
pinMode(N, INPUT);
digitalWrite(N, HIGH):

where "N" is your pin number or with recent IDEs:
pinMode(N, INPUT_PULLUP);

ok, +1, also change intenral to internal

You can also activate them with: pinMode (N, INPUT_PULLUP); which is the preferred method these days. I think in the case of some other architectures (like ARM) that function call generates the correct code whereas doing a digitalWrite like you showed might not.

A short answer from Arduino Playground:

Pull-up resistors are used in electronic logic circuits to ensure that
  inputs to the arduino settle at expected logic levels if external
  devices are disconnected or high-impedance. 'Just because you have
  nothing at all connected to an input pin doesn't mean it is a logical
  zero.'


text:
arduino usb android controller
i am pretty much newbie with arduino and want to start my first project so i may be asking stupid questions.
My goal is to make usb controller for android tv (running on raspberry pi or s905). I want it rotary, so turning will be "arrow up/down" or "left/right" (i dont know exact android tv menu controlling) and "return" on push. I found this rotary switch on ebay, is it suitable?
To communicate i want to use arduino. I found libraries MouseKeyboard, which might be suitable for my needs, will arduino nano support this library or do i need arduino uno?
Do i need something else, or just connect switch to pins on arduino and plug arduino to raspberry?
As i need this controller to operate in menu, not just in some application, will this work as some mouse or keyboard connected via otg to android and function immediately?
Thanks.

Yes, that rotary encoder is fine.
Neither the Nano nor the Uno support that library. You will need a device that has native USB support such as the Leonardo or Due, just like it says on the page.
The rotary encoder library you use will tell you how to connect it.
As for specific Android functionality, you will need to ask on Android.SE.


text:
Timeout error uploading code to Arduino Mega 2560
I am new to Arduino programming, and my first sketch (from a tutorial) failed to upload. I am having trouble trying to figure out what is causing it (have tried to upload the sketch using different COM ports on my Mac).
Here's my setup:

USB COM Port -> Arduino Mega 2560 -> Grove Mega Shield -> Grove Temperature Sensor
  v1.2 connected to Mega Shield UART0.

Here's the code from the tutorial:
// Demo code for Grove - Temperature Sensor V1.1/1.2
// Loovee @ 2015-8-26

#include <math.h>

//R0 = 100000 results in 'overflow in implicit constant conversion'

const int B=4275;                 // B value of the thermistor
const int R0 = 100000;            // R0 = 100k
const int pinTempSensor = A5;     // Grove - Temperature Sensor connect to A5

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

void loop()
{
    int a = analogRead(pinTempSensor );

    float R = 1023.0/((float)a)-1.0;
    R = 100000.0*R;

    float temperature=1.0/(log(R/100000.0)/B+1/298.15)-273.15;//convert to temperature via datasheet ;

    Serial.print("temperature = ");
    Serial.println(temperature);

    delay(100);
}

And here's the error output:
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_ReceiveMessage(): timeout
avrdude: stk500v2_cmd(): short reply, len = 0
avr_read(): error reading address 0x0000
    read operation not supported for memory "signature"
avrdude: error reading signature data for part "ATmega2560", rc=-2
avrdude: error reading signature data, rc=-1
avrdude: stk500v2_ReceiveMessage(): timeout

What I have done so far:
1) Disconnect and reconnect USB Cable
2) Restart Arduino IDE (1.6.9)
3) Changed COM Ports
4) Press the reset button
Could someone please explain to me what the error output means?

Have you tried to upload your sketch without the shields? I had a similar problem once where I couldn't upload while a connection was plugged into UART0. Unplugging the sensor worked for me.

I unplugged the sensor but it didn't work. What I did to finally get it to work was, to plug it into a different UART port and reset the board. Glad it works now.

With an arduino Mega I usually use UART1 for sensors and so on and I keep UART0 free fror communication with the PC. Sorry, I should have mentioned that in my answer...

Connect Mega 2560 in one of your port, select the right com port, and try to load the white sketch, look if you obtain the same error..
//white sketch
void setup(){}
void loop(){}

Under tools I think it is. Make sure that the arduino you are using is selected and also the right com port (usb port) That might fix the problem


text:
What is the Arduino compiler's version of `__unused` for function parameters?
When I first started with the Arduino environment I noticed that it had File | Preferences | Compiler Warnings set to None, so I set it to All - and there were many, many warnings in the supplied libraries! So I quickly set it to None again - until later.
Well, "later" is now, and I started going through the warnings to fix the code to quiet the compiler.
Note that I don't want to disable any warnings - I want to placate the compiler at each spot so that it says to itself "No problem here!"

If the compiler complains of an unused variable, I comment out the variable;
If it complains of a signed/unsigned comparison, I change the type;
If it complains of an unused parameter in a function, I...

...hmmm. If this was C++, I'd simply comment out the parameter name, leaving the type naked:
void Fn(int /*param*/) {
} // Fn(param)

Arduino reports:
error: parameter name omitted

But that isn't legal in C. With some compilers you can use the __unused attribute:
void Fn(int __unused param) {
} // Fn(param)

Arduino reports:
error: expected ';', ',' or ')' before 'param'
    It's interpreting __unused as the actual parameter name

or if they're fussy:
void Fn(int __attribute__((unused)) param) {
} // Fn(param)

Arduino reports:
warning: unused parameter 'param' [-Wunused-parameter]
    That's not the correct __attribute__, obviously

So none of the above work in the Arduino environment. Suggestions?

I've been programming in C and C++ for over twenty years, and I know that the #1 thing you should always do is ask the compiler to tell you about everything it notices. You need a warning-free compile at all times! Otherwise, you spend hours or days trying to find a bug - only to discover that the compiler has been warning you about it all along...

The Arduino core is a mixture of C and C++. The void f(int) {...} idiom should work in the C++ files. I agree it's a shame the core generates so many warnings.

Well, I typed all that question up for posting, then tried one last thing. It worked!
void Fn(__attribute__((unused)) int param) {
} // Fn(param)

So, rather than let a good question go to waste: here's the answer!
Now all we need to do is get the maintainers of all the libraries to put these in... and fix the other warnings...

Another idiom often used in C is void f(int param) { (void) param; ... }.

Within the body of a function you can do this to suppress a warning:
void do_something(int value) {
  (void) (value);
  . . .
}

You can use a macro to do the same thing, for better clarity:
#define UNUSED(v) (void) (v)

void do_something(int value) {
  UNUSED(value);
  . . .
}

This can be helpful in situations where you have conditional compilation:
void do_something(int value) {
  #ifndef USES_PARAM
    UNUSED(value);
  #else
    other_stuff(value);
  #endif
  . . .
}

I know most compilers will do the "right thing" with that, but I've seen some that emit the "load" - and then do nothing with it. The nice thing about "decorating" a variable declaration is that it does two things: it signals the compiler, not the code generation part; and it merely flags a possibility, not a guarantee. If you actually use a variable that is flagged as unused, then the compler doesn't complain. So in your final example, you decorate value and don't need both sides of the #if[n]def


text:
How to connect the 3.3v pin of arduino mega to multiple sensors
I am connecting 3 accelerometers to an arduino mega. I have everything except how to connect them to the 3.3v pin. I know that I can just connect the 3 of them to the same ground pin but I have been told I can't do the same with 3.3v pin. Can anyone tell me what is the best way to power them from the arduino mega?

You can connect all of them as long as the total current draw is not over 50mA as described here. If you need more than 50mA, you need to create your own 3.3v supply or use something like a breadboard power supply for instance (keep in mind to make a shared ground line).

Yes sorry, that's what I meant by connecting the 3 ground wires to the same ground pin. Can I do the same with the 3.3v pin then? Is that what you're saying? Just use a shared 3.3v line?

yes, take a look at the datasheet of your sensors. There should be a Max current field in the specs. If the sum of total max current in each sensor is less than 50mA you can use the 3.3v of arduino mega.


text:
Where can I find magnetic declination lookup table?
Is there a way to get approximate value of magnetic declination from GPS coordinates?
My Arduino-based device has a Magnetometer and a GPS, and uses magnetic declination in calculations. I would like to avoid having to configure it by hand.
I have found references to https://www.ngdc.noaa.gov/geomag/WMM/soft.shtml online, but the site seems to be down (Google has a cache of the site but not of the code).
Is there another way of getting magnetic declination from GPS coordinates? Doesn't have to be precise, +/- 10% would work just fine.

No, the North pointed by GPS coordinates are extracted using the velocity heading which would represent the true North. If you get the ECEF (earth centered earth fixed) coordinates from the GPS you can convert it to a local ENU (east north up frame) and calculate the heading from the velocity vectors (take a look here if you need the formulas for that).
However, this site http://www.magnetic-declination.com/ can provide you a estimate for magnetic declination at your location.
EDIT
From the comment I came across this topic which lead to this
you can play with the code provided and take it as a template for your needs to create a lookup table. The software used for creation of the files is the one present in the site you pointed. Just downloaded the linux zip file and tested it with the sample txt coordinates provided and all seems ok.
For the record the command used was (yes for some reason the extension exe is present but this is linux binary):
./wmm_file.exe f sample_coords.txt out.txt

which created a out.txt equal to sample output file provided. Now this file can be used by the function void build_lookup_table() (present on grab60_char.c) to build the lookup table you need.

I'm basically only looking for an offline lookup table of data on that site. I already have latitude, longitude and altitude coordinates (either hardware or software does the transformations already).

@frnhr I edit my answer with more info I came across, hope it helps you.


text:
how to use an object of a class within that same class?
I want to write a tree data structure made up of Nodes, but I'm having a problem with my Node.h class as each Node need to have a reference Variable to other Nodes,it's children. which ends up giving me the following error

"field 'child' has incomplete type"

so I thought to myself if I was to #include "Node.h" within my Node.h class which gave another error

"#include nested too deeply

how can I have reference to my child Nodes within my node class

With a forward declaration.

thanks, I'm new to c++ so i didn't know that . anyways, i define my child node as Node* child; is this correct?

Yes node* is a pointer.  Always make sure you initialise a pointer to NULL though, and check to see if it is NULL before you do anything to it.
And don't forget to free the memory when you have finished with it.  And never mix new/malloc and delete/free

You will need to forward declare the class and add a pointer to it from within  the class.  i.e.
class CElement;  // Forward declaration

class CElement
{
public:
    CElement();
    ... // Other functions
private:
    CElement *m_NextElement;
};

Just to be clear you can't have your class as a member variable, it has to be a pointer or a reference.  This is because:

You can't use a type that hasn't been fully defined.
You would end up with your class consuming an infinite amount of memory, because every node would contain a node, which contains a node, etc...

You don't actually need to pre-declare the class the way you did on your first line: the class CElement is known about by the time the compiler gets to the CElement *m_NextElement; line

Also, check your "Just to be clear" line: you say "you can have your class as a member variable" - you mean "you can't". If you want you can have it as a reference - you imply you can't.

@Matt thanks, I added the forward declaration to my Node class. while i did manage to solve this I'm having a lot of trouble understanding when to use * or -> and new keyWord

@JohnBurger - Thanks, good spot.  My fingers were traveling faster than my brain.  Hopefully corrected them now.

@Matt Why do you think you can't have it as a reference? It may not be useful (in this instance), but it's certainly legal.

@Raed Its difficult to guess your code, but assuming this is a simple class, I don't think you need to use a * except in the declaration of variables where it declares a pointer.  In the code pointer will give you the data that is pointed to by pointer, which you can access with ->.  You use new to allocate memory CElement pNewObject = new CElement(); and delete pNewObject should be all you need.  However I would recommend that you check that pNewObject has been allocated after the new and before the delete calls.  if (!pNewObject) // If not allocated report error.

@Raed: About "understanding when to use * or ->": *pointer means the thing pointer points to. It could be a simple entity like a number, or a whole bunch (tech term, heh) of entities like an array or a struct or a class. pointer->foo means the member named foo within the thing pointer points to. (In this case the "thing" would have to be a struct, a union, or a class, to have named members).

If you have a class like this:
class Node {

public: // Methods

    inline Node() :
           left(nullptr),   // No children yet!
           right(nullptr) {
    } // Node()

public: // Variables (normally this should be private, but for this example...)

    Node *left;
    Node *right;

}; // Node

Node root; // The root of the tree

You now have a class that has two members, both pointers to Nodes. Obviously there's going to be more data in there - strings or whatever - but let's ignore that for now.
I've also created the root of the tree - note that I didn't use new! It's a file variable that is always accessible, and there's not an * in sight (except inside root...).
What are left and right? Pointers to the children. They are not the children: just pointers to them. As soon as any Node is created (after the constructor has finished), the Node has no children - both pointers are nullptr.
So (ignoring any attempt to sort the children into place) you could now do the following:
void AddChildren() {
    Node sister;           // Create a sister
    Node brother;          // Create a brother
    root.left = &sister;   // Point to sister
    root.right = &brother; // Point to brother
} // AddChildren()

Note you couldn't do node.left = sister; - you're not trying to put sister inside root, you're only trying to point to sister with one of root's children. So you take sister's address with the & operator.
Only... as soon as AddChildren() exits, both sister and brother are destroyed (they're local to the function, so get destroyed as the function leaves) - but root is still pointing to where they used to be! It doesn't know that they are dead!
That is why you call new. It creates the object on the heap rather than the stack, and the object stays around until explicitly destroyed with delete. Only, new returns a pointer to the object, not the object itself. So:
void AddChildren() {
    Node *sister = new Node();  // Point to new object on the heap
    Node *brother = new Node(); // Point to new object on the heap
    root.left = sister;         // Already a pointer! Just copy it
    root.right = brother;       // Already a pointer! Just copy it
} // AddChildren()

Or, perhaps easier:
void AddChildren() {
    root.left = new Node();  // Point to new object on the heap
    root.right = new Node(); // Point to new object on the heap
} // AddChildren()

Now, how do you access the different fields inside Node? It depends on whether you're accessing them through an object or through a pointer:

Through an object?
With ., like root.left above
Through a pointer?
Using ->, such as ptr->left

So finally, how can you use it for real?
// TraverseTree is going to call a function that looks like this:
typedef void TraverseFn(const Node &node);

// Traverse a (sub)tree, calling the passed-in fn() on each Node.
void TraverseTree(Node *node, TraverseFn *fn) {
    if (node == nullptr) { // Nothing to traverse!
        return;
    } // if
    TraverseTree(node->left, fn);  // Trees love recursion!
    fn(*node);                     // Call the passed-in fn with node
    TraverseTree(node->right, fn); // More recursion!
} // TraverseTree(Node)

And you can call the above with:
// A function to print the contents of Node
void PrintNode(const Node &node);

// Traverse the whole Tree, from root, calling PrintNode at each Node
TraverseTree(&root, &PrintNode);

Beware! Do not pass! Here be dragons!
(or at least pointers to member functions...)
Personally, I would have put TraverseTree() inside Node:
class Node {

public: // Methods to call with Traverse()

    // Print this Node
    void Print();

public: // Traverse

    // This is the type of the function that Traverse will call
    typedef void TraverseFn();

    // Note we're passing in a pointer-to-member-function!
    void Traverse(TraverseFn Node::*fn) {
        if (left != nullptr) {
            left->Traverse(fn);
        } // if
        (this->*)fn();
        if (right != nullptr) {
            right->Traverse(fn);
        } // if
    } // Traverse(fn)

}; // Node

If you do that, you'd print out the tree like this:
root.Traverse(&Node::Print);