message:
Compiling error:passing as 'this' argument

I am trying to make a small keyboard class to handle two buttons(in the future >2)  that are connected to my arduino UNO. The buttons being pressed are detected using interrupts. Here is the code:

**Timer**

    class Timer{
      private:
        uint32_t start_time;
      public:
        Timer(){
          start_time=millis();
        }
        void mark(){
          start_time=millis();
        }
        uint32_t lapsed(){
          return millis()-start_time;
        }
    };
**Keyboard**

    class KeyboardBtn{
      private:
        const static byte clicksDelay=255;      //255 ms max
        struct btn{
          byte state=0;   //0->nothing;1-click;2-dblClick
          Timer clickDelay;
        };
        volatile static btn buttons[2];         //only two buttons for now

      public:
        KeyboardBtn(){
          attachInterrupt(digitalPinToInterrupt(2),this->int_handler_btn0,FALLING);       //Initially the pins are set to HIGH(pullup behaviour)
          attachInterrupt(digitalPinToInterrupt(3),this->int_handler_btn1,FALLING);
        }

        static void int_handler_btn0(){
          btns_handler(0);
        }
        static void int_handler_btn1(){
          btns_handler(1);
        }
        static void btns_handler(byte key){
            if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
              buttons[key].state=2;
            }else{
              buttons[key].state=1;
              buttons[key].clickDelay.mark(); //Pressed one time? mark this and wait for second press
            }
        }
        byte stateChanged(byte key){
          //Function called to get key status
          byte temp_state=buttons[key].state;
          if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
            return 0; //We still wait:don't know if it's a dblClick or single
          }else{
            buttons[key].state=0;
            return temp_state;
          }
        }
    };
    volatile KeyboardBtn::btn KeyboardBtn::buttons[2];

But the compiler gives me headaches(of course my code is wrong somewhere but he could just have kept quite about it):

