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

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.

Just out of curiosity, why have 6 outputs all at the same frequency? Why not just have one or two?

I am working on a DC/DC converter project. Initially I am using 2 outputs only so only Timer0 is used. But now i need to control 2 extra things, thus a total of 4 outputs to be controlled. Reaching to this point, might as well learn how to use all 6 of them :)

Where did you get your datasheet from, exactly. I have several datasheets for ATmega328P (for 2013 and 2014), but I certainly do not have the same info as you have. The chapter titles themselves look weird. On mine, I have "TCCR1A – Timer/Counter1 Control Register A" and the bits description is complete. It seems new datasheets edited by microchip have lost quite some information. Try to find youself an older datasheet from Atmel.

And for your information, the bits COM1xx are the same as for COM0xx and COM2xx, in terms of their position in the register.

The datasheet I referred to is atmega328p 2016. I just checked an older version and you are right! It shows me 'COM1A1|COM1A0|COM1B1|COM1B0'. Now down to one question. Will be more than willing to set your answer as answered if you can answer the first question together with the second question

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:

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

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

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.

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.


text:
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!

Does the  “freezed in first reading” thing, whatever it might be, happen to last about 500 milliseconds?  What does  “freezed in first reading” mean, exactly?  ¶ Note, “changed the above code only in the switch case” probably is false.  Not showing a  Minimal, Complete, and Verifiable example of code – eg, you don't show declarations of display, sensorValue, and sensorPin, and don't indicate nature of sensor or model of OLED –  makes it difficult to diagnose problems.

I mean to say that the OLED displays one LDR reading taken at the moment I say "on". And the display doesnt refresh to give continuous LDR reading . Eg : the OLED shows " LDR Reading :372"  This will remain on the screen as it is until I say "off" which clears the display and make it blank. Then again when I say "on" , it displays another reading taken at the moment and it remains as it is on screen. I want the OLED to display continuous readings at an interval of 500 milli seconds and should clear the display once I say "off".  I am uploading the full code.

For debugging, add a Serial.print() or and/or an OLED output (on a different line) that every half second or so tells the current sensor reading and the most-recent voice-unit output.  Or temporarily add a button to simulate an On event.  Do you know for sure that the sensor reading should change?  Or does the OLED obviously blink each time a reading is put up?  Do you know if an  On event is occurring after the first On, or if it is a display issue?

I am just trying to print the analog values (example from basic arduino). Here I am getting analog values and I am trying to print the same on OLED. Without voice module , I am able to get the LDR readings on OLED. Now after adding the voice command, my statement is isnide switch case followed by break. I am able to verify whether my voice command is recorded or not from serial monitor. The problem is with code. The display should run in a loop showing LDR values after half second. The code is the problem.

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.

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);
}

I tried your solution. I initialized static bool Tellsensor= False in loop. Modified case OnRecord and OffRecord as you said. And after if(ret>0){..}.. added the if statement. But the results where same , the loop does not run when I say "On". It displays first reading and remains as it is. Once I say "off" it turns off the display. I tried moving the same if statement within if(ret>0){..} and here when I say "on" it displays one reading , again by saying "on" it refreshes and prints the next reading. By saying "off" the display goes blank. Any idea how to fix this?

By "static bool Tellsensor= False in loop", are you referring to a declaration and initialization right at the beginning of loop(), or some other loop?  It should be the former.  But the symptom sounds like it isn't.  Anyway, for testing I'd move its  declaration and initialization to global.  Note, I'll be away a few days.

source: Stack Exchange

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

sort: votes


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

Check the max payload size. The NRF24L01 does not allow more than max 32 bytes in total.

If you want to send a longer message you will have to split it into several messages and then merge them at the receiver.

Is there another Arduino receiving the message? The nrf24 will check if it receives an ACK message back. If it doesn't the write method will return 0

@Gerben Yes, there is another arduino that acts as receiver. Also check and radio.write returns 0.

@MikaelPatel Yes, I have sent a single char to verify this and I continue the same thing.

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 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 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?"

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

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


