body:
Have been working on a Button Menu for a while now and can't break thru to the 3rd level, which in theory would give access to levels 4/5/6/etc.
It's layed out long hand, I'll neaten the code up after its working.
Could you pls have a look and see if you can access level 3....
Also if there is an alternative for ***multi level menus***, happy to look at those also, just after something that works, have tried dozens that i have found on the web.....either no sketch with the video(how i hate that) or sketch just doesn't work period.
Thanks in advance
Doug

        /*
    Description : Simple Menu function on LCD
              Button Function:
                Up/Down - change Menu Page
                Select - enter page
                Left - Exit

    Link: http://youtu.be/cMqif5ICS5M

    +++++++++++++++++++++++++++++++++++++++++++++++++++*/
    */
    #include <LiquidCrystal_I2C.h> //from newliquidcrystal library
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    int keypad_pin = A0;
    int keypad_value = 0;
    int keypad_value_old = 0;

    bool menu2 = false;
    char btn_push;

    int selection1 = 0;
    int selection2 = 0;

    int mainMenuPage = 1;
    int mainMenuPageOld = 1;
    int mainMenuTotal = 4;

    int levelMenuPage = 1;
    int levelMenuPageOld = 1;
    int levelMenuTotal = 4;

    void setup()
    {
      Serial.begin(9600);
    lcd.begin(20, 4);  //Initialize a 2x16 type LCD

    MainMenuDisplay();
    delay(1000);

    }
    void loop()
    {
    MainmenuBtn();

    if((btn_push == 'S')&&(menu2 == false))//enter selected menu
    {
      Serial.println("i'm here");
        WaitBtnRelease();
        switch (mainMenuPage)
        {
            case 1:
              MenuA();
              break;
            case 2:
              MenuB();
              break;
            case 3:
              MenuC();
              break;
            case 4:
              MenuD();
              break;
        }

          MainMenuDisplay();
          WaitBtnRelease();
      }
      else
    {
       if((btn_push == 'S')&&(menu2 == true))//enter selected menu
    {
      LevelmenuBtn();
        WaitBtnRelease();
        switch (levelMenuPage)
        {
            case 1:
              MenuA2();
              break;
            case 2:
              MenuB2();
              break;
            case 3:
              MenuC2();
              break;
            case 4:
              MenuD2();
              break;
        }

          LevelMenuDisplay();
          WaitBtnRelease();
      }

      delay(10);
    }
    }
    //--------------- End of loop() loop ---------------------
    void MainmenuBtn()
    {
      btn_push = ReadKeypad();
    WaitBtnRelease();
    if(btn_push == 'U')
    {
        mainMenuPage++;
        if(mainMenuPage > mainMenuTotal)
          mainMenuPage = 1;
          Serial.println(mainMenuPage);
    }
    else if(btn_push == 'D')
    {
        mainMenuPage--;
        Serial.print(mainMenuPage);
        if(mainMenuPage == 0)
          mainMenuPage = mainMenuTotal;
          Serial.println(mainMenuPage);
    }

    if(mainMenuPage != mainMenuPageOld) //only update display when page change
    {
        MainMenuDisplay();
        mainMenuPageOld = mainMenuPage;
    }
    }
    void LevelmenuBtn()
    {
      btn_push = ReadKeypad();
    WaitBtnRelease();
    if(btn_push == 'U')
    {
        mainMenuPage++;
        if(levelMenuPage > levelMenuTotal)
          levelMenuPage = 1;
          Serial.println(levelMenuPage);
    }
    else if(btn_push == 'D')
    {
        levelMenuPage--;
        Serial.print(levelMenuPage);
        if(levelMenuPage == 0)
          levelMenuPage = levelMenuTotal;
          Serial.println(levelMenuPage);
    }

    if(levelMenuPage != levelMenuPageOld) //only update display when page change
    {
        LevelMenuDisplay();
        levelMenuPageOld = levelMenuPage;
    }
    }
    void MainMenuDisplay()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    switch (mainMenuPage)
    {
        case 1:
          lcd.print("1. Menu A");
          break;
        case 2:
          lcd.print("2. Menu B");
          break;
        case 3:
          lcd.print("3. Menu C");
          break;
        case 4:
          lcd.print("4. Menu D");
          break;
    }
    }
    void LevelMenuDisplay()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    switch (levelMenuPage)
    {
        case 1:
          lcd.print("1. Menu A2");
          break;
        case 2:
          lcd.print("2. Menu B2");
          break;
        case 3:
          lcd.print("3. Menu C2");
          break;
        case 4:
          lcd.print("4. Menu D2");
          break;
    }
    }
    void MenuA()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu A");
     menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu A here
     selection1=1;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuA2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu A2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu A here
     selection2=1;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuB()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu B");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu B here

     selection1=2;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuB2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu B2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu B here
     selection2=2;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuC()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu C");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu C here
     selection1=3;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuC2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu C2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu C here
     selection2=3;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }
    void MenuD()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu D");
    menu2 = true;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu D here
     selection1=4;
     Serial.print("Selection1=");
     Serial.println(selection1);
    }
    }
    void MenuD2()
    {
    lcd.clear();
    lcd.setCursor(0,0);
    lcd.print("Inside Menu D2");
    menu2 = false;
    while(ReadKeypad()!= 'N')
    {
        //Insert Task for Menu D here
     selection2=4;
     Serial.print("Selection2=");
     Serial.println(selection2);
    }
    }

    char ReadKeypad()
    {
    /* Keypad button analog Value
    no button pressed 1023
    nul     <450
    select  <400
    left    <350
    down    <290
    up      <190
    right   <50
    */
    keypad_value = analogRead(keypad_pin);

    if(keypad_value < 50)
    return 'R';
    else if(keypad_value < 190)
    return 'U';
    else if(keypad_value < 290)
    return 'D';
    else if(keypad_value < 350)
    return 'L';
    else if(keypad_value < 400)
    return 'S';
    else if(keypad_value < 450)
    return 'N';

    }

    void WaitBtnRelease()
    {
      while( analogRead(keypad_pin) < 600){}
    }

title: Multi Level Button Menu

Answers: 1

body:
Ok...nobody bought into this and I understand why...menus have been done to death, but not being one to quite I have answered my own question.
Here is a simple, fool proof button menu, that i think has NO limit in depth.
I have just tested this before posting, so if you don't get it to work, check your wiring. instructions at the bottom of the sketch.

        /* Rebuilt by Doug 07/02/2017 Australia.
     * This is a bare bones menu using buttons to navigate and select, there are no special libraries,
     * I am using an I2C LCD2004, but any display will work with minor mods. This has been translated from,
     * I believe Slovakian, that was fun, stripped down and modified for button control, I have found that
     * buttons are less picky than rotary encoders, even the good ones, just my experience.
     * I believe that I have removed all unnecessary script, but I may have missed some.
     * look at the last 2 --page()-- sections for instruction on extending down even further, I don't think
     * that there is a limit to how many levels you can have, how many do you really need.
     * The original sketch is from: Stanislav Petrek of Slovakia, you can find sketch on YouTube comments.
     * https://www.youtube.com/watch?v=gIP29m12wjQ&t=41s
     * Have fun with the translation  ;-}
     * The last thing I did before posting was to relaod and test this sketch, so it works.
     */
    #include <LiquidCrystal_I2C.h> //from newliquidcrystal library
    LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address

    // menu system
    int poz = 0; //  cursor position on actual page
    int poz_max = 1;
    int poz_min = 0;

    int pozOld = 0;
    int pozNew = 0;

    int page = 0; //  actual page
    int page_max = 1;
    int page_min = 0;

    int press = 0;
    int press_max = 1;

    int keypad_pin = A0;                      //analoge A0 to sense button values.
    int keypad_value = 0;
    int keypad_value_old = 0;

    //bool menu2 = false;
    char btn_push;
    //****************************************************************setup*****************************************
    void setup() {
    Serial.begin(9600);
    lcd.begin(20, 4);
    lcd.clear();
    lcd.home();
    }
    //************************************************************loop************************************************
    void loop() {
    MainmenuBtn();
    if (btn_push == 'S') //enter selected menu
    {
    press++;
    delay(250);
    if (press > press_max) {
      press = 0;
    }
    }
    // page select
    switch (page) {

    case 0:
      page0();
      break;
    case 1:
      page1();
      break;
    case 2:
      page2();
      break;
    case 3:
      page3();
      break;
    case 4:
      page4();
      break;
    case 5:
      page5();
      break;
    }
    }
    //****************************************************up/down************************************************
    void MainmenuBtn()
    {
    btn_push = ReadKeypad();
    WaitBtnRelease();
    if (btn_push == 'U')
    {
    poz++;
    if (poz > poz_max) {
      poz = poz_max;
    }
    }
    else if (btn_push == 'D')
    {
    poz--;
    if (poz < poz_min) {
      poz = poz_min;
    }
    }
    pozNew = poz;
    if (pozNew != pozOld) { //only update display when page change
    pozOld = pozNew;
    }
    }
    //*************************************************************read buttons***********************************
    char ReadKeypad()
    {
    /* Keypad button analog Value
    no button pressed 1023
    *********************adjust these values to suit your keypad***********************
    nul     >400
    select  <400
    left    <350
    down    <290
    up      <190
    right   <50
    */
    keypad_value = analogRead(keypad_pin);
    if (keypad_value < 50)
    return 'R';
    else if (keypad_value < 190)
    return 'D';
    else if (keypad_value < 290)
    return 'U';
    else if (keypad_value < 350)
    return 'L';
    else if (keypad_value < 400)
    return 'S';
    else if (keypad_value > 400)
    return 'N';
    }
    //********************************************************button release*************************************
    void WaitBtnRelease()
    {
    while ( analogRead(keypad_pin) < 600) {}
    }
    //*******************************************************Front Page 0*******************************************
    void page0() {
    poz_min = 0;
    poz_max = 3;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Pg1 Pg2 Pg3 Pg4     ");
    lcd.setCursor(0, 2);
    lcd.print("                    ");
    lcd.setCursor(0, 3);
    lcd.print("                    ");

    switch (poz)
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("---                 ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 1;
      }
      break;
    case 1:
      lcd.setCursor(0, 1);
      lcd.print("    ---             ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 2;
      }
      break;
    case 2:
      lcd.setCursor(0, 1);
      lcd.print("        ---         ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 3;
      }
      break;
    case 3:
      lcd.setCursor(0, 1);
      lcd.print("            ---     ");
      if (press == 1) {
        press = 0;
        poz = 0;
        page = 4;
      }
      break;
    }
    }
    //*************************************************Pages 1*****************************************
    void page1() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page1               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page1 Case0         ");
      if (press == 1) {
        press = 0;
      }
      break;
    case 1:
      lcd.print("Page1 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.print("Page1 Case2    exit ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 0;
      }
      break;
    }
    }
    //*************************************************Pages 2*****************************************
    void page2() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page2               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page2 Case0         ");
      if (press == 1) {
        press = 0;
      }
      break;
    case 1:
      lcd.print("Page2 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.print("Page2 Case2  exit   ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 1;
      }
      break;
    }
    }
    //*************************************************Pages 3*****************************************
    void page3() {
    poz_min = 0;
    poz_max = 2;
    press_max = 1;
    lcd.setCursor(0, 0);
    lcd.print("Page3               ");

    switch (poz)
    {
    case 0:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case0         ");
      if (press == 1) {
        lcd.setCursor(0, 1);
        lcd.print("                    ");
        //navi();
      }
      break;

    case 1:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case1         ");
      if (press == 1) {
        press = 0;
      }
      break;

    case 2:
      lcd.setCursor(0, 1);
      lcd.print("Page3 Case2  exit   ");
      if (press == 1) {
        press = 0;
        page = 0;
        poz = 2;
      }
      break;
    }
    }
    //*************************************************Pages 4*****************************************
    void page4() {
    poz_min = 0;
    poz_max = 1;
    press_max = 1;

    lcd.setCursor(0, 0);
    lcd.print("Page4               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page4 Case0  branch ");
      if (press == 1) {
        press = 0;
        page = 5;                                   //branches to page5() menu
        poz = 0;                                    //at position 0 on button 'S' press
        break;

      case 1:
        lcd.setCursor(0, 1);
        lcd.print("Page4 Case1  exit   ");
        if (press == 1) {
          press = 0;
          page = 0;
          poz = 3;
        }
        break;
      }
      }
    }
    //*************************************************Pages 5*****************************************
    void page5() {
    poz_min = 0;                      //see void MainmenuBtn()
    poz_max = 1;                      //see void MainmenuBtn()
    press_max = 1;                    //used when you have multiple selection within a section-increase number
                                      //see  original script for example
    lcd.setCursor(0, 0);
    lcd.print("Page5               ");
    lcd.setCursor(0, 1);
    switch (poz) {

    case 0:
      lcd.print("Page5 Case0         ");
      break;

    case 1:
      lcd.setCursor(0, 1);
      lcd.print("Page5 Case1  exit   ");
      if (press == 1) {                 //variable set to '1' when the 'S' key is pressed
        press = 0;
        page = 4;                         //this is the page() that you return to after the 'S' button is pressed
        poz = 1;                          //this is the 'case' number that you will return to for that page
      }
      break;
    }
    }

