message:
ESP8266 - Error: unknown opcode or format name 'jmp'

I bought a nodeMCU 8266 and I'm hoping that it can replace my bulkier UNO+WiFi 101.

I'm getting an error when I compile:
Error: unknown opcode or format name 'jmp'

I'm using it in void SoftReset() function:

    void softReset() {
      delay(1000);
      asm volatile ("  jmp 0");
    }
This reset works great with my Uno+101 setup but, for whatever reason, doesn't like the ESP8266.  I removed the WiFi101 library and added the ESP8266 WiFi libraries.  That has been the only change.

Can you please help me understand why I'm receiving this error?

EDIT:  I have read [this SO answer][1] but the "syntactical sugar" didn't work for me.

I am also perusing various ESP8266 sites but they are not as well managed as SE/SO and answers are tough to find.

  [1]: https://stackoverflow.com/questions/18517634/tiny-c-compiler-error-unknown-opcode-jmp

body:
The ESP8266 is not an Arduino Uno. It talks a completely different language.

It's like you're talking Spanish to a Chinese person. It can't understand you.

If you want to use assembly language then you have to use the assembly language of the chip you are programming for - not the assembly language of a completely different chip.

The assembly language is detailed here: http://techblog.realisaatio.fi/wp-content/uploads/2015/04/xtensalx_overview_handbook.pdf

Bear in mind, though, that jumping to 0 may not reset the device - it may do something nasty.

The only sure-fire way of resetting a chip where you don't really know what is going on inside is to connect a GPIO signal to the RESET pin and use that GPIO to pull RESET low and reset the board that way.

If you want to call address 0 and don't know how to do it in assembly there are ways of arranging it in C using a function pointer:

    void (*addressZero)() = 0;

    void setup() {
        addressZero(); // Call address 0
    }

    void loop() {
    }

That way it will work on multiple different architectures without having to understand the underlying assembly language.  That, of course, is assuming that calling address 0 is a valid way of resetting the board on the target chip.

Browsing through the document I link to above it looks most likely that you would first have to load a register with 0 and then use `JX` to jump to the address stored in the register (i.e., zero).


sender: user

sender: assistant

body: The proper way to reset the esp8266 when using the Arduino IDE is to call `ESP.reset()`. You may need to `#include <Esp.h>`, but almost all esp8266 headers you include to use any of its functionality will have included it already.


message:
Need help on HC05 and Nano

I am new to Arduino programming and currently working on this instructable
http://www.instructables.com/id/Control-Led-RGB/ (following this diagram http://cdn.instructables.com/F6Q/IMHF/I0LCDK6B/F6QIMHFI0LCDK6B.LARGE.jpg)

I have ordered these parts as well.

 1. Arduino Nano: www.ebay.in/itm/Arduino-Nano-SOLDERED-PINS-V3-0-ATmega328-CH340G-BUY-2-GET-1-USB-CABLE-FREE-/172117729247?
 2. HC-05: www.amazon.in/Bluetooth-Transceiver-Module-TTL-Outputs-HC05/dp/B00R95Y0AK?ie=UTF8&psc=1&redirect=true&ref_=ox_sc_act_title_2&smid=A1NDZY44BCNIQJ

My questions are:

 1. Is there need to add voltage divider? If yes can you please provide link?
 2. Can I connect two 5050 RGB modules?
 3. Will 12 V, 1 A will be enough to power this board.

body:
1A will be enough to power you arduino but the total powerconsumtion will depend on the amount of leds that you want to drive. If you follow the instuctable, it should be enoug but it's never a good idea to use your power source at max capacity all the time.

It allows you to connect 2 modules indeed.

Why would you need a voltage divider?


message:
Piezo not loud enough

I'm trying to get 110dB out of a 25khz Piezo Transducer.  This piezo resonates at 25khz and as per the illustration in its datasheet should emit 110dB with 10 volts and 25khz frequency.

Any assistence as to what I'm doing wrong here would be GREATLY appreciated !!

My code is bit-banging it.  With an oscilloscope, I confirmed that I'm getting a nice clean 25khz square wave.

I have attached a step-up circuit to the device and am seeing 10volts across the terminals of the piezo while it is emitting it's 25khz frequency.

However, instead of 110dB, I'm only getting 50dB.

I've tried upping the voltage to 20, and still get the same volume level.  The voltage is adjustable via the screw on the top of the blue capacitor on the Voltage Step Up (pictured below).

I've tried changing the duty cycle having HIGH go for 25microseconds and LOW go for 5microseconds.  I've tried several combinations and a 50/50 duty cycle appears to achieve maximum volume which is 50dB.