text:
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 (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!

I'd just measure the voltage, and use that to calculate the charge level. Or at least use it to "reset" the current, when the battery is full. Just measuring the current in and out will eventually lead to some drift. Due to self discharge of the battery and/or losses.

Why not do both?

Is there any progress on this project ? It would be a great help if there is because our project is somehow like this.

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 explain it pretty well, also here is a library 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.

Hi there, I appreciate the help. We are using some Rolls 4000 series, 12kWh total (http://www.windandsun.co.uk/products/Batteries/Rolls-Batteries#.WPNJtmmGPIU). Both the solar PV and the wind turbine have charge controllers, and together with the battery they will all be connected to a positive and negative bus. What we want is to monitor  battery SOC to ensure that if the battery level goes below a certain level, a warning is sent to someone. We will also attempt to estimate SOC via voltage measurement (what Gerben suggested) however doing coulomb counting is a project requirement :(

Which is the voltage of your battery bank?

you should probably determine the soc using both current integration and open circuit voltage method.It is possible to cover the weakness of both techniques and provide an accurate monitoring technique.I can provide you the codes if you need,
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
const int mVperAmp = 100;const float chargingdfficiency= 0.7;
int RawValue= 0, ACSoffset = 2500;
double Voltage = 0, Amps = 0;
double g,q;
int m=0,c=0,d;
void resett(){
digitalWrite(8,LOW);
digitalWrite(7,LOW);}

void setup() {
pinMode(A0, INPUT);pinMode(A1, INPUT);
pinMode(7,OUTPUT);pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
Serial.begin(9600);
delay(10);lcd.begin(20, 4); delay(10);}

void loop() {
resett();
double vini=analogRead(1);vini = vini*5/1023;
vini=5*vini;Serial.print(vini,3);vini=vini/6;
double soc=((666.6667)*vini)-1300;delay(10);
q=soc*.42;
if(soc<30){m=1;resett(); digitalWrite(7,HIGH);} //charging
if(soc>=100){m=0;resett();digitalWrite(8,HIGH); } // DISCHARGING
if(m==0){resett();digitalWrite(8,HIGH);}
delay(10);
while(1){
RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if((Amps<.098)&&(Amps>-.098)){Amps=0;}
if(Amps>9){
resett();
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Overload");digitalWrite(9,HIGH);
while(1);}
if(m==0){
if(Amps<=1.5){g=1.183;}
else if(Amps<=2){g=0.042*Amps+1.12;}
else if(Amps<=4){g=0.028*Amps+1.148;}
else if(Amps<=5){g=0.032*Amps+1.132;}
else if(Amps<=6){g=0.03*Amps+1.142;}
else if(Amps<=7){g=0.325*Amps-0.628;}
else if(Amps<=7.5){g=0.066*Amps+1.185;}
else if(Amps<=8){g=0.028*Amps+1.47;}
else if(Amps<=10){g=1.694;}
soc=(q-Amps*g*0.0002778)*2.38095; q=soc*.42;
if(soc<5){m=1;resett();digitalWrite(7,HIGH);} }
if(m==1){
soc=(q-Amps*chargingdfficiency*0.0002778)*2.38095;
q=soc*.42;
if(soc>=100){m=0;resett();digitalWrite(8,HIGH);}}
lcd.clear();
lcd.display();
lcd.setCursor(1,0);
lcd.print("Soc = ");
lcd.setCursor(13,0);
lcd.print(soc,1);
lcd.setCursor(19,0);
lcd.print("%");
lcd.setCursor(1,1);
lcd.print("Amps= ");
lcd.setCursor(13,1);
lcd.print(Amps,1);
if(m==1){lcd.setCursor(1,2);lcd.print("Charging");}
else{lcd.setCursor(1,2);lcd.print("Discharge");}
lcd.setCursor(1,3);lcd.print("Normal");
Serial.println((vini),3);
Serial.print("Amps = ");
Serial.println(Amps,9);
Serial.print(" Soc = ");
Serial.println(soc,9);

for(d=0;((Amps==0)&&(d<=1200));d++){RawValue = analogRead(0);
Voltage = (RawValue / 1024.0) * 5000;
Amps = ((Voltage - ACSoffset) / mVperAmp);Amps=-Amps;
if(d==1200){vini=analogRead(1);vini = vini*25/(6*1023);
soc=((666.6667)*vini)-1300;d=0;}}

delay(1000);
}
}


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

Your code might communicate with an external sensor. If the sensor doesn't respond (correctly) your could could get stuck. Or there could be noise on the signal wires resulting in a response that you wouldn't get ordinarily. You could do a lot of checks in software, but you might just miss that edge case that only occurs once in a blue moon.

@Gerben    the case is I have made a Mega based device with GSM to send certain sensor data to my server. It works fine everywhere, but at a specific place I have seen the device stops communicating with GSM; it simply gets struck. What I believe it could be a power issue, or ground mismatch with the sensor device which communicates with RS-232. So I consider implementing watchdog here and see the result.

The watchdog doesn't necessarily reset the processor. It can call a watchdog ISR. Also it's worth noting that sometimes the issue is external hardware, like an SD card interface or an RFID card reader. Resetting the processor in these cases doesn't fix the underlying problem that the attached hardware is locked up. A totally independent watchdog might be useful, which completely powers down, and back up, the entire device (including peripherals).

Agreed, the watchdog ISR has the option to RESET or raise an interrupt, whichever is necessary. Yes, the above case is equivalent to disconnect and reconnect power to the device and periperials again.

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:

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

If you want a heavily studied heavily reviewed real world example of watch-dog-timers simply search the Internet using a term similar to: "toyota watchdog timer".

That seems a good explanation. Well any idea on how to implement in real code which are complex and don't return within 8 seconds timebound set by watchdog timers.

One approach, place all non-blocking polling in an infinite loop which also checks the elapsed time.... I'll add this to the answer.

Yes, these are the alternatives to using watchdog timer and a good understanding of code flow is mandatory for prevention of lockup.

Thanks to @st2000 it was a good understanding of what watchdog does. What I gather is when dealing with a time-critical situation, where a mistake would cost you a lot, it is a must to use watchdog as a failsafe. Most importantly the code should be deterministic in time, where the system or the programmer is aware of how much time every action takes to complete. Unlike in GSM, where a majority of the tasks are dependent on network quality, it will hard to make a deterministic call on time.
Here is a good [ckecklist](https://criticaluncertainties.com/2013/11/13/watchdog-timers-the-unsung-heroes

If acceptable, consider accepting the answer.  Otherwise the system might kick the question back to the top of the list soliciting for more or better answers.


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

Edit your question and format the code. Select the code and click the {} button in the editor.

First off, did you use pullup or pulldown resistors for your button?

Second, what's the purpose of ledon variable, in its current usage, it is just useless.

Nothing will happen as lastbuttonstate is never changed.

so i got to change the last buttonstate according to the led state ??

I'd add a delay(100); at the end of the loop to have to very basic debouncing of the button.

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.

Can  u plz explain me how u r using the variable waspressed here ?

At every loop, it reads the variable buttonpin for its value. In case it is HIGH, it sets waspressed to true. This means that by the time you are holding the button, the value of waspressed will always be true. At the time you release the button, the next loop will read buttonpin as false and will check if waspressed is true. In case it is true, this means that the button has just being released. In this case it changes the value of the led pin and set waspressed to false again so you go back to the initial state.

I can explain it in a slower rhythm if necessary. Just ask me if you need it. :)

I edited the answer to provide a more detailed explanation

thanx for the elaboration.....now i'm completely  able to understand this program.....it was easier than a complex program that i was unable to understand from youtube.

can you help me in one more question? I had posted it it 1 year ago which is related on this same concept of push button, integrating fading effect with push button. P.S. :- I have made some changes in the program after learning this concept. plz help me out !!

This appears to be the classic "how to debounce a mechanical button" problem.
You can either denounce a button using external hardware.  Or you can denounce a button using software.
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.

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.


text:
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).
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 ?

If this was an ordinary computer I would suggest using C++ vectors as you don't need to describe its size to the compiler.  But we are talking embedded and there may not be enough physical RAM for you to work with.  Have you consider using a much more powerful Arduino such as an ARM based Arduino?  Also, likely all libraries have never been tested with all other libraries for comparability.  Given the limited hardware resources of most Arduino processors, you are likely running into a conflict between the WIFI and SDCard libraries.

Also, considering the low cost of most Arduino platforms, it may be easer to split the tasks between two Arduinos.  The sensor sampling & SDCard logging can be accomplished on the 1st Arduino.  And the WIFI & web page serving can be accomplished on the 2nd Arduino.  It is certainly not the first time hardware has been used instead of software to solve a problem.

It would be a great solution, but I saddly can't do this (mostly because this is a project for school and I can't choose the hardware I'm working with, along with the fact that time is beginning to run out...)

Someone might have a direct solution for you (use the libraries as is and still run on a single Arduino).  Otherwise, start thinking "out of the box". Consider polling the Arduino on a periodic bases to avoid storing large amounts of data on the embedded processor.  Again, investigate alternative Arduino's with large amounts of built in RAM (such as the ARM based Ardiuno).  In this way you can set aside large amounts of RAM for data storage with little modifications to your existing WIFI only code (w/o the SDCard code).

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

Thanks ! I already heard about ring buffers in Java, this shouldn't be too hard to implement ; but I'm not sure if it'll be enough. Well, can't know without trying, if it's enough I'll mark the answer as accepted then.

What do you mean by "enough"? The problem with your question is that it doesn't have any clear criteria, such as the amount of data that must be stored. (If you must store more data than will fit in memory, clearly both this solution and the "Strings in memory" solution you originally used are both completely unacceptable and you should have asked two, separate, different questions: one specifically about how to get the SD Card working with WiFi (detailing your hardware precisely), and the other about other options for external storage.

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.


text:
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:
//#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.

MOSI and SCK both on GPIO19...?

I have now corrected the discription of connections sck is at pin 18 not 19.

Why have you commented out the TFT initialisation function?

That function works only wit h tft shield. I am using a separate breakout board so I have to innitialise in the format given two lines bellow.  : Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS ,TFT_DC, 23, 18, TFT_RST);