I have only inserted print statements where operational code can be placed, to keep it universally open. To reduce the size of the Global variables use the >>lcd.print(F("TEXT"));<< method, it works really well. Also works on Serial.print....Something for you to fiddle with.


body:
If I store in an array a double-value in this format, in which format I should be able to read the same double out?

    double myDouble = 12.123456;
    byte myArray[] = {0x00, 0x00, 0x00, 0x00};

    myArray[0] = (myDouble >> 0);
    myArray[1] = (myDouble >> 8);
    myArray[2] = (myDouble >> 16);
    myArray[3] = (myDouble >> 24);

title: What is the opposite of this data operation?

Answers: 2

body: in the simplest form (compiler dependent however), a pointer will do.

body:
You are better off making a union, that will be compiler independent, and won't give you the (possibly) odd results that trying to shift a double would give.

Example:

      union
        {
        byte myArray [4];
        double myDouble;
        } foo;

       foo.myArray [0] = Serial.read ();
       foo.myArray [1] = Serial.read ();
       foo.myArray [2] = Serial.read ();
       foo.myArray [3] = Serial.read ();

       double f = foo.myDouble;

Even then be cautious that whatever is sending you this double in 4 bytes is using the same encoding for doubles that the Arduino does. For one thing, **double** and **float** are the same on the 8-bit Arduinos (they are only 4 bytes).


body:
I have a simple project for my arduino : light some leds when i send a certain frequency from my smartphone through the jack output . For example ,
 I play a simple audio file generated with a frequency generator (it generates sinwaves, sawtooth, quadrate waves...) at 1kHz --> a red led turns on
I play another frequency (5kHz) --> a green led turns on.
I read similar questions , but they needed a precise reading of the signal frequency, so they had to convert from AC to DC and from 700mV to 2,5V, is it necessary in my case ? I can also prepare a track with a program called audacity with the current remaining always positive but oscillating between 0 and 0,7 mV.
How can i realize my project in the simplest way possible ?

Thank you

title: Arduino audio frequency reader

Answers: 2

body:
Connect the signal to an analogue input on the Arduino, via a DC blocking capacitor, with a potential divider centring it around 2.5v.  Make sure the voltage swing is within range, which it should be.

Keep the frequencies of the signal low, under say 2KHz.  For example, use 500Hz, 1000Hz, 1500Hz, 2000Hz.

Sample (`analogRead()`) the signal as fast as you can (which is about 10KHz) for a short while, recording the min and max values.  From this, you can find the centre value, 1/4 value and 3/4 value.

Now to find your frequency, sample until the signal goes above the 3/4 value.  Get the time with `micros()`.  Sample until the signal goes below 1/4, and then sample until it goes above 3/4 again and get the time with `micros()`.  Do this a few times and average them.  The difference between the two times is *approximately* your sample period, so you can easily find the frequency.

Determine which of your chosen frequencies most closely matches the frequency you've sampled.

body:
If you can properly bias your signal, say with a cap and a pot, you
could read it with a digital input. You can then time the rising edges
with `micros()`, either by polling the pin or using an interrupt. You
could achieve greater accuracy by using the “input capture” feature of a
16-bit timer, if you are using an AVR-based Arduino and are not afraid
of getting your hands dirty with low-level programming.

You need to get the right voltage range for this to work though. On an
Arduino Uno, for example, the thresholds for the input switching from
`HIGH` to `LOW` and back are typically around 2.1 and 2.6 V
respectively, so you must make sure that your signal amply covers this
range. If you can get 1 V peak to peak, that should be enough, and
you can then use the pot to tune the offset.


body:
After googling much I have found that MCP23017 can be used with esp8266-12e for more number of output pins.
I have tried all the programs from different tutorials on internet but could not make it work.

Basically my question is , i want to control all the 16 leds connected to GPA0-7 AND GPB0-7 individually , hence i need a program snippet for make it work.
I am using AP mode for esp8266-12e and sending get methods with params to identify which led to turn on/off.

Even i have written the basic program , can anyone help me completing the entire program. thanks for the help in advanced.

 Pins i have connected are

    ESP8266-12E    |   MCP23017
    −−−−−−−−−−−−−−−+−−−−−−−−−−−−−−
    GPIO-14 (scl)  |  PIN-12 (SCL)
    GPIO-2 (sda)   |  PIN 13 (SDA)
    GND            |  A0,A1,A2

My code:

    #include <Wire.h>
    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>

    ESP8266WebServer server(80);

    void handleRoot() {
        server.send(200, "text/html", "
You are connected
");
    }

    void setup() {
        delay(1000);
        Serial.begin(115200);
        Serial.println();
        Serial.print("Configuring access point...");
        WiFi.softAP(ssid, password);

        IPAddress myIP = WiFi.softAPIP();
        Serial.print("AP IP address: ");
        Serial.println(myIP);
        server.on("/", handleRoot);

        server.on("/led1", [](){});
        server.on("/led2", [](){});
        server.on("/led3", [](){});
        server.on("/led4", [](){});
        // up to 16 leds i have written same method.

        server.begin();
    }

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

title: ESP8266-12E and MCP23017 , unable to identify the application

Answers: 1

body:
You have an MCP23017 which connects to the device using the I2C protocol, which means you need the <Wire.h> library.  You also need to ensure that SCL and SDA are 'pulled up' using 4.7Kohm resistors between the data lines and the +ve line.
You will then need to send commands to the device to initialise it and set the pins to OUTPUT.  (See http://ww1.microchip.com/downloads/en/DeviceDoc/21952b.pdf).

When running you will need to update the state of this pins by sending messages such as <ADDR> 0x09 0xFF to turn them all on.

It is going to be worth looking for a library that already does all this, but writing your own shouldn't be too hard.  You will be able to use an Arduino library on an ESP8266.

These chips are the easiest ones to use and learn about I2C, so its worth looking at the manual and trying to write your own "library" (Just start by writing a C++ class within your sketch folder.)


body:
I have a processor `AT328` , Arduino bootloaded, and a `Bluetooth` on the serial lines `Tx,Rx` .

I would like to program the chip over Bluetooth, **not using a computer or IDE, but mobile phone with my own Hex uploader.**

So, if the `hex` file was just a huge text that you have to send, i would obviously just send it and thats it, as I understand there is a mechanism ?

**Question** : How exactly a `Hex` file is sent over serial to program the chip ? is it like any other text file? is there any mechanism I have to write? specific `baud rate`? is there any article about this ?

title: Flash a hex file to an MCU/Arduino over the air?

Answers: 1

body:
*Basically, this is much more involved than it might appear on the surface. If you haven't already, I would make sure that I was comfortable with finding things in [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf) (and it's a really good datasheet, at that). If you're still up for it, read on.*

## Bootloader
The way a bootloader works on the ATmega328 is that the memory on the chip is self-modifying. This means you can have a piece of code on the chip that modifies memory on the rest of the chip. A bootloader is one such piece of code that runs when the chip first starts up, and checks to see if there's code to be loaded. If there is, it writes that code to the rest of the memory, and then executes it. See section 12.2 of the datasheet.

The way you would program an actual bootloader is described in detail in section 30 "BTLDR - Boot Loader support". I haven't programmed a bootloader before, so you're on your own here, but there are plenty of resources to guide you. In fact, the datasheet has example code in there for it.

(Note that you must program your chip normally at least once, to put the bootloader on it.)

One thing to note is that bootloaders should be small. You don't want bootloaders to take up a lot of your memory, since they only run once on boot and are really just a convenience feature. There are competitions for writing the smallest/most efficient bootloader, and you'll almost certainly want to write your bootloader in assembly. Notice that the only example code given in the datasheet is in assembly. Which brings me to my next point:

## Bluetooth
Bluetooth is very annoying to program for. You have to set up different profiles, or do GATT stuff if your module is actually BLE/"Smart" instead of classic bluetooth, etc. However, I'm assuming from your post that you just have one of those serial modules you can find on eBay for dirt cheap. Before I go on, I want to make this very clear: It is **non-trivial** to set up. It will take up lots of precious code space on your microcontroller that you would want to use on your actual program. Remember how bootloaders are written in assembly? Writing a bluetooth interface in assembly will probably take a while.

As for how your bluetooth module works; it is basically a serial port, but over-the-air. This means the bluetooth interface that you write would need to bit-bang everything if you don't use the built-in USART (say you need those pins for your actual program), and if you do use the built-in USART, setting that up will take even more time. (For a guide on how to setup the USART, see section 24 of the aforementioned datasheet. See? It's really handy.)