> C:\Users\....\Humidity.ino:
> In static member function 'static void
> KeyboardBtn::btns_handler(byte)':
>
> C:\Users\...\Humidity\Humidity.ino:74:68: warning: passing 'volatile Timer' as
> 'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
> [-fpermissive]
>
>          if(buttons[key].state==1 && buttons[key].clickDelay.lapsed()<=clicksDelay){
>
>                                                                     ^
>
> C:\Users\...\Humidity\Humidity.ino:78:40: warning: passing 'volatile Timer' as
> 'this' argument of 'void Timer::mark()' discards qualifiers
> [-fpermissive]
>
>            buttons[key].clickDelay.mark();
>
>                                         ^
>
> C:\Users\....\Humidity\Humidity.ino:
> In member function 'byte KeyboardBtn::stateChanged(byte)':
>
> C:\Users\....\Humidity\Humidity.ino:83:58: warning: passing 'volatile Timer' as
> 'this' argument of 'uint32_t Timer::lapsed()' discards qualifiers
> [-fpermissive]
>
>        if(temp_state==1 && buttons[key].clickDelay.lapsed()<clicksDelay){
>
>                                                           ^

What is the problem?
Note:It does allow me to upload the code but I am almost certain it will generate some errors while running...

body:
If you want to use an instantiated object as volatile then the functions within it also have to be marked as volatile. That tells the compiler that the instance pointer you will be passing to the function (the auto-inserted `this` parameter) is volatile:

    class Timer{
      private:
        uint32_t start_time;
      public:
        Timer(){
          start_time=millis();
        }
        void mark() volatile {
          start_time=millis();
        }
        uint32_t lapsed() volatile {
          return millis()-start_time;
        }
    };


sender: user

message:
Logic level converter not working?

I'm trying to connect a 3.3v depth sensor to an Arduino uno. The logic level converter does not seem to send any current over (the sensor does not work and the voltmeter reads nothing). I tested the depth sensor separately, so I know it works, meaning it must be the converter. Why wouldn't it be working?

I've tried two logic level converters so far, but neither seems to work. This is basically how I connected it:

[![wires][1]][1]

Here's the LLC:
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/g7EFk.jpg
  [2]: https://i.stack.imgur.com/qxo2a.jpg

Did I mess something up soldering it or by plugging it in wrong earlier?

sender: assistant

body:
Based on your schematic, you need to provide a 3.3v power source to the 3.3v side of the logic level converter. You can use the 3.3v pin on the Arduino.

Also, it's really hard to evaluate your soldering with such a shaky picture. Just make sure none of the pins are connected. A visual inspection usually will do, but if you want to be sure, use your multimeter's continuity function. Test all adjacent pins to confirm they are not bridged.


message:
How do i get stored Midi to Play back without the notes sounding sustained?

How can i get my stored midi notes to play back without sounding sustained like in this video : https://youtu.be/zc1zbwheyE0?t=2m30s. Here is some of my code:

    // Callback function to for recording note played is called upon reception of a NoteOn.
    void MyHandleNoteOn(byte channel, byte pitch, byte velocity) {

    if ((currentState != STATE_R) || (noteIndex >= MAX_NOTE))
          return;

      // Record the note
      noteList[noteIndex].channel = channel;
      noteList[noteIndex].pitch = pitch;
      noteList[noteIndex].velocity = velocity;
      noteList[noteIndex].deltaT = millis() - lastNoteTime;

      lastNoteTime = millis();
      noteIndex++;

     }

     void StateMachine(void)
    {
      static uint16_t  nextNote;

    MIDI.read();   // keep this going as fast as possible and empty buffer all the time

      switch (currentState)
      {
        case STATE_I2P:    // Set up for playback

          nextNote = 0;
          lastNoteTime = millis();
          SwitchState(STATE_P);
          break;

        case STATE_P:      // Play the notes back
       lcd.clear();
     lcd.setCursor(5,0);
      lcd.print("Playing Recorded Song");
      if (nextNote >= noteIndex) SwitchState(STATE_P2I);  // we are done

           if ((millis() - lastNoteTime) >= noteList[nextNote].deltaT)
           {
             MIDI.sendNoteOn(noteList[nextNote].pitch, noteList[nextNote].velocity, 1); //noteList[nextNote].channel);  // Send the note
            noteOn(0x90,noteList[nextNote].pitch,100);
             nextNote++;
             lastNoteTime = millis();
           }
          break;
       }

body: You need to store and send out the 'note off' messages in addition to the 'note on' messages.


body:
A MIDI stream is far more than just a list of notes to play. It's a set of instructions to the musical instrument on exactly *how* to play the music.

Take the typical MIDI keyboard, for example.  When you press a note a "Note On" message is generated. This contains the note number (pitch) of the note to play along with the *velocity* (volume) of the note. It's called *velocity* because it's derived from how fast the key travels between two points - the faster it travels the harder you must have hit it and so the louder it should sound.

Then when you release the key a "Note Off" message is generated. This tells the target to *stop playing the note*.

Normally if you get two "Note On" messages for the same note without a "Note Off" for that note in between the new "Note On" replaces the old one, and a subsequent "Note Off" will stop all sound for that note, not just the most recent "Note On".

As well as those there are other messages as well detailing various other aspects of the music - patch and bank (instrument) selection, pitch bend, sustain, after-touch, etc. All of these are important to the overall sound of the music. And then there are "SysEx" messages (System Exclusive) which are (to a large extent) exclusive to the system that is generating them (hence the name). To faithfully recreate the music all of these *should* be stored as well.

The bare minimum though would be to store both the "Note On" and "Note Off" and maybe the velocity. How you store them is up to you, but both of them are required.

In your existing code you would need to expand the structure of your array to include *what* the instruction is. Not just assume it's all "Note On", but store whether the instruction is a "Note On" or a "Note Off", so when you play the MIDI back you can send the correct sequence of On and Off for the notes.


message:
Flash Arduino Micro code on Atmega32U micro controller

First of all, I am not an expert on electronics, so forgive me for asking something which is trivial for probably the most of you.

I am trying to get my Arduino (Micro) code running on a custom PCB with the Atmega32U chip on it. The person who made the PCB copied parts of the schematics of the Arduino Micro onto a custom PCB. What he did, is place the Atmega chip on it, and also copied the wiring for the micro USB connector.

That way, I can hook up the PCB to my USB port but now Windows does not recognize the chip as a "Arduino hosted via a COM port", but just as a atmega chip.

I learned that installing Atmel Studio 7 will also provide the correct drivers so that Windows recognizes the chip correctly via USB:

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

The next step for me was to get my code running on the atmega chip. So with some help from the internet I came to the following steps:

* open my sketch in Arduino IDE
* compile with verbose output
* find the location where the ".HEX" file is stored

But how can I flash this .HEX to the Atmega chip?

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

body:
To get your chip to respond to the Arduino environment over USB you need a booloader (some extra code) to be running on the Atmega32.

To install the bootloader you can use another Arduino as a programmer to the ICSP pins (or any other AVR ICSP programmer).
This [procedure and description][1] from Sparkfun for the Arduino Pro will help you.

This may help you understand the [ICSP][2] aspect, again from Sparkfun.

  [1]: https://learn.sparkfun.com/tutorials/pro-micro--fio-v3-hookup-guide/troubleshooting-and-faq#faq-reinstall
  [2]: https://learn.sparkfun.com/tutorials/installing-an-arduino-bootloader


body:
You can flash the .hex file to the chip with avrdude.

First, you have to add avrdude to your PATH variables.
This can be done by adding the folder of avrdude.exe to the PATH variables, described in [this][1] method.
An example path to your avrdude.exe can be this:
``C:\Program Files (x86)\Arduino\hardware\tools\avr\bin\``.

Then go to your project where the .hex file lies, and use avrdude to flash the .hex file to the chip.

Example commands can be found on the [avrdude website][2], the description of avrdude flashing can be found [here][3].

My example command that I use in Atmel Studio with an Arduino Mega clone that has an ATmega2560 chip (slightly modified to fit the question:
``avrdude.exe -v -p atmega2560 -c wiring -P COM3 -b 115200 -D -U flash:w:<hexfile.hex>:i``

  [1]: http://www.computerhope.com/issues/ch000549.htm
  [2]: http://www.nongnu.org/avrdude/user-manual/avrdude_6.html
  [3]: http://www.nongnu.org/avrdude/user-manual/avrdude_4.html


message:
Arduino Nano PWM pin not functioning

I am building a project using an Arduino Nano. In it, I am using pin 3 as PWM output. However, If I supply values lower than 255 to it, the pin does not output any voltage at all.

According to this diagram, pin 3 is PWM:

[![NANO pinout][1]][1]

I have tested it on two boards, it doesn't function on either one. It's not my sketch, either (I tested it with a simple `analogWrite();`).

This is the code:

    void setup() {
      // put your setup code here, to run once:
      #define E1 3  // Enable Pin for motor 1
      #define E2 10  // Enable Pin for motor 2
      #define I1 4  // Control pin 1 for motor 1
      #define I2 2  // Control pin 2 for motor 1
      #define I3 A1  // Control pin 1 for motor 2
      #define I4 A0  // Control pin 2 for motor 2
    }

    void loop() {
      // put your main code here, to run repeatedly:
      // I use differential steering, speed is important
      analogWrite(E1, 100); // Run in full speed
      analogWrite(E2, 100); // Run in full speed

      // always go forward
      digitalWrite(I1, LOW);
      digitalWrite(I2, HIGH);
      digitalWrite(I3, LOW);
      digitalWrite(I4, HIGH);
    }

What could be the reason of this?

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

body:
Try to replace #define E1 3 with #define E1 PD3 and see if that helps.

The PBx, PCx and PDx designations are unambiguous, so using those are pretty much a safe bet.


body:
The third pin (pin 3) is not a PWM pin, it is the `RESET` pin.

The PWM pins are 6, 8, 9, 12, 13 and 14 (for Arduino Nano).

See [this image][1]:

[![Nano pinout][2]][2]

  [1]: https://goo.gl/images/j5AMdv
  [2]: https://i.stack.imgur.com/8flVu.png "Nano pinout"


message:
Atmega328p low voltage

I am using atmega328p in my PCB prototype, due to some reason I can use only 4 volt for power supply.
My question is that
"How to run atmega328P through 4 voltage"

body: Shouldn't be a problem. The minimal voltage required to run at 16MHz is 3.8 Volt. No extra steps required.


body: Having only a 4V power supply, you can insert a boost converter to step up the voltage to 5V and then supply it to VCC of atmega328p


message:
8 bits 62.5kHz PWM signal

// TIMER/COUNTER 0
    // PIN 6(OC0A) = NON-INVERTED [_BV(COM0A1)]
    // PIN 5(OC0B) = INVERTED     [_BV(COM0B1) | _BV(COM0B0)]
    // PWM MODE    = FAST PWM     [_BV(WGM01) | _BV(WGM00)]
    // PRESCALER   = 1            [_BV(CS00)]
    TCCR0A = _BV(COM0A1) | _BV(COM0B1) | _BV(COM0B0) | _BV(WGM01) | _BV(WGM00);
    TCCR0B = _BV(CS00);

    // TIMER/COUNTER 1
    // PIN 9(OC1A)  = ?????
    // PIN 10(OC1B) = ?????
    // PWM MODE     = FAST PWM 8BIT[_BV(WGM12) | _BV(WGM10)]
    // PRESCALER    = 1            [_BV(CS10)]
    TCCR1A = ????? | _BV(WGM10);
    TCCR1B = _BV(WGM12) | _BV(CS10);

    // TIMER/COUNTER 2
    // PIN 11(OC2A) = NON-INVERTED [_BV(COM2A1)]
    // PIN 3(OC2B)  = NON-INVERTED [_BV(COM2B1)]
    // PWM MODE     = FAST PWM     [_BV(WGM21) | _BV(WGM20)]
    // PRESCALER    = 1            [_BV(CS20)]
    TCCR2A = _BV(COM2A1) | _BV(COM2B1) | _BV(WGM21) | _BV(WGM20);
    TCCR2B = _BV(CS20);

Hi. My intention of writing the codes is to clarify my doubts regarding arduino timer.

First of all, I intend to have 6 consistent PWM outputs which is **8 bits** and **runs at 62.5kHz**. The confusion here is FAST PWM and PHASE CORRECT PWM. TIMER 1 and 2 is usually presented as PHASE CORRECT PWM. So does changing the PWM mode of TIMER 1 and 2 to FAST PWM enables the PWM to reach a frequency of 62.5kHz (prescaler set as 1)? Is the code that I have written correct? Do take note of the inverted and non-inverted pin mode.

Secondly, as seen from my code above, Timer/Counter 1 is not properly written (?????). I wish to control pin 9 and 10 so that it can invert or non-invert individually.
Timer 0 and 2 allows me to set the pins individually (inverted and non-inverted). However from the atmega328p datasheet, Timer 1 control register is  weird. How can I **set the register** so that I can do what I want to do which is to **control the pins individually**?
[![Timer0,1,2 Control Register A comparison][1]][1]

I truly apologize for any confusion caused by my sentence structure. I am aware I have a poor way of organizing and presenting my idea. And lastly, thank you for taking your time reading these doubt of mine.

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

body:
As mentioned in my comment, it seems latest ATmega328P datasheet from Microchip have lost some information. I use the datasheet from 2014 and it is complete:

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

Regarding PWM frequency of Timer1 and Timer2, as you spotted yourself, those timers support Phase Correct PWM **in addition to** Fast PWM.

To reach a 62.5KHz PWM frequency, you have to apply the formulas available in the datahseet.

For Fast PWM
------------

[![enter image description here][2]][2]

i.e. with 16MHz MCU frequency and prescaler set to 1:

> fPWM = 16000000/(1 . (1 + 255)) = 62.5 KHz

which is what you want.

For Phase Correct PWM
---------------------

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

i.e. with 16MHz MCU frequency and prescaler set to 1:

> fPWM = 16000000/(2 . 1 . 255) = 31.4 KHz

which is the maximum PWM frequency you can get here.

Conclusion
----------

To get 62.5KHz PWM frequency with Timer 1 and Timer2, you shall absolutely use FastPWM, not Phase Correct PWM.

For Timer 1, that means setting `WGM12` and `WGM10` to `1`.

For Timer2, that means setting `WGM21` and `WGM20` to `1`.

Hence your code snippet is correct towards what yu want to achieve.

  [1]: https://i.stack.imgur.com/9xoJF.png
  [2]: https://i.stack.imgur.com/gupkE.png
  [3]: https://i.stack.imgur.com/3rJxX.png


body:
for an arduino, 16Mhz / 62.5Khz = 256 -> prescaler = 1 and single sloped pwm, with its top at 255.

the number of timer modes meeting those conditions are limited.

if you move outside of arduino, a lot more of choices.


message:
Loop inside switch statement

I am using voice command to start/stop display of LDR readings over Arduino. The module I am using is voice module V3. I have downloaded some of its examples. First we need to train the module with specific commands. I have trained it as "on" and "off". Hence I could turn on and off the led using voice command .
code:

    #include <SoftwareSerial.h>
    #include "VoiceRecognitionV3.h"

    /**
      Connection
      Arduino    VoiceRecognitionModule
       2   ------->     TX
       3   ------->     RX
    */
    VR myVR(2,3);    // 2:RX 3:TX, you can choose your favourite pins.

    uint8_t records[7]; // save record
    uint8_t buf[64];
    int led = 13;

    #define onRecord    (0)
    #define offRecord   (1)

    /**
      @brief   Print signature, if the character is invisible,
               print hexible value instead.
      @param   buf     --> command length
               len     --> number of parameters
    */
    void printSignature(uint8_t *buf, int len) {
      int i;
      for(i=0; i<len; i++) {
        if(buf[i]>0x19 && buf[i]<0x7F){
          Serial.write(buf[i]);
        } else {
          Serial.print("[");
          Serial.print(buf[i], HEX);
          Serial.print("]");
        }
      }
    }

    /**
      @brief   Print signature, if the character is invisible,
               print hexible value instead.
      @param   buf  -->  VR module return value when voice is recognized.
                 buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
                 buf[1]  -->  number of record which is recognized.
                 buf[2]  -->  Recognizer index(position) value of the recognized record.
                 buf[3]  -->  Signature length
                 buf[4]~buf[n] --> Signature
    */
    void printVR(uint8_t *buf) {
      Serial.println("VR Index\tGroup\tRecordNum\tSignature");
      Serial.print(buf[2], DEC);
      Serial.print("\t\t");
      if(buf[0] == 0xFF) {
        Serial.print("NONE");
      } else if(buf[0]&0x80) {
        Serial.print("UG ");
        Serial.print(buf[0]&(~0x80), DEC);
      } else {
        Serial.print("SG ");
        Serial.print(buf[0], DEC);
      }
      Serial.print("\t");
      Serial.print(buf[1], DEC);
      Serial.print("\t\t");
      if(buf[3]>0){
        printSignature(buf+4, buf[3]);
      } else {
        Serial.print("NONE");
      }
      Serial.println("\r\n");
    }

    void setup() {
      /** initialize */
      myVR.begin(9600);
      Serial.begin(115200);
      Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");
      pinMode(led, OUTPUT);
      if(myVR.clear() == 0) {
        Serial.println("Recognizer cleared.");
      } else {
        Serial.println("Not find VoiceRecognitionModule.");
        Serial.println("Please check connection and restart Arduino.");
        while(1);
      }
      if(myVR.load((uint8_t)onRecord) >= 0){
        Serial.println("onRecord loaded");
      }
      if(myVR.load((uint8_t)offRecord) >= 0){
        Serial.println("offRecord loaded");
      }
    }

    void loop() {
      int ret;
      ret = myVR.recognize(buf, 50);
      if(ret>0) {
        switch(buf[1]) {
          case onRecord:
            /** turn on LED */
            digitalWrite(led, HIGH);
            break;
          case offRecord:
            /** turn off LED*/
            digitalWrite(led, LOW);
            break;
          default:
            Serial.println("Record function undefined");
            break;
        }
        /** voice recognized */
        printVR(buf);
      }
    }

The code is running fine. Now to start/stop display on OLED I have included all the necessary OLEd libraries and all and changed the above code only in the switch case as:

    void loop() {
      int ret;
      ret = myVR.recognize(buf, 50);
      if(ret>0) {
        switch(buf[1]) {
          case OnRecord:
            display.clearDisplay();
            sensorValue = analogRead(sensorPin);
            display.setCursor(30,0);
            display.setTextSize(1);
            display.print("LDR Reading:");
            display.setCursor(30,10);
            display.setTextSize(2);
            display.print(sensorValue);
            delay(500);
            break;
          case OffRecord:
            display.clearDisplay();
            break;
          default:
            Serial.println("Record function undefined");
            break;
        }
        display.display();
        printVR(buf);
      }
    }

Here when I say "on" the OLEd is starting on my voice command. But it remains frozen in the first reading. When I say "off" it turns of the display(as required). The process runs in loop.

I just want to keep on displaying LDR values by running all the statements in "case Onrecord" until case "offrecord" is encountered. Any idea how to do this?

The entire code for the voice controlled LDR readings on OLED is:

    #include <SoftwareSerial.h>
    #include "VoiceRecognitionV3.h"
    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    int sensorPin = A0; // select the input pin for ldr
    int sensorValue = 0;

    #define OLED_RESET 4
    Adafruit_SSD1306 display(OLED_RESET);

     char inChar;
     String string;
    /**
      Connection
      Arduino    VoiceRecognitionModule
       2   ------->     TX
       3   ------->     RX
    */
    VR myVR(2,3);    // 2:RX 3:TX, you can choose your favourite pins.
    uint8_t records[7]; // save record
    uint8_t buf[64];

    #define OnRecord    (0)
    #define OffRecord   (1)

    /**
      @brief   Print signature, if the character is invisible,
               print hexable value instead.
      @param   buf     --> command length
               len     --> number of parameters
    */
    void printSignature(uint8_t *buf, int len) {
      int i;
      for(i=0; i<len; i++) {
        if(buf[i]>0x19 && buf[i]<0x7F) {
          Serial.write(buf[i]);
        } else {
          Serial.print("[");
          Serial.print(buf[i], HEX);
          Serial.print("]");
        }
      }
    }

    /**
      @brief   Print signature, if the character is invisible,
               print hexible value instead.
      @param   buf  -->  VR module return value when voice is recognized.
                 buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
                 buf[1]  -->  number of record which is recognized.
                 buf[2]  -->  Recognizer index(position) value of the recognized record.
                 buf[3]  -->  Signature length
                 buf[4]~buf[n] --> Signature
    */
    void printVR(uint8_t *buf) {
      Serial.println("VR Index\tGroup\tRecordNum\tSignature");
      Serial.print(buf[2], DEC);
      Serial.print("\t\t");
      if(buf[0] == 0xFF) {
        Serial.print("NONE");
      } else if(buf[0]&0x80) {
        Serial.print("UG ");
        Serial.print(buf[0]&(~0x80), DEC);
      } else {
        Serial.print("SG ");
        Serial.print(buf[0], DEC);
      }
      Serial.print("\t");

      Serial.print(buf[1], DEC);
      Serial.print("\t\t");
      if(buf[3]>0) {
        printSignature(buf+4, buf[3]);
      }
      else{
        Serial.print("NONE");
      }
      Serial.println("\r\n");
    }

    void setup() {
      /** initialize */
      myVR.begin(9600);
      pinMode(13, OUTPUT);
      // initialize with the I2C addr 0x3C / mit I2C-Adresse 0x3c initialisieren
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
      display.display();
      display.clearDisplay();
      display.setTextColor(INVERSE);
      Serial.begin(115200);
      Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");
      pinMode(sensorPin, INPUT);
      if(myVR.clear() == 0) {
        Serial.println("Recognizer cleared.");
      } else {
        Serial.println("Not find VoiceRecognitionModule.");
        Serial.println("Please check connection and restart Arduino.");
        while(1);
      }
      if(myVR.load((uint8_t)OnRecord) >= 0) {
        Serial.println("startRecord loaded");
      }
      if(myVR.load((uint8_t)OffRecord) >= 0) {
        Serial.println("endRecord loaded");
      }
    }

    void loop() {
      int ret;
      ret = myVR.recognize(buf, 50);
      if(ret>0) {
        switch(buf[1]) {
          case OnRecord:
            display.clearDisplay();
            sensorValue = analogRead(sensorPin);
            display.setCursor(30,0);
            display.setTextSize(1);
            display.print("LDR Reading:");
            display.setCursor(30,10);
            display.setTextSize(2);
            display.print(sensorValue);
            delay(500);
            break;
          case OffRecord:
            display.clearDisplay();
            break;
          default:
            Serial.println("Record function undefined");
            break;
        }
        display.display();
        printVR(buf);
      }
    }

I am able to control the display of LDR readings on OLED using pushbutton. Initially it will be in "off" mode. Once I push the button it starts displaying LDr values in the interval of 500 milli seconds. Once I press the button again, It will clear the display.This will run in a loop.

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>
    int sensorPin = A0; // select the input pin for ldr
    int sensorValue = 0;
    bool toggle = false;
    int buttonpin;

    #define OLED_RESET 4 // not used / nicht genutzt bei diesem Display
    Adafruit_SSD1306 display(OLED_RESET);

     char inChar;
     String string;

    void setup()   {

      pinMode(13, OUTPUT);

      buttonpin = 2;
      pinMode(buttonpin, INPUT_PULLUP);
      // initialize with the I2C addr 0x3C / mit I2C-Adresse 0x3c initialisieren
      display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

      Serial.begin(9600);
      display.display();
      delay(2000);
      display.clearDisplay();

      display.setTextColor(INVERSE);
    }

    void loop()
    {
         if (digitalRead(buttonpin) == HIGH)
         {
          toggle = !toggle;
          while(digitalRead(buttonpin) == HIGH);
         }
          switch( toggle )
             {

              case 1:
               display.clearDisplay();
                sensorValue = analogRead(sensorPin);
                Serial.println(sensorValue);
                display.setCursor(30,0);
                display.setTextSize(1);
                display.print("LDR Reading:");
                display.setCursor(30,10);
                display.setTextSize(2);
                display.print(sensorValue);
                delay(500);

                break;

               case 0:
                display.clearDisplay();

                break;
               }
           display.display();

     }

If you could suggest how I should merge my previous code and the above code so that I could control the display using voice commands, It'll be great!!.

Thanks in advance!

body:
To keep reading and reporting a sensor within `loop()` after each `On` command, until an `Off` command occurs, add a flag variable – eg, `tellSensor` – to control that reading and reporting.  Declare the variable outside `loop()`, or declare it static within `loop()`, and initialize it false.

In the code for `case OnRecord:`, initialize the display (eg, clear display and print the `LDR Reading:` heading) and set  `tellSensor` true.

In the code for `case OffRecord:`, clear the display and set  `tellSensor` false.

After the end of the `if(ret>0) { ... }` if statement, say something like

    if (tellSensor) {
       display.setCursor(30,10);
       display.setTextSize(2);
       display.print(sensorValue);
       delay(500);
    }


body:
> But it remains frozen in the first reading.

because in the next run of loop(), the "ret = myVR.recognize(buf, 50);" returns a value of 0 -> no voice command is recognized.

the way to do it is to have a state machine like this:

      ret = myVR.recognize(buf, 50);  //read the voice command
      switch(buf[1]) {
          case OnRecord:
            if (vr_state == OffRecord) vr_state = OnRecord; //from previous off to on now
            break;
          case OffRecord:
            vr_state = OffRecord; //now to be off
            break;
          default:
            break; //do nothing -> keep status quo
      }
      //process vr_state
      switch (vr_state) ...

basically, there is potentially information even if no voice command is received (aka. previously OnRecord and now silence). your code's reaction to "ret" is dependent on its value now and its value previously.


message:
radio.write () always returns 0

I'm trying to send a char [] through an NRF2401 but the radio.write () method always return 0. Check that msg contains the message read from str.

    #define TAM 50

    RF24 radio(9,10);

    const uint64_t pipe = 0xE8E8F0F0E1AA;

    char  msg[TAM];

    void setup() {

      Serial.begin(9600);

      radio.begin();

      radio.openWritingPipe(pipe);
    }

    void loop() {
        if(Serial.available() > 0){
          String str = Serial.readString();
          str.toCharArray(msg,TAM);
          if(!radio.write(msg, TAM)){
            Serial.println("Message not send");
          }
          else
            Serial.println(msg);
        }
    }

What am I doing wrong?

**Edit1:**
What I have noticed, is that the first time I was allowed to send it but the others no longer.

**Edit2:**
Remove the keyboard input by a char [] and sent it to without problems. Why can this be? Anything else happen when I make a keyboard entry?

body:
I hope you resolved your issue by now, but I had the same problem with an Arduino UNO/nRF24l01+ combination and this question was one of the search results.

In my case, the write() call returned false, but the receiver received the message.

As soon as I added one of the ubiquitous [Adapter Boards][1] into the mix the write() call started returning true.

My uneducated guess is that the sending and then the switch from transmit to receive and then waiting to receive the ACK used a bit too much power or something like that.

In any case, even though [everyone recommends adding a capacitor][2] and I had the adapter boards on hand, I had thought to tough it out without one and see how far I could get.

I kicked myself for the wasted time, but I learned a lot in the process and I'm having a lot of fun with the transceiver boards now. I'm glad that I didn't just shrug and say "well the message got through so who cares?"

  [1]: https://www.google.com.au/search?q=nrf24l01+ adapter board
  [2]: https://arduinoinfo.mywikis.net/wiki/Nrf24L01-2.4GHz-HowTo


message:
Determining state of charge using current sensor (ACS758) with arduino uno

I am working on a university project and I am struggling with estimating the state of charge of our batteries, by using coulomb counting.

Background: We are supposed to build a power supply for a mostly constant load of 100 W (can go up to 140 W) which will be placed outdoors for two years. The plan is to have a small wind turbine plus some solar PV connected to a large battery assembly. The system has to run close to 24/7 with limited downtime.

I have bought some ACS758 50A bidirectional current sensors as well as an Arduino UNO. I am extremely new to Arduino and I would really appreciate some help with the coding. The plan is to have the arduino do the sampling of current and integration, which is then translated to SOC as a percentage and sent to a Raspberry Pi which will send email alerts if the SOC is below a certain level.

I have been looking at sample code describing how to extract the raw data from the ACS sensor: https://www.dfrobot.com/wiki/index.php/50A_Current_Sensor(SKU:SEN0098) as well as sample code that performs integration (https://arduino.stackexchange.com/questions/9436/integrating-an-analog-signal-using-arduino-uno-smd), which is what I would use for coulomb counting.

What I need is most likely a combination between the two, however I do not even know where to start from.

Thanks in advance!

body:
Instead of using a separated component for each thing you can use a proper solution that is itself already a combination of both: the **DS2438's integrated current accumulator**. This [link][1] explain it pretty well, also here is a [library][3] to use it with arduino. They are pretty cheap (a few dollars) and will perform very well!

Although, in your place I would consider choosing a different approach. I don't know which kind of battery (Li-ion, LiPo, Lead-acid..) you are using, but in many cases if you monitor the battery voltage, you can have enough information about the battery state. I can't ask you in comment yet beause I'm new here and don't have enough reputation, but if you can describe better the kind of battery you are using and what you intend to monitor which your circuit, I can edit this post to offer you a better solution.

  [1]: https://www.maximintegrated.com/en/products/power/battery-management/DS2438.html
  [2]: https://datasheets.maximintegrated.com/en/ds/DS2438.pdf
  [3]: https://github.com/jbechter/arduino-onewire-DS2438


message:
What are the causes of Arduino lockup?

We know watchdog timer if enabled RESETs when Arduino is locked up somewhere inside the code. As the title suggests has anyone experienced this unless they put deliberately a while(1) loop inside the code? Of course, buffer overflow or memory related issues are excluded.

I mean is it worth in Arduino to use watchdog and RESET rather than to fix the code to not get locked up. Are there still some behavior which are not predictable here?

body:
Most Arduino projects involve sensing the physical world or controlling the physical world (hopefully with some feed back).  When sensing the physical world, it is best to add extra code to protect the project from locking up.  And then, even more code concerned with what to do when the unlikely happens.  Unfortunately, many projects leave out this extra code.  Reasons vary:

 - The project is a prototype and the effort is thought necessary.
 - There is no time in the schedule to create this "extra code".
 - The unexpected event is thought to be an impossible situation.
 - There is no room left to add code that is not expected to run.

As an example:

A bicycle is outfitted with an Arduio base digital speedometer.  Speed is calculated based on the period of a wheel mounted magnet passing a frame mounted Hall Effect switch.  It works as long as the bicycle is moving at a reasonable speed.  However, the program does not take into account what happens if the bicycle is not moving.  If the magnet does not pass the Hall Effect switch.  The program's period counter continues to count up.  Eventually the watch dog timer reset the program.  Over and over again.

Approaches to avoid lockup or to avoid using the watch dog timer:

 1. Place all "non-blocking" polling in an infinite loop which also check the elapsed time.  Consider the amount of time allowed to make a successful reading.  If that time expires consider a good course for the program to follow.  For instance a warning to the user or a default value when the measured value is unavailable.
 2. Use interrupts.  That is, use the above method, but relay on external signal changes to generate interrupts to set values and / or flags.  This is a good (however more complex) alternative if the external signal occurs too fast for "non-blocking" polling.


message:
i am unable to make a correct program using the pushbutton to toggle LED on/off?

I want to toggle the the LED on on my first complete click(i.e. pushing and even releasing the pushbutton) and i want to make my LED off at my second click.

This is the program :-

    int led = 13;
    int buttonpin = 8;
    boolean lastbuttonstate = LOW;
    boolean ledon = LOW;

    void setup ()
    {
      digitalWrite(buttonpin,HIGH);
      pinMode(buttonpin,INPUT);
      pinMode(led,OUTPUT);
    }

    void loop ()
    {
      if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon = !digitalRead(buttonpin))
      {
        digitalWrite(led,HIGH);
      }
      else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =!digitalRead(buttonpin))
      {
        digitalWrite(led,HIGH);
      }
       if( digitalRead(buttonpin) == HIGH && lastbuttonstate == LOW && ledon =digitalRead(buttonpin))
      {
        digitalWrite(led,LOW);
      }
      else if (digitalRead(buttonpin) == LOW && lastbuttonstate == HIGH && ledon =digitalRead(buttonpin))
      {
        digitalWrite(led,LOW);
      }
    }

I have connected all the connections on my breadboard according to schematic but there is something wrong in the program itself.

body:
This appears to be the classic "how to debounce a mechanical button" problem.

You can either [denounce a button using external hardware][1].  Or you can [denounce a button using software][2].

***Using Hardware:***

Normally a Set Reset or SR Latch is used to debounce mechanical buttons.  It is common to use a single poll double throw (break before make) type switch to accomplish this.

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

***Using Software:***

When solving this in software, one needs to create a state machine with 4 states.  Two of which are the normally expected ON and OFF state.  The other two are the state where we are not sure if the button is pressed or not. As the button is in motion or is "bouncing".  These 2 extra states have a time component much longer then the expected time it takes the switch to stop "bouncing".  But much shorter then to be noticeable to the operator of the button.

For a really good explanation of using state machines for debouncing switches specifically for an Arduino refer to the "denounce a button using software" link at the top of this answer.

  [1]: http://www.ganssle.com/debouncing-pt2.htm
  [2]: https://www.arduino.cc/en/tutorial/debounce
  [3]: https://i.stack.imgur.com/eKhdl.jpg


body:
I would use a different approach

    int led = 13;
    int buttonpin = 8;
    boolean waspressed = false;

    void setup (){
        pinMode(buttonpin,INPUT);
        pinMode(led,OUTPUT);
        digitalWrite(led,LOW);
    }

    void loop(){
        if(digitalRead(buttonpin) == HIGH){
            waspressed = true;
        }else{
            if(waspressed == true){
                digitalWrite(led, !digitalRead(led));
                waspressed = false;
            }
        }
    }

We can understand it better if we just take a step by step view. When the controller is started, it first executes the setup(), setting the led pin as output, buttonpin as input and setting the led pin value to low. The led pin is set to LOW because it needs to have an initial value once it is an output. The initial value can also be HIGH without changing the behavior of the circuit. Always remember to set an initial value to all your output pins. This prevent them to float, which may lead no unpredictable results.

The loop() can be a little more tricky.

**State 1 - button not pressed**

The first interaction tries the value of buttonpin:`if(digitalRead(buttonpin) == HIGH)`. Once the button is not pressed (buttonpin is LOW), the interpreter moves to the `else` element. At this element, there is another conditional - i.e, another `if`. This conditional looks for the value of `waspressed`. This is false, as set at the begging of the code. Because of this, the information inside the conditional is not executed and the loop() is executed over and over with no change until the button is pressed.

**Stage 2 - button is pressed**

When the button is pressed, the next iteraction of loop() will catch this action when trying the first conditional `if(digitalRead(buttonpin) == HIGH)`. Once buttonpin is high if the button is pressed, `waspressed` will be set to true. This will repeat as long as the button remain pressed.

**Stage 3 - button is released**

After being released, the first conditional will read buttonpin as LOW, and the interpretor will move the the `else` element. At that element, it will try the second conditional `if(waspressed == true)`. Until now, there is no difference from what was executed at the first stage, however this time, `waspressed` is true because it was set true when the button was pressed. This leads the interpreter inside the conditional and execute the lines

    digitalWrite(led, !digitalRead(led));
    waspressed = false;

The first one set the led pin to the opposite value it has. I.e, if the led pin is HIGH, it becames LOW, if it is LOW, it becames HIGH. This happens because `!digitalRead(led)` outputs the complement of the value of `digitalRead(led)` - without the !.

The second one set waspressed to false again. With this, the next iteration will be back to stage one and wait for another press on the button.


message:
Saving sensor logs of unknown length

I have a sensor giving me values (ints) which I want to keep, and send to a computer via the WiFi shield when requested via HTTP. I have the HTTP thing working, however, I do not know how to have a String or whatever able to store what is basically an array of ints, when I do not know any maximum size.

I have read that using Strings on Arduino is not recommended because how RAM works and such things, so I translated all my String uses to C-style arrays (as it was recommended), this solved my memory issues, however, C-style strings are not resizable.

While browsing the forums, I found that for similar problems the recommended way of handling things would be to create an array of max size instead of dynamically growing the array, but I do not know the maximum size in this case.

Here are the requirements

 - A way of storing each values (in order) so they can be sent later after an HTTP request (but they can get requested multiple times so I can't delete them then),
 - Whatever storage way is fine by me (Strings, arrays of ints, ...), as long as it works.
 - A request to the data should take ~100ms (I don't think this will cause issues, but I'll mention it just in case).

I thought about printing the values to the SD card, since there I have far enough memory, but for some reason I can't get the WiFi and the SD card to work together (as soon as I init the SD library, the WiFi library doesn't work anymore - I asked an other question about this [here][1]).

PS.
I'm quite new to C++ and Arduino, but I'm not too bad at Java.

What would be the best (or at least a working one) way of achieving this ?

  [1]: https://arduino.stackexchange.com/questions/37200/conflict-between-sd-card-and-wifi-shield "here"

body:
This is basically two questions: how to get your SD card and WiFi working at the same time (in which case memory limitations are not an issue), and how to deal with the memory limitations if you choose in-memory storage of your data. I'll address the second one here; you should split out the WiFi/SD conflict into a separate question where you detail the exact hardware you're using and how it's connected.

You've got only 2 KB of RAM in an Uno and similar models, so you will have to discard data at some point, whether or not it was successfully sent in a reply to a web request. The key here is to use a fairly compact method of storing the data and to have an easy way to get rid of old values to free up space for new values.

One common way to deal with this is to use a ring buffer. This is a fixed size storage array with a pointer or index, which I'll call _head_, indicating the next storage location to use. You start with _head = 0_ (the beginning of the buffer) and every time you receive a new value you store it at _head_ and then increment _head_ by one. You also need to compare _head_ to the end of the buffer and, when it would pass the end, reset it back to the beginning of the buffer. After the first pass through the buffer, storing at _head_ will overwrite the oldest value previously stored.

Going back through the buffer to read out the old values is easy: you just start by reading the value at _head - 1_ (or the end of the buffer if _head_ is 0) and work downwards, wrapping around when you hit 0, and stopping when you reach _head_.

You can handle the initial states where the buffer hasn't been filled yet in two ways: just fill the buffer with a value such as 0 that you don't mind returning as a "nothing stored here" value, or just set a flag at the start to say that the buffer hasn't been filled yet and you should stop at 0 when reading it out; this flag would be cleared the first time that _head_ reaches the end of the buffer and wraps around.

Since you're getting data that are ints, storing them as (larger) strings would be silly; just create an array of ints of the smallest type that can store all possible values of your sensor, e.g., `uint16_t` if you're getting unsigned 16-bit values. With some experimentation and checking, you should be able to figure out how large a buffer you can use based on how much storage you have free after the RAM for other parts of the program has been allocated. I'd imagine that if you're careful and you're making sure you [store strings in program memory](https://www.arduino.cc/en/Reference/PROGMEM) you could make room for a buffer that would hold a couple of hundred entries.

Since this seems to be a student assignment, I won't provide sample code here; writing your ring buffer code will prove an excellent exercise in the details of programming.


body:
> What would be the best (or at least a working one) way of achieving this ?

none. Because the upper end of your possibilities (ie. infinite amount of data) is way beyond anything a computer can possibly handle now and into the distant future.

So unless you have some reasonable upper bound for the data in question, there isn't a whole lot you can do to satisfy your application.


message:
ESP-32 with tft display

I recently got a Adafruit TFT screen and an ESP-32 development kit. I was trying to interface these two the pin connections I used areas follows:

    TFT   |   ESP-32
    ------+----------
    3V3   |   Vcc
    Gnd   |   Gnd
    MOSI  |   GPIO19
    SCK   |   GPIO18
    CS    |   GPIO5
    D/C   |   GPIO16
    RST   |   GPIO 17

I used this library: https://github.com/MartyMacGyver/ESP32_Adafruit_ILI9341

The SPI library used was the one that comes while installing Arduino support for ESP-32.

The code compiles and uploads without any error/ warning but the TFT screen does not show any response (except powering up).

This is the code I used for testing:

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

    //#include <Adafruit_ST7735.h>

    #include<Adafruit_ILI9341.h>
    #include <Adafruit_GFX.h>
    #include "SPI.h"

    #define TFT_CS     5
    #define TFT_RST    17
    #define TFT_DC     16

    // Use hardware SPI (on Uno, #13, #12, #11) and the above for CS/DC
    //Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);
    // If using the breakout, change pins as desired
    Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

    void setup() {
        // put your setup code here, to run once:
        Serial.begin(115200);
        Serial.println("In the setup.");
        //tft.initR(INITR_BLACKTAB);
        unsigned long t=micros();
        tft.fillScreen(ILI9341_RED);
        Serial.println(micros()-t);
    }

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

    }

The code compiles and uploads without any error/warning but the TFT screen does not show any response (except powering up).

NOTE: The library works fine with Arduino Mega and TFT display.

body:
Ok, sorry for the delay, I had my exams. But I have finally solved the issue.
There were several issues:

1. MOSI should be connected to pin 23 not 19.
2. `tft.begin()` function should be in the setup to initialize the TFT. (for ILI9341)
3. The SPI library used should be the one that comes with ESP-32 support. The general SPI library for Arduino does not work with ESP-32.

Note: the ST7735 library currently does not work with ESP-32. It can be made to work by adding the following definitions given bellow to the Adafruit_ST7735.h header file.

        #elif defined(ESP32)
        volatile uint32_t *dataport, *clkport, *csport, *rsport;
        uint32_t  _cs, _rs, _rst, _sid, _sclk,
        datapinmask, clkpinmask, cspinmask, rspinmask,
        colstart, rowstart;

(add this just after the ESP8266 definitions).


message:
Do motors need to have capacitor even if being used with motor shield

I'm using a 12V DC geared motor with an Adafruit motor shield which is connected to Arduino.

So, I want to know inspite of using the motor shield, do I need to add capacitors to the motor?

body:
If the motors have a lot of "brush noise" you need to add capacitors to the motor. It is written in the [FAQ](https://learn.adafruit.com/adafruit-motor-shield/faq#faq-21).

The noise must be suppressed at the source or the motor leads will act like antennae and broadcast it to the rest of the system [link](https://learn.adafruit.com/adafruit-motor-shield/faq#faq-24).


message:
ESP8266 + Slack (ssl->need_bytes=16432 > 6859)

I'm trying to connect an [Adafruit Huzzah ESP8266][1] with [Slack][2].

I'm facing an issue with the connection I'd like some help or tips on.  I'm able to get a connection *sometimes*, but sometimes during the initial step where I'm making the first connection, I get errors and it completely fails, repeating the connect/disconnect over and over again.

The error I get is usually this:

    ssl->need_bytes=16432 > 6859

#My Troubleshooting So Far

As per this github issue:
https://github.com/esp8266/Arduino/issues/1375

My understanding is that the error is caused by Slack's SSL certificate being too large.  This makes sense, but sometimes my code (see below) actually works which is why I'm confused.

When it *does work*, it usually fails a couple times at first, before maintaining a consistent ping with Slack.  At that point, it works as expected, and I can send commands from Slack to the board without fail.

[![Slack command to ESP8266][3]][3]

Does anyone have an idea why this sometimes works, and sometimes doesn't?

I'm assuming it has something to do with the SSL certificate size being too large, but if that was the case why wouldn't it fail each time, but work sometimes?

Any help is greatly appreciated.

---
#Errors in Serial Monitor

Here's what I see in the Serial Monitor log:

    ⸮scandone
    f r0, scandone
    f r0, scandone
    state: 0 -> 2 (b0)
    state: 2 -> 3 (0)
    state: 3 -> 5 (10)
    add 0
    aid 7
    cnt

    connected with 2WIRE952, channel 3
    dhcp client start...
    ip:192.168.1.73,mask:255.255.255.0,gw:192.168.1.254

    Waiting for time sync
    please start sntp first !
    .please start sntp first !
    .Sun Apr 16 06:57:35 2017

    Time is synced
    ssl->need_bytes=16432 > 6859
    WebSocket Host=mpmulti-4pcb.slack-msgs.com Path=/websocket/Z5ZDermv9h2Q7HL88ukG5ddIvY--zrBAVCN4423KOy5t_6wN3AW859grAYCYr6L-0l0leeXA3AhlO1VmIxcCopS1pJ-IkrVOdmel50tgcA7hBJwEIkpI-biYnraTFc88K4F6wqL3TE_gi1jU0SJHhR6_aD5435yE8FRALEflTkY=
    [WebSocket] Connected to: /websocket/Z5ZDermv9h2Q7HL88ukG5ddIvY--zrBAVCN4423KOy5t_6wN3AW859grAYCYr6L-0l0leeXA3AhlO1VmIxcCopS1pJ-IkrVOdmel50tgcA7hBJwEIkpI-biYnraTFc88K4F6wqL3TE_gi1jU0SJHhR6_aD5435yE8FRALEflTkY=
    [WebSocket] Disconnected :-(
    ssl->need_bytes=16432 > 6859
    WebSocket Host=mpmulti-eavp.slack-msgs.com Path=/websocket/HjuUTJUL4ghmBCthwdFxOYNWD0wGjWbCgQZwnum546F5Nj8rrJ7LJgeyVOLqSv9sBHtkZBrCBLyxdM2oMB85-GXGwtIgg9anVYFL66vMB8yEN9Xout7OMmqlEewZsL7n2vqJyvx_qAnQ9M8UwOnZwETkNYJ51XrUvR6EjIAvAQE=
    [WebSocket] Connected to: /websocket/HjuUTJUL4ghmBCthwdFxOYNWD0wGjWbCgQZwnum546F5Nj8rrJ7LJgeyVOLqSv9sBHtkZBrCBLyxdM2oMB85-GXGwtIgg9anVYFL66vMB8yEN9Xout7OMmqlEewZsL7n2vqJyvx_qAnQ9M8UwOnZwETkNYJ51XrUvR6EjIAvAQE=
    [WebSocket] Disconnected :-(
    ssl->need_bytes=8496 > 6859

#My Sketch Code
The Sketch file I'm compiling using the Arduino IDE.
**Note:** be sure to update Wifi + Slack Bot Token if testing  8-)
<!-- language-all: lang-cpp -->

    #include <Arduino.h>

    #include <ESP8266WiFi.h>
    #include <time.h>
    #include <ESP8266WiFiMulti.h>
    #include <ESP8266HTTPClient.h>

    #include <WebSocketsClient.h>
    #include <ArduinoJson.h>

    #define SLACK_SSL_FINGERPRINT "AC 95 5A 58 B8 4E 0B CD B3 97 D2 88 68 F5 CA C1 0A 81 E3 6E" // If Slack changes their SSL fingerprint, you would need to update this

    #define WIFI_SSID       ""
    #define WIFI_PASSWORD   ""

    String SLACK_BOT_TOKEN = ""; // Get token by creating new bot integration at https://my.slack.com/services/new/bot

    #define WORD_SEPERATORS "., \"'()[]<>;:-+&?!\n\t"

    ESP8266WiFiMulti WiFiMulti;
    WebSocketsClient webSocket;

    long nextCmdId = 1;
    bool connected = false;

    //Timezone Settings
    const int timezone = 9;
    const int dst = 0; //daylight savings

    /**
      Sends a ping message to Slack. Call this function immediately after establishing
      the WebSocket connection, and then every 5 seconds to keep the connection alive.
    */
    void sendPing() {
      DynamicJsonBuffer jsonBuffer;
      JsonObject& root = jsonBuffer.createObject();
      root["type"] = "ping";
      root["id"] = nextCmdId++;
      String json;
      root.printTo(json);
      webSocket.sendTXT(json);
    }

    /**
      Looks for color names in the incoming slack messages and
      animates the ring accordingly. You can include several
      colors in a single message, e.g. `red blue zebra black yellow rainbow`
    */
    void processSlackMessage(char *payload) {
      char *nextWord = NULL;
      bool zebra = false;
      for (nextWord = strtok(payload, WORD_SEPERATORS); nextWord; nextWord = strtok(NULL, WORD_SEPERATORS)) {
        if (strcasecmp(nextWord, "red") == 0) {
          Serial.printf("Yay! Its red.");
        }

      }
    }

    /**
      Called on each web socket event. Handles disconnection, and also
      incoming messages from slack.
    */
    void webSocketEvent(WStype_t type, uint8_t *payload, size_t len) {
      switch (type) {
        case WStype_DISCONNECTED:
          Serial.printf("[WebSocket] Disconnected :-( \n");
          connected = false;
          break;

        case WStype_CONNECTED:
          Serial.printf("[WebSocket] Connected to: %s\n", payload);
          sendPing();
          break;

        case WStype_TEXT:
          Serial.printf("[WebSocket] Message: %s\n", payload);
          processSlackMessage((char*)payload);
          break;
      }
    }

    /**
      Establishes a bot connection to Slack:
      1. Performs a REST call to get the WebSocket URL
      2. Conencts the WebSocket
      Returns true if the connection was established successfully.
    */
    bool connectToSlack() {
      // Step 1: Find WebSocket address via RTM API (https://api.slack.com/methods/rtm.start)
      HTTPClient http;
      http.begin("https://slack.com/api/rtm.start?token=" + SLACK_BOT_TOKEN, SLACK_SSL_FINGERPRINT);
      int httpCode = http.GET();

      if (httpCode != HTTP_CODE_OK) {
        Serial.printf("HTTP GET failed with code %d\n", httpCode);
        return false;
      }

      WiFiClient *client = http.getStreamPtr();
      client->find("wss:\\/\\/");
      String host = client->readStringUntil('\\');
      String path = client->readStringUntil('"');
      path.replace("\\/", "/");

      // Step 2: Open WebSocket connection and register event handler
      Serial.println("WebSocket Host=" + host + " Path=" + path);
      webSocket.beginSSL(host, 443, path, "", "");
      webSocket.onEvent(webSocketEvent);
      return true;
    }

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

      WiFiMulti.addAP(WIFI_SSID, WIFI_PASSWORD);
      while (WiFiMulti.run() != WL_CONNECTED) {
        delay(500);
      }

      //setup network time protocol (ntp)
      configTime(timezone * 3600, dst, "pool.ntp.org", "time.nist.gov"); //configtime is esp8266 function

      Serial.println("\nWaiting for time sync");
      while (!time(nullptr)) {
        Serial.print(".");
        delay(1000);
      }
      Serial.println("Time is synced");

      delay(500);
    }

    unsigned long lastPing = 0;

    /**
      Sends a ping every 5 seconds, and handles reconnections
    */
    void loop() {
      webSocket.loop();

      if (connected) {
        // Send ping every 5 seconds, to keep the connection alive
        if (millis() - lastPing > 5000) {
          sendPing();
          lastPing = millis();
        }
      } else {
        // Try to connect / reconnect to slack
        connected = connectToSlack();
        if (!connected) {
          delay(500);
        }
      }
    }

  [1]: https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout
  [2]: https://slack.com
  [3]: https://i.stack.imgur.com/QyAEo.png

body: replace `rtm.start` with `rtm.connect` as per April 2017 Recent Updates log


message:
Move a servo slowly between 2 positions based on input

I am trying to move model railroad crossing gates from a vertical position to a horizontal position when a train is detected. I have the electronics in for the sensing of train position but want the gates to go down and stay down while the train passed.

To do this, I am looking to be able to use an Arduino to slowly move a servo between two different positions based on a digital input (HIGH or LOW) to one of the digital input pins.

When this digital input goes HIGH, the servo needs to slowly move to the other end of travel and then stop. It must stay there until the digital input goes LOW, at which time it needs to slowly move back to the starting position and again await for a HIGH input.

I cannot figure out how to move the servo slowly to each position and keep it there.

body:
Lacking information about the context of the servo action (ie, what needs to happen at the same time), I'll assume your paradigm uses a `loop()` function that executes fairly rapidly, and from time to time invokes any necessary actions.

Servo angles can be measured in degrees (typically 0 to 180) or microseconds (typically 1000 to 2000, corresponding to 0° to 180°).  The servo library will accept numbers in either range, and act according to which range the numbers are in.  Note that representing servo angles in microseconds instead of degrees gives about 5.55 times better resolution.  The method outlined below doesn't care which you use.

Also assume the two servo angles mentioned in the question are A and B, with the servo at A if the input pin is low for a long time; and that the desired rate of swing is ±U units of angle every S milliseconds.  Let P = current servo position; T = `millis()` value at most recent step, initially 0; and V = previous value of input pin.

In each pass through `loop()`:

• Test the input pin.  If it isn't equal to V, toggle V and take a step.  (See below.).
• If  `millis()`-T > S, take a step.  (See below.)
• Do any other brief per-loop actions

To take a step:
• Add (2*(V>0)-1) * U to P.  The expression (V>0) equals 1 or 0, so (2*(V>0)-1) is 1 if V is true, and -1 if V is false.
• If (V) and P > B, set P = B
• If (!V) and P < A, set P = A
• Servo to position P
• Set T = `millis()`

*Edit:* You should create meaningful variable or constant names to represent the quantities A, B, P, S, T, U, V.  Note that S and T should be declared as constants; and if A, B won't change, make them constants also.  State-maintaining quantities P and T should be declared via file-scope variables or globals (outside `loop()`) or with static allocation (inside `loop()`), so that their values are maintained as `main()` repeatedly calls `loop()`.


message:
Can I compile a sketch for my attiny85 without an arduino board?

I have a lot of Raspberry Pi's laying around, so I want to use those to program my attiny85 chips. The problem is that most of the code examples, libraries, and documentation out there assume you're using Arduino. Can I run Arduino commandline software on my Raspberry Pi, and use that to program the attiny85?

I'm trying to compile an RF24 program for the attiny using avr-g++, but I'm running into too many dependency errors, and I wonder if things will just be easier if I use Arduino software.`

body:
"Arduino" makes a statement on the mcu in use.

Technologically, it's extremely unlikely you could run most sketches on devices with less than 1kB of RAM (largest SRAM in Attiny85 is 512 B; most models are smaller).

So, no. The idea "microcontrollers are by now capable enough to run a C++ subset on them directly" behind arduino simply doesn't seem to apply to the Attiny85.

However, there's the "cuteduino", which actually should work with a small set of basic Arduino libraries. It's based on the Attiny85.

I'd argue that you simply *don't want to* use Arduino on Attinies; these devices are so resource-constrained, that you probably want to keep in control.

Now, the RF24 lib comes with non-arduino attiny85 support, so go for that? http://tmrh20.github.io/RF24/ATTiny.html


body:
Why wouldn't you be able to?

The compiler runs on the computer, not on the Arduino board. You don't need a board to be connected to compile either. If you enable verbose output during compile in the Arduino IDE settings it will tell you where it puts the resulting .hex file, after which you can use `avr-dude` to upload it to the target MCU.

If you want to use Arduino libraries you'll need to use an core for ATTiny devices (e.g. ATTinyCore). But either way you don't need an Arduino board to compile.

---

I'd also echo what @Marcus says, for the small devices you are better off completely ditching the Arduino stuff (it's such badly written, bloated, and inefficient), and simply starting with a nice clean C file.

There is nothing stopping you using the Arduino IDE or the `avr-libc` tools which it uses. If you add your own `main()` function in a C file and don't put anything in the `.ino` file you will be able to compile without any of the bloat.


body:
You can disregard the answers that say you can't compile for the ATtiny85 using the Arduino IDE. I have done so many times, for example my [torch locator](http://www.gammon.com.au/forum/?id=12769) project which uses the ATtiny85 and the Arduino IDE to compile for it.

Here's my "board":

[![Torch locator (1)][1]][1]

View from other side:

[![Torch locator (2)][2]][2]

Code:

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

    // ATtiny85 torch detector
    // Author: Nick Gammon
    // Date: 25 February 2015

    // ATMEL ATTINY 25/45/85 / ARDUINO
    // Pin 1 is /RESET
    //
    //                  +-\/-+
    // Ain0 (D 5) PB5  1|    |8  Vcc
    // Ain3 (D 3) PB3  2|    |7  PB2 (D 2) Ain1
    // Ain2 (D 4) PB4  3|    |6  PB1 (D 1) pwm1
    //            GND  4|    |5  PB0 (D 0) pwm0
    //                  +----+

    /*

      Pin 2 (PB3) <-- LDR (GL5539) --> Pin 7 (PB2) <----> 56 k <----> Gnd

      Pin 5 (PB0) <---- LED ---> 100 R <-----> Gnd

    */

    #include <avr/sleep.h>    // Sleep Modes
    #include <avr/power.h>    // Power management
    #include <avr/wdt.h>      // Watchdog timer

    const byte LED = 0;          // pin 5
    const byte LDR_ENABLE = 3;   // pin 2
    const byte LDR_READ = 1;     // Ain1 (PB2) pin 7
    const int LIGHT_THRESHOLD = 200;  // Flash LED when darker than this

     // when ADC completed, take an interrupt
    EMPTY_INTERRUPT (ADC_vect);

    // Take an ADC reading in sleep mode (ADC)
    float getReading (byte port)
      {
      power_adc_enable() ;
      ADCSRA = bit (ADEN) | bit (ADIF);  // enable ADC, turn off any pending interrupt

      // set a2d prescale factor to 128
      // 8 MHz / 128 = 62.5 KHz, inside the desired 50-200 KHz range.

      ADCSRA |= bit (ADPS0) | bit (ADPS1) | bit (ADPS2);

      if (port >= A0)
        port -= A0;

    #if defined(__AVR_ATtiny85__)
      ADMUX = (port & 0x07);  // AVcc
    #else
      ADMUX = bit (REFS0) | (port & 0x07);  // AVcc
    #endif

      noInterrupts ();
      set_sleep_mode (SLEEP_MODE_ADC);    // sleep during sample
      sleep_enable();

      // start the conversion
      ADCSRA |= bit (ADSC) | bit (ADIE);
      interrupts ();
      sleep_cpu ();
      sleep_disable ();

      // reading should be done, but better make sure
      // maybe the timer interrupt fired

      // ADSC is cleared when the conversion finishes
      while (bit_is_set (ADCSRA, ADSC))
        { }

      byte low  = ADCL;
      byte high = ADCH;

      ADCSRA = 0;  // disable ADC
      power_adc_disable();

      return (high << 8) | low;

      }  // end of getReading

    // watchdog interrupt
    ISR (WDT_vect)
    {
       wdt_disable();  // disable watchdog
    }  // end of WDT_vect

    #if defined(__AVR_ATtiny85__)
      #define watchdogRegister WDTCR
    #else
      #define watchdogRegister WDTCSR
    #endif

    void setup ()
      {
      wdt_reset();
      pinMode (LED, OUTPUT);
      pinMode (LDR_ENABLE, OUTPUT);
      ADCSRA = 0;            // turn off ADC
      power_all_disable ();  // power off ADC, Timer 0 and 1, serial interface
      }  // end of setup

    void loop ()
      {
      // power up the LDR, take a reading
      digitalWrite (LDR_ENABLE, HIGH);
      int value = getReading (LDR_READ);
      // power off the LDR
      digitalWrite (LDR_ENABLE, LOW);

      // if it's dark, flash the LED for 2 mS
      if (value < LIGHT_THRESHOLD)
        {
        power_timer0_enable ();
        delay (1);  // let timer reach a known point
        digitalWrite (LED, HIGH);
        delay (2);
        digitalWrite (LED, LOW);
        power_timer0_disable ();
        }

      goToSleep ();
      }  // end of loop

    void goToSleep ()
      {
      set_sleep_mode (SLEEP_MODE_PWR_DOWN);
      noInterrupts ();       // timed sequence coming up

      // pat the dog
      wdt_reset();

      // clear various "reset" flags
      MCUSR = 0;
      // allow changes, disable reset, clear existing interrupt
      watchdogRegister = bit (WDCE) | bit (WDE) | bit (WDIF);
      // set interrupt mode and an interval (WDE must be changed from 1 to 0 here)
      watchdogRegister = bit (WDIE) | bit (WDP2) | bit (WDP1) | bit (WDP0);    // set WDIE, and 2 seconds delay

      sleep_enable ();       // ready to sleep
      interrupts ();         // interrupts are required now
      sleep_cpu ();          // sleep
      sleep_disable ();      // precaution
      }  // end of goToSleep

Compiled under the IDE it uses 16% of program memory:

    Sketch uses 1,370 bytes (16%) of program storage space. Maximum is 8,192 bytes.
    Global variables use 9 bytes of dynamic memory.

Claims that the Arduino IDE is badly written and inefficient are not generally true. To a certain extent the Arduino libraries favour ease-of-use over compactness, however you don't have to use them.

The IDE is just a front-end to the avr-g++ compiler. It is easy to use, and produces a .hex file which you can then upload to your chip using a suitable ICSP interface.

The avr-g++ compiler itself does aggressive code optimization. You won't get any advantage from ditching the IDE and using the avr-g++ compiler yourself - it's the same compiler. And if you think you can do better in assembler, good luck! The compiler-writers know all the tricks for storing variables in registers, and minimizing code in various ways. You will be hard pressed to write better code than the compiler generates anyway.

---

Claims that the IDE generates bloated code are Complete Nonsense. Take this sketch:

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

    int main ()
      {
      DDRB = bit (2);  // pin 7 on chip

      while (true)
        {
        PINB = bit (2); // blink it
        }
      }

Compiled for the ATtiny85 under the IDE 1.6.9 I get this program memory usage:

    Sketch uses 60 bytes (0%) of program storage space. Maximum is 8,192 bytes.
    Global variables use 0 bytes of dynamic memory.

There are 15 interrupt vectors at the start of program memory, for which space has to be reserved. So 30 of those bytes are accounted for by that unavoidable overhead.

Here is the full disassembly of the above:

    Disassembly of section .text:

    00000000 <__vectors>:
       0: 0e c0        rjmp .+28      ; 0x1e <__ctors_end>
       2: 15 c0        rjmp .+42      ; 0x2e <__bad_interrupt>
       4: 14 c0        rjmp .+40      ; 0x2e <__bad_interrupt>
       6: 13 c0        rjmp .+38      ; 0x2e <__bad_interrupt>
       8: 12 c0        rjmp .+36      ; 0x2e <__bad_interrupt>
       a: 11 c0        rjmp .+34      ; 0x2e <__bad_interrupt>
       c: 10 c0        rjmp .+32      ; 0x2e <__bad_interrupt>
       e: 0f c0        rjmp .+30      ; 0x2e <__bad_interrupt>
      10: 0e c0        rjmp .+28      ; 0x2e <__bad_interrupt>
      12: 0d c0        rjmp .+26      ; 0x2e <__bad_interrupt>
      14: 0c c0        rjmp .+24      ; 0x2e <__bad_interrupt>
      16: 0b c0        rjmp .+22      ; 0x2e <__bad_interrupt>
      18: 0a c0        rjmp .+20      ; 0x2e <__bad_interrupt>
      1a: 09 c0        rjmp .+18      ; 0x2e <__bad_interrupt>
      1c: 08 c0        rjmp .+16      ; 0x2e <__bad_interrupt>

    0000001e <__ctors_end>:
      1e: 11 24        eor r1, r1
      20: 1f be        out 0x3f, r1 ; 63
      22: cf e5        ldi r28, 0x5F ; 95
      24: d2 e0        ldi r29, 0x02 ; 2
      26: de bf        out 0x3e, r29 ; 62
      28: cd bf        out 0x3d, r28 ; 61
      2a: 02 d0        rcall .+4       ; 0x30 <main>
      2c: 05 c0        rjmp .+10      ; 0x38 <_exit>

    0000002e <__bad_interrupt>:
      2e: e8 cf        rjmp .-48      ; 0x0 <__vectors>

    00000030 <main>:
      30: 84 e0        ldi r24, 0x04 ; 4
      32: 87 bb        out 0x17, r24 ; 23
      34: 86 bb        out 0x16, r24 ; 22
      36: fe cf        rjmp .-4       ; 0x34 <main+0x4>

    00000038 <_exit>:
      38: f8 94        cli

    0000003a <__stop_program>:
      3a: ff cf        rjmp .-2       ; 0x3a <__stop_program>

I can't see much bloat there.

---

>  I wonder if things will just be easier if I use Arduino software

Yes, much easier.

  [1]: https://i.stack.imgur.com/Cb78g.jpg
  [2]: https://i.stack.imgur.com/9dMGZ.jpg


message:
Powering 4 servos with an external source

I am powering 4 tower pro sg90's and I NEED them to run at maximum torque for at least a few minutes, so 4.8volts. I am wondering how many AA batteries I will need to power all 4 servos at maximum torque for a short amount of time (like 5minutes type of thing). The servos are basically lifting different 3d printed objects.

body:
**When choosing a power source, you'll have to consider a few requirements:**

 - Required max amperage (max draw of power)
 - Required voltages (AC or DC, and available voltages)
 - Does it have to be mobile?
   - How long does it have to be powered? (how to recharge/refuel?)

Also see this [tutorial][1] it explains that you need a certain voltage for a device to work, too high voltage can result in permanent damage. For amperage, you need to have at least the minimal required, too much is no problem.

Since you don't really have a problem to fix, I can only tell you what I've worked with or what I've liked.

**Bench supplies**

Bench supplies are great while prototyping, they don't run out (like batteries) and can have a large range of voltage and supply a lot of power. I've looked around to get a nice bench power supply, but I found that they're quite expensive. If you want a variable supply that can do up to 5A, it'll cost you some real money (though it usually is well worth it).

Though my setup has always worked great for me, I use:

 - [converted PSU][2] (PC power supply)
 - [Adjustable step down module][3]

For the PSU, you could also add indicator LED's, they're great because they can supply very much power at very convenient voltages (12v, 5v, 3.3v, -12v). Also since it's a PSU it has overcurrent protection and thus is reasonably safe.

I've also bought the "adjustable step down module" from E-bay, you can power it from a 24V or 19V source like a laptop charger. You can set the output voltage and output max amperage. You can even see when the supply is limiting on power or on amperage. (So you can check if your device is taking more current than set)

**"Moving" projects**

The easiest thing here is (multiple) batteries, check the tutorial of sparkfun again. If you put them in series, you will sum up the voltage. If you put them in parallel, you will sum up the capacity.

I think batteries are the easiest way to power your device. You can [check different types of batteries][4], they have different voltages and "ampere hours". Battery holders are cheap and you can easily replace them if they run out.

On the subject of rechargeables, I would go with an Ni-Mh pack. I've got a Ni-Mh pack for airsoft and it's very reliable and easy to charge. Li-Ion requires much more care in handling and charging.

Other options can be solar-cells or other harvestable energy, but these often aren't really viable.

**Extra**

When starting to move, a servo can suddenly pull a lot of power. Not all supplies can handle this well. So the other servo's may "jiggle". Often, it's good to have a capacitor that can act as a "reservoir" or for smoothing. Same goes with devices that reset in some scenario's.

*I hope this gives you an idea on some possibilities, I haven't highlighted all options (there are too many), you should check tutorials/video's and see what works for you.

For example, check [this instructable][5] that focusses on some (analog) points that I didn't mention.*

  [1]: https://learn.sparkfun.com/tutorials/how-to-power-a-project
  [2]: https://www.youtube.com/watch?v=5TJaREOi1SY
  [3]: http://www.ebay.com/itm/5A-Adjustable-CC-CV-Display-Step-Down-charge-Module-LED-Panel-Voltmeter-Ammeter-/401092492732?hash=item5d62f9bdbc:g:Vj4AAOSw-0xYeX~n
  [4]: https://en.wikipedia.org/wiki/List_of_battery_sizes
  [5]: http://www.instructables.com/id/Powering-your-project/


message:
Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor?

Here's my circuit:
[![][1]][1]

And the code:

    //pins
    const int control1 = 2;
    const int control2 = 3;
    const int enable = 9;
    const int pinDirection = 4;
    const int pinOnOff = 5;
    const int pot = A0;
    //states
    int stateOnOff = 0;
    int stateOnOffPrev = 0;
    int stateDirection = 0;
    int stateDirectionPrev = 0;

    int motorEnabled = 0;
    int motorSpeed = 0;
    int motorDirection = 1;

    void setup(){
      pinMode(pinDirection, INPUT);
      pinMode(pinOnOff, INPUT);
      pinMode(control1, OUTPUT);
      pinMode(control2, OUTPUT);
      pinMode(enable, OUTPUT);

      digitalWrite(enable, LOW);
      Serial.begin(9600);
    }

    void loop(){
      stateOnOff = digitalRead(pinOnOff);
      delay(10);
      stateDirection = digitalRead(pinDirection);
      motorSpeed = analogRead(pot)/4;

      if(stateOnOff != stateOnOffPrev){
        if(stateOnOff == HIGH){
          motorEnabled = !motorEnabled;
        }
      }

      if(stateDirection != stateDirectionPrev){
        if(stateDirection == HIGH){
          motorDirection = !motorDirection;
        }
      }
    Serial.println(stateDirection);
      if(motorDirection == 1){
        digitalWrite(control1, HIGH);
        digitalWrite(control2, LOW);
      }else{
        digitalWrite(control1, LOW);
        digitalWrite(control2, HIGH);
      }

      if(motorEnabled == 1){
        analogWrite(enable, motorSpeed);
      }else{
        analogWrite(enable, 0);
      }

      stateDirectionPrev = stateDirection;
      stateOnOffPrev = stateOnOff;

    }

As you can see, the switch on pin 5 controls whether the motor is on and the potentiometer controls motor speed. Both work.

However, when the switch on pin 4 is closed the `stateDirection` variable still reads 0, or open circuit. It should when pressed change the direction of the motor via the H-bridge. I've tried everything I could, new switches, higher resistance. The only time it read HIGH is when I literally plugged switch out to GND.

Serial shows `stateDirection` as an unending chain of zeroes.

And finally the schematics from the original project.
[![schematics][2]][2]

Thank you.

**PS: Forgive for lack of comments! But I think a good Arduino programmer should not need comments. **

  [1]: https://i.stack.imgur.com/SF6jX.jpg
  [2]: https://i.stack.imgur.com/zleTK.jpg

body:
> when the switch on pin 4 is closed the stateDirection variable still reads 0, or open circuit.

you could have pull-up enabled on that pin: with a nominal value of 50k, 10k pull-down is just on the cusp of making it a logic low.

solution?

1) disable pull-up;
2) use a stronger pull-down;
3) get rid of the pull-down and rely on the pull-up alone.
...


body:
If it shows low when bypassing switch and jumping to ground.. Then either bad switch or maybe simply wrong orientation of switch.

Edit: if GND is making pin 5 HIGH in logic, then your button needs to jump to GND and have the resistor on 5v. Currently it is opposite according to your schematic.


message:
how to get precise value from float variable?

#include <NeoSWSerial.h>

    //#include <SoftwareSerial.h>
    #include <AltSoftSerial.h>
    #include <NMEAGPS.h>

    NeoSWSerial GSM(2, 3); // RX, TX: Connect TXD to RX & RXD to TX

    static const int RXPin = 8, TXPin = 9;
    AltSoftSerial gpsPort(RXPin, TXPin);
    static const uint32_t GPSBaud = 9600;

    NMEAGPS gps;
    gps_fix fix;
    uint8_t fixCount = 0;
    char dt[15],tm[15];
    float lati,longi;
    //int block = 0;

    enum _parseState {
      PS_DETECT_MSG_TYPE,

      PS_IGNORING_COMMAND_ECHO,

      PS_HTTPPARA_RESPONSE,

      PS_HTTPACTION_TYPE,
      PS_HTTPACTION_RESULT,
      PS_HTTPACTION_LENGTH,

      PS_HTTPREAD_LENGTH,
      PS_HTTPREAD_CONTENT
    };

    enum _actionState {
      AS_IDLE,
      AS_WAITING_FOR_RESPONSE
    };

    byte actionState = AS_IDLE;
    unsigned long lastActionTime = 0;

    float s;

    byte parseState = PS_DETECT_MSG_TYPE;
    char buffer[160],url[160];
    byte pos = 0;

    int contentLength = 0;

    void resetBuffer() {
      memset(buffer, 0, sizeof(buffer));
      pos = 0;
    }

    void sendGSM(const char* msg, int waitMs = 500) {
      GSM.println(msg);
      while(GSM.available()) {
        parseATText(GSM.read());
      }
      //delay(waitMs);
    }

    void setup()
    {
      GSM.begin(9600);
      Serial.begin(9600);
      gpsPort.begin(GPSBaud);

      Serial.println(F("Hinder LOADING....."));
      Serial.println(F("obtain gps and store data to database"));
      Serial.println(F("Testing by : "));
      Serial.println(F("Nikhil,Muthumani and Mathews"));
      Serial.println();

      sendGSM("AT+SAPBR=3,1,\"APN\",\"vodafone\"");
      delay(500);
      sendGSM("AT+SAPBR=1,1",3000);
      delay(500);
      sendGSM("AT+HTTPINIT");
      delay(500);
      sendGSM("AT+HTTPPARA=\"CID\",1");
      delay(500);
    }

    void loop()
    {
      unsigned long now = millis();
      while (gps.available( gpsPort )) {
        fix = gps.read();
         //Serial.println(F("b"));
        // Once every 5 seconds...
        if (++fixCount >= 5) {
           //Serial.println(F("a"));
          displayInfo();

          //send the next report if previous one is finished
          if ( actionState == AS_IDLE ) {
          sprintf(url, "AT+HTTPPARA=\"URL\",\"http://**************/***.php?lat=%d&lng=%d&speed=%d&date=%s&time=%s\"",lati,longi,s,dt,tm );
          sendGSM(url);
         // lastActionTime = now;
          parseState = PS_HTTPPARA_RESPONSE; // a new state
          actionState = AS_WAITING_FOR_RESPONSE;
          fixCount = 0;
        }

        }
      }

    /*  if ((gps.statistics.chars < 10) && (millis() > 5000)) {
         Serial.println( F("No GPS detected: check wiring.") );
         while(true);
         block=1;
        }*/

      while(GSM.available()) {
        //lastActionTime = now;
        parseATText(GSM.read());
      }
     }

    void displayInfo()
    {
      Serial.print(F("Location: "));
      if (fix.valid.location) {
        lati=( fix.latitude());
        //sprintf(lati,"%d",fix.latitude(),5);
        Serial.print(lati);
        Serial.print( ',' );
        longi= ( fix.longitude());
        //sprintf(longi,"%d",fix.longitude(),5);
        Serial.print(longi);
      } else {
        Serial.print(F("INVALID"));
      }

      Serial.print(F("  Speed: "));
      if (fix.valid.speed) {
        s=fix.speed_kph();
        Serial.print(s);
        Serial.print(F(" KMPH "));
      } else {
        Serial.print(F("INVALID"));
      }

      // Shift the date/time to local time
      NeoGPS::clock_t localSeconds;
      NeoGPS::time_t  localTime;
      if (fix.valid.date && fix.valid.time) {
        using namespace NeoGPS; // save a little typing below...

        localSeconds = (clock_t) fix.dateTime; // convert structure to a second count
        localSeconds += 5 * SECONDS_PER_HOUR + 30 * SECONDS_PER_MINUTE; // shift timezone
        localTime = localSeconds;              // convert back to a structure
      }

      Serial.print(F("  Date : "));
      if (fix.valid.date) {
        sprintf(dt,"d/d/20%d",fix.dateTime.date,fix.dateTime.month,fix.dateTime.year);
        Serial.print(dt);
      } else {
        Serial.print(F("INVALID"));
      }

      Serial.print(F("  Time : "));
      if (fix.valid.time) {
        if (localTime.hours>12)localTime.hours-=12;//To convert 24 hr format to 12 hr format
        sprintf(tm,"d:d:d",localTime.hours,localTime.minutes,localTime.seconds);
        Serial.print(tm);
        //block=1;
      } else {
        Serial.print(F("INVALID"));
      }

      Serial.println();
    }

    void parseATText(byte b) {

      buffer[pos++] = b;

      if ( pos >= sizeof(buffer) )
        resetBuffer(); // just to be safe

      /*
       // Detailed debugging
       Serial.println();
       Serial.print("state = ");
       Serial.println(state);
       Serial.print("b = ");
       Serial.println(b);
       Serial.print("pos = ");
       Serial.println(pos);
       Serial.print("buffer = ");
       Serial.println(buffer);*/

      switch (parseState) {

      case PS_HTTPPARA_RESPONSE:
        {
          parseState = PS_DETECT_MSG_TYPE;
          sendGSM("AT+HTTPACTION=0");
         /*  while(GSM.available()) {
        //lastActionTime = now;
        parseATText(GSM.read());
      }*/

        }
        break;

      case PS_DETECT_MSG_TYPE:
        {
          if ( b == '\n' )
            resetBuffer();
          else {
            if ( pos == 3 && strcmp(buffer, "AT+") == 0 ) {
              parseState = PS_IGNORING_COMMAND_ECHO;
            }
            else if ( b == ':' ) {
              //Serial.print("Checking message type: ");
              //Serial.println(buffer);

              if ( strcmp(buffer, "+HTTPACTION:") == 0 ) {
                Serial.println("Received HTTPACTION");
                parseState = PS_HTTPACTION_TYPE;
              }
              else if ( strcmp(buffer, "+HTTPREAD:") == 0 ) {
                Serial.println("Received HTTPREAD");
                parseState = PS_HTTPREAD_LENGTH;
              }
              resetBuffer();
            }
          }
        }
        break;

      case PS_IGNORING_COMMAND_ECHO:
        {
          if ( b == '\n' ) {
            Serial.print("Ignoring echo: ");
            Serial.println(buffer);
            parseState = PS_DETECT_MSG_TYPE;
            resetBuffer();
          }
        }
        break;

      case PS_HTTPACTION_TYPE:
        {
          if ( b == ',' ) {
            Serial.print("HTTPACTION type is ");
            Serial.println(buffer);
            parseState = PS_HTTPACTION_RESULT;
            resetBuffer();
          }
        }
        break;

      case PS_HTTPACTION_RESULT:
        {
          if ( b == ',' ) {
            Serial.print("HTTPACTION result is ");
            Serial.println(buffer);
            parseState = PS_HTTPACTION_LENGTH;
            resetBuffer();
          }
        }
        break;

      case PS_HTTPACTION_LENGTH:
        {
          if ( b == '\n' ) {
            Serial.print("HTTPACTION length is ");
            Serial.println(buffer);

            // now request content
            GSM.print("AT+HTTPREAD=0,");
            GSM.println(buffer);

            parseState = PS_DETECT_MSG_TYPE;
            resetBuffer();
          }
        }
        break;

      case PS_HTTPREAD_LENGTH:
        {
          if ( b == '\n' ) {
            contentLength = atoi(buffer);
            Serial.print("HTTPREAD length is ");
            Serial.println(contentLength);

            Serial.print("HTTPREAD content: ");

            parseState = PS_HTTPREAD_CONTENT;
            resetBuffer();
          }
        }
        break;

      case PS_HTTPREAD_CONTENT:
        {
          // for this demo I'm just showing the content bytes in the serial monitor
          Serial.write(b);

          contentLength--;

          if ( contentLength <= 0 ) {

            // all content bytes have now been read

            parseState = PS_DETECT_MSG_TYPE;
            resetBuffer();

            Serial.print("\n\n\n");

            actionState = AS_IDLE;
          }
        }
        break;
      }
    }

in this I try obtain the GPS latitude and longitude at every 5 secs and and use that values to find the name of the location.I need to pass the value of latitude and longitude over the URL to the php code and there it is converted to the location name.I also need to pass the speed,date and time (speed and date works fine). When i try to sent them the command displayed on the window is `Ignoring echo: AT+HTTPPARA="URL","http://[link]/hinder.php?lat=?&lng=?&speed=?&date=&time=16/04/2017"` here you can see instead of value of latitude,speed and longitude a question mark appears.So i tried

    sprintf(url, "AT+HTTPPARA=\"URL\",\"http://masp203.000webhostapp.com/hinder.php?lat=%f&lng=%f&speed=%d&date=%s&time=%s\"",fix.latitude(),fix.longitude(),fix.speed_kph(),dt,tm ); sendGSM(url);
but that too didnt worked.I need a presice value of latitude and longitude (about 5 decimal points) since it is used to find the location.Can any one tell me hoe can i do that .

body:
Floating point values aren't precise.

However you problem has nothing to do with precision, but purely how you are representing the value as text. You are asking for the format `%f` which, by default on Arduino, is not supported by `sprintf`.

Instead you have to use the function `dtostrf()` (a non-standard libavr specific function).

    char floatval[10]; // Room for 9 characters + NULL
    float myVal = 48.53927853;

    dtostrf(myVal, 9, 5, floatval);

Selection of the right numbers is critical. The first is the total space you have available in the target character array (not including the required NULL, so one less than the size of the array). The second is the number of decimal places to render. So you have to make sure you have enough room for the integer portion, any sign (if it's negative) and the decimal point, plus the number of decimal places you want to render - in this case:

* 1 - Sign
* 2 - Integer
* 1 - Decimal point
* 5 - Decimal portion

Total: 1+2+1+5 = 9.

The first value, width, can also be given as a negative value, in which case left alignment of the content will be performed.


body: If you aren't going to be computing with the GPS coordinates, I'd suggest keeping the character strings just as they were delivered by the device. You'll keep all of the precision available without introducing any quantization or roundoff errors.


body:
> how to get precise value from float variable?

possible solutions:

1) don't use float where precise values are needed - by far the best solution;

2) use fixed point types;

3) use integer types;

...


body:
> I need a precise value of latitude and longitude (about 5 decimal points) since it is used to find the location.  Can any one tell me how can I do that.

If you only need 5 decimal points, you can continue to use `float` values.  If you would like more precision, you can use the 32-bit integer forms of lat/lon provided by NeoGPS.

For `float` values, you can do as Majenko suggested.  Just like the date and time arrays, you format that floating-point lat and lon values into their own character arrays.  Then put them in the `url` array with `sprintf` and "%s", just like the `dt` and `tm` arrays.

To get the extra digits of precision, you have to use the `fix.latitudeL()` and `fix.longitudeL()` functions.  They return integers that have 10 significant digits.  They are scaled by 10000000, so you have to insert the decimal point at the right place.  The example program NMEAloc.ino shows how to print those integers as if they were floating-point values.

Since you are using `sprintf`, you could format latitude like this:

    char lat[16];
    int deg = fix.latitudeL() / 10000000L; // possibly negative
    int decimals = abs( fix.latitude() - deg * 10000000L );
    sprintf( lat, "%d.d", deg, decimals );

Then format this into the `url` array with %s:

    sprintf( url, " ... &lat=%s&...", ... , lat, ... );

That gives you 7 decimals, like `9.7451145`


message:
Programming Attiny45 using Arduino Uno with weird behavior

I bought an Arduino Uno a few days ago.

I programmed an ATtiny45 using an Arduino Uno following "How-To: Shrinkify Your Arduino Projects" video on YouTube.

I uploaded the blink example successfully. I altered the sketch in a way so there is also a blinking on pin 4 (which is ATtiny45 pin 3).

Now, if I connect +5V from the Arduino to ATtiny45 pin 8, ground to pin 4 and the LEDs from pin 2 and 3 to ground everything works as expected.

But if I use 4 AA batteries instead of the power from the Arduino I only get a blinking on ATtiny pin2.

What could be the reason for this behavior? Is it because I use 4 AA -> 6 V instead of 5 V? I tested it also with 3 AA batteries and got the same result.

So why does it work if I use power and ground from the Arduino but not from the batteries?

body:
If you take a look at Attiny45 [datasheet][1], you will find at the very first page:

> Operating Voltage
>
> - 1.8 - 5.5V for ATtiny25V/45V/85V
>
> - 2.7 - 5.5V for ATtiny25/45/85

Your circuit will have unpredictable behavior out of this range. If you want to use four AA cels, you can organize them to have a 3V output or use a step-down voltage regulator.

  [1]: http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf


message:
Arduino constant vs Microchip PIC constant

[2.2 THE BASICS OF C PROGRAMMING][1] LANGUAGE book is has like this,

> CONSTANTS
>
>A constant is a number or a character having fixed value that cannot be changed during program execution. Unlike variables, **constants are stored in the flash program memory** of the microcontroller for the purpose of saving valuable space of RAM. The compiler recognizes them by their name and prefix const.

And [Arduino references][2] has not said where is constant variables are stored either program memory or RAM.

My questions are, where is the saving location of Arduino constant variables?
Is it same to Microchip PIC?
Those two compilers are same or not in this case?

  [1]: https://learn.mikroe.com/ebooks/piccprogramming/chapter/the-basics-of-c-programming-language/
  [2]: https://www.arduino.cc/en/reference/const

body:
Constants can still use RAM. The decision whether to store it or not in RAM is up to the compiler. It may, for example, put the constant into RAM and then reference that constant throughout the code. The main use of constants is to act as a remainder that you cannot change that value. My personal experience tells me that `const` occupy the same RAM that `int` type does.

Using `const` does not prevent the values to be stored in RAM. If you want to prevent this behavior you should use [PROGMEM][1]

> Store data in flash (program) memory instead of SRAM. There's a description of the various types of memory available on an Arduino board. The PROGMEM keyword is a variable modifier, it should be used only with the datatypes defined in pgmspace.h. It tells the compiler "put this information into flash memory", instead of into SRAM, where it would normally go.

This [link][2] may also be useful.

  [1]: https://www.arduino.cc/en/Reference/PROGMEM
  [2]: http://playground.arduino.cc/Learning/Memory


body:
`const` means different things in different contexts as far as storage goes.

For a simple numeric value the compiler will generally replace the constant with the literal value. Any mathematics using purely constants or literals will be replaced at compile time with the result.

For instance, the code:

    const int a = 3;
    const int b = 4;

    void setup() {
        int c = a + b;
        Serial.println(c);
    }

    void loop() {

    }

results in the AVR assembly:

    be: 4a e0        ldi r20, 0x0A ; 10
    c0: 50 e0        ldi r21, 0x00 ; 0

    c2: 67 e0        ldi r22, 0x07 ; 7
    c4: 70 e0        ldi r23, 0x00 ; 0

    c6: 80 e2        ldi r24, 0x20 ; 32
    c8: 91 e0        ldi r25, 0x01 ; 1
    ca: 0c 94 4a 01  jmp 0x294 ; 0x294 <_ZN5Print7printlnEii>

Registers `r22` and `r23` store the second integer parameter to the Serial.println() - the actual function call generated is `_ZN5Print7printlnEii(&Serial, 7, 10)`.

So you see that the literal value 7 has replaced both the sum of the constants and the variable it is placed in.

However it is very different when more complex values are called for - such as arrays (either numeric or character arrays, AKA "C Strings"). In this case yes the values are stored in Flash, however the startup code `crt0.o` copies that data into SRAM so that the software can access it easily.

Generally flash is hard for software to read from. In some architectures it requires special instructions to be executed. In others it requires setting values in SFRs (Special Function Registers) and reading from other SFRs to get the data. In other words it's far harder than just reading from a memory location (a limitation of Harvard Architecture). So it's copied at boot time into SRAM so that it then becomes easy to access, as it's just now accessing a memory location.

However that then defeats one of the objectives of using a constant value - reduction of SRAM usage by placing the data in Flash. So the Arduino has a specific macro `PROGRMEM`, which sets attributes on the variable to say "Never copy this data to SRAM".

More specifically it's actually provided by the file `avr/pgmspace.h` in the avr-gcc compiler:

    #define __ATTR_PROGMEM__ __attribute__((__progmem__))
    #define PROGMEM __ATTR_PROGMEM__

But now of course you can't access the data using simple memory accesses, so there are special functions to allow it to be done. Some are alternate versions of standard C library routines, for instance `strcmp_P()` shadows `strcmp()` with the second parameter being a PROGMEM variable. Others are special functions for reading bytes or words from locations in flash, such as `pgm_read_byte_near()`.

The Arduino API also provides an extra little trick, called the `__FlashStringHelper` which is an empty class used to identify strings held in flash for the purpose of *function overloading* so that the `F()` macro can be used to call the right variant of a function to use the flash reading functions instead of assuming the string is in SRAM.

So as you can see it's not as straight forward as "consts are in Flash, non-consts are in RAM".

----

Highlighting the differences between how the AVR accesses Flash and how the various PIC sub-families access Flash:

* The AVR has one single instruction that can read Flash - LPM:

> There is only one instruction for the read access to the program storage space. It is defined for the pointer pair Z and it is named LPM (Load from Program Memory). The instruction copies the byte at program flash address Z to the register R0. As the program memory is organized word-wise (one instruction on one address consists of 16 bits or two bytes or one word) the least significant bit selects the lower or upper byte (0=lower byte, 1= upper byte). Because of this the original address
must be multiplied by 2 and access is limited to 15-bit or 32 kB program memory. Like this:
>
>     LDI ZH,HIGH(2*address)
>     LDI ZL,LOW(2*address)
>     LPM

* PIC10, PIC12 and PIC16 chips have no way of reading the flash.

Instead a "lookup table" of "RETLW" calls is used. For instance the string "Hello" would be stored in flash as:

    RETLW 72    ; H
    RETLW 101   ; e
    RETLW 108   ; l
    RETLW 108   ; l
    RETLW 111   ; o
    RETLW 0     ; NULL

`RETLW` returns from a `CALL` with the `W` register set to the literal value in the instruction. The entire command, that is both the `RETLW` and the 8 bit literal value, fits into a single 14-bit opcode.

* PIC18 uses SFRs to access the Flash memory. Set the three registers `TBLPTRU`, `TBLPTRH` and `TBLPTRL` to the three bytes of the address in flash you want to read, a `TBLRD` instruction is issued through the `EECON1` register, then you can read the byte from `TABLAT`.

* PIC24 / dsPIC33 uses PSV - Program Space Visibility. This gives you the ability to map a 32kB chunk of the flash memory into the upper 32kB portion of the data space. This allows direct reading of data from within that 32kB chunk as if it were in RAM.

* PIC32 uses a *Von Neumann* architecture which means that Flash and SRAM both share the same 32-bit address space. There is no difference reading from Flash or SRAM, so no special instructions are needed.

The only chip from those above where `const` really means `const` is the PIC32 where there is no need to copy from Flash to SRAM during startup since all the Flash memory can be directly accessed with normal MIPS `LW` and `LB` etc instructions.