That instantiates the object, it doesn't initialise the TFT. I repeat: why have you commented out the initialisation function?

Also why tell the library MOSI is on 23 when it is on 19?

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

MOSI should be connected to pin 23 not 19.
tft.begin() function should be in the setup to initialize the TFT. (for ILI9341)
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).


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

You should connect the shield as Adafruit prescribes. In what way do you think you need capacitors?

Post a schematic of how you think extra capacitors should be added, a description of what you think they'll do, and what you think the problem with what the shield documentation suggests (not necessarily in that order), and then we can comment.

lots of motor shields have that sort of thing (dioides too) built-in

If the motors have a lot of "brush noise" you need to add capacitors to the motor. It is written in the FAQ.
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.


text:
Using Arduino and Motor Shield
I am a beginner in Arduino.I want to connect 2 motors to Arduino.
Do I require a motor shield?And if yes please tell why?
Also can i use an amplifier to increase the voltage for the motors?
And one last important question, I have just seen the motor shield's pic. Does it restrict arduino's pin usage? I mean we can't use the arduino pins if we use the motor shield right?
PS: I am talking about this model: SLAEX039 L293D Motor Shield
Thank a lot

Yes. To use standard D.C. motors, you must use a motor shield or the L239D chip. This is mainly due to motor noise, and control to run the motor at different speeds and directions. Also you get very easy to use libraries!