Once you actually have bluetooth working, you can do whatever you want. Since you write the bootloader, you can read data from your bluetooth serial link however you fancy. As long as you know what you're sending, all you have to do is read it back accordingly.

## Bonus: Flashing
You are correct that a `.hex` file is just a huge text file that you send to the chip. However, the way the ATmega is actually programmed is *not* simply using the serial port; instead, it's a slightly extended SPI protocol. (If you don't know what SPI is, you really shouldn't be doing this. If you're curious, Sparkfun has [a nice tutorial on SPI](https://learn.sparkfun.com/tutorials/serial-peripheral-interface-spi).) This is called ICSP, or "in-circuit serial programming". The way to do this for AVRs is explained in [an application note](http://www.atmel.com/Images/Atmel-0943-In-System-Programming_ApplicationNote_AVR910.pdf).

Of course, you cannot replicate this with just a bluetooth module. Instead, you would need a co-processor to program your chip for you, and read the data to-be-programmed from your bluetooth module.

---

**TL;DR: This is probably not worth it. If you're planning on doing this, it will take significant resources, and you might even need a better chip to get anything done. You almost certainly should just buy an ESP8266 / ESP32 instead.**


body:
Basically I want my motor to run after let's say 10 seconds passed since the program started up.

The amount of time is determined by user input, and I have already coded for that. The motor is connected to a breadboard and powered by a 9v battery, also connected to the breadboard.

The thing is, the motor runs as soon as I connect it to the breadboard. How can I use the Arduino board to make the motor wait 10 seconds before it moves? I am new to both circuitry and code... Sorry for my cluelessness.

Thanks so much.

title: How to make the motor move after a certain period of time?

Answers: 2

body: I would recommend connecting the motor to a controller of some sort of a controller, maybe a relay or something like that, and then write some code that waits 10 seconds, and then turns on your controller / relay. That will turn on the motor.

body:
You will need to add a logic level mosfet of the appropriate size and specs to control the power to the motor.  You can drive the gate of the mosfet from a pin through a current limiting resistor with a larger bleed resistor.  For a brushed motor you'll need a ceramic RF supressor cap plus flyback diode for back EMF protection:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/oaQPu.png)

<!-- End schematic -->

For greater RF supression (if your motor is pretty beefy) you can use a 0.1uF between each input lead and the motor case.

When you turn the pin on, motor turns on, low turns off.  Using analog and appropriate R values you can control motor speed (setting 0-255):

    int motorControl = [your pin];

    void setup()
    {
      pinMode(motorControl, OUTPUT);
    }

    void loop()
    {
      delay(10000); // delay 10 seconds plus board boot time
      analogWrite(motorControl, 255); // turn motor on full
    }

You can time the delay with a stop watch and adjust to be exactly 10s by dropping the delay() call to compensate for the boot up time of the board.

More about MOSFETS here:

https://electronics.stackexchange.com/questions/81935/mosfet-usage-and-p-vs-n-channel


body:
A little while ago i tried using AT commands on my HC05 bluetooth module using my arduino mega 2560 and it worked fine , skipping a few weeks ahead i tried doing the same , only now i suddenly doesn't work , i tried replacing the arduino and HC05 module , even used the same script for the commands. So i unplugged the module's VCC , pressed the button on the module , reconnected the VCC and the module was blinking every 2 seconds (it's in AT mode !) , now i go ahead to the serial monitor and using that [script][1] i typed the command i wanted to execute and it just didn't do nothing , i saw the serial LED on the arduino blink , but nothing was written in the serial monitor and nothing was changed in the arduino.

Does anyone know how to solve this ? it worked perfect before , but now it wont D:

  [1]: http://pastebin.com/s4hjSqcE

title: Arduino HC05 - AT commands won't respond

Answers: 2

body: Maybe you should try a couple of different baud rates for your script? Also check that your RX/TX wires are connected in the right order. I've had some HC-05 modules where RX/TX markings on the module were reversed.

body:
Here's the solution!
First, you have to wire the board like the solution 2 in the instruction.
http://www.elecfreaks.com/wiki/index.php?title=Bluetooth_Shield
Then, Use this code!

    /*********************************************************************
     **  Description:                                                    **
     **  This file is a sample code for your reference.                  **
     **                                                                  **
     **  Copyright (C) 2011 ElecFreaks Corp.                             **
     **  Created by ElecFreaks Robi.W /29 Sep 2011                      **
     **                                                                  **
     **  http://www.elecfreaks.com                                       **
     *********************************************************************/
    void setup()
    {
       Serial.begin(57600);
       Serial1.begin(38400);

    }

    void loop()
    {
      int i = 0;
      char someChar[32] = {0};
      // when characters arrive over the serial port...
      if(Serial.available()) {
        Serial.print("------->  ");
        do{
          someChar[i++] = Serial.read();
          //As data trickles in from your serial port you are grabbing as much as you can,
          //but then when it runs out (as it will after a few bytes because the processor
      //is much faster than a 9600 baud device) you exit loop, which then
     // restarts,
      //and resets i to zero, and someChar to an empty array.So please be sure to keep this delay
          delay(3);
        }while (Serial.available() > 0);
        Serial1.println(someChar);
        Serial.println(someChar);
      }

      while(Serial1.available())
          Serial.print((char)Serial1.read());
    }


body:
The first project I did was just making the led blink (it was pulsing a signal to pin 13. I'm guessing most of you have seen similar tutorials).

Today I plugged in some wires and resistors and wrote a program for a volt meter.

How am I to stop the pulses on the output pins from my previous project from messing everything up in the newer project in that interval of time after plugging in the usb and before compiling/ uploading the new code?

The question occurred to me when I saw the led blinking from the last project, before I could hit the upload button... maybe I'm wrong, but I'm envisioning this causing problems for me in the future as my circuits become more and more complex.

title: Working on my second project and I'm confused about proper procedure for turning on the arduino

Answers: 1

body:
If you've rewired an Arduino board for a new project, such that outputs from the currently-loaded sketch may cause problems, temporarily jumper from ground to Reset, to hold the MCU (ATmega328, etc.) in reset until you are ready to load the new sketch.  Pull the jumper upon starting a download, of either your new project or an empty sketch as suggested in Majenko's comment.  Typically, Arduinos are reset at the beginning of each download.

Arduino boards (Uno, Nano, Mega, et al) that use an additional chip (FT232, Atmega16U2 or 32U4, CH340G, etc) as a USB interface should be able to register as USB devices even when the MCU is reset.  Arduino boards without a separate USB chip (Leonardo, Micro, et al) should not.


body:
On the Arduino UNO and NANO with the serial port connected to an on-board device connected to a USB port, I can obviously send and receive messages to the serial console......now the question:

I have no idea how to use the serial port to send data elsewhere, specifically to an HC-12 radio type device that communicates serially. I cannot use a software serial port because of timing issues, so I need to use the HW port.

During development I expect to use the serial console for diagnostic messages, but I also need to use the port to send and receive data using the radio.

So, how does the handshake/protocol handle both the serial console in the IDE and something else, or better yet, can it handle sending OR receiving data to or from 2 devices at the same time?

Does anyone use the HC-12 type device using the one onboard serial port on an UNO or NANO?

Remember, the goal is to use the HW serial port to communicate with the HC-12 buy issuing Serial.print commands, which logically will also go to the serail console of the IDE.

title: Using HC-12 radio on UNO or NANO without software serial

Answers: 0


body:
I have a SIM808, connected via hardware serial to an Arduino Mega. Communication between the Arduino and the SIM808 is fine. However, the quality of the signal is listed as 0 all the time. (AT+CSQ)

I've checked, and there is definitely 2G (and 3G) signal. Power is fine. SIM is unlocked, and works in other M2M equipment.

The network status lights blink rapidly (ie searching for a network) for about 5 seconds. Then it takes one long blink, then goes back to blinking rapidly.

The module is picking up the names of the available networks, yet does not seem to be able to register.

I'm using a prepaid data SIM card from Vodacom (South Africa).

title: Having problems registering my SIM800 with the network

Answers: 2

body: I think you are not giving it enough power, SIM800 module needs 5v/2A stable power source in order to register to network. Try to use a desktop computer power supply it has 5v/2A output wire (refer to colors).

body:
Actually the SIM800 should not be supplied with more than 4.4 V according to the datasheet.  I would be interested to know how this problem was resolved.

I have a similar problem.  I cannot get the SIM800 to connect to Three or the O2 network even though both SIMs work in my mobile phone.

In my case the SIM800 is connected directly to two 18650 Li-Ion batteries in parallel so I don't think it is lack of power.  Perhaps a big capacitor would help.  I will give it a try.  Failing that it might just have a much less adequate antenna and needs to be out in the open.


body: Firmata seems to be a popular protocol for communicating between the Arduino and host computer. However, there only seems to be C/C++ libraries for the Arduino. Most Firmata libraries for the host appear to be in Python. I've found a few C/C++ Firmata libraries for the host, but they seem incomplete and unmaintained. Is anyone aware of a full-featured C++ Firmata library designed to run on the host computer?

title: Firmata C++ library for host?

Answers: 1

body:
[openFrameworks][1] appears to have this capability. It's written in C++.

From [openFrameworks - Communication][2]:

> **Arduino and other serial devices communication**
>
> The communication module has classes to communicate with other devices
> by now through the serial protocol. This mainly allows to communicate
> with devices like the Arduino. There's 2 classes in this module,
> [ofSerial][3] which allows to communicate with any device through the
> serial protocol. It can be used to send custom commands to for example
> an Arduino sketch that will receive them and do something in response
> like turn an LED on, move a motor... It also works the other way
> around, you can send messages from the Arduino (or any other serial
> device), for example the read from a temperature sensor to
> openFrameworks.
>
> The second class, [ofArduino][4], is specific to the arduino, it uses a
> protocol called **firmata** to send messages to and from the arduino that
> way you don't need to care about implementing the communication
> protocol from the Arduino sketch to openFrameworks and viceversa but
> instead you can just send and read values directly to and from any pin
> in the Arduino.

  [1]: https://openframeworks.cc
  [2]: https://openframeworks.cc/documentation/communication/
  [3]: https://openframeworks.cc/documentation/communication/ofSerial.html
  [4]: https://openframeworks.cc/documentation/communication/ofArduino


body:
I have an arduino due sending and receiving data from a server using a GSM module (UBLOX SARA-U270). The issue I am having with it is that after a period of time working correctly the module stops replying or replies with random characters. It has been suggested to me that if I receive no reply to a command and continue to send commands it can cause issues like this and I need to take action before I send any more commands but I am unsure of what this action should be.

I was wondering is there a recommended action to be taken if I receive an empty response from an AT command to a GSM module after it has been previously working. I am currently working to find out the cause of the issue but I just wanted to know what should be done if an AT command that replies with nothing.

To try and correct this issue I have a function in place which if the module hasn't received data correctly for 1 minute will clear the modules setting using the AT+CFUN=1,1 command and resend all the setting to the module. My issue is that because the module is not replying, my AT+CFUN=1,1 command does nothing.  Physically removing the power to the module seems to be the only thing that will get it running correctly again.

And suggestions or advice would be greatly appreciated, Thanks guys.

title: No reply from GSM module

Answers: 0


body:
I'm trying to use this example [link][1]

  [1]: http://playground.arduino.cc/Learning/ArduinoSleepCode

source:

    #include <avr/sleep.h>

    /* Sleep Demo Serial
     * -----------------
     * Example code to demonstrate the sleep functions in an Arduino.
     *
     * use a resistor between RX and pin2. By default RX is pulled up to 5V
     * therefore, we can use a sequence of Serial data forcing RX to 0, what
     * will make pin2 go LOW activating INT0 external interrupt, bringing
     * the MCU back to life
     *
     * there is also a time counter that will put the MCU to sleep after 10 secs
     *
     * NOTE: when coming back from POWER-DOWN mode, it takes a bit
     *       until the system is functional at 100%!! (typically <1sec)
     *
     * Copyright (C) 2006 MacSimski 2006-12-30
     * Copyright (C) 2007 D. Cuartielles 2007-07-08 - Mexico DF
     *
     *  This program is free software: you can redistribute it and/or modify
     *  it under the terms of the GNU General Public License as published by
     *  the Free Software Foundation, either version 3 of the License, or
     *  (at your option) any later version.
     *
     *  This program is distributed in the hope that it will be useful,
     *  but WITHOUT ANY WARRANTY; without even the implied warranty of
     *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
     *  GNU General Public License for more details.
     *
     *  You should have received a copy of the GNU General Public License
     *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
     *
     */

    int wakePin = 2;                 // pin used for waking up
    int sleepStatus = 0;             // variable to store a request for sleep
    int count = 0;                   // counter

    void wakeUpNow()        // here the interrupt is handled after wakeup
    {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
    }

    void setup()
    {
      pinMode(wakePin, INPUT);

      Serial.begin(9600);

      /* Now it is time to enable an interrupt. In the function call
       * attachInterrupt(A, B, C)
       * A   can be either 0 or 1 for interrupts on pin 2 or 3.
       *
       * B   Name of a function you want to execute while in interrupt A.
       *
       * C   Trigger mode of the interrupt pin. can be:
       *             LOW        a low level trigger
       *             CHANGE     a change in level trigger
       *             RISING     a rising edge of a level trigger
       *             FALLING    a falling edge of a level trigger
       *
       * In all but the IDLE sleep modes only LOW can be used.
       */

      attachInterrupt(0, wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                          // wakeUpNow when pin 2 gets LOW
    }

    void sleepNow()         // here we put the arduino to sleep
    {
        /* Now is the time to set the sleep mode. In the Atmega8 datasheet
         * http://www.atmel.com/dyn/resources/prod_documents/doc2486.pdf on page 35
         * there is a list of sleep modes which explains which clocks and
         * wake up sources are available in which sleep mode.
         *
         * In the avr/sleep.h file, the call names of these sleep modes are to be found:
         *
         * The 5 different modes are:
         *     SLEEP_MODE_IDLE         -the least power savings
         *     SLEEP_MODE_ADC
         *     SLEEP_MODE_PWR_SAVE
         *     SLEEP_MODE_STANDBY
         *     SLEEP_MODE_PWR_DOWN     -the most power savings
         *
         * For now, we want as much power savings as possible, so we
         * choose the according
         * sleep mode: SLEEP_MODE_PWR_DOWN
         *
         */
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);   // sleep mode is set here

        sleep_enable();          // enables the sleep bit in the mcucr register
                                 // so sleep is possible. just a safety pin

        /* Now it is time to enable an interrupt. We do it here so an
         * accidentally pushed interrupt button doesn't interrupt
         * our running program. if you want to be able to run
         * interrupt code besides the sleep function, place it in
         * setup() for example.
         *
         * In the function call attachInterrupt(A, B, C)
         * A   can be either 0 or 1 for interrupts on pin 2 or 3.
         *
         * B   Name of a function you want to execute at interrupt for A.
         *
         * C   Trigger mode of the interrupt pin. can be:
         *             LOW        a low level triggers
         *             CHANGE     a change in level triggers
         *             RISING     a rising edge of a level triggers
         *             FALLING    a falling edge of a level triggers
         *
         * In all but the IDLE sleep modes only LOW can be used.
         */

        attachInterrupt(0,wakeUpNow, LOW); // use interrupt 0 (pin 2) and run function
                                           // wakeUpNow when pin 2 gets LOW

        sleep_mode();            // here the device is actually put to sleep!!
                                 // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

        sleep_disable();         // first thing after waking from sleep:
                                 // disable sleep...
        detachInterrupt(0);      // disables interrupt 0 on pin 2 so the
                                 // wakeUpNow code will not be executed
                                 // during normal running time.

    }

    void loop()
    {
      // display information about the counter
      Serial.print("Awake for ");
      Serial.print(count);
      Serial.println("sec");
      count++;
      delay(1000);                           // waits for a second

      // compute the serial input
      if (Serial.available()) {
        int val = Serial.read();
        if (val == 'S') {
          Serial.println("Serial: Entering Sleep mode");
          delay(100);     // this delay is needed, the sleep
                          //function will provoke a Serial error otherwise!!
          count = 0;
          sleepNow();     // sleep function called here
        }
        if (val == 'A') {
          Serial.println("Hola Caracola"); // classic dummy message
        }
      }

      // check if it should go to sleep because of time
      if (count >= 10) {
          Serial.println("Timer: Entering Sleep mode");
          delay(100);     // this delay is needed, the sleep
                          //function will provoke a Serial error otherwise!!
          count = 0;
          sleepNow();     // sleep function called here
      }
    }

I'm using a Tester for test really efficient of power saving; I read only a power save of 2 mA. Is it possible the Arduino Mega saves only that in sleep mode? Or am I doing something wrong?

title: Power save Sleep Mode Arduino

Answers: 1

body:
I have [a page about power saving](http://www.gammon.com.au/power). About the first suggestion on that page is to not use an Arduino "board" (particularly one with a USB interface chip, power LED and voltage regulator). They all take power - a lot of it. These boards are designed for prototyping, not low-power use in the field.

Something like this would be better:

[![Bare-boned Arduino][1]][1]

Of course, that isn't an Atmega2560 chip. They only come in surface-mount and will be hard to solder yourself. You may be able to get an Atmega2560 board in minimal form. Or downgrade to a smaller processor that you can assemble yourself. The Atmega644P comes in PDIP which is easy enough to work with.

If you don't need all that RAM and program memory, you could go down to an Atmega328P which are easy to work with and can get down to 100 nA power consumption under the right circumstances.

---

You could conceivably do what Edgar Bonet suggested and cut traces on your Mega2560 board, but be warned that if you do that you won't be able to program the board via the USB interface afterwards. You can still program via the ICSP socket however, if you have a suitable programmer.

---

> What are you using as resonator there?

This one - I can't remember where I got it from.

[![Resonator][2]][2]

The Arduino Uno has a resonator on it for the main chip (not a crystal) so using a resonator is fine.

  [1]: https://i.stack.imgur.com/lIfJv.jpg
  [2]: https://i.stack.imgur.com/BZ2rJ.jpg


body:
For my engineering class, I am designing a digital scale.  I have already made a working proof-of-concept by using jumper wires to connect several arduino modules to an Arduino UNO.

I want to make a PCB to simplify the design, and not just have a mess of arduino modules.  I want the design to be flat and small, so I need to make a custom PCB, integrating each module onto the board.  Say I'm not using a protoboard, but sending it to a company to get it custom manufactured.  This PCB would use through-hole components, and not SMD.

I am trying to build the eagle files for the PCB.  I have rounded up the SCH file for each arduino module, and the arduino itself.

I am trying to make this PCB in the easiest and fastest way possible.

Should I just copy and paste, and connect the modules' SCH files into one big SCH file?  Then create a BRD file to create the proper footprints and holes?

Thanks

title: How do I go from modules to PCB?

Answers: 0


body:
I am using an Adafruit 64x32 RGB LED panel with my Arduino Mega 2560. I tried to find/construct working examples of a 32x32 or wider scrolling text/bitmap but have failed.

The smaller version is working and is calling two functions for it to implement:

    loadSprite(IMAGES2,60);
    bildmittig_sprite(data,dpink,300);

 - `IMAGES2` is of type `const PROGMEM byte IMAGES2[][8]` and is an array
   of several 8x8 bitmaps
 - `data` is a buffer data array element,    containing the dynamic
   movement of bitmaps, called in the `void loop()`

For the whole code [here](https://www.dropbox.com/s/jrq7l6tzg31f7fl/sketch_led32-64-painter.ino?dl=0). For the video clip smaller scroller [here](https://www.dropbox.com/s/mu4qxkurma10qyp/MOV_0055.mp4?dl=0).

For the video clip to what I would like to extend to:

>! Russian Letters: http://dropbox.com/s/n2ilxqgubn83ii9/MOV_0056.mp4?dl=0
>!<br> Or Chinese Letters: http://dropbox.com/s/9rad116adc575u1/MOV_0057.mp4?dl=0

`loadSprite()` looks like this:

    void loadSprite(const PROGMEM byte bild[][8],int anzahl) {
      for(int row=0; row < 8; row++) {
        //iterate through each row
        data[row] = 0;
        //reset the row we're working on
        for(int column=0; column < 8; column++) {
          //iterate through each column
          data[row] = data[row] + ((powers[column] & (pgm_read_byte(&(bild[index][row])) << offset)));
          //loads the current charachter offset by offset pixels
          data[row] = data[row] + (powers[column] & (pgm_read_byte(&(bild[index+1][row])) >> (8-offset)));
          //loads the next charachter offset by offset pixels
        }
      }
      offset++;
      //increment the offset by one row
      if(offset==8){offset = 0; index++; if(index==anzahl){index=0;}}
      //if offset is 8 load the next character pair for the next time through
    }

The displaying function (places it i the middle of 32x32 panel) like this:

    void bildmittig_sprite (byte bild[8],word cchsv, int duration) {
      for(int i = 0; i <8; i++) {
        for(int ii = 0; ii<8; ii++) {
          int bit = (bild[i] >> ii) & 1;
          if(bit == 0) {
            matrix.drawPixel(7-ii+12, 12+i, black);
          } else {
            matrix.drawPixel(7-ii+12, 12+i, cchsv);
          }
        }
      }
      delay(duration);
    }

Working for 8x8 bitmaps, It eludes me how I could possible extend the coding (scrolling) for bitmaps like this:

    const PROGMEM unsigned char rus5[] = {
      0x00, 0x00, 0x00, 0x00,
      0x00, 0x00, 0xff, 0x03,
      0x00, 0x00, 0x78, 0x00,
      0x00, 0x00, 0x38, 0x00,
      0x00, 0x00, 0x3c, 0x00,
      0x00, 0x00, 0x1c, 0x00,
      0x00, 0x00, 0x1c, 0x00,
      0x00, 0x00, 0x1e, 0x00,
      0x00, 0xfc, 0xde, 0x0f,
      0x00, 0x8f, 0xef, 0x1f,
      0x80, 0x07, 0x3f, 0x3c,
      0xc0, 0x03, 0x0f, 0x3c,
      0xe0, 0x01, 0x0f, 0x3c,
      0xe0, 0x01, 0x07, 0x3c,
      0xf0, 0x80, 0x07, 0x3c,
      0xf0, 0x80, 0x03, 0x3c,
      0x70, 0x80, 0x03, 0x1e,
      0x78, 0xc0, 0x03, 0x1e,
      0x78, 0xc0, 0x03, 0x0f,
      0x78, 0xe0, 0x01, 0x0f,
      0x78, 0xf0, 0x81, 0x07,
      0xf0, 0xf8, 0xc3, 0x03,
      0xf0, 0xef, 0xf6, 0x01,
      0xe0, 0xf7, 0x7c, 0x00,
      0x00, 0xf0, 0x00, 0x00,
      0x00, 0x70, 0x00, 0x00,
      0x00, 0x70, 0x00, 0x00,
      0x00, 0x78, 0x00, 0x00,
      0x00, 0x78, 0x00, 0x00,
      0x00, 0x7c, 0x00, 0x00,
      0x80, 0xff, 0x03, 0x00,
      0x00, 0x00, 0x00, 0x00
    };

I tried variants of concatenation, like:

 - 4 bytes as a row, stitching together several with beforehand created
   `data` (`data1` `...` `data4`) elements (also adjust coherence for vertical elements).
 - And then have them displayed at the correct place to be able to use
   the existing code but so far only vertical concatenation seemed to
   work briefly.

I am at the end of my wits for this project, but maybe somebody else sees a better way.

title: On extending scrolling 8x8 bitmap to 32x32 or 32x64 (see clip)

Answers: 1

body:
I've looked at your code briefly, long enough to get the impression that each array like `rus5[]` contains 32 groups of 4 bytes each, with each 4-byte group representing a row of a character.  [If not, let me know.]  Also, I read the question a time or two, but don't see specified what direction you want to scroll, and whether you will scroll a string of characters or just one character.  Anyhow, in following I suppose you want to scroll a string horizontally with characters entering at the right end of the display and scrolling off the left end.

To support horizontal scrolling, arrange your bit maps such that each group of 4 bytes represents the 32 bits of a single column of the display.  Regarding four bytes as an unsigned long, suppose the LSB (least significant bit) corresponds to the top LED in a column.  Use code like the following to set pixels, supposing `cn` = current column number; `d` = number of character columns already scrolled off, in range 0 to 31; `maxCol` = number of display columns; and `t[]` is a three-character string corresponding to three characters currently on the 64x32 display.  [That is, a right-hand part of `t[0]` is at the left end of display; then all of `t[1]` appears; then a left-hand part of `t[2]`.]  [Generally, where this sets `cc=0`, you would set it to point at a current-character in a longer string, instead of at the first character in a three-character array `t[]`; and would advance one character each time `d` gets up to 32.]

    cc = 0;     // index of first character to display
    c = t[cc];  // first character to display
    e = d;      // how far we have scrolled so far
    for (cn=0; cn<maxCol; ++cn) {
      unsigned long colData = pgm_read_dword(charData[c][e]);
      for (ro=0; ro<32; ++ro) {
        matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
        colData >>= 1; // discard used-up bit
      }
      ++e;
      if (e >= 32) {  // Done with current character?
        c = t[++cc];  // Set c to next character
        e = 0;        // Start with leftmost col of character
      }
    }

*Edit 1:* In the code above, `charData[c][e]` is an unsigned long int.  Its 32 bits represent column `e` of ascii character `c`, with the LSB representing the top-row pixel.  To create `charData[][]`, write a program on your development system that reads whatever bitmaps you have now and writes out code to properly set up `charData[][]` in ProgMem.

Note, for initial scroll-testing, you could skip writing a development-system program to re-orient characters and instead test with character-data arrays as they are.  Characters might display sideways or upside down, but would scroll ok anyway.  Or, if bytes are not in proper [Endianness](https://en.wikipedia.org/wiki/Endianness) to be an unsigned long, they would display in four mis-ordered slices.

*Edit 2* With the following code,

    void  scroller (const PROGMEM byte bildo1[][4],const PROGMEM byte bildo2[][4],int maxCol, word cchsv) {

    int d = 0;
    int cc = 0;
    unsigned long c[32];

    for(int ii=0;ii<32;ii++) {
      c[ii]=0;
      c[ii] += (long) pgm_read_byte(&(bildo1[ii][0]))<< 24;
      c[ii] += (long) pgm_read_byte(&(bildo1[ii][1]))<< 16;
      c[ii] += (long) pgm_read_byte(&(bildo1[ii][2]))<< 8;
      c[ii] += (long) pgm_read_byte(&(bildo1[ii][3]));
    }
    int e = d;      // how far we have scrolled so far
    for (int cn=0; cn<maxCol; ++cn) {
      unsigned long colData = c[e];
      for (int ro=0; ro<32; ++ro) {
        matrix.drawPixel(cn, ro, (colData&1)? cchsv : black);
        colData >>= 1; // discard used-up bit
      }
      ++e;
      if (e >= 32) {  // Done with current character?
        for(int ii=0;ii<32;ii++) {
          c[ii]=0;
          c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]))<< 24;
          c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 16;
          c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 8;
          c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]));
        }
        e = 0;        // Start with leftmost col of character
      }
    }}