Here's how I'm connected:
1.  The inputs of the Step Up are attached to GND and 3.3V pins on the Arduino.
2.  The output+ of the Step Up is connected to 1 pin of the Piezo.
3.  The output- of the Step Up is NOT connected to anything. (tried to connect it to GND but it didn't change anything.
3.  The other pin on the Piezo is connected to D11 on the Arduino.

I'm Running the following code:

     #include<Wire.h>

    const int SPK = 11;

    void setup()
    {
      Serial.begin(9600);
      pinMode(SPK, OUTPUT);
      digitalWrite(SPK, LOW);
    }

    void loop()
    {
      long startTime = millis();
      for (int i = 0; i < 25000; i++)
      {
        digitalWrite(SPK, HIGH);
        delayMicroseconds(15);
        digitalWrite(SPK, LOW);
        delayMicroseconds(15);
      }

      Serial.println(millis() - startTime);
    }

[![Voltage Step-Up Module][1]][1]

UPDATE:

Ok, I am now set up to look like this:
[![enter image description here][2]][2]

Is this the next step (ie: Adding an Inducer) ?

[![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/bW2yi.jpg
  [2]: https://i.stack.imgur.com/bEQx6.png
  [3]: https://i.stack.imgur.com/lGx5b.png

body:
The device you pictured seems to be a switch-mode power module which will output 10V **DC**. Get rid of it before you do any damage.

You don't post any link to data, but I assume you mean the Transducer needs 10V peak-to-peak.

This can easily be accomplished by using 2 digital outputs, connected to the transducer, and driven in anti-phase.

The answer to https://arduino.stackexchange.com/questions/19250/push-pull-tone-code may be an answer to your problem, but may be overkill. If you just want to output a single tone it is easily done with simple code.

I don't know why you think the transducer outputs 50dB. If it really is doubling the drive voltage will only give 56dB.


body:
Alternatively there are [COTS parts][1] (Common Off The Shelf) which are simpler to use and may satisfy your requirements.  This is just the 1st one I found (search for "5 volt piezo buzzer").  Of course you have no control over the frequency.  These type of devices are just to get your attention (you didn't say what your application was for).   While it works at 5 volts it is only rated at 85dB @ 10cm.  It appears to contain an internal driver so (apparently) only needs 3 to 15 volts to start making noise.  It is specified to draw 10mA at 12V.  So be careful and measure the current (using a power supply, not from an Arduino) demand at 5 volts.  I think the [GPIO pins on an Arduino can only handle less than 40mA][2].  So stay well below that to be safe.

  [1]: http://www.alliedelec.com/m/d/884b78cb9e915349d3e84cb62d58bd3e.pdf
  [2]: http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations


message:
Lighting LED Strip via HC-06 Bluetooth Module

**What I Am Working With:**
I am working on a project involving an Arduino, some RGB led strip, and my PC.

**My Project:**
The PC sends UART (serial) data to the Arduino over Bluetooth (through a HC-06 Bluetooth module connected to the Arduino) to change the color of the LED strip. The user could also change "lighting modes" to instruct the Arduino to make the LED blink, fade, etc.

**My Problem:**
Having no RTOS nor interruptions on data reception, it would be impossible for me to make the LED fade and, also, to receive Bluetooth data to change the lighting mode.

I would appreciate whatever input the community has regarding this problem.

Thanks in advance,
Stanislas.

body:
Yes, it can be done. You don't need a realtime OS for something as simple as that. Basically in your loop function you would check the serial port and parse the input (if available) to see if the PC instructed the arduino to change its mode. Then you would call a function - say nextstep() - which would perform whatever the next step is, depending on your current mode. True, when you get serial input your loop() will take longer to execute, which will alter the 'rhythm' of your fades etc. If this is important, you should replace the call to delay() with a loop checking millis() against a value stored at the start of loop().

    int currentmode ;
    int previousmode ;

    void loop()
    {
       previousmode = currentmode ;
       currentmode = getnewmode(currentmode) ;
       if (currentmode != previousmode)
          initmode(currentmode) ;  // turn new mode on e.g. change LED color
       nextstep(currentmode) ;     // if current mode is dynamic, make change
       delay(DELAY_INTERVAL) ;
    }

    int getnewmode(oldmode)
    {
       if (!serialpending()) // no serial input
          return oldmode ;
       return parseinput() ;
    }


message:
Is it possible to overclock the baudrate from the mega to 230400 bps?

i have a Arduino Mega 2560 and want send data with 230400bps to my laptop without any framingerror.

I want send the data over USB with serial.print ist that possible or must i use the ethernet?

When that is possible it will be really nice when someone can write what i have to do.

With friendly wishes sniffi

body:
> Is it possible to overclock the baudrate from the mega to 230400 bps?

Yes, setting that baud-rate is not a problem but this specific baud-rate may will give a high error rate. According to the AVR baud-rate calculation (UBRRn Settings for 16 Mhz system clock) the error is 8.5% (U2Xn=0) and -3.5% (U2Xn=1).

Simply choosing 250000 bps will remove this error.

Cheers!


message:
AVRDUDE Error (Arduino Leonardo)

I, like many others, have encountered the avrdude error. However, I am not sure how to go about fixing mine after looking at numerous forums, etc.

    avrdude: verification error, first mismatch at byte 0x0002
         0x74 != 0xe6
    avrdude: verification error; content mismatch

I am simply trying to upload a simple sketch, but right when it seems it is about to finish, I get this error and the uploading loading bar simply never finishes...

Thanks for the help!

body:
I had lots of issues when I first started.  these are all things I tried and at least one of them stopped this problem occurring, but I haven't a clue which.

 1. Close the IDE (if you are using it and open it again)
 2. Disconnect your board, wait 10 seconds and reconnect it.
 3. Check you settings, are you using the correct board, etc.
 4. Use a different cable.
 5. Update your drivers.
 6. Update your IDE/Toolset.
 7. Use a different physical port on your PC.
 8. Load the Blink example, if that doesn't work you serious have issues.
 9. Reboot your PC.
 10. If you can, try a different PC.


body: I have a USB socket on the PC which causes the Arduino to lose track of its COM port although apparently Ok with other USB devices. Check your COM port before and after you try uploading.


message:
Overwritten EEPROM

I have a problem with the Teensy, its EEPROM and another Array.

My program contains two Arrays, the first one is a 128x4 long Array, the other one a 2560x2 double Array. The first Array is meant to be written to the EEPROM once a certain time (=number of loops) is reached. The other Array is meant to be written to an SD-Card or just the terminal, can't deiced yet.

My problem is that whenever I uncomment the save()-function the first 17 data-quadruples in the EEPROM get somehow overwritten by random data. Always the first 17 with would be the first 68 numbers or 272 byte.

I have tried renameing the save()-function, but the onlything that works for now is to comment the function in the loop()-function out so that it won't be called at all. I even have enough RAM left, the Arduino IDE tells me I am using about 73% of the RAM for variables.

Could it be that be creating more variables somewhere else the Teensy overwrites the Array for the EEPROM? But than again why doesn't that happen if I don't write into the everything-Array?

Thank you in advance for any help!

Greetings,

John

PS: Please excuse my not perfect English for it's not my native language.

    //Includes
    #include <stdlib.h>
    #include <stdio.h>
    #include <math.h>
    #include <SPI.h>
    #include <String.h>
    #include <EEPROM.h>

    elapsedMillis looptime = 0; //time for each loop in ms
    int loopnumber = 0; //number of loops
    elapsedMillis overalltime = 0; //overalltime in ms
    const int iterationtime = 25; //time for each loop in ms

    //EEPROM
    //Deklarations
    int nsd = 0; //counter for saving into eepromArray
    const int maxArrayrows = 128; //Max number of row in eepromArray
    int iArray = 0; //Number of used rows in eepromArray
    long eepromArray[128][4]; //Array for EEPROM-storage
    bool writtentoEEPROM = false;
    double everything[2560][2]; //Big Araay with a pair of numbers of each loop

    // Some more variables
    double z, zpunkt, alpha, angle;

    void setup() {
     // Just inititialing stuff, nothing to do with the Arrays
    }

    void loop() {
      //Calculating more stuff

      ++nsd;
      if (nsd >= 20) {
        WritetoArray();
      }

      save(loopnumber);

      ++loopnumber;

      looptime = 0;
    }

    //********************************************************
    //
    // Save Data in Array. If full write into EEPROM
    //
    // long: 4 byte
    // Storeage needed for each quadruple: 4*4 byte = 16 byte
    // EEPROM-size: 2 kibyte
    // Max number of quadruples: 2048 byte / 16 byte = 128
    // Quadrupels per second: 2
    // Max time: 128 / 2 = 64 s
    //
    //********************************************************
    void WritetoArray() {
      int scale = 10000;
      long zArray = (long)(scale * z);
      long zpunktArray = (long)(scale * zpunkt);
      long alphaArray = (long)(scale * alpha);
      long angleArray = (long)(scale * angle);
      if (iArray < maxArrayrows) {
        eepromArray[iArray][0] = zArray;
        eepromArray[iArray][1] = zpunktArray;
        eepromArray[iArray][2] = alphaArray;
        eepromArray[iArray][3] = angleArray;
        ++iArray;
      }
      else {
        if (writtentoEEPROM == false) {
          WritetoEEPROM();
          writtentoEEPROM = true;
        }
        while(true){
          for(int n = 0; n < 2560; ++n){
            Serial.printf("%f, %f\n", everything[n][0], everything[n][1]);
          }
          Serial.println("----------");
        }
      }
      nsd = 0;
    }

    //********************************************************
    //
    // Write Data to EEPROM
    //
    //********************************************************
    void WritetoEEPROM() {
      byte data;
      int adress = 0;
      int  i = 0;
      while (adress < 2048) {
        for (int n = 0; n <= 3; ++n) {
          for (int a = 0; a <= 3; ++a) {
            data = (eepromArray[i][n] >> ((3 - a) * 8)) & 0x000000ff;
            EEPROM.write(adress + a, data);
          }
          adress = adress + 4;
        }
        ++i;
      }
    }

    //********************************************************
    //
    // Save data-pair for later usage
    //
    //********************************************************
    void save(int l) {
      everything[l][0] = z;
      everything[l][1] = angle;
    }

body:
In your loop(), you increment repeatedly loopnumber without ever resetting it. You should at the very least replace

    loopnumber++ ;

with

    loopnumber = (loopnumber+1)%60 ;

Otherwise, when loopnumber becomes >= 2560, your save() function will begin writing outside the 'everything' array and overwriting whatever is written in the adjacent positions of memory.


message:
What is using up all the RAM in my program?

I am running a program on the ATtiny and for some reason I am way over the 512 bytes of RAM that are available to me. This is confusing because when I did the math by hand I should have 432 bytes. Here is my code:

    #include <SoftwareSerial.h>

    #define FASTADC 1

    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    SoftwareSerial mySerial(0,1);    //This uses 47 bytes of RAM

    byte i = 0;      This uses 1 byte of RAM

    byte pixelsArray1[128];   //Arrays use 128 bytes of RAM each
    byte pixelsArray2[128];
    byte pixelsArray3[128];

    void setup()
    {
    #if FASTADC
    // set prescale to 16
    sbi(ADCSRA,ADPS2);
    cbi(ADCSRA,ADPS1);
    cbi(ADCSRA,ADPS0);
    #endif

    pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
    pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
    pinMode(A3,INPUT);         //Input for Camera 3
    pinMode(A2,INPUT);         //Input for Camera 2
    pinMode(A1,INPUT);         //Input for Camera 1

    mySerial.begin(9600);     //Setting the data transfer rate
    }
It's telling me that I am using 510 Bytes of memory but my math gave me 432 bytes of RAM. Does anyone see what I'm missing?

body:
There is a lot you are missing.  Such as:

1. SoftwareSerial is using RAM.
2. The system stack is using RAM.
3. The Arduino core software is using RAM.

There's plenty more going on than just your sketch. For instance, where do you think it stores the current `millis()` and `micros()` counts? Where do you think incoming serial data gets buffered? Where do you think your registers, PC, etc, get stashed when a function (such as `setup()`) is called? All that takes RAM.


message:
Extracting a specific sequence of characters from an array

I have a character array called `storebuffer` that contains data from a POST submission and its in the format `ssid=abcdef&pswd=ghijk`. I wanted to extract everything after `ssid=` into one array called `acqSSID` and the portion after `&pswd=` into another array called `acqPaswd`. I tried using this but it does not seem to be working. MAX_STORE_BUFFER_LEN is 255. Can anyone help?

    int ctr = 0;
    for (ctr = 5; ctr < MAX_STORE_BUFFER_LEN; ctr++)
    {
      if ( (storebuffer[ctr] == '&') && (storebuffer[ctr+1] == 'p') && (storebuffer[ctr+2] == 's') && (storebuffer[ctr+3] == 'w') && (storebuffer[ctr+4] == 'd') && (storebuffer[ctr+5] == '=') )
      {
        break;
      }
      acqSSID[ctr] = storebuffer[ctr];
    }

    Serial.print("acqSSID: ");
    Serial.println(acqSSID);
    Serial.print("ctr: ");
    Serial.println(ctr);

body:
Rather than `acqSSID[ctr] = storebuffer[ctr];`, say (eg) `acqSSID[ctr-5] = storebuffer[ctr];`.  Also, after the break but before printing `acqSSID`, say `acqSSID[ctr-5] = 0;` to terminate the string.

Note, rather than coding a literal 5, you might say `enum { acqOffset=5 };` up front, and subsequently use `acqOffset` in place of the literal.


body:
You can simply chop it up in place without requiring more than a few extra bytes of RAM using `strtok()`:

    char storebuffer[] = "ssid=abcdef&pswd=ghijk";

    // Slice it into two parts around the &:
    char *lefthalf = strtok(storebuffer, "&");
    if (lefthalf != NULL) { // We found a & and split the string OK
        char *righthalf = strtok(NULL, "&");

        // Now you can slice each half around the =
        char *ssidtag = strtok(lefthalf, "=");
        char *ssid = strtok(NULL, "=");
        char *pswdtag = strtok(righthalf, "=");
        char *pswdtag = strtok(NULL, "=");

        Serial.print("SSID: ");
        Serial.println(ssid);
        Serial.print("Password: ");
        Serial.println(pswd);
    }

The existing string gets chopped up and the pointers point to different places:

    ssid\0abcdef\0pswd\0ghijk
    ^     ^       ^     ^
    1     2       3     4

    1: ssidtag
    2: ssid
    3: pswdtag
    4: pswd


message:
Would rewriting my code in C help reduce RAM usage?

So my program fails to run because there is not enough room for my variables as well as the Arduino Core and Stack. I can't find any more ways to optimize my program so I'm thinking about just rewriting it in C.

However, I'm not sure if that will actually help me. For example I know that in C my program will run faster because things like `digitalWrite()` and `analogRead()` have a bunch of "extras" that make it go slower, but I don't know if this will affect RAM.

So can any of the experts on here tell me if writing my code will help before I waste time doing so?

Here is my code:

    #include <SoftwareSerial.h>
    #include <avr/pgmspace.h>

    #define FASTADC 1

    // defines for setting and clearing register bits
    #ifndef cbi
    #define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
    #endif
    #ifndef sbi
    #define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
    #endif

    SoftwareSerial mySerial(0,1) PROGMEM;

    byte i;

    byte pixelsArray1[128];   //Array to hold the values of the individual pixles.
    byte pixelsArray2[128];   //Array to hold the values of the individual pixles.
    byte pixelsArray3[128];   //Array to hold the values of the individual pixles.

    void setup()
    {
      #if FASTADC
       // set prescale to 16
       sbi(ADCSRA,ADPS2);
       cbi(ADCSRA,ADPS1);
       cbi(ADCSRA,ADPS0);
      #endif

      pinMode(1,OUTPUT);        //Setting the 1 pin to be used for output
      pinMode(0,OUTPUT);        //Setting the 0 pin to be used for output
      pinMode(A3,INPUT);        //Input for Camera 3
      pinMode(A2,INPUT);        //Input for Camera 2
      pinMode(A1,INPUT);        //Input for Camera 1

      mySerial.begin(9600);     //Setting the data transfer rate
    }

Notes:

- I'm programming on the ATtiny85
- I'm running Windows 10
- I've never programmed in Arduino before

body:
The simplest approach to reducing RAM usage of the program shown is to get rid of the three 128-byte pixel arrays.  They are not needed for the program to function.

Instead of writing

    pixelsArray1[i]=analogRead(A1)/4;
    pixelsArray2[i]=analogRead(A2)/4;
    pixelsArray3[i]=analogRead(A3)/4;

write

    if (analogRead(A1)/4 == 0 && analogRead(A2)/4 == 0 && analogRead(A3)/4 == 0) ++foundZero;

where `foundZero` is initialized to zero before the loop.  After the loop, you say something like

    while (foundZero--) {
      digitalWrite(1, HIGH);
      delay(2000);
      digitalWrite(1, LOW);
      delay(2000);
    }

to toggle pin 1 as many times as there were three zero pixels.

Note, the timing of the `if (...) ++foundZero;` statement may differ from pixel to pixel because the `&&` evaluation may short circuit.  If the timing matters, save data in temporary variables, or check if the sum of the three is zero, etc.


body:
I don't believe that rewriting it in C is going to help you much: the framework is pretty tight already, and you'd only get the C library's versions of the various drivers' buffers etc.

I do think your only solution (apart from getting larger hardware!) is to 'optimise' the `pixelArray`s. To do that, could you consider the following questions:

1. What is the worst value resolution that you'll get away with? You're currently compressing each camera feeds' pixel to the range 0-255, to store them into their individual bytes. What about 0-31? (See why below)
2. Will you always be comparing each feed's individual pixels against the same pixel in another feed? If so, perhaps you could pack all three values into one 16-bit quantity:
`X 11111 22222 33333`
where each quintet of bits is that feed's value compressed down. The `X` is cute: before compressing, you could compare all three values with each other, or zero, or something, and if true set the X bit to `1`. That then means that you can later test for that exact condition in the triple-pixel with a `<0` check - the sign bit will be set, so the condition will be true.
3. Or, if compressing down to 0-31 is too extreme, what about storing a 'master' copy of the pixel, and then two (scaled) differences from there: `11111111 2222 3333` where the master `1` value is unscaled (other than `/4`), while the other values are from the following table:

    `0000` - Identical pixel value
    `0001` - Within +2
    `1111` - Within -2
    `0010` - Within +4
    `1110` - Within -4
    `0011` - Within +8
    `1101` - Within -8
    `0100` - Within +16
    `1100` - Within -16
    `0101` - Within +32
    `1011` - Within -32
    `0110` - Within +64
    `1010` - Within -64
    `0111` - Within +128
    `1001` - Within -128
    `1000` - More than ±128
4. Even more radical: could you do all the tests when you read the data (do you have time???), and then simply store a one-bit result for each pixel? Such a packed-bit array is VERY efficient - if you can boil down your decision to yes/no...

I'd be happy to help write (reasonably) efficient C code to implement the TriplePixel functions - or even attempt it in assembly...


message:
Unable to create a desired periodic signal with Arduino Mega 2560 and DAC0808

I wrote the code to produce the periodic signal by using arduino and DAC0808 where i turned on and off the respectively pins of PORTA by using a logic in iterative manner and created the periodic signal. But even without using delay logic, i couldn't get signal time period as comparable to 50 Hz voltage signal. And what i seek to get is to decrease the time period of generated signal. Pls note, blue signal is reference signal of 50Hz frequency.

    float increment = 3.14159 / 500;
    float initial = 0;
    float value = 0;

    void setup() {
      Serial.begin(115200);
      DDRA  = B11111111;
    }

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

      PORTA = B00000000;
      while (1)
      {
        initial = initial + increment;
        value = sin(initial)  * 255;
        PORTA = abs(value);
      }

    }
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/UyZ8f.png

body:
I'm interpreting your phrase “even without using delay logic, i couldn't get signal time period as comparable to 50 Hz” as meaning that the code shown runs Too Slow.  At 1000 samples per cycle and 50 Hz on an 8-bit 16-MHz processor, you only have 320 clocks to compute a `sin()`, which probably is not enough to compute a 32-bit floating `sin()`.

To speed it up, you can either issue fewer samples per cycle or make the loop go faster.

For the “fewer samples per cycle” approach, you would make `increment` bigger; for example, instead of 3.14159/500, or 1000 samples per cycle, perhaps an interval of 2π/500, or 500 samples per cycle.

For the “make the loop go faster” approach, you could use a lookup table or fixed-point integer arithmetic or both.  Note, the lookup table only needs to cover 90° (or π/2 radians); index in reverse for quadrants 2 and 4, and negate values for quadrants 3 and 4.

Note, after you speed up the code, you will need to set up a time base for issuing samples.  This could use a clock-based interrupt routine that gets and issues the next array value, or that sets a flag so your main loop can get and issue a value.  Or you could spin until `micros()` exceeds a deadline, at which time you (1) issue a value, (2) set the next deadline, and (3) compute the next value.


body:
As has been mentioned before, in comments and in jwpat7's answer, your
main problem here is the time taken to compute the sines. I already
provided a link to a [faster fixed-point implementation of
`sin()`][sin_fix] but, since you have an Mega2560 with loads of RAM, I
would go to the simpler look-up table method. I would not even bother
optimizing the size of the table.

For controlling the timing, you can use the canonical method described
in the [Blink Without Delay][] Arduino tutorial, with one twist: times
should be measures with `micros()` instead of `millis()`. Here is a
first version of the program:

<!-- language-all: lang-c++ -->

    const float FREQUENCY = 50;            // hertz
    const float PERIOD = 1e6 / FREQUENCY;  // microseconds
    const size_t TABLE_SIZE = 512;
    const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
    uint8_t wavetable[TABLE_SIZE];

    void setup()
    {
        // Prepare the wavetable.
        for (size_t i = 0; i < TABLE_SIZE; i++) {
            wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
        }

        // Set port A as output.
        DDRA = 0xff;
    }

    void loop()
    {
        uint16_t now = micros();
        static uint16_t last_sample;
        static size_t phase;

        if (now - last_sample > SAMPLE_TIME) {
            last_sample += SAMPLE_TIME;
            PORTA = wavetable[phase];
            phase = (phase + 1) % TABLE_SIZE;
        }
    }

A few things worth noting:

1. The float constants `FREQUENCY` and `PERIOD` are used only at compile
   time.
2. The table size is a power of two because wrapping a table index
   modulo a power of two is way faster than modulo, say, 500: the
   compiler optimizes the modulo into a bitwise AND.
3. The `+ 0.5` in the expression of `SAMPLE_TIME` is intended to ensure
   that the result is rounded to the _nearest_ integer. In this instance
   it happens to be useless because rounding down would give the same
   result.
4. The `micros()` function returns a 32-bit integer, but in this
   application it is sufficient and faster to track only the 16 least
   significant bits, hence the `uint16_t` timing variables. And no,
   [these variables overflowing is not a problem][millis rollover].

This should give you, in theory, a frequency of 50.08 Hz, i.e.
0.16% too fast. The discrepancy is due to `SAMPLE_TIME`, which should be
39.0625 µs, being rounded to 39 µs. You could fix this by
counting time with a higher resolution, but given the poor accuracy of
the ceramic resonator clocking the Arduino, this is probably not worth
the trouble.

A potentially worse problem is the large jitter you have with this
approach, on the order of 10 µs. This is due both to the time taken
to run through the loop and the occasional timer interrupt taking some
extra time. You can get rid of this jitter by using a timer interrupt
instead of `micros()`. Here is a second version of the program that uses
this approach:

    #include <avr/sleep.h>

    const float FREQUENCY = 50;              // hertz
    const float PERIOD = F_CPU / FREQUENCY;  // CPU cycles
    const size_t TABLE_SIZE = 512;
    const uint16_t SAMPLE_TIME = PERIOD/TABLE_SIZE + 0.5;
    uint8_t wavetable[TABLE_SIZE];

    int main()
    {
        // Prepare the wavetable.
        for (size_t i = 0; i < TABLE_SIZE; i++) {
            wavetable[i] = 255 * abs(sin(M_PI * i / TABLE_SIZE));
        }

        // Set port A as output.
        DDRA = 0xff;

        // Configure Timer 1.
        OCR1A = SAMPLE_TIME - 1;  // set the period
        TIMSK1 = _BV(OCIE1A);     // enable TIMER1_COMPA interrupt
        TCCR1B = _BV(WGM12)       // CTC mode with TOP = OCR1A
               | _BV(CS10);       // clock at F_CPU / 1

        // Sleep while waiting for interrupts.
        sei();
        sleep_enable();
        for (;;) sleep_cpu();
    }

    // Service routine for the Timer 1 interrupt.
    ISR(TIMER1_COMPA_vect)
    {
        static size_t phase;

        PORTA = wavetable[phase];
        phase = (phase + 1) % TABLE_SIZE;
    }

Again, a few notes:

1. The `SAMPLE_TIME` is now computed in CPU cycles and, since it is an
   integer number of cycles (namely 625), there should in principle be
   no frequency discrepancy.
2. For counting 625 cycles we need a 16-bit timer clocked at the full
   CPU speed (prescaler = 1). We are using Timer 1 here. See the
   [datasheet of the ATmega2560][ATmega2560], chapter 17, for details on
   using the timer.
3. Sleeping between interrupts is needed in order to obtain
   cycle-accurate timings. If we had simply an infinite loop, there
   could be a few CPU cycles of jitter, which may not be a big deal.
4. Writing `main()` instead of `setup()` and `loop()` is a way to skip
   the initialization normally done by the Arduino core library. In this
   application that initialization is better avoided, because it creates
   an extra jitter-inducing interrupt and it messes with Timer 1 in a
   way that we would need to undo.

[sin_fix]: https://www.logre.eu/wiki/Trigonométrie_en_virgule_fixe
[Blink Without Delay]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
[millis rollover]: https://arduino.stackexchange.com/questions/12587

[ATmega2560]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf


message:
Is the a low memory alternative to SoftwareSerial?

I'm running a program on a ATtiny85 and running into problems because of a lack of available RAM. When I ran `avr-nm` on my ELF file I found that SoftwareSerial was taking up a lot of RAM even though I'm just using it to set the data transfer rate with `mySerial.begin(9600);` and nowhere else.

So I'm wondering if there is another way of doing this without using so much memory:

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(0,1);

    mySerial.begin(9600);

body:
Simplest thing would probably be to edit your copy of SoftwareSerial.h
and replace [`#define _SS_MAX_RX_BUFF 64` on line
42](https://github.com/arduino/Arduino/blob/master/hardware/arduino/avr/libraries/SoftwareSerial/src/SoftwareSerial.h#L42)
by something smaller. If your `loop()` runs fast enough (no delays, no
blocking code) you could probably get away with buffering only a very
few bytes.

Or you could rewrite the library so that, instead of buffering the
incoming bytes, it handles them to you for processing. See for example
this [receive-only UART code based on the USI
port](http://www.technoblogy.com/show?VSX) for an illustration of the
approach.


message:
Create a library without a class?

I'd like to know if it's possible to create a library for Arduino that does not contain a class, just functions.

I know how to create a library with a class, but I'd like to create a library of general purpose functions that don't need to be instantiated to be used. Just used like the standard functions included in the Arduino IDE:  sizeof(), etc..

Is this possible?  If so, can anyone point me in the direction of a template?  I've been searching, but haven't found anything.

Thanks!

body:
Yes, it's possible.

Just don't make a class. Just make functions instead.

Like a class-based one, have a `.cpp` and a `.h` file. In the `.cpp` file (or `.c` file if you don't want any of the C++ functionality or 90% of the Arduino API available to you) place your functions.

In the `.h` file place prototypes for them. I am in the habit of adding the `extern` keyword, but you don't actually need to for functions.

For example:

    foo.cpp:

    void doSomething() {
        // whatever
    }

    foo.h:

    extern void doSomething();

Then you can include your `.h` file and call your functions:

    #include <foo.h>

    // ...

    doSomething();


message:
Arduino mega 2560 Stacked with Ethernet/SD card Shield Heat up

Stacked mega and ethernet/sd shield:

[![enter image description here][1]][1]

When I do this stacking, it heats up. I tried connecting the SPI via ports 13-10 (no stacking), it doesn't work. Also tried connecting the ICSP (red circled mark) via male-female wires without stacking, it works, but still heats up. So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?

*PS: the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.

**update, I think I got it working, the problem was not about the heating, but the program. Consulted a more experienced person, he said what's happening is normal.

  [1]: https://i.stack.imgur.com/Ufrib.png

body:
> *the heat in the "pain" level when I touch it, no burning IC odor. Maybe it's because I unplug it immediately after short use? IDK.
> So I think the ICSP has a defect? or does it? Is it supposed to be like this and I'm just being paranoid?*

Well you're right in being a bit paranoid. And temperature building up is very likely to mean you've got a short somewhere, it might be a bad solder or a component that fails (like a cap that conducts).

So you've got to isolate the issue:

1. Isolate the faulty board: whichever board is getting hot, it might be that one that has a failure *or* the other one ruining it
 * you need to try the shield with another arduino (whatever version it is) and see if the issue is replicating
 * then you need to try the arduino you were using with another shield running on ICSP (like another ethernet shield, or an SDCard shield), which will confirm the hypothesis that only one component of the two is failing.
2. Once you've isolated the board, you need to isolate the component.
 * you first have to isolate which component is building up heat.
   - If you've got access to a thermal camera, it's a good idea to use it.
   - If not: start locating the area where heat is building with your finger, and then test each component of the area with a thermometer (like the ones you plug on a multimeter, or simply a "meat" thermometer for cooking).
3. Once you've isolated the component, then look it up on the schematics and layout, and lookup all connected components. Either that component or one on the track is failing, or there's a short on that track.

If the solution is not obvious, you can come back on Stack Exchange (get on the [electronics QA site](http://electronics.stackexchange.com) with your results), and some EE expert will help you find out what's wrong!

HTH


message:
Basic Question - ESP8266 Board Pins

I have an embarrassingly simple question.

My experience to date has been limited to Arduino Uno + Wifi101.  I bought an ESP8266 and noticed that the GPIO pins don't match the printed numbers on the board.

When programming and defining pins, does `#define <pin name> 16` call the pin with the printed designation D0?

I can't find a straight answer to this anywhere.

Image credit: http://crufti.com/content/images/2015/11/nodemcudevkit_v1-0_io.jpg

[![NodeMCU ESP8266][1]][1]

  [1]: https://i.stack.imgur.com/93qIq.jpg

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

  [1]: https://github.com/esp8266/Arduino


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

[![Arduino Uno pin mappings][1]][1]

(Image credit: <https://www.arduino.cc/en/Hacking/PinMapping168>)

There, for example, pin 2 on the chip, is D0 (digital pin 0) on the board.

Their board will use their own mappings, but the concept is the same.

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

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

  [1]: https://i.stack.imgur.com/W6hdF.png


body:
Well based on my experience with [NodeMcu][1] and Arduino, in Arduino you use the GPIO by reffering its pin number (like 0-13), whereas in NodeMcu you will have to use D0-D8.

It's better to use D0 to use GPIO 16.

  [1]: http://www.nodemcu.com/index_en.html


message:
Serial available doesn't work right after upload

I have 2 programs to test serial communication, an simple arduino program that echoes whatever is on the serial port and a python program that writes to the serial port and prints the reply.

I'm having an issue where whenever I upload the arduino program and try to run the python code the arduino code wouldn't detect serial available on the first run.  I would have to either

 - open and close serial monitor before I run python program
 - run the python program, quit, and run it again

and it would continue to work until I re-upload the arduino then the same thing happens.  Does anyone know what is the issue?  This is on Ubuntu.

arduino

    String str;

    void setup() {
    // Turn the Serial Protocol ON
      Serial.begin(115200);
    }

    void loop() {
      if (Serial.available()) {
          str = Serial.readStringUntil('\n');     // Read the serial input
          Serial.println(str);             // sends ascii code

      }
    }

Python

    import serial

    ser = serial.Serial('/dev/ttyACM1', 115200)

    for i in range(0,4):
        str = "test string\n"
        ser.write(str)
        print ser.readline()

body:
This fails due to the typical auto-reset-on-open serial port configuration interacting with a problematic assumption made by the PC code.

The first issue means that it will typically take a few seconds between when the port is opened (unless the port is configured *not* to manipulate modem control signals on open) and when the usual bootloader times out, yields to the custom sketch loaded in the Arduino, and the latter becomes able to accept input and potentially respond.

The second issue is with the PC side code:

    for i in range(0,4):
        str = "test string\n"
        ser.write(str)
        print ser.readline()

Assuming that `import serial` refers to [pySerial][1], then because you did not specify a timeout when opening the port, the `ser.readline()` is an eternally **blocking read**.  To quote the documentation:

>Be carefully when using readline(). Do specify a timeout when opening the serial port otherwise it could block forever if no newline character is received.

If we look at what happens with your python program and a typical serial port configuration where modem status lines change on open, then the first thing your program does is implicitly reset the Arduino.  Next, it writes "test string\n" - but because of the reset, it writes this at the bootloader, not the sketch which is not running yet.  Finally your program eternally waits for a newline terminated reply - which it will never receive, because your sketch will not send that until it receives something from the PC, which will not send anything else until it receives the newline terminated response to its first message.

**Your programs are thus stuck in a "no, after you" deadlock.**

There are many potential ways to work around this.  For example, you might open the port with a timeout, wait a few seconds, and conduct this test write and attempt to read a reasonable number of times, but declare an error to the user if success is not achieved in ten or so seconds of those attempts.

Note also that the sketch may start running midway through transmission of the test string, so you will have to handle the possibility of a message with the beginning missing, either by declaring an error or discarding it and waiting for a subsequent intact one.

  [1]: https://pythonhosted.org/pyserial/index.html


message:
Remove certain characters from char*

I've got an array of char* with serial data that I'm trying to remove ':' from. I have tried to iterate through the char*, find and remove any colons but it just comes out as garbage.

<!-- language: c -->

      char* espData[15];

      // pull data from serial and tokenize with strtok > feed to espData

      for(int x = 0; x < index-1; x++){
        size_t nullTerm = strlen(espData[x]);
        espData[x][nullTerm - 1] = '\0';
        char* output
        for(size_t i = 0; i < strlen(espData[x]); ++i){
          if(espData[x][i] != ':') output += espData[x][i];
        }
        espData[x] = output;
        Serial.println(espData[x]);
      }

Moving the null character works fine (I wanted to get rid of the last character in every string). Most of the answers I found for general C++ used std::string which we don't have access to.

body:
You've assumed that a `char *` is some kind of string object, since you've got the following line of code: `output += espData[x][i];`, and then later `espData[x] = output;`

It quite simply doesn't work like that. At best you can point `output` inside `espData[x]` and then do some other logic: but your attempt to "accumulate" the correct characters is incorrect.

Please consider the following code instead:

    char* espData[15];

    for(int x = 0; x < index-1; x++){
        size_t nullTerm = strlen(espData[x]); // Get current length
        char* output = espData[x];            // Start of string
        for (size_t i = 0; i < nullTerm; ++i){
            if(espData[x][i] != ':') {        // If it's NOT a colon
                *output++ = espData[x][i];    // Copy character 'up'
            } // if
                                              // If it WAS a colon, then
                                              // output does NOT get incremented
        } // for
        *output = '\0'; // End string off with NUL
        Serial.println(espData[x]);
    } // for


message:
Dynamicly sized array as a class member

I want to create a dynamic sized array of chars as a member in a class.
This is being done inside a library that I've created.
I have the `.h` and the `.cpp` files created. I'm not sure how to declare the array in the `.h` file. I've tried a few things so far:
`char* content;`
`char content[];`
But these don't seem to work.

Here's what I have in my `.h` file:

    class bufr{
     public:
  //constructor and deconstructor
  bufr(char* _chars, uint8_t _len);
  ~bufr();

  //variables
  uint8_t len;
  char content[];

    };

Here's what I have in my `.cpp` file (this is the constructor):

    bufr::bufr(char* _chars, uint8_t _len){
     char* content = new char[_len];
     content = _chars;
     len = _len;
 }

I've also tried replacing the line `content = _chars` with:

    for (int i = 0; i < _len; i++){
        content[i] = _chars[i];
    }
But this also doesn't work.  When I print the `content` member to the serial port from within the constructor, or in the main loop it prints nonsense characters, not what I passed it.

Here's my main loop:

    void loop(){
        char chars[] = "1234";
        bufr buf(chars, 4);
    }

Have I explained myself well enough?  Can anyone give me a hand?
Much appreciated!

Oh, and yes, I know - in my deconstructor that's not shown, I have `delete [] content`

I plan on using this class nested inside another class in a few spots and hoping to take advantage of the dynamic mem allocation.  I know I can simply declare an array of fixed length, but I wanted to learn the proper way to use `new` and `delete`.

Thanks!

body:
This is wrong on a number of levels. First in the class declaration:

    char content[];

<s>That gives you a pointer to an array of zero length.</s>

This gives you an array of char, of zero length. This is not useful.

    char* content = new char[_len];
    content = _chars;

That does a `new` into a **new** variable `content` - not the class variable. Then you assign (overwrite) the passed pointer into `content` (discarding the memory you just allocated). That pointer is then discarded when the constructor ends. Perhaps using `strcpy` would be better.

I made up a small example based on your code which prints the correct result:

    class bufr
      {
      public:
        //constructor and deconstructor
        bufr(char* chars, uint8_t len);
        ~bufr();

        //variables
        uint8_t len_;
        char * content_;
      };    // end of class bufr

    bufr::bufr(char* chars, uint8_t len)
      {
      content_ = new char[len];
      memcpy (content_, chars, len);  // copy into allocated memory
      len_ = len;   // remember length
      }   // end of constructor

    bufr::~bufr()
    {
      delete [] content_;
    } // end of destructor

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

      char chars[] = "1234 ";
      bufr buf(chars, sizeof chars);

      Serial.println (buf.content_);
    } // end of setup

    void loop()
    {
    } // end of loop

---

> Can you explain to me why it was making a new variable content and not using the class variable?

Small example:

    char * content;

    void loop ()
      {
      char * content = "foo";  // makes a NEW variable
      }

In this example there are **two** variables named `content`. The one in the function "shadows" the global one. However the code below only has one variable:

    char * content;

    void loop ()
      {
      content = "foo";  // uses existing variable
      }

---

> In the destructor, when you delete the pointer to the array, does this free up the memory allocated to the array? It's now free to be assigned again by something else? Or does it sit there still initialized as that array, not being able to be used again?

You aren't deleting the pointer. You are deleting the *memory it points to*. The pointer is now pointing to freed memory, so using it as a pointer at this stage would be wrong. You can do another `new` to make it point to something else.

---

> they delete pointer and then delete[] pointer.

You misinterpreted that. You either `delete pointer` **or** `delete [] pointer` depending on whether `pointer` is an array or not. I reworked `content` to not be an array, <s>thus deleting it without the brackets is correct</s> however as it is allocated using `new []` it must be deleted with `delete []`.

---

> on the link posted above they say to use delete this way: delete pointer if it was a single element allocated with new or delete [] pointer to release memory allocation for arrays of elements allocated with new and a size in []'s. So in my case I want to use delete [] content_?

No, you don't want to be setting up an array in the first place. Take a look at this small example:

    struct   {
      char bar [];
      } foo;

    void setup()
    {
    Serial.begin (115200);
    Serial.println ("Starting");
    Serial.println (sizeof (foo));
    Serial.println (sizeof (foo.bar));
    }

    void loop()
    {
    }

That prints:

    Starting
    0
    0

The variable `bar` is a zero-length array. Thus the entire struct `foo` is also zero length. It isn't even a pointer (that would be two bytes on this platform).

It is wrong to use an array of char like that, when you want to dynamically allocate memory. Look at this:

    char foo [4];

That allocates 4 bytes of memory for `foo`. You can't later on make it longer by doing a `new`.

What you want is:

    char * foo;

Now you have allocated a **pointer** and can do a `new`, like this:

    foo = new char [10];  // allocate 10 bytes

And then delete it:

    delete [] foo;

You use the brackets on the delete, as you used them with the `new`.

If you allocated **one char** you wouldn't use brackets. eg.

    char * foo;
    foo = new char;  // allocate a pointer to one byte
    ...
    delete foo;


body:
# Many programmers have a disjoint between a pointer and an array. Here's an explanation.

### Here is a variable of type `char`, initialised with the value `'A'`:

    char c = 'A';

`'A'` has the ASCII value of 65, so that means that there's a byte in memory that holds the value 65. Let's say that byte in memory is at address `0x2000`. If you were to add `1` to that byte, it would become 66, and if you were to print it as a character, it would print `B` (ASCII 66).

### Here is a pointer to a `char`, initialised with the address in memory of `c`:

    char *p_c = &c; // Get the address of c into p_c

> [Note that `char *p_c = c;` would be invalid: you can't initialise a pointer with a `char`! That'd give `p_c` the value `65` - not what you want!]

In Arduino, `p_c` represents two successive bytes of memory that together store the address of a `char`: in this case the value 0x2000. Where those two bytes are doesn't matter for this explanation - but trust that they too have an address...

If you were to change `c` into a 'Z', that would change `c`'s contents, but not `p_c`'s (it would still be `0x2000`). But if you were to use `p_c` to look at the byte it was pointing to (`c`), then you'd see the 'Z'.

- If you were to do a `printf("%c", c);` you'd get a 'Z'.
  > `%c` means "I've got a character as the next variable in the `printf()` list".
- If you were to do a `printf("%c", *p_c);` you'd also get a 'Z'.
- If you were to do a `printf("%c", p_c);` you'd get horrible results.
  > You lied to `printf()` - you didn't give it a one-byte character, you gave it a two-byte pointer!

Now let's move on to arrays.
### Here is a variable of type `char []`, initialised with the value `"John"`.

    char s[] = "John";

`'J'` has the ASCII value 74, `'o'` 112, `'h'` 104, and `'n'` 111. That means that in memory there are four sequential bytes with the values 74, 112, 104, 111. Let's say that those bytes are at addresses 0x3000 through 0x3003.

### And here is another pointer to `char`, this time initialised with the address in memory of `s`.

    char *p_s = s; // Point to s with p_s

> I hate that the C language allows the above. It is one of the roots of the whole array/pointer confusion. It kind-of implies that `p_s` somehow gets all of `"John"` assigned to it. Nope!

A better statement would have been:

    char *p_s = &s; // Initialise p_s with the address of s // ILLEGAL!

That gives a MUCH better idea of what's happening - alas, it's not how it's done...

But also note that neither of the above could possibly store `0x3000-0x3003` (the addresses for all of `s`), so they have to be satisfied with only storing the start of the string: `p_s` will get the value `0x3000`.

Note that `s` does **NOT** have the value `0x3000` in it. That is its address, like `0x2000` was `c`'s address (it too doesn't have `0x2000` in it). But `p_s` _does_ have `0x3000` in it - and don’t forget that `p_s` also has its own address (I won't bother with that here).

### And this is where the "equivalency" (they're not) between a pointer and an array starts to get people confused:

- `s[2] = 'h';` and `p_s[2] = 'h';` do the same thing - but in different ways!
  - The first accesses `0x3002` directly.
  - The second needs to find out that `p_s` is `0x3000` and add `2` to it before it can access `0x3002`.
- `*(p_s + 2) = 'h';` is yet a third way to do the same thing.

So now let's `printf()` these new variables:

- `printf("%c", *s);` wouldn’t compile.
  > `s` is not a pointer, so you can’t dereference it with `*`.
- `printf("%c", *p_s);` would print the **character** at where `p_s` was pointing.
  > This would print out `J`.
- `printf("%c", s[0]);` would print the **character** at `s[0]`.
  > This would print out `J`.
- `printf("%c", s);` would give horrible results.
  > Again, you lied to `printf()`!
- `printf("%s", s);` would work (but see below).
  > `%s` means "I've got a sequence of characters that I'd like you to print. I've provided the address of the first character."
- `printf("%s", p_s);` would be identical to the previous one.
  > After all, the same address value was passed!
- `printf("%s", *p_s);` would give horrible results.
  > Again, you lied to `printf()`!

But note something: you've given `printf()` the beginning of the string, so it can start printing. How does `printf()` know where the end of the string is? You didn't provide the number `4`; it's not stored anywhere; how can it know when to stop?

That's where a C convention for strings steps in. By convention, when the compiler sees a string `"between quotes"`, it stores the ASCII values of the characters, and _then follows them with a `0`_. Not an ASCII `'0'` (with value 48), but an ASCII `NUL` (with value 0). Thus if you looked at address `0x3004` (the byte directly after `John`), you'd see a 0 in that memory byte. That's how `printf()` knows to stop printing - and yes, many a bug has resulted from forgetting to maintain a `NUL` at the end of a sequence of chars!

### That then leads me to the `sizeof()` function
`sizeof()` always returns a constant _at compile time_ using information that the compiler _then_ knows about:

- `sizeof(c)` would return `1`.
- `sizeof(p_c)` would return `2`.
- `sizeof(p_s)` would _also_ return `2`.
  > It is after all merely a pointer too.
- `sizeof(*p_c)` would return `1`.
- `sizeof(*p_s)` would **also** return `1`.
  > It's only pointing to a single char...
- `sizeof(s)` would return `5`.
  > The compiler knows what `s` is: an array of **5** bytes (including the final `NUL`).
- Given a pointer, there is _no (native) way_ to find out how large the buffer it is pointing to can be.

OK: so if you've got a `char []` you can find out its size. Note that that is its maximum size - the string inside it could be a lot shorter! If you did the following:

    s[3] = 0; // Overwrite the fourth character (arrays start at 0)
    printf("%s", s);

> [Note a better version of the first line would be `s[3] = '\0';` which means "store the ASCII character `0` (**NOT** `'0'`)" instead of "store the number `0`".]

you'd get `Joh` printed out. Note:

- `sizeof(s)` remains `5`;
- You can't get the length with `sizeof(*p_s)`;
- The string inside it is only 3 characters long.

So... if you've got a string buffer, or a pointer to one, how do you know how long it is? Count the number of characters until you reach a `NUL` - and there's already a function to do that for you: `strlen()`.

### Which now leads to the final point about pointers: dynamic allocation of memory.
The array `s` above was sized by the compiler at compile time: it could count the characters, add one for the `NUL`, and reserve the right number of bytes. You could also have written:

    char s[10] = "John";

which would have reserved 10 bytes and only initialised the first **5** of them. The following would be an error:

    char s[3] = "John"; // Buffer too small!

> Scarily, `char s[4] = "John";` works... (The compiler says to itself "No room for the `NUL`?! Ah well...”) Better never pass that string to `strlen()` or `printf()` then!

What if you don't know at compile time how big a string is going to be? If you know at runtime, you can ask the system for a lump of memory from the heap - a reserved area that can have chunks taken from it and returned as required. There are two ways to do this:

    char *p_b = (char *)malloc(size); // Where size is a variable
    char *buffer = new char[size];    // Grab 'size' new chars

The first calls `malloc()`, passing in the number of desired bytes. If `malloc()` can give those bytes it will reserve them and return a pointer to them. If it can't it will return `0`. You should always test the return value! If not, you'll corrupt things horribly...

The second uses the more sophisticated `new[]` syntax, which is more object oriented. Notice how `malloc()`'s return value needed to be turned into a `(char *)`? That's because it doesn't know what type of pointer it's returning, so it just picks `void *`. `new` does know, so it returns the correct type - but it still may return `0` if there's no room!

Once you've got either pointer, you use them just like `p_s` before. There is nothing stopping you from accessing outside the boundaries of the buffer - just like there isn't for `p_s`! Be careful!

Oh, and once you've finished with the lump of memory, you need to return it to the heap:

    free(p_b);
    delete [] buffer;

If you used `malloc()`, return it with `free()`. If you used `new[]`, return it with `delete[]`.

### And all of the above is why they invented the `String` object.
It manages the memory; keeps track of the string's length; lets you access and modify individual characters; lets you resize the string as needed; and gets rid of the used memory once you're finished with it. No wonder people start to use `String` syntax when they see string pointers...

But `String`s are only useful for `char`s. Arrays and pointers can be of and to anything - including `String`s and (_**GASP!**_) pointers! Uh oh - here we go again...


message:
How do I use interrupt service routines inside libraries and classes?

I'm trying to have a `millis()` timer run to emulate a hardware timer inside a library, but I'm having issues compiling the code. I want the callback (pseudo ISR) to be part of the class, and not use global variables.

I'm using [Christensen's / Monk's Timer library](https://github.com/JChristensen/Timer/tree/v2.1), but I'm open to suggestions if there are other better/easier timer libraries out there.

This is what I have so far. It's just an example for me to understand how this might work. I'm sure there are better ways of making an LED blink, but this is just for illustrative purposes.

Compiling gives a bunch of "invalid use of member variables in static functions" errors.

> error: invalid use of member 'Blink::_led_status' in static member function
         int _led_status;

EDIT
------
After trying to add glue routines as per your other answer I can seem to get one instance working, but adding another stops the first light from blinking, and the second one blinks on and off at the wrong times.

The test library is on [github](https://github.com/waspinator/test-timer)

Blink.h

<!-- language: c++ -->

    #ifndef Blink_h
    #define Blink_h

    #include "Arduino.h"
    #include <Timer.h> // https://github.com/JChristensen/Timer/master
        // Timer.h uses millis() instead of built in timers

    class Blink {
    public:
      Blink (int led_pin, int duration);
      void begin ();
      void updateTimer();

    private:
      static void _callbackGlue();
      void _callback();

      static Blink *_instance;
      Timer *_blink_timer;
      int _led_pin;
      int _duration;
      int _led_status;
      int _blink_event;
    };
    #endif

blink.cpp

<!-- language: c++ -->

    #include "Arduino.h"
    #include "Blink.h"

    Blink *Blink::_instance;

    Blink::Blink (int led_pin, int duration) {
      _blink_timer = new Timer();
      _led_status = 0;
      _led_pin = led_pin;
      _duration = duration;
      pinMode(_led_pin, OUTPUT);
      digitalWrite(_led_pin, LOW);
    }

    void Blink::begin () {
      _blink_event = _blink_timer->every(_duration, _callbackGlue);
      _instance = this;
    }

    void Blink::_callbackGlue() {
      _instance->_callback();
    }

    void Blink::_callback() {
      if (_led_status == 0) {
        digitalWrite(_led_pin, HIGH);
        _led_status = 1;
      } else if (_led_status == 1) {
        digitalWrite(_led_pin, LOW);
        _led_status = 0;
      }
    }

    void Blink::updateTimer() {
      _blink_timer->update();
    }

test/test.ino

<!-- language: c++ -->

    #include "Blink.h"

    Blink first_blink (13, 500);
    //Blink second_blink (12, 1000);

    void setup() {
      Serial.begin(9600);
      Serial.println("Starting...");
      first_blink.begin();
      //second_blink.begin();
    }

    void loop() {
      first_blink.updateTimer();
      //second_blink.updateTimer();
    }

body:
Nick Gammon's answer is good for one `Timer` - but now you want two!

OK, then you can take advantage of the Timer Library's `context` parameter. What's that? If you take a look at the header for `every()`, you'll see as well as passing in the function to call, you can _also_ pass in another value (called `context`) to pass back to that function when it fires*. So instead of you remembering just one copy of `instance`, get each `Timer` to remember it for you.
> *If you can't see the `context` parameter in `Timer.h`, then make sure you're using the [`v2.1`][1] branch, _**not**_ `master`.

So:

1. Get rid of `_instance` everywhere.
2. Change:
   `static void _callbackGlue();`
   to
   `static void _callbackGlue(void *context);`
3. Change:
   `void Blink::_callbackGlue()`
   `{`
   `_instance->_callback();`
   `}`
   to
   `void Blink::_callbackGlue(void *context)`
   `{`
   `((Blink *)context)->_callback();`
   `}`
4. Change:
   `_blink_event = _blink_timer->every(_duration, _callbackGlue);`
   to
   `_blink_event = _blink_timer->every(_duration, _callbackGlue, this);`

Note that I've submitted these changes as a Pull Request on your GitHub repo.

----

Incidentally:

You don't need `_blink_timer` to be a pointer. Get rid of the `*`, get rid of the line with `new Timer()` in it, and replace all your `_blink_timer->` with `_blink_timer.`

  [1]: https://github.com/JChristensen/Timer/tree/v2.1


body:
You may add handler (AKA hook) functions using function pointer to the Timer0 ISR inside the core wiring.c source file shipped with Arduino core, and assign latter (attache) this function pointer to any desired function in the other library/class or in the main application code.

More about this trick in this [article here][1].

  [1]: https://atadiat.com/en/micros/e-arduino-trick-share-interrupt-service-routines-between-libraries-application/


message:
Computer to Arduino to hardware, controlling on / off state of hardware via user input on computer

First time coding for Arduino. I'm working on code to operate an electronic valve switch. We have a laptop connected to an Arduino Mega, and that Arduino is hooked up to the valve (hardware) on Pin 53.

I was trying to work off of the "blink" example originally, but that gives no basis for user prompted control. Basically I want to have the computer ask me if I should turn it on or off, type in my response (I was using "HIGH" for on and "LOW" for off, as in voltage control), and have that activate or deactivate the hardware.

My main problem right now stems from how best to ask for that input. I've been trying to work with the Messenger.h library thus far. I'm definitely getting hung up on how to define the pin, or what the simplest method for user input would be. (HIGH or LOW? 0 or 1? Something else?)

Code is below. Thanks!

<!-- language: c -->

    #include <Messenger.h>

    Messenger message = Messenger();

    // Variable definitions. Switchinput is what the user commands, current state is whether the air is flowing or not.
    boolean currentstate;
    boolean switchinput;
    String pin53; // Something is up on this line?? How to define this pin??

    // FUNCTION DEFINITIONS
    // Startup fxn
    void start()
    {
      Serial.print("LOW = off, HIGH = on. Switch is ");
      Serial.println(currentstate);
      Serial.print("Enter LOW to turn on or HIGH to turn off: ");
      switchinput = Serial.read();
    }

    // Go off to on
    void offtoon()
    {
        digitalWrite(pin53,HIGH);
        currentstate = switchinput;
    }

    // Go on to off
    void ontooff()
    {
        digitalWrite(pin53,LOW);
        currentstate = switchinput;
    }

    // Stay same -- already off
    void staysameoff()
    {
      if ((currentstate = switchinput) && (switchinput = LOW))
      {
          void start();
      }
    }

    // Stay same -- already on
    void staysameon()
    {
      if ((currentstate = switchinput) && (switchinput = HIGH))
      {
        void start();
      }
    }

    // Running actual code
    void setup()
    {
      // initialize digital pin 53 as an output.
      pinMode(pin53, OUTPUT);

      // Sets default state to switch being off (Off = LOW, On = HIGH)
      String currentstate = LOW;
    }

    void loop()
    {
       if ((currentstate != switchinput) && (switchinput = HIGH))
      {
          void offtoon();
      }

      if ((currentstate != switchinput) && (switchinput = LOW))
      {
          void ontooff();
      }

      if ((currentstate = switchinput) && (switchinput = LOW))
      {
          void staysameoff();
      }

      if ((currentstate = switchinput) && (switchinput = HIGH))
      {
          void samestayon();
      }
    }

body:
This seems way too complex for your purpose:

* you really do not need to do anything to stay in the same state
* if you want to switch the valve ON, no need to check whether it's OFF:
  there is no harm in switching ON a valve that is already ON.

Here is a simplified version of the program:

<!-- language: lang-c++ -->

    void setup()
    {
        Serial.begin(9600);
        Serial.println("Type '0' to turn OFF, '1' to turn ON");
    }

    void loop()
    {
        int command = Serial.read();
        if (command == '0') digitalWrite(53, LOW);
        if (command == '1') digitalWrite(53, HIGH);
    }

Notice that `Serial.read()` returns -1 if there is nothing in the input
buffer, and since -1 is neither '0' nor '1', this will not change the
output.

If you want to use more elaborate commands (not single characters), you
may want to take a look at this [simple command-line
interpreter][interpreter.ino]. It is intended to be easy to adapt to
different purposes.

[interpreter.ino]: https://gist.github.com/edgar-bonet/607b387260388be77e96


message:
ATtiny85 (Sparfun Clone/Trinket), detect/read operation voltage

I just started with Arduino programming and currently I'm using this Sparkfun clone board:

o http://nl.aliexpress.com/item/Digispark-kickstarter-Micro-development-board-ATTINY85-module-for-Arduino-usb/32584975067.html

It's really nice and like the way to program it and 'burn' it, it's easy to do. For the first project, I came along this instructable, an USB volume knob:

o http://www.instructables.com/id/Digispark-Volume-Control/

I'm using the Sparkfun Arduino programming IDE with added AdaFruit Trinket USB library (Trinket is also ATtiny85), download source, tweak it a bit to my needs and it's working perfectly. Had some programming question though, see also:

o https://stackoverflow.com/questions/37740026/change-override-trinket-attiny85-usb-identification-name-device-name/37743886#37743886

o  https://stackoverflow.com/questions/37769451/arduino-make-a-library-more-optional-by-project?lq=1

o https://stackoverflow.com/questions/37824336/arduino-trinket-attiny85-usb-possible-to-read-the-state-of-all-keys

Anyway, optimized the source code (original not really a beauty), play with it and added also a fade-In/fade-out idle feature to the LED on PIN 1 and it blinks when turning the dial encoder.

I want to add add some more features to this knob, such as pushbuttons to change some internal modes. For example:

 - Toggle button for knob sensitivity (3-modes: slow (default), normal, fast)
 - A mute button

I want to that device 'remember' the state of the toggle button but there is no option (flash memory) to save the state. So I came with the idea to use a backup button cell to keep the device 'alive' when disconnected from USB (or computer turned off). A Button cell is 3V and USB is 5V so maybe is possible to 'test' the input voltage. If this is possible you can put the device in sleep mode (low power mode) directly after detecting USB connection lost and this voltage drop.

I have read already an article how to put the device into sleep mode (and awake from it):

o https://bigdanzblog.wordpress.com/2014/08/10/attiny85-wake-from-sleep-on-pin-state-change-code-example/

**Question is:**

Can I measure somehow the voltage is used to power the device? Any ideas (code example please if it is possible)?

body:
There are a few solutions.

 - If you want to save te state of your toggle button you can save it in the eeprom of your attiny85
 - You can use an ADC pin to check your VCC against the internal 1.1V reference
 - alternatively you can read the 1.1ref aganist Avcc. https://digistump.com/board/index.php?topic=1104.0


message:
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.][1]. 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][2]. 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.

  [1]: http://forum.arduino.cc/index.php/topic,8237.0.html
  [2]: http://elteesee.pehrhovey.net/

body:
    ((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.


message:
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 :-)

body:
> 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.


message:
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

body:
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.


message:
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.

body:
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.


message:
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][1] 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?

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt

body:
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.


body:
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*`:

<!-- language-all: lang-c++ -->

    #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:

1. The main loop reads the value of `time_elapsed` and it turns out to
   be false
2. At this point the interrupt fires and the ISR sets that boolean to
   `true`
3. 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][avr-libc]. 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.

[avr-libc]: http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html


message:
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.

body:
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.


body: 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;


message:
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 ?

[![Audio visualization][1]][1]

   [pulse width][2]

  [1]: https://i.stack.imgur.com/U0XQK.jpg
  [2]: https://drive.google.com/open?id=0B8TRhtqczb3_bFJiOFNadEx5T3M

body:
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.

[sound-meter program]: https://gist.github.com/edgar-bonet/e693799f58a545ca89a2


message:
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();
    }

body:
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.

<!-- language: lang-c++ -->

    #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](http://www.gammon.com.au/power).