Can we use amplifiers then?

Please don't recommend the L293 (or L298) these are horribly antiquated, lossy devices which cause users no end of problems.  One should pick modern motor shield with an FET bridge instead, for example the ones with the TB6612FNG.  Additionally, the basic explanation of this answer is wrong - the need is not due to "motor noise" or directional control but rather the required motor current.   H-bridges have basically the exact same output structure as ATmega pins, but are built to handle the required current and possible voltage range, while ATmega pins are not.


text:
ESP8266 + Slack (ssl->need_bytes=16432 > 6859)
I'm trying to connect an Adafruit Huzzah ESP8266 with Slack.
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.

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

#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);
    }
  }
}

it probably works sometimes becuase you happen to have enough RAM at that moment. You can try reducing RAM usage with the F() macro on long stings, and removing any libs you don't need. The sure-fire way is to proxy the request to slack using something like a php server with a smaller SSL cert; you then talk to the PHP box instead of slack, and it relay's the request/response back to the ESP.

@dandavis - I think you're spot on.  Reducing the amount of code in the Sketch and testing again makes it more reliable, but simply not enough still to ensure 100% bulletproof.  The response back from Slack is simply too large to handle.  I'm just going to use a Raspberry Pi to communicate with Slack, and then send the commands down to an Arduino.