chrisoutwright reports getting an image like the following [cropped from [a larger dropbox.com image](https://www.dropbox.com/s/qu7rmzgkyt2l0kk/DSC_0062.JPG?dl=0)]:

[![mixed up house][1]][1]

Cutting this into 4 equal-size horizontal slices and swapping slices top to bottom, we get:  [![mirrored house][2]][2]

That image suggests packing the bytes in reverse order, eg via

    c[ii] += (long) pgm_read_byte(&(bildo2[ii][0]));
    c[ii] += (long) pgm_read_byte(&(bildo2[ii][1]))<< 8;
    c[ii] += (long) pgm_read_byte(&(bildo2[ii][2]))<< 16;
    c[ii] += (long) pgm_read_byte(&(bildo2[ii][3]))<< 24;

Continuing on, if we rotate the left half of the above 90° then flip the rotated image left to right we get a reasonable facsimile of the letter 春 :

 [![ok Chinese character for house][3]][3]

The "flip left to right" amounts to reading bits out MSB first instead of LSB first.  During testing, one might do that by saying

    matrix.drawPixel(cn, ro, (colData&(1<<31))? cchsv : black); colData <<= 1;

instead of

    matrix.drawPixel(cn, ro, (colData&1)? cchsv : black); colData >>= 1;

but in the longer run, a development-system program should be used to re-orient characters instead of using up MCU memory space and time for bitmap organizing.

---

To make the characters scroll, add a parameter (eg, `byte escroll`) to the calling sequence.  Discard variable `d` if it isn't used within scroller, and instead of initializing `e` to `d` (which is always zero hence does not allow for scrolling) initialize it via

    e = escroll;

In the routine that calls `scroller()`, say something like

    byte es=0;
    while (scrolling) {
      scroller(bildo1, bildo2, maxCol, cchsv, es);
      delay(msPerScrollStep);
      ++es;
      if (es >= 32) {
        es = 0;
        // do stuff here about next characters to display
      }
    }

That is, call `scroller()` within a scroll-timing loop (or perhaps put the timing into `scroller()`, whichever meshes better with overall design).

Note, with the code as it stands, plus suggested changes, `bildo2` will scroll in a second time[1] unless a third character is supplied to scroll in.

[1]For example, with `maxCol` of 64, if `es` is 16, when`scroller()` is called, `e` will go from 16 to 31 displaying the second half of `bildo1`, then from 0 to 31 displaying all of `bildo2`, then from 0 to 15 displaying the front half of `bildo2`.

  [1]: https://i.stack.imgur.com/ggJ55.jpg
  [2]: https://i.stack.imgur.com/4TgaZ.jpg
  [3]: https://i.stack.imgur.com/y1YPD.jpg


body:
I'm trying to post data to my SQL database and it seems that I'm not sending the data correctly. My PHP file is working since I have tried it and it writes to the database.

I am getting an `esp.find("SEND OK")` but I must be sending it wrong or something.

Here is the code:
DT 0050 - GLASSES - from sun to sound - chk oil filter malibu old or new?

<!-- language-all: lang-cpp -->

    void loop() {
        // call sensors.requestTemperatures() to issue a global temperature
        // request to all devices on the bus
        Serial.print(" Requesting temperatures...");
        sensors.requestTemperatures(); // Send the command to get temperatures
        char tempC = sensors.getTempCByIndex(0);
        char buffer[10];
        Serial.println("DONE");
        Serial.print("Temperature for Device 1 is: ");
        // You can have more than one IC on the same bus.
        // 0 refers to the first IC on the wire
        Serial.print(sensors.getTempCByIndex(0)); // "byIndex"
        delay(5000);
        data = "temperature=" + tempC; // d
        httppost();
        delay(1000);
    }

    void httppost() {
        esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80"); //start a TCP connection.
        if (esp.find("OK")) {
        Serial.println("\r\nTCP connection ready");
        }
        delay(1000);
        String postRequest =
         "POST /http://manilla.technoaid.net/esp8266.php HTTP/1.1\r\n"
         "Host: 66.96.134.25\r\n" "User-Agent: Arduino/1.0\r\n"
         "Connection: close\r\n"
         "Content-Type: application/x-www-form-urlencoded\r\n"
         "Content-Length: \r\n" "data";
        **String sendCmd = "AT+CIPSEND=";
        esp.print(sendCmd);
        esp.println(postRequest.length());
        delay(1000);
        if (esp.find(">")) {
         Serial.println("Sending..");
         esp.print(postRequest);
         if (esp.find("SEND OK")) {
             Serial.println("Packet sent");
             while (esp.available()) {
              String tmpResp = esp.readString();
              Serial.println(tmpResp);
             }
             // close the connection
             esp.println("AT+CIPCLOSE");
         }
        }
    }

title: Arduino Mega + ESP8266 - Post Data to website issue

Answers: 0


body:
I would like to program the arduino such that if I reset it by disconnecting and then reconnecting the usb.. A particular led glows BUT If I press the manual reset button on my nano... I want a different led to glow. How can I achieve this.
I have 2 leds and my nano... Along with the laptop and any other necessary components.

title: Run different code on different type of reset in arduino nano

Answers: 1

body:
The MCUSR register (page 79 of [the datasheet](http://www.atmel.com/Images/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf)) tells you what kind of reset happened most recently. As long as the USB interface chip on your nano isn't controlling the RESET pin without the port being opened (i.e., toggling it at power up regardless of the USB state) then you could query that register to see how it reset:

    if (MCUSR & (1 << 0)) { // POR
        digitalWrite(4, HIGH);
    } else if (MCUSR & (1 << 1)) { // External Reset
        digitalWrite(5, HIGH);
    }

However, if the USB chip does toggle the RESET pin then there is no way you can distinguish between the two resets since they are bot the same "external" reset using the RESET pin.


body:
I'm trying to write a generic "Test Bench" type of sketch using booleans to indicate whether or not to include specific libraries.  After those are defined, I'm attempting to use preprocessor #if statements to determine if the libraries need to be included and create the objects if need be.

Example:

    const bool useLCD = true;

    ...

    #if (useLCD)
      #include "NHD_4x20.h"
      NHD_4x20 lcd(9);
    #endif

These statements are before the setup() and loop() functions.  This in itself doesn't generate compiler errors, however I get "lcd has not been defined in this scope" when trying to use the object in the setup() and loop() functions.

Is there some simple trick to accomplish this that I'm overlooking here ?

Thanks in advance !

title: How do I "conditionally" include libraries and declare global objects of them?

Answers: 1

body:
    const bool useLCD = true;

should be:

    #define useLCD 1

----

Here is a complete working example of how to use preprocessor macros for conditional compilation:

    #define USE_A 1
    // #define USE_B 1

    #if (USE_A)
    int a = 4;
    #endif

    #if (USE_B)
    int b = 6;
    #endif

    void setup() {
        Serial.begin(115200);
        Serial.print(F("The result is: "));
    #if (USE_A)
        Serial.println(a * 2);
    #endif
    #if (USE_B)
        Serial.println(b * 2);
    #endif
    }

    void loop() {
    }


body:
Sorry if this question has been asked but I can't seem to find an answer because I don't really know if I'm phrasing the question correctly.

I'm trying to control a grid of LED to light up in a specific sequence that is based on a long list of data (and loops over time). Is there any way to bring in the data automatically? (vs individually coding the digitalWrites and delays) I think I found a reference project a few days ago but I lost it.

Thanks!

title: Inputting list of data

Answers: 1

body:
Your question is vague so I have made some assumptions, I hope they are right.

The first is I have assumed you are relatively in experienced at programming, I hope that's right otherwise the rest of this may seem patronising.

You have a number of LEDs arranged in a grid (lets say 3x3 to make life easy).
You are asking is there an alternative to doing this:

    // Step 1
    digitalWrite (LED1, HIGH);
    digitalWrite (LED4, HIGH);
    digitalWrite (LED8, HIGH);
    delay (100);
    digitalWrite (LED1, LOW);
    digitalWrite (LED4, LOW);
    digitalWrite (LED8, LOW);
    // Step 2
    // And so on...

Yes there are, and there are many, I think this is probably going to be the easiest to start with.

**Coding the data in a 2D array.**

An array is a fixed length list of values of the same type.  One obvious use for an array is to hold the pin numbers for you LEDS, rather than having LED0 through to LED8.

    #define LED0 2
    #define LED1 3
    // and so on

Alternative array version

    //  Define the number of elements in the array
    #define MaxLEDs 9
    // Define the array
    const int LEDPins[MaxLEDs] = {2, 3, 4, 5, 6, 7, 8, 9, 10};

I have declared the array as `const` because the values in it aren't going to change.  The array is going to hold integers (because that's what `digitalWrite()` takes as a pin number) and there are 9 of them.  Rather than use the literal 9 I have defined a constant because I know that value is going to be used elsewhere in the code and this means it is easier to change the number of LEDs.

So how does this help you?  Well you can define an array of 'steps' and each step has a list of which LEDs are switched on.  As your code loops through the steps it turns the specified LEDs, waits and then turns them off.  The simplest way to encode the data would be for each 'step' element to be an array of Boolean values (each true value indicates a light that should be on during this step).  I have chosen Booleans because it will use the least amount of space, which is always an issue on an Arduino.  Depending on the number of steps and LEDs you may need to look at alternative storage methods, like just the LEDs that are on, but it will do for now.

    const bool theSteps[MaxSteps][MaxLEDs] =
    {
        {false, false, false, false, false, false, false, false, false}
      , {false, true , false, false, true , false, true , false, false}
      , {false, false, true , true , false, false, false, true , false}
      , {true , false, false, false, false, true , true , false, false}
    };

You still have to code the data within the program, but its much smaller

    //  Define the number of elements in the array
    #define MaxLEDs 9
    // Define the array
    const int LEDPins[MaxLEDs] = { 2, 3, 4, 5, 6, 7, 8, 9, 10 };

    const bool theSteps[MaxSteps][MaxLEDs] =
    {
     { false, false, false, false, false, false, false, false, false }
     ,{ false, true , false, false, true , false, true , false, false }
     ,{ false, false, true , true , false, false, false, true , false }
     ,{ true , false, false, false, false, true , true , false, false }
    };

    #define StepDelay 100

    void setup()
    {
    }

    void loop()
    {
     for (int onOff = 0; onOff < 2; ++onOff) // Turns the LED on and off
     {
      for (int step = 0; step < MaxSteps; ++step)
      {
       for (int led = 0; led < MaxLEDs; ++led)
       {
        if (theSteps[step][led])  // If the LED should be on
        {
         digitalWrite(LEDPins[led], (onOff < 1) ? HIGH : LOW);
        }
       }
      }
      if (onOff < 1)
                {
                      delay(StepDelay);
                }
     }
    }

I'm afraid I haven't tested any of this code (it might not even compile) but the theory is right and it should give you a shove in the right direction.


body:
I make my own library for arduino.

The file structure is like below.

    AAA - README.md
        - examples - A - A.ino
                   - B - B.ino
        - AAA.h
        - BBB.h
        - CCC.h
        - BBB.cpp
        - CCC.cpp

It works well. But I want to grouping a library source files like below.

    AAA - same as above
        - src - AAA.h
              - BBB.h
              - CCC.h
              - BBB.cpp
              - CCC.cpp

It doesn't work at all.

Arduino IDE shows the message

>Specified folder/zip file does not contain a valid library.

But, WiFi101 library was made by src folder. Why isn't it possible for mine?

title: Arduino library making

Answers: 1

body:
I'm going to assume your library structure is like this because the structure you described above would not cause that error:

    AAA
    |_src
     |_AAA.h
     |_BBB.h
     |_CCC.h
     |_BBB.cpp
     |_CCC.cpp

To be considered valid by the Arduino IDE, a library must either have a .h file in the root folder or a library.properties file if you are using the [1.5 library format](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#15-library-format-rev-21). Putting all the source files in the `src` subfolder means your library is in the 1.5 library format. So you need to add a library.properties file in the root of the library formatted as described here: https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification#libraryproperties-file-format. Then your library should look like this:

    AAA
    |_library.properties
    |_src
     |_AAA.h
     |_BBB.h
     |_CCC.h
     |_BBB.cpp
     |_CCC.cpp


body:
I'm trying to write floats to I2C FRAM (like I2C EEPROM) but without result. I tried with this function but I lose all number after the decimal. Thank's for replying.

This for writing:

    float floatNumber = 123.123;
    byte floatPt1 = 0;
    byte floatPt2 = 0;
    byte floatPt3 = 0;
    byte floatPt4 = 0;
    byte b1 = (floatNumber);
    byte b2 = (floatNumber >> 8);
    byte b3 = (floatNumber >> 16);
    byte b4 = (floatNumber >> 24);

This is for reading:

    long floatRicomposto = 0;
    floatPt1 = fram.read8(3);
    floatPt2 = fram.read8(4);
    floatPt3 = fram.read8(5);
    floatPt4 = fram.read8(6);
    //float RECOMPOSITION
    floatRicomposto = (uint32_t) floatPt1 <<  0
      | (uint32_t) floatPt2 <<  8
      | (uint32_t) floatPt3 << 16
      | (uint32_t) floatPt4 << 24;

title: Splitting a float into bytes for storage in FRAM (like EEPROM)

Answers: 2

body:
I solved it with the use of UNION:

    //---------------------------------------------------------
    union Scomp_float {
      // si utilizza union x float
      float temp;
      char byte_s[4];
    } S_float;

    //---------------------------------------------------------
    //-------------------------FLOAT--------------------------------
    float mioFlo = 123456.29;
    byte f0 = 0;  // contengono i byte del float
    byte f1 = 0;
    byte f2 = 0;
    byte f3 = 0;
    S_float.temp = mioFlo;
    f0 = S_float.byte_s[0];
    f1 = S_float.byte_s[1];
    f2 = S_float.byte_s[2];
    f3 = S_float.byte_s[3];
    Serial.println(f0);
    Serial.println(f1);
    Serial.println(f2);
    Serial.println(f3);
    fram.writeEnable(true);
    fram.write8(7, f0);
    fram.writeEnable(false);
    fram.writeEnable(true);
    fram.write8(8, f1);
    fram.writeEnable(false);
    fram.writeEnable(true);
    fram.write8(9, f2);
    fram.writeEnable(false);
    fram.writeEnable(true);
    fram.write8(10, f3);
    fram.writeEnable(false);
    S_float.byte_s[0] = fram.read8(7); // si ricompone il float
    S_float.byte_s[1] = fram.read8(8);
    S_float.byte_s[2] = fram.read8(9);
    S_float.byte_s[3] = fram.read8(10);
    float masterFloat = S_float.temp;
    Serial.println(masterFloat);
    //-------------------------FLOAT--------------------------------

body: A pointer can be used to easily decompose and reconstitute any multi byte type, like a float.


body:
am working with and Arduino nano and according to [this][1], I can append strings to numbers by doing: `stringThree =  stringOne + 123;` but
when I do:

 sensorValue = analogRead(A0);
 String x1 = "{\"Volt\":"+sensorValue;
 Serial.print(x1);

I get this unwanted output!

> =gëÙrïË:_³ß»þ™¹Æ3+Ç#ÿ¼¿.Õ[Oû\/g¯>ïÿ1þ†lú0

but doing this it works fine.

 sensorValue = analogRead(A0);
 String x1 = "{\"Volt\":";
 x1 += sensorValue;
 Serial.print(x1);

> "Volt":646

why?

  [1]: https://www.arduino.cc/en/Tutorial/StringAdditionOperator

title: Why is my Serial port not printing the right output?

Answers: 1

body:
In the first example you are adding an integer to the address of a string literal and then converting it to a `String`.

In the second example you are converting a string literal to a `String` and then appending an integer.

The key point here is *string literal*. The compiler just sees it as an address in flash memory. It's down to the functions you use with that address that define it as a string. So when you add an integer to it you are just adding an integer to the address, which of course changes the address. So then when you go to convert whatever is at that address to a `String` you end up with garbage.


body:
Hi fellow programmers,

I started to program Arduino a little deeply and popped out the following error when I was writing a class to read the pulses of a Hall effect flow rate sensor:

    SensorDeVazao.cpp.o: In function `SensorDeVazao::Resetar()':
    SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
    SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
    SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
    SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
    SensorDeVazao.cpp:141: undefined reference to `SensorDeVazao::SensorHandle'
    SensorDeVazao.cpp.o:SensorDeVazao.cpp:141: more undefined references to `SensorDeVazao::SensorHandle' follow
    collect2: error: ld returned 1 exit status

The code is divided in two files, a *.h and a *.cpp, so it is uncircumstantial to paste the code here (pos-edited: the codes are the following: *.h: [codepad.org/UyLfik6W][1] *.cpp: [codepad.org/5KJmraCC][2]). But I will explain the context:

SensorHandle is a static object of the own class SensorDeVazao (Brazilian Portuguese to FlowRateSensor) and it is used in an glue function used by the attachinterrupt to read the pulses I've mentioned previously. The function claimed in the error log ("Resetar", Brazilian Portuguese for reset) don't use the variable "SensorHandle". Last but not least, the message shown in the second line appears subsequently multiple times in the error window.

I hope, I provided all the informations to help you solve this issue.
Thank you for the attention.

 PS.: Sorry if this is a duplicated post. If yes, please forward it in the comments below.

  [1]: http://codepad.org/UyLfik6W
  [2]: http://codepad.org/5KJmraCC

title: "undefined reference to" - C++

Answers: 2

body:
Without seeing the actual code (BTW why can't you add it? Is it top-secret?) I can't be sure, but usually this happens when you don't define a variable but just declare it. Example:

    // File myclass.h
    class A {
    public:
      static int i;
    };

    // File myclass.cpp
    void myfunc() {
     A::i = 0;
    }

If you actually declare it the error should go away:

    // File myclass.h
    class A {
    public:
      static int i;
    };

    // File myclass.cpp
    int A::i = 0;

    void myfunc() {
     A::i = 0;
    }

Remember that the class definition (so the class {}) can go in a header file, but the variables definition MUST go in a source file (so the .cpp one) AND if you have multiple source files you have to put this in ONLY ONE file (usually the file where you implement the functions).

This only applies to static variables.

EDIT: Further explanation.

You should understand the difference between declaration and definition of a variable.

Definition is just stating "there exist a variable called i, which is an integer"; for instance the statement `extern int i;` defines a variable. All the variables listed in a class are only defined there.

Declaring a variable is one more step: it tells the compiler to reserve the space in memory (this operation is called allocation) and so to physically create the variable. Always keep this in mind.

Little example. Let's say you have a library, using files lib.h and lib.cpp, and files A.cpp and B.cpp both referencing the library (they have a statement saying `#include "lib.h"`). When writing a library without a class you usually write global variables in this way:

    // header file: lib.h
    extern int i;

    // source file: lib.cpp
    int i;

(note: it is better to always define an initialization value, so for instance `int i = 0;`). The two files (A and B) both have the line `extern int i;` in they, which means "there exist a variable called i, and someone else is allocating the space for it. Result: the compiler will link all those definitions to the same memory location, thus actually sharing the variable. If you wrote `int i;` in the header file each cpp file would have its i variable allocated, so each would point to a different block of memory.

Now, for the classes. If you write

    class A {
    public:
        int a;
        static int b;
    }

you have two variables. A gets instantiated when you instantiate an object, so does not have any problems. But b... well, b is just defined, never declared. So there is no place in memory where b actually resides (the reference is undefined).

To deal with this, you have to manually declare it in a cpp file, with the syntax `int A::b;`. This way you are reserving some space for that variable

body:
An explanation of what is happening:

When you define a class you indicate what variables will be in it.

When you then instantiate the class (`MyClass c;`) the variables within the newly instantiated object get allocated.

Static variables never get instantiated. After all - which instance of the class should instantiate them when you create one? And if you never create one? So it's simple: static variables *never* get created by the class definition or anything else. It is up to *you* to provide the storage space for that variable, which means statically allocating it in your C++ code as has been demonstrated.


body:
I'm trying to save in memory (FRAM in this case) DOUBLE value, i try the same method with use of UNION for save FLOAT value, but don't go over the 2nd number after dot, why? Where I'm wrong? thank's for help .

     //---------------------------------------------------------

      union Scomp_double  // si utilizza union x double
      {
        double temp;
        char byte_s[8];
      } S_double;

      //---------------------------------------------------------

    double mioDouble = 1234567.12345678;

    //-------------------------DOUBLE--------------------------------

      Serial.println("DOUBLE");
      byte d0 = 0;  // contengono i byte del float
      byte d1 = 0;
      byte d2 = 0;
      byte d3 = 0;
      byte d4 = 0;
      byte d5 = 0;
      byte d6 = 0;
      byte d7 = 0;

      S_double.temp = mioDouble;
      d0 = S_double.byte_s[0];
      d1 = S_double.byte_s[1];
      d2 = S_double.byte_s[2];
      d3 = S_double.byte_s[3];
      d4 = S_double.byte_s[4];
      d5 = S_double.byte_s[5];
      d6 = S_double.byte_s[6];
      d7 = S_double.byte_s[7];

      Serial.println(d0);
      Serial.println(d1);
      Serial.println(d2);
      Serial.println(d3);
      Serial.println(d4);
      Serial.println(d5);
      Serial.println(d6);
      Serial.println(d7);

      fram.writeEnable(true);
      fram.write8(11, d0);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(12, d1);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(13, d2);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(14, d3);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(15, d4);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(16, d5);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(17, d6);
      fram.writeEnable(false);
      fram.writeEnable(true);
      fram.write8(18, d7);
      fram.writeEnable(false);

      S_double.byte_s[0] = fram.read8(11); // si ricompone il double
      S_double.byte_s[1] = fram.read8(12);
      S_double.byte_s[2] = fram.read8(13);
      S_double.byte_s[3] = fram.read8(14);
      S_double.byte_s[4] = fram.read8(15);
      S_double.byte_s[5] = fram.read8(16);
      S_double.byte_s[6] = fram.read8(17);
      S_double.byte_s[7] = fram.read8(18);

      double masterDouble = S_double.temp;
      Serial.println(masterDouble);
      //-------------------------DOUBLE-------------------------------

expected result 1234567.12345678 , result taken 1234567,12

title: Splitting DOUBLE in byte for save on EEPROM

Answers: 2

body:
how suggest in the comments, and on [Arduino reference DOUBLE website][1]

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

only on arduino 2 float it's 8 byte.

body: The problem here is the serial output, which by default only outputs 2 decimal places. Solution: Serial.println(masterDouble,8);


body:
I have a project where I'm providing power via the DC jack to my Arduino then accessing the DC power via the VIN pin. According to this [http://forum.arduino.cc/index.php?topic=453955.0][1] I am ok to draw up to 1A from the VIN pin. I have measured 400ma out of VIN, so ok on that front.

But according to this [http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations][2] I can draw max 400ma, So I'm a bit confused, which is the correct amount of power VIN can supply if the Arduino is being powered via the DC jack?

If I take the first thread as correct and assume it's ok to draw up to 1A from the VIN pin (from the DC power jack), is it ok to ground that current on the Arduino GND pin ? if VIN can supply up to 1A then I assume that it's ok to ground up to 1A, is this correct?

All help appreciated

  [1]: http://forum.arduino.cc/index.php?topic=70445.0
  [2]: http://playground.arduino.cc/Main/ArduinoPinCurrentLimitations

title: Arduino Ground Current and DC power jack

Answers: 1

body:
Going by the schematic [here][1] there is an M7 diode (D1) between the power jack and the VIN pin on a Uno (you don't actually say which board you're using, I'm guessing based on the first link).

The datasheet [here][2] indicates that the maximum forward current for a M7 diode is 1.0 A. However different manufacturers datasheets seem to disagree as to whether that is a sustained DC current or only rectified current (so 50% load implying ~500mA constant load).

Either way you are looking at a potential 1.1 V drop across the diode so your VIN will be below the supply voltage by up to that much.

If you want to live dangerously you can always replace D1 with a piece of wire (or put the wire across it). You will lose reverse voltage protection on the DC jack, using a supply with it backwards will blow things up, but your current will then be limited by how much current the connector pins and PCB trace can cope with before they melt.

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: http://www.kingtronics.com/pdf/M7-diode.pdf


body: I am a beginner to Arduino, and a relative beginner to electronics in general. I have the official Arduino Starter Kit. I've looked through my bag of components looking for a black diode but was unable to find it among all of the LEDS & the other black components.

title: How do I find my 1N 4007 diodes?

Answers: 4

body:
While the [ArduinoStarterKit page](https://www.arduino.cc/en/Main/ArduinoStarterKit) at arduino.cc lists “5 Diodes [1N4007]” as part of it, and has a picture where 5 diodes apparently appear slightly left of center in the top row, several other pictures that come up in a [google images search for *official Arduino Starter Kit*](https://www.google.com/search?hl=en&site=imghp&tbm=isch&source=hp&biw=1400&bih=896&q=official+Arduino+Starter+Kit&oq=official+Arduino+Starter+Kit&gs_l=img.3..0j0i24k1l3.1366.1366.0.3233.2.2.0.0.0.0.88.88.1.1.0....0...1ac..64.img..1.1.87.0.eMHm1WmRzhk#imgrc=IBZ9ux6HxlSEfM:) apparently don't show the diodes.  Eg, as at [arduino starter kit](http://www.arduino.org/products/kits/arduino-starter-kit).  But [4 Best Starter Kits for Arduino Beginners](http://www.nbcdaily.com/4-best-starter-kits-for-arduino-beginners/3883/) does show them.

Note, unless you are working with medium to high AC voltages (eg above 50 V) you can substitute 1N4001 - 1N4004 which have lower PIV ratings but also slightly lower forward voltage drop.  For many beginning projects, [1N4148 signal diodes](https://en.wikipedia.org/wiki/1N4148_signal_diode) will be adequate and perhaps less expensive.

body: 1N4007 are usually black with a white stipe indicating the cathode. Use a magnifying glass and you should be able to see the marking.

body:
They are stuck next to a string of resistors.

[![Diodes and resistors][1]][1]

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

body:
This is image of 1N4007 diodes. I think now you can find them easily.

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

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


body:
I'm trying to start a project where I have a 6 sec recording (wav file: 8 bit, 8 or 16 kHz, mono) on a micro-SD card and want to play it through my Arduino Uno on an 8 Ohm, 0.1 W speaker. I've looked at many different forums and threads for how to do this. One that continually comes up is [this link][1], but this is for the Due and I can't figure out how to adapt for the Uno.

The important bit is I am using an Ethernet R3 shield which has a built in micro-SD card reader. Much of the code and tutorials I found use the TMRpcm library, setting the speaker pin to 9, the SDChipSelectPin to 4, with various wire connection geometries depending on which tutorial you read. I really need help trying to figure out how the wiring is supposed to go. I, honestly, do not understand what's going on and am hoping someone will take the time and can explain this pretty pedagogically. Currently, no matter what I try, I just hear high-pitched static or fast periodic noises.

  [1]: https://www.arduino.cc/en/Tutorial/SimpleAudioPlayer

title: Playing WAV file from Arduino Uno using Ethernet R3 Shield

Answers: 1

body:
Your Arduino UNO won't play any wave file the way you're expecting. There's not enough processing power to do that.
In order to play audio using small MCUs such as AVR (or PIC for example) you must use the BTC algorithm. Please, check this out : http://www.radanpro.com/Radan2400/mikrokontroleri/How to make sound with a PIC chip.htm
and download the software which can convert your wave file into an array which can be then played by Arduino using a BTC algorithm. Schematics on how to place reistors and speakers to match impedance are provided and suggested on the software as well.


body:
   Sorry for any grammar mistakes. It's my second language.

I had a little test with my Arduino Uno R3 I connected 2 buttons to power , GND using 10k resistors and pins 2 and 4.
I connected piezo to power and ground.

When you pressed a button1 then you should hear 'c' tone,
but when I pressed the second button nothing happend and I don't understand why?

Here is my code below:

    const int buttonPin2 = 4;
    const int buttonPin1 = 2;
    const int piezopin =  6;

    int buttonState1 = 0;
    int buttonState2 = 0;

    void setup() {

      pinMode(piezopin, OUTPUT);
      pinMode(buttonPin2,INPUT);
      pinMode(buttonPin1, INPUT);
    }

    void loop() {

      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);

      if (buttonState1 == HIGH) {
        tone(6,261.63,500);

      } else {

      }
      if (buttonState2 == HIGH) {
        tone(6,392.00,500);
      } else {

      }

title: Anything wrong with this code?

Answers: 1

body:
Try calling `noTone()` after the tone is played. This is a kind of "reset" for the pin.

Also, you forgot a `}` at the end of your code.

If these didn't solve your code, then it most probably is an electric problem.


body:
I am trying to control my WS2812B with a remote control. To archive this, I am using IRRemote library. The problem is that this two libraries doesn't work together.

I did some research and found out that it is a problem with timers.But, inside the IRRemote library file (boarddefs.h) there is a possibility to choose different timer (It uses TIMER2 as default, so I supposed that FastLed uses also Timer2).

So when I change the timer in boarddefs.h file to TIMER1, it is also now working fine for me. I keep recieving random IR codes. When I stop using FastLed library, I recive correct codes.

Some workaround to this problem is to read IR signal only once irrecv is idle:

      while (!irrecv.isIdle());  // if not idle, wait till complete
      if (irrecv.decode(&results)) {
         ...
      }

It makes around 80% of readings correct.

I am using arduino NANO clone. My question is, if there is any way to use IRRemote and FastLed libraries together other than using two arduino NANO (use one to read IR and other to control LEDs)?

title: FastLed (WS2812B) and IRRemote problem

Answers: 2

body:
The WS2812B chips are highly timing-dependent. You have to clock out bits within a range of ±150 ns. This isn't likely to work well with clocking in bits from an IR remote. You are finding errors on the IR codes - that doesn't surprise me.

I suggest you use your idea of two Nanos. One can be reading IR codes. The other can display a stream of pixels and then "ask" the other one (eg. via serial or I2C) if a different command has arrived. That way the timing can be shifted in such a way that both processors are not interrupted when they are busy.

body:
update in 2021, similar problem, fastLED causing unintelligible IR codes,
adding that while loop:
```
while (!irrecv.isIdle());  // if not idle, wait till complete
```
just before the ir check
worked for me, not 100% of the codes are correct but more than good enough for my use,
you life saver


body: I want to use the audio from my PC and have it going to the speakers and Arduino for some lighting effects. This project is a bit of a struggle because I don't know what the best way of analysing audio is. So for the lights I only want bass frequencies to affect the lights.

title: How to analyse audio and to affect source?

Answers: 2

body:
I have actually just finished a project doing exactly that. I used a frequency analyser chip called an MSGEQ7 (Available from Sparksfun), here's the datasheet.

<https://www.sparkfun.com/datasheets/Components/General/MSGEQ7.pdf>

These little things are really easy to use. Give me a shout if you would like any help with it such as coding or wiring.

body:
There's many ways of achieving what you want - some in software, some in hardware.

Since you are only interested in the lower frequencies this opens up the possibility of a *low pass filter* - either a hardware one, or a software one.  The simplest hardware one is just a resistor in series followed by a capacitor in parallel:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/Wio7P.png)

<!-- End schematic -->

(representative component values: increase capacitance and/or resistance to decrease frequency)

Doing it in software is just as simple: you sample at a regular frequency through whatever means are suitable (there's plenty of resources for sampling at a specific frequency on the Arduino - google them), then you average samples together to remove higher frequency components. The more you average the lower your cut-off frequency. Each time you average you halve the frequency range. Note that the frequency range is already *half* the sample frequency.

For instance: if you sample at 8kHz (say 512 samples) you get a 0-4kHz frequency range in your sample set. Averaging each pair of samples (which results in 256 samples) gives you a 0-2kHz frequency range. Averaging again, for 128 samples, gives you 0-1kHz. Average again, for 64 samples, gives you 0-500Hz. Again, 32 samples, 0-250Hz.  Keep going, until you have your desired cut-off frequency.

Then you can scan the sample set for the maximum and minimum and take that as your peak amplitude for the sample set.

You have to make sure that your sample frequency is at least twice the highest frequency you are interested in (preferably more so that you can do some averaging), and that your sample set is large enough, at the chosen sample frequency, to contain at least one full cycle of the lowest frequency you are interested in.  For instance, at 8kHz sample frequency, if you are interested in responding to frequencies down to 50Hz, you need to sample for at least (1/50) 20ms, which at 8kHz means (8000 samples per second times 0.02 seconds) 160 samples. Since it's usually better to work with powers of 2 that means 256 samples is the next biggest "slot" that would do.

If you want to access more information about the actual frequency content of your sample set so as to light different LEDs when different frequency components are in the signal you need a *Fast Fourier Transform* (FFT). This converts the sample set into a collection of *buckets* (exactly half the buckets as you have samples) each representing a portion of the frequency range of your sample set. For 256 samples that gives you 128 buckets, each representing 1/128 of your total frequency range. So at 8000 samples per second, or a 4kHz frequency range, each bucket gives you a 31.25Hz resolution.

The problem with FFT is it is computationally expensive. It also needs more memory than simple averaging.

Depending on the algorithm you use, you will probably find you need 16 bit samples, and each sample should be in the form of a "real" and "imaginary" component, amounting to 32 bits per sample. Most algorithms require powers-of-two for the number of samples. For 256 samples that means you are using 1024kB of memory just for sample storage and processing, which is half of what the Uno has. You certainly won't be able to go over 256 samples on an Uno (the next step up is 512, which would want to use the entire memory leaving no room for any other variables).

There are two basic forms of algorithms for FFT: floating point, and integer. The floating point variant is great on a CPU that has an FPU with it to do the number crunching, but on an Arduino that just isn't possible. So the floating point version would take a massive amount of time to process making your results incredibly jittery. Far from desirable. So you need to find the integer version ([one example](http://wiki.openmusiclabs.com/wiki/ArduinoFFT)) which runs much faster.

Calculating an FFT is done in two parts: first it calculates the real and imaginary components from the sample set, and second it converts those two components into a single vector, the length of which is the amplitude of the bucket. Whether or not you are using the integer FFT algorithm that second phase is going to be slow. It involves a square root (it's basically pythagoras: `sqrt((r*r) + (i*i));`) and that is almost always slow. Getting that to work fast on an Arduino is not at all easy. You can sacrifice accuracy for speed though and write your own square root approximation routine (as I have done before for 3D vector manipulation in a graphics library):

    float quick_sqrt(float number) {
        int32_t i;
        float x2, y2;
        const float threehalfs = 1.5F;

        x2 = number * 0.5F;
        y2  = number;
        i  = * ( long * ) &y2;
        i  = 0x5f3759df - ( i >> 1 );
        y2  = * ( float * ) &i;
        y2  = y2 * ( threehalfs - ( x2 * y2 * y2 ) );

        return 1.0/y2;
    }

That uses a few tricks to do with the way a floating point number is stored to create an approximation of the square root.

With all that you can see that the Arduino can do FFT, but it's not the best solution for FFT. Ideally you need a faster, more powerful, chip with more memory (personally I use a PIC32MZ "EF" variant: 200MHz, 512kB RAM, FPU).