@Axel, the PI actually also has GPIO pins (3.3V!) and should be able to handle basic I/O, so you might even consider letting out the Arduino.

@Paul - I actually ended up using a Raspberry PI Zero W which ended up having the memory requirements that could handle my API calls, and all the other functionality built such as WIFI and GPIO pins.  Not bad for a $10 board.

@Axel Arduino's are development boards for microcontrollers which is a quite different thing. If you're going to mass produce, using microcontrollers (the chip on the Arduino itself) works very well (stable, reliable, cheap, small).

@Paul - I understand the differences.  But coming back to the topic of my question - the Arduino board I was using did not have the memory requirements for the project I was building.  My issue had nothing to do with 3.3V GPIO pin availability as your first comment stated.  I already knew the Arduino had those :P

Also - this isn't for mass production.  It was a one-off project for personal use ;)

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

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


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

You may want something like this: https://www.coolcomponents.co.uk/en/sparkfun-servo-trigger.html . Notice that their firmware is licensed CC-BY-SA.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

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().

Thank you for your help.  It should get me going on the project.  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 wanted the gates to go down and stay down while the train passed.

I see how you are incrementally increasing or decreasing the servo position without going beyond the boundaries of the preset servo positions.  I am not sure, however, how to get the servo to stay in the assigned positions since the variables are reinitialized each time it goes through the loop.  Are some of these static variables?  Sorry if stupid questions.  New to Arduino programming.

@BobPerry, see edit.  Note, please upvote or accept answer if useful.

Thanks.  Setting up the variables as static didi the trick!


text:
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.`

I would suggest that things might be easier if you don't use the Arduino software. The AVR toolchain should work well in just about any *nix environment, as well as the command line programming tools.

The answer is s simple and plain yes. I know this is not a very useful answer, but you did not provide enough details about your problem to enable people to write useful answers.

Can I run Arduino commandline software on my Raspberry Pi? - what command line software are you referring to? The Arduino IDE has a GUI interface.

By "program the attiny85", do you mean "upload an already build program to the attiny85" or do you mean "build an executable program for attiny85 from source code", or both?

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.

"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

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 project which uses the ATtiny85 and the Arduino IDE to compile for it.
Here's my "board":

View from other side:

Code:
// 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:
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.

Although your answer is OK, I think it does not answer the main OP question: is it possible to program ATtiny85 chips on a Raspberry Pi?

Does the Pi not use Unix? The Arduino IDE runs under Unix. I run it myself under Ubuntu.

@jfpoilpret  The question was actually Can I run Arduino commandline software on my Raspberry Pi? - what Arduino commandline software?

Well I would say this one: https://github.com/arduino/Arduino/blob/master/build/shared/manpage.adoc

That's because you are bypassing all of the bloat by adding your own main() function. Try doing the same with loop() instead you'll end up with 326 bytes - that's a 400% overhead on top of the simple one. But also you are using direct port access rather than digitalWrite() which is again bypassing the bloat. Try doing digitalWrite() in loop() and you'll end up with 812 bytes - a 1200% overhead! Tell me, would you consider that bloat?

@TomCarpenter - as I said, functions like digitalWrite allow for a variable pin number to be passed, as opposed to a constant. For that to be looked up at runtime takes code. It is designed to be beginner-friendly. If you don't want to use those functions, then don't.

Unix can be different binary-wise, hence one executable running on a PC Linux might not be able to run on an ARM Linux. It does not seem so obvious to use the AVR buildchain (itself used by Arduino) on a Respberry Pi.

Well I would say this one - that wasn't referenced in the question. I am not assuming that is what the OP is on about.

@TomCarpenter Tell me, would you consider that bloat? - not really. You are asking if 246 bytes of code, which allow you to pass a variable rather than a constant is bloat? No, code which does something has to take space.

If I write some code that takes 16 bytes, and you can rewrite it to take 8 bytes, you can say that my code is 100% bloated. But it's only 8 bytes longer! You need to distinguish between percentages and actual values.

Like, if country X has one murder per year, and next year it has two murders, you can say that the number of murders doubled! Shock, horror, employ more police! But, it's only one more murder.

Guys, your comments seem totally unrelated to the original question. The OP did not even mention "bloated".

@NickGammon but we aren't taking about 1 or 2 bytes, we are talking about 10% of the ATTiny85 flash! And on a relatively slow MCU those extra instructions are bloated in speed as well. At 8MHz direct port manipulation will take 250ns, whereas digitalWrite will take about 30us, which again is a massive overhead. I understand the reason behind the abstraction, but I think the point was it's very costly on very small MCUs.

Yes, but if you abandon the IDE, you also abandon digitalWrite. My point was that you can abandon digitalWrite and still use the IDE.


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

Well, theoretically that should work, so what is the problem? You want something mobile? You'll most likely need batteries or an accu-pack.

@Paul Oh there isnt really a problem, just looking for other suggestions :) Havent bought the 4x AA holders yet, as its easter! Happy easter by the way!!

Okay, (Arduino) StackExchange is aimed on helping people who run into problems. We prefer questions that can be answered and that aren't to broad. Your question should give more of a clue on what you're trying to achieve etc. You could/should also do some research yourself.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

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 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 (PC power supply)
Adjustable step down module

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, 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 that focusses on some (analog) points that I didn't mention.*

Thanks for replying, i am following the sparkfun article; The batteries i am using are 2100mAh so 2.1A for one hour (which is enough for my project), and the battery supplies 1.5V. This gives a total power of 3.15W for one battery. The servos I am using have a stall current of 600mA and a stall torque of 4.8V, which = 2.88W and11.52W for all 4 servos. so 11.52W/3.15W = 3.67, so does this mean that it should be sufficient to use 4 of my AA batteries to power my servos

You'll need 3x batteries in series, to get the 4.5V. If the batteries can discharge at 1C (2,1A) and 4x 0,6 = 2,4A you really are on the low end. Maybe two rows of three in series. But a lot of accupacks are made for RC applications and fall inbetween the min/max of servo's and can deliver enough power. (If it's on a table next to your 3D printer, why not use a 5V adapter?)


text:
Why digital pin not reading ON from push button switches connected to 5V and pull-down 10K resistor?
Here's my circuit:

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.

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

Comments are not for extended discussion; this conversation has been moved to chat.

What if you use an empty breadboard and put in a button and resistor only? And make your code print the button state over and over?

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

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.


text:
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,"%02d/%02d/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,"%02d:%02d:%02d",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 .

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.

how can i make use of dtostrf() function in my url (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);.Can u explain it with my example

You could use format %s to insert the string, or you could not use sprintf() at all and build it up piecemeal using strcat(), etc.

it works fine!!

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.

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;
...

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.%07d", deg, decimals );

Then format this into the url array with %s:
sprintf( url, " ... &lat=%s&...", ... , lat, ... );

That gives you 7 decimals, like 9.7451145


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

I just used 2 AA batteries and it worked fine.

6V is no problem for the Uno.  It likes 7-9 volts better (to keep the regulator chip cool) but can go from 5-12 volts.

Welcome to Arduino SE.  Be sure to take the tour at https://arduino.stackexchange.com/Tour

If you take a look at Attiny45 datasheet, 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.