text:
How to make battery last for months?
I have a simple circuit: detect that a person is walking towards the circuit (with HC-SR04), measure distance, light diodes (a wave effect) according to that distance – the closer, the faster the led wave.
When no person detected, sleep longer:
LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);

When person detected, sleep shorter (so that diodes can be often turned on/off):
LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);

Without LowPower use – delay() used instead – the current taken is 15 mA. This is with diodes off. After using LowPower – it's still ~15 mA. This is very disappointing. I've expected the battery to last at least for 3 months, but it (9V) was drained within hours. Am I missing something?
Also a curiosity: the execution was fully blocking itself on LowPower calls, I've had to add short delay() before the calls, then they don't block execution.
#include <LowPower.h>
#include <NewPing.h>

#define trigPin 13
#define echoPin 12

NewPing sonar(trigPin, echoPin, 250);

// Defines speed of LEDs traversal
int delayTime = 40;

// Current led
int currentLED = 0;

// Direction of travel over LEDs
int dir = 1;

// Stores the last time LEDs were changed
unsigned long timeChanged = 0;

// Stores the last time sensor was read
unsigned long timeOfQuery = 0;

// LEDs
byte ledPin[] = { 4, 5, 6, 7, 8, 9, 10, 11 };

// Stores if any diodes are on
int leds_used = 1;

// Stores if wave is active
int off = 1;

// 5 last distances, circular buffer;
long distances[7] = { 400, 400, 400, 400, 400, 400, 400 }, currentDistance = 0;

// Last chosen distance
long distance = 400;

void setup() {
  Serial.begin (9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  for (int x = 0; x < 8; x++) {
    pinMode(ledPin[x], OUTPUT);
  }
  timeChanged = millis();
}

void loop() {
  long duration, cur_time, cm;

  cur_time = millis();

  /* Read distance when off, or when some time passed */
  if (off || (!off && (cur_time - timeOfQuery) > 100)) {
    timeOfQuery = cur_time;

    cm = sonar.ping_cm();
    if ( cm == 0 ) {
      cm = 400;
    }

    distances[(++currentDistance) % 7] = cm;
    // At least 1 proper distance?
    off = 1;
    for (int i = 0; i < 7; i++) {
      if (distances[i] <= 200) {
        off = 0;
        // Remember minimum distance
        if (distances[i] < distance) {
          distance = distances[i];

        }
      }
    }
    delayTime = distance;
  }

  if (!off) {
    // Check whether it has been long enough
    if ((cur_time - timeChanged) > delayTime) {

      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }

      // Turn on the current LED
      digitalWrite(ledPin[currentLED], HIGH);

      // Mark that diodes are being used
      leds_used = 1;

      // Increment by the direction value
      currentLED += dir;

      // If we are at the end of a row, change direction
      if (currentLED == 7) {
        dir = -1;
      }
      if (currentLED == 0) {
        dir = 1;
      }

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Shorter delay when sleeping
    delay(5);
    LowPower.powerDown(SLEEP_30MS, ADC_OFF, BOD_OFF);
    //delay(50);
  } else {
    if (leds_used) {
      // Turn off all of the LEDs
      for (int x = 0; x < 8; x++) {
        digitalWrite(ledPin[x], LOW);
      }
      currentLED = 0;
      dir = 1;
      leds_used = 0;

      // Store the current time as the time we last changed LEDs
      timeChanged = cur_time;
    }

    // Longer delay when sleeping
    delay(10);
    LowPower.powerDown(SLEEP_250MS, ADC_OFF, BOD_OFF);
    //delay(200);
  }

  /*
    if (distance >= 200 || distance <= 0) {
      Serial.print(distance);
      Serial.println(" Out of range");
    }
    else {
      Serial.print(distance);
      Serial.println(" cm");
    }
  */
}

Update: The board is Arduino UNO.

Are you using an Arduino board or are you using an MCU directly on a breadboard? Could you mention which board/MCU you are using?

@jfpoilpret: It's UNO

Are your other questions answered? It's allowed to ask multiple questions, but don't forget to accept answers and/or give feedback on your other questions' answers.

Please see http://arduino.stackexchange.com/questions/18759/powering-the-arduino-uno/18760#18760

The Arduino UNO always consumes current mainly because:

it has 2 MCU, the ATmega328 which you can power down, and an ATmega16u2 for USB communication which is never powered down.
in addition, the voltage regulator is permanently leaking some current

To be honest, I am surprised your UNO consumes only 15mA, on my boards, it is rather near 40-50mA.
Also, a 9V battery is probably the battery with the smallest charge capacity.
I would suggest you:

work on a breadboard with just the ATmega328,
power it with two 1.5V batteries (AA or AAA)
and run @8MHz

That should already reduce current consumption.
You may even try smaller MCU (e.g. ATtiny84A) which consumes less current than the ATmega328 in the same conditions.
Finally, I highly recommend Nick Gammon's blog on that topic. It includes many good tricks to help you with current consumption.

I work with some radio microphones on a regular basis. We have two sets - old ones and new ones. The old ones use 9V batteries and the batteries often need changing mid concert. The new ones use two AA batteries each, and last for many concerts before they need changing. The difference is staggering.


text:
Get data from website with ESP8266 using AT commands
I'm trying to get data from a website by sending a HTTP GET request via AT commands for the ESP8266. Here is my current code:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

Running this code I get the following response:
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,

It looks like it gets a response, but nothing is printed.
I tried doing the same thing by sending the AT commands manually using this code:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;
SoftwareSerial ESP8266 (rxPin, txPin);

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

void loop() {
  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }
  if (Serial.available()) {
    ESP8266.write(Serial.read());
  }
}

With this approach I actually get a response:
AT+CIPMUX=1

OK
AT+CIPSTART=4,"TCP","192.168.1.19",80
4,CONNECT

OK
AT+CIPSEND=4,27

OK
>
Recv 27 bytes

SEND OK

+IPD,4,275:HTTP/1.1 200 OK
Date: Thu, 22 Dec 2016 20:20:47 GMT
Server: Apache/2.4.23 (Win64) PHP/5.6.25
Last-Modified: Thu, 22 Dec 2016 19:37:22 GMT
ETag: "13-5444465f69339"
Accept-Ranges: bytes
Content-Length: 19
Connection: close
Content-Type: text/html

THIS IS MY WEBSITE!4,CLOSED

Does anyone know what is happening and how I can get this to work with my Arduino code?
Other ways to get data from a website are also welcome.

This has been bugging me for days - it seems to simple!  Since you don't have any replies that, here's my suggestion: is your printResponse() function working as expected?  It relies on all the data being available at the time time (more or less) and on it ending with a \n.  If it comes a bit at a time, it'll terminate early.  If the data doesn't end with a \n it will never end.

I'm studying the esp and the at commands and I can't seem to figure out the cipsend get request, I wonder if its because of the data length, I saw u summd 4 in the end of the length, is it because of the \r\n, or why is it? thanks

@RodolfoAlbuquerque Yes, as far as i can remember, the extra 4 bytes are for the "\r\n".

hey I am trying your code but i am getting the whole css html file not the main contain.

As pointed out in the first comment, my printResponse() function was not working correctly when waiting for a response from a website. I changed my code to the following, and now it seems to work every time.
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis > 30000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.1.19\",80");
    delay(1000);
    printResponse();

    String cmd = "GET /test.html HTTP/1.1";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

Slightly modified code. With the addition of a more correct query
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

unsigned long lastTimeMillis = 0;

void setup() {
  Serial.begin(9600);
  ESP8266.begin(9600);
  delay(2000);
}

void printResponse() {
  while (ESP8266.available()) {
    Serial.println(ESP8266.readStringUntil('\n'));
  }
}

void loop() {

  if (millis() - lastTimeMillis < 3000) {
    lastTimeMillis = millis();

    ESP8266.println("AT+CIPMUX=1");
    delay(1000);
    printResponse();

    ESP8266.println("AT+CIPSTART=4,\"TCP\",\"192.168.0.79\",80");
    delay(1000);
    printResponse();

    String cmd = "GET / HTTP/1.1\r\nHost: 192.168.0.79\r\nConnection: close\r\n\r\n";
    ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
    delay(1000);

    ESP8266.println(cmd);
    delay(1000);
    ESP8266.println("");
  }

  if (ESP8266.available()) {
    Serial.write(ESP8266.read());
  }

}

source: Stack Exchange

license: 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/

sort: votes


text:
Connecting Something Big to an Arduino - Sending more than 5V
So I am turning a relay on and off with my Arduino. I am using python to control it but wrote the simple basic code in the Arduino IDE. I am able to send 5 or 0 volts to the pin. My question is, how can I turn something on and off that requires more than 5 volts to turn on?
Thank you.

Many relays are controlled w a 5v signal, yet switch 120-240 volts on the second set of contacts.

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


text:
How do I initialize a servo object in my own library?
I'm trying to make my first library for Arduino and want to use a servo object in my library. How can I do this?

Welcome to Arduino SE! First of all, getting frustrated isn't going to get you anywhere. I understand it can be painful coding sometimes with problems, but it's easier to get help with a calm tone. Secondly, do you mean like creating an object like Servo myservohere; within your library and using that object within your main code?

Yes! Is that possible?

Important point: do you intend to create a C++ library i.e. with one -or more- class, which would then encapsulate a servo object?

It would be good to post some code to your question, showing what you have already done so far, and more importantly what part of the current code you would want to put into your own library.

Considering the fact you are a young hobbyist, I will first ask the question "do you absolutely need to write a library?". Writing libraries for Arduino generally comes in a second stage after writing several sketches, and it requires a good understanding of the language used by Arduino (C++).

This should give you an idea of how to create a custom library which you can use in your project. I actually compiled it with Arduino IDE 1.0.5 on Mac OsX.
I did not run it on an Arduino board, but have similar code in a production project, that works just fine.
Start a new Arduino sketch, name it as you like.
Go to the folder where you saved that file.
Add a new file called MyServoLib.h parallel to your main project file.
In your main file, include the servo library from Arduino and your custom library like so:
#include <Servo.h>
#include "MyNewLib.h"

If you close and reopen your project, it the Arduino IDE will automatically load your custom library file as well.
Copy the following simple stub code into your custom library file:
#ifndef MY_SERVO_LIB_H__
#define  MY_SERVO_LIB_H__

#include <Servo.h>
#include <Arduino.h>

class MyServoLib
{
public:

  MyServoLib()
    : _servoPin(9)
    , _attached(false)
  {}

  void attach()
  {
    if (_attached)
      return;

    _attached = true;
    _servo.attach(_servoPin);
  }

  void detach()
  {
      if (! _attached)
          return;

      _attached = false;
      _servo.detach();
  }

  void setPin(int pin){
    _servoPin = pin;
  }

private:

  bool _attached;
  Servo _servo;
  int _servoPin;

};

#endif

Your main file should look like this:
#include <Servo.h>
#include "MyNewLib.h"

// use your custom lib here
MyServoLib myServo;
int MyServoPin = 5;

void setup(){

  pinMode(MyServoPin, OUTPUT);
  myServo.setPin(MyServoPin);
  myServo.attach();

  // your additional setup code here
}

void loop(){

  // your main code here

}

That's it!
Upload it to an Arduino board and give it a try. The servo won't move, but it should get powered on.

This is a simple solution. All you need to do is declare a global variable (i.e. make it accessible everywhere in your sketch), and then add some additional code to "share" the servo between the different parts of the code.
Code you need:
Your library:
Servo servoname;
void foo() {
  //Some code here!
}

void bar() {
  //More code here!
}

The methods foo() and bar() are irreverent to the code, you just need to declare it.
Your library header file (name.h):
extern Servo servoname;

All you need to do then is import your new library and use servoname. You will have to still call servoname.attach([pin]); before you can use the servo, but then you just need to use the servo.
Source

when I do that I get an error: "Servo does not name a type"

@Zack Have you imported the servo library into your library? I can't help you without any code...

If your question is about including library A inside library B and then including library B in your main program, then you need to be aware of a limitation of Arduino IDE (discussed in this answer to a similar question).
Arduino IDE (at least 1.0.x, I have not checked with 1.5) for an obscure reason will not include libraries included by other libraries.
The only way to work around this issue is to include ALL libraries (direct and indirect) in your main program file (.ino file):
// Needed by library "B"
#include "A.h"
// Needed by your program
#include "B.h"

void setup() {
    // You can use B stuff here
}

void loop() {
    // You can use B stuff here
}

Another workaround is to trash Arduino IDE and use a better (I mean a real) IDE: many good options have been discussed in this question.


text:
USB MIDI HID with the ATmega32u4?
There are existing projects that allow the Uno and other devices using the ATmega8u2 to operate as a USB MIDI HID, such as MocoLUFA. Unfortunately, as far as I am aware, these require uploading new firmware that isn't compatible with programming via the Arduino UI.
Are there any similar projects for the ATmega32u4 (Leonardo, Micro)?
Is it possible to use an Arduino as a USB MIDI HID, while still being able to program it as normal?

Note that even with a custom boot loader and in circuit programming with a hardware programmer, you can still use the Arduino IDE to upload, and all libraries should work as normal.

The teensy series from pjrc.com allows USB MIDI natively (full USB speed!).  It works well and does not require any firmware tomfoolery.  It can also do HID keyboard/mouse/joystick natively as well.
There's the 2.0, which is 32u4, and the 2.0++ which has more pins and memory.  If you want to step off the Atmel reservation the teensy 3.0 and 3.1 have more speed and memory; in a couple of weeks they are coming out with a Teensy LC which is a 3 with less bells and whistles for cheaper.


text:
If statement behaves erratically
I connected the output from an encoder motor to int0. this is used to increment a counter at every pulse. in the loop(), I check this counter and stops the motor if it is above certain value. But this "if statement" works erratically. The while loop should break at 380, but sometimes it breaks at 256.
Serial.print(cnt);
cnt=0;
Serial.print("  ");
Serial.print(cnt);
motor1_up(255);
motor2_up(255);
while(1)
{
    if(cnt>380)
    {
        Serial.print(" break ");
        Serial.print(cnt);
        break;
    }
}
motor1_down(255);
motor2_down(255);
Serial.print("  ");
delay(40);
Serial.println(cnt);
motor1_down(0);
motor2_down(0);
delay(2000);

Here is the serial output
 1  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389
 396  0 break 381  389
 396  0 break 256  264
 270  0 break 381  389
 397  0 break 381  390
 396  0 break 381  389
 397  0 break 381  389
 396  0 break 256  264
 271  0 break 381  389

Welcome to Arduino SE! It's really hard to answer this question with such a small code snippet. It's fine if you've isolated the problem, but you don't explain the code much. For example, what is the motor1_down() for? It's fine to remove snippets that aren't useful (i.e. polling from a light sensor in this scenario), but it's generally helpful to have all the libraries/methods/etc. Can you please edit your code? Thanks!

I've just come back to have another look at this. It is very unclear what it is you are doing. Is this an ISR? If so, you've go a locking while(1) in there. If it's not, then when does this get called? Please post the full code

@madivad I guess that for a rotary encoder you have no other option than use interrupts, otherwise you may miss ticks, depending on the encoder steps and the motor RPM. However, the posted code is obviously part of loop().

Ok, I see it now, I misread the question (and so I have removed my answer).

Not only must cnt variable be declared volatile, but accessing it from the main loop must also be protected because:

it can be modified by an ISR
it is longer than 1 byte

In AVR architecture (8-bits), read/write operations on bytes are guaranteed to be atomic, i.e. no function can access a byte while it is read/written by an ISR.
However, operations on types larger than bytes are not atomic!
This means that reading e.g. an int variable from your main loop might be interrupted in the middle of the operation (only 1 byte read) by an ISR that could modify the value (both bytes this time); then when the ISR is finished the main loop would resume reading the second byte -modified by the ISR- of the variable, while keeping the first original byte -not modified by the ISR.
I would advise you to write a pair of functions to read and write cnt in a protected way, i.e. with interrupts disabled:
volatile int cnt;

void set_cnt(int val) {
    uint8_t status = SREG;
    cli();
    cnt = val;
    SREG = status;
}

int get_cnt() {
    uint8_t status = SREG;
    cli();
    int val = cnt;
    SREG = status;
    return val;
}

What those functions do are:

get the current status of exceptions (from SREG register)
disable exceptions with cli()
access cnt without any risk of it being accessed concurrently
restore initial status of exceptions (to SREG register)

Everywhere in your code (except in code called from an ISR where it is not necessary), you must then call these functions to access cnt variable.

It looks like it could be a caching issue. If you're accessing a variable from the main loop and from an interrupt handler, then you need to ensure it's declared as volatile. For example:
volatile int cnt = 0;

That tells the compiler that the contents of the variable could change unexpectedly, i.e. when an Interrupt Service Routine is triggered. The result is that it always fetches the actual value from RAM, instead of relying on a cached copy which could be out-of-date.


text:
Resend data traffic from an Arduino
I have an Arduino with an Ethernet shield and I want to capture all Ethernet data traffic that connects to the Arduino via [as?] a router. This is because I want to use the Arduino like a honeypot and at the same time resend the Ethernet traffic to the Raspberry, but only specific TCP traffic instead of UDP.
In other words, I want to resend all of the traffic data from an Arduino to a Raspberry Pi, but I need to only resend all of the TCP traffic because the Raspberry reads and parses this. However, I only see examples of UDP traffic but nothing related to TCP. It doesn't matter what kind of port the Arduino listens on, I just need the data out of the other side, can you help me?

I am sorry, I am having a hard time understanding what you are asking here (I am guessing a language barrier). Can you clarify what it is you are trying to achieve? What traffic are you referring to - how does the arduino receive it? What form does it take?

Your question statement doesn't make a lot of sense, but I have to wonder at your design.  Given that a conventional Arduino has no network interface, and is terribly short on resources to deal with network traffic at all, it really makes little sense to connect a network to the Arduino, rather than directly to the pi.

Sorry, my english is not as well as I want, I am spanish user...well, I have an arduino with its ethernetshield, I want to capture all ethernet data traffic that connects to arduino since a router because I want to use the arduino like honeypot and at the same time resend the ethernet traffic to raspberry, but specific TCP traffic instead of UDP, I don't now If your are understand me, sorry.

I have tried to reword your question, although a few points remain unclear: when you say since a router ("desde un router"?) do you mean that you have the Pi and the Arduino both connected to a router? Or are you using the Arduino as a router/filter to filter the traffic and only resending TCP traffic on to the Pi? To do the latter, you would need two Ethernet shields, one for the incoming UDP and TCP packets and one for the outgoing TCP packets that will go to the Pi. You would also need to use a hub, and not a switch or router as otherwise the Arduino will only see traffic intended for it.

Also, can you post your sketch that you are using with the Arduino, to filter the packets, and also a network diagram to clarify how you have the Pi and the Arduino (and the router (if there is one) and the rest of the network) connected? As it stands your question is rather unclear and is likely to be closed, unless your provide clearer information and the sketch and the network diagram to illustrate what you actually mean.


text:
Printing decimal numbers
I made simple sketch that generates three random numbers and then calculates the average of these three random numbers.
It divides the total by 3 and then displays that average number with serial.println.
Sometimes the generated average number can be decimal (for example 261,333333 or 124,33333).
Interestingly, the serial print doesn't print in decimal format 124,33333
it prints just integer 124.
How do I print the value in decimal?

Please show your code. Without that we can't help you.

Please edit your question, and post your code. How have you declared your variables, as ints or floats?

In languages such as C or C++ there is a distinction between integer types and floating-point types. You see, computers work using bits. A bit is either 0 or 1. A bit obviously lack in both range and precision, so we combine multiple bits in order to improve.
Integral Types
A byte is a group of 8 bits. In C, the type used is either
uint8_t x; // Values from 0 to 255.
int8_t  x; // Values from -128 to 127
char    x; // Values from the ASCII character set (still -128 to 127)

On Ardiuno Uno, an int is a group of 16 bits:
uint16_t c; // Values from 0 to 2^16-1 = 65535, synonym: unsigned int (Arduino)
int16_t  c; // Values from -32768 to 32767,     synonym: int (Arduino)

A long is a group of 32 bits:
uint32_t v; // Values from 0 to 2^32-1 = 4,294,967,295 = 4 GiB (unsigned long)
int32_t  v; // Values from -2,147,483,648 to 2,147,483,647 (long)

There is also usually support for 64-bit numbers, but we try not to use them in Arduino code. The reason is that most Arduino MCUs use 8-bit registers, so 64-bit operations such as "add", "sub", etc. would be very slow.
Note: Different architectures use different numbers of bits for these types. In order to be compatible with other architectures, use int32_t etc. to be sure.
Literals and Casts
Oftentimes, the compiler can not see what type a literal value is supposed to be. In C, the compiler picks a default which is usually larger than you would like. For this reason, it is useful to know how to specify a literal exactly with the type:
 ((uint8_t)200)   // Casting 200 to an unsigned 8-bit integer
 ((char)65)       // Making the ASCII letter 'A'
 ((int32_t)42)    // Force 32 as a signed 32-bit integer (long)
 42L              // The 'L' suffix does the same as above

Division and Remainder
A common cause of problems when programming in C is the division operator /. If the operands are both integer types, the result will also be an integer. So 1/3 is in fact 0. You can get the remainder of the division using the modulus operation %. For instance:
void show_division(int n, int d)
{
    Serial.print("The division: ");
    Serial.print(n);
    Serial.print(" / ");
    Serial.print(d);
    Serial.print(" equals ");
    Serial.print(n / d);
    Serial.print(" with a remainder ");
    Serial.println(n % d);
}

Floating-point Types
All of the above types are integrals, so they do not support any fractional value. Therefore C defines two different floating-point types: float and double. The former is a 32-bit value and the latter is a 64-bit value. The way it works is that the bits are split in 3:

A single bit is used for the sign.
A certain number of bits represent the fractional part, the mantissa.
The rest of the bits are used for the exponent.

As an example, the 32-bit float value representation for 1.25 is
seeeeeee_emmmmmmm_mmmmmmmm_mmmmmmmm = s * 2^(e-127) * (1.m...)_2
00111111_10100000_00000000_00000000 = (+1) * 2^(127-127) * (1.0100)_2
// Note: Binary 1.01 equals 1.25 in decimal

For performance, use the f suffix
Although 64-bit doubles are very accurate, the resulting code will run much slower. I, therefore, recommend using 32-bit floats instead. It is useful to know that you can tack on an f after the floating-point literal:
(a + b + c) / 3.0f; // Make sure to divide using 32-bit operations.

If a, b and c above are integer types, the additions will also be integer additions. When the compiler sees an int divided by a float, it will convert the int to a float, and then perform a float division. This is slow, but certainly faster than a double division.
The compiler is smart, but it doesn't hurt to help it. There is only a very small precision loss in converting this to a float multiplication:
(a + b + c) * (1.0f / 3.0f);

The compiler will pre-calculate (1.0f / 3.0f), so you get a much faster floating-point multiplication (in addition to the int to float cast).
Note: Arduino Uno defaults all floating point literals to 32-bit, and double is the same as float. Therefore, the f suffix is strictly not needed. It is still good practice to add these for compatibility with other architectures.

Your answer would be correct on many CPU architectures. However, the question is tagged “arduino-uno”, which implies an AVR architecture, and there are three specific details in your answer which are incorrect in this specific architecture: 1) chars are signed. 2) ints are 16 bits, not 32. 3) doubles are 32 bits, just like floats. Then, obviously, the f suffix has no effect at all. Could you please fix your answer?

Thanks, I will. Note though, that I do mention that in the int section.

In the C family of languages, if you divide an integer by another
integer, the compiler interprets the division operator (/) as an
integer division, i.e. you get the integer part of the quotient. Thus,
(first_int + second_int + third_int) / 3

is an integer.
If either operand is a floating point number, then the other one is
implicitly converted to floating point, and you get a floating point
division. Thus
(first_int + second_int + third_int) / 3.0

is a floating point number, and the result you expect.

shouldn't one of your variables in the second code line be a float? All ints divided will still be an int

3.0, as any constant having a decimal point, is a floating point number. As opposed to 3, which is an int.


text:
Oddness with #define and #ifdef in a sketch
I'm putting together a simple sketch to read a few sensors and have come across some odd behaviour associated with #define and #ifdef.
Here are some snippets from my code:
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

With this snippet the rest of the sketch compiles, but with this:
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
#endif

The compile fails, claiming that the error is in some functions further down.
BTW, Mth, Day and TMZ are not used anywhere yet, not are they defined anywhere else.  What is even more odd is that the error messages are announcing the erroneous line numbers to be about 12 lines removed from where they really exist in the sketch, and have no association with the declarations here.
Now, this gives a clean compile:
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

as does this:
// Defines
//#define DEBUG 1
#define ACCELEROMETER 1
#define GYROSCOPE 1
//#define GPSSYSTEM 1
//#ifdef GPSSYSTEM
  unsigned int Mth=0;
  unsigned int Day=0;
  char TMZ[2];
//#endif

I've been chasing this weirdness for a day now and am getting nowhere.

It's hard to pinpoint the error withouth having the actual error and code. @ARK is right, but I'm not sure if that is the error you're looking at.

Try removing all and adding one define at a time to see who the problem child is. Additionally versions 3&4 compile because you're only defining three small variables. More color on errors would've been helpful

The #ifdef Directive you are using is one of Conditional
  Directive.
  This directive checks whether the identifier is currently defined.

In general, it has following syntax:
#ifdef identifier newline

For Arduino, you can modify your #ifdefs to following code:
#if defined(GPSSYSTEM)
    //Code here
#endif

Explaining your code snippets behaviors:

In your first code snippets, GPSSYSTEM has been defined by following line of code:
#define GPSSYSTEM 1

Now, For this code snippets, #ifdef GPSSYSTEM is true, and following variables are defined.
But, when you comment this #define GPSSYSTEM 1 line in your 2nd code snippets, GPSSYSTEM is no more defined and so #ifdef GPSSYSTEM is false, and thus following variables are not defined which result in compilation errors in your code.
Following same logic, behavior of your 3rd and 4th code snippets can be explained easily.


text:
Arduino Hello World in Serial monitor
Hi we were asked to program something which when i enter something in the serial monitor it prints Hello world but the catch is it only prints hello world under the conditions that your input in the serial monitor is a 3 bit input and after that i need to have a code which then stops it from printing over and over again.
my only problem is that i don't really know how to count the number of bits of an input and also to stop it from printing continuously.
void setup() {
  Serial.begin(9600);

}

void loop() {
  String readSerial;
    String input;
    while(Serial.available() > 0){// put your main code here, to run repeatedly:
    delay(2);
  input.concat(String((char)Serial.read()));
  return input;
  }
  Serial.println("HELLO WORLD");
}

Is this a school class assignment?

Please add your code.

Yes it is. And its also an assignment before the actual lesson

What exactly do you mean by 3-bit input? The serial interface only sends whole bytes. Is this about specific values in 3 of the 8 bits of a single byte?

it says here that 3 ready to be read character(bytes) is that 3 bits? or am is my assumption wrong?

Some separate comments: "// put your main code here, to run repeatedly:". This is a comment that belongs to the loop function, not to the while loop. Also "return input" is not an advised way of coding. One reason because return in the middle of a function is bad coding practice, but moreover it returns a type while the function (void) does not expect anything to return. I don't know what you want to program so I cannot give more useful comments.

Judging from the comments, you lag some basic knowledge. To really learn, what you are supposed to learn in this assignment, you should review your learning material or C/C++ and Arduino Tutorials on the web. Here I will only give you some hints with reasoning, that may help you in solving the assignments task. (Unfortunately it is not really clear, what exactly the task is here)

The Serial interface of the Arduino (an UART interface) sends the data in bytes, one at a time and one after another (hence the name serial). 1 byte is a series of 8 bits, each of them with a value of 1 or 0. Together the 8 bits form a value, that can also be expressed as a decimal value from 0 to 255. For example 01001011 is the binary equivalent of the decimal number 75. (For further explanations google the binary number system) The byte data can also be expressed as characters, as they are defined in the ASCII standard. Every binary value refers to a specific character. This is what happens in the serial monitor of the Arduino IDE. (For more explanations google ASCII)
Since the data is send serially, there may appear some delays in the transmission, which are unnoticeable by humans, but the Arduino is fast enough, so that the Serial.available() command may return 0, because at that moment a little delay in the transmission occurred. Hence it is important to catch the whole message, before trying to work with it. You can do this by either counting bytes (waiting until at least 3 bytes are available in the buffer) or by marking the end of the message with a special character (for example the newline character '\n'). There are a lot of tutorials on the web how to do both. You can start with Majenko's blog.
You can get the number of bytes, that were received, with the return value of Serial.available(). It will return 3, when there are 3 ready to be read bytes in the buffer.
If you define a variable inside the void loop(), it will be thrown away when the function ends and redefined, when the function starts again (In the Arduino world the void loop() function is called again and again forever). You will loose all content, that was written to this variable. If you want to persist data over the executions of the void loop() function, you can define the variable outside of any function at the top of your program. This variable is then global and will be defined only once at the start of the program and hold for the whole lifetime of the program.
As wrote in the comment you should not return a value from a void function, since void mostly means, that there is no return value. And returning from the void loop() function will only restart this function (since we are in the Arduino world).
You can ditch the delay(2). There is no need for it. And if it only works with the delay, then something else is not correct and you are just working with the symptoms instead with the real issue.

Also you should not try to build everything on your own and reinvent the wheel. Instead try to look at the examples, that come with the Arduino IDE. For example the SerialEvent example, which shows how to receive a serial message (which is ended by a newline character '\n'). Also have a look at the other related examples. If you understand, how they work, you will be able to do the assignment without any problem.

Hi again , i think  I'm close to getting it but one quick question is there anyway of resetting the serial.available(); value  and reverting it back to 0 ?

You can do Serial.read() without using the returned value, until Serial.available() returns 0.

Assuming that the sketch should print "Hello World" when the input character has 3 bits high. Here are a few different variants of counting the number of bits set in a byte.
int bits1(int c) {
  int res = 0;
  for (int i = 0; i < 8; i++) {
    if ((1 << i) & c) res = res + 1;
  }
  return (res);
}

int bits2(int c) {
  int m = 0x80;
  int res = 0;
  do {
    if (m & c) res++;
  } while (m >>= 1);
  return (res);
}

int bits3(int c) {
  int m = 0x80;
  int res = 0;
  do {
    res += (m & c) != 0;
  } while (m >>= 1);
  return (res);
}

#define bits4(c) __builtin_popcount(c)

#define bits bits4

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

void loop() {
  if (Serial.available() > 0) {
    int c = Serial.read();
    if (bits(c) == 3) {
      Serial.print((char) c);
      Serial.print(':');
      Serial.print(c, BIN);
      Serial.println(": Hello World");
    }
  }
}

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


text:
What is a simple way to measure the ambient light?
I want to install some LED stripes on my motorcycle, i.e. as brake light and indicators. I use WS2812 LED stripes which can be very bright - especially with many LEDs on at the same time.
I want to measure the ambient light so that in the bright sun I can light the LEDs with, let's say, 100%. But in the night maybe just with 30% intensity. I want to detect the ambient light to change the intensity.
I don't need high resolution and I don't need high speed. If the ambient light is measured i.e. once per second with 4 bit resolution that would be already good enough.
Which ambient light sensor (or photo diode or whatever) makes sense for this little project and how to connect it?
Does it make sense to use more than one light sensor for a better average ambient light value (just in case one sensor is in the shadow, another in the sun)?
I found these sensors form a Chinese supplier:
https://www.banggood.com/CJMCU-9930-APDS-9930-Digital-Proximity-And-Ambient-Light-Sensor-For-Arduino-p-1103139.html
https://www.banggood.com/GY-49-MAX44009-Ambient-Light-Sensor-Module-For-Arduino-p-1196674.html
But an I2C interface seems to be overkill for my simple project.
Any suggestions?

Perhaps a LDR and a 10k ohm resistor might work.

#define LDRpin A0
unsigned int LDRvalue = 0;

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

void loop(){
  LDRvalue = analogRead(LDRpin);
  Serial.println(LDRvalue);
  delay(1000);
}

Note that swapping the LDR and the resistor might make the wiring easier: you will just have to pull a single wire from the LDR to the Arduino, as the ground connection can be made through the chassis. And even if you pull two wires, you have an extra safety: an accidental short from the GDN wire to the chassis won't fry anything, whereas a short from +5V could burn the Arduino.

Thanks, that looks good. I just checked and it seems there are many types of this sensor 5506 / 5516 / 5526 / 5528 / 5537 / 5539 / 5549. The main difference seems to be the resistance. Min is 2~6kOhm for the GL5506, max is 45~140 kOhm for the GL5549. I guess they will all work with the correct fixed resistor. Any recommendation?

Different resistance + LDR combinations will all work - it's just a matter of what sensitivity it gives you to different light levels.

You can also use an LED. Connect the LED and its resistor between two port pins. Then, when you want to measure ambient light in your program, do this:

Make sure any pullups/pulldowns are disabled.
To discharge the LED, start with switching it on for a short moment (a clock cycle is enough) by setting the pins to output and setting anode high and cathode low.
Reverse the polarity by setting the anode pin low and the cathode pin high.
Set the cathode pin to input.
Using a timer and a pin change interrupt, measure the time it takes for the cathode pin to become low.

Since the capacity of the LED varies with light intensity, the time it takes for the LED to discharge through its resistor and the pin resistance is is an indication of light intensity.

Thanks, I saw that example. But somehow I think let LEDs do what they are designed for and use other parts (i.e. LDR from the answer above) for what they are designed for...

You're saying the functionality of a LED changes with external light intensity? What? How does that even work? Can you provide more details, or a citation, because this is really surprising to me.

@Benubird Turns out, there is a Wikipedia article about it: https://en.wikipedia.org/wiki/LED_circuit#LED_as_light_sensor

@Benubird In fact any semiconductor junction will function as a (poor quality) photodiode. There is nothing special about light emitting diodes, except that for non-light-emitting diodes that are not designed to be photodiodes, the junction is covered in opaque material to prevent the photoelectric effect happening. In some semiconductor devices, the opaque material is simply black paint which can be scraped off to make a photodiode!

@alephzero Wow, that is very cool! So OP doesn't need a separate sensor, they can just repurpose their LEDs. I wonder if anyone has built some sort of prepackaged auto-adjusting LED


text:
Hardware logic gates for a simple demo with LEDs
I need some logic gates for a simple demo like this one. I will use a regular breadboard and an Arduino UNO as a 5 V and GND supply.
I found these ICs from Texas Instruments SN74LSxxN (NOT, AND, OR, NAND, NOR, XOR). For my demo I only need two inputs (well obviously only one on NOT) and one output on each chip. I want to connect the output to a LED via resistor to demonstrate that for example 1 XOR 1 equals 0 (LED off), or NOT 0 equals 1 (LED on):

My LSs seem to work as expected without an LED connected:

int value;

void setup() {
 pinMode(10, OUTPUT);
 pinMode(11, OUTPUT);
 Serial.begin(1200);
}

void loop() {
 digitalWrite(10, LOW);
 digitalWrite(11, LOW);
 value = digitalRead(5);
 Serial.println(value);
}

…but it would be great to make an LED demo too.
These ICs are probably a better choice in my case?

SN74ACT04N (NOT)
SN74ACT08N (AND)
SN74ACT32N (OR)
SN74ACT00N (NAND)
CD74ACT02 (NOR)
SN74ACT86N (XOR)

For everyone who isn't happy with Arduino as power supply here an alternative circuit with the same question - which IC family should I use?

Update: Well, probably I should better use something like LogicBlocks for my demo.
There is no NOR, XOR or NAND in this set, but it should be much easier to handle.

No, that is not OK. Those chips have ±4mA outputs at 5V. You are asking around 15mA (depending on LED forward voltage).

Majenko could you recommend some suitable ones?

GeMir, you can increase the resistor, say to 2K, and see if you have enough brightness.  Some high-brightness LEDs are ok with up to about 15K series resistance at 5V.  Note, see Ohm's law.   5V/200Ω = 25 mA, too much for typical 74HC outputs to source. [Actually, the calc. should be (5V-Vled)/200]   5V/4mA = 1250Ω, so a 2KΩ is ok.  Or you could add a buffer to drive LEDs.

@jwpat 1.8 kΩ carbon ones?

GeMir, those should work ok.  The current calc. for red LEDs at say 1.6V drop would be (5-1.6)/1800 = .00188, a little less than 2 mA.  You could go as low as about 1K; (5-1.6)/1000 = .0034.  With white LEDs at say 3.4V, (5-3.4)/1000 = .0016 = 1.6 mA and (5-3.4)/470 = .0034 = 3.4 mA.  Anyhow, you don't need anything except a meter, an LED, a resistor, and a 5V supply to test if LEDs are bright enough at low enough current.

@jwpat7 Should I better change the family? The ACT family outputs are ±20mA.

You cannot drive only one gate on each chip. The other floating inputs could cause power issues, so tie them to one of the rails.

@IgnacioVazquez-Abrams sure, I'll use only two inputs and all other ones will be connected to GND. Thank you.

GeMir, first run a test with a meter, an LED, a resistor, and a 5V supply to see how much LED current you actually need.  If you need more than 3 or 4 mA, you could change families or use a buffer.  For example, run a 74HCxx output through an SN74ACT245, or through 2 inverters on an SN74ACT04.  Note, if you are only making one of these demo units, the chip costs might not be a factor; if you are making several, the 74ACT parts probably will cost several times as much as 74HC parts.

A 1k resistor will let around 3 mA through an LED with a 2V forward voltage drop (from a 5V source). On a test here with a cheap LED it was quite visible when on. (5 - 2) / 1000 = 0.003. See LED calculator site

@NickGammon I found something very similar to the demo I want to make on YouTube (see the first post above).

Note: Lengthy series of posts by the OP on the same issue on the Arduino Forum.

The circuit I was looking for looks like this:

And the HC family seems to do the job. Thanks to dlloyd (link).

I gather you have decided to source 9.7 mA from the 74HC08N output driver. Since the device is specified to provide ±4 mA I'm just curious to know why you did that? You are running at 243% of its documented ability.

@NickGammon It was dlloyd's recommendation, I've got HC- and ACT-family chips and use ACTs now.

The SN74HC04 has a documented output driver capability of ±4 mA when running at 5V:

Assuming you are using red LEDs with a forward voltage of 1.6V (as I measured one of mine lying around on the bench to be), then to not exceed this you need to get a resistor of:
(5 - 1.6) / 0.004 = 850 Ω

A reasonable (and safer) value would be a standard 1k resistor, which you are likely to have lying around (and if not, get a few hundred of them). That would give you 3.4 mA current through the output pin, which is in range.

I found something very similar to my demo on YouTube ...

Yes, well, people on YouTube aren't always doing things exactly like they should. :)
See Mike Cook's tutorial The care and feeding of LEDs. As he points out, a lot of people use the wrong, or no, resistors because "it seems to work".
It may well seem to work for a while, but if you want a design that will last for a long time, you work within the manufacturer's specifications.
The problem with people disseminating wrong information is that someone will then copy it, and repeat it, and before long you find people saying "everyone does it this way".

Thank you very much for your time and explanations! Since SN stands for "Texas Instruments" and there is no SN74ACT02N (NOR), shouldn't I look for CD74ACT04, CD74ACT08 etc. (I prefer buying parts of same manufacturer)?

Ok, found it. CD means "CMOS digital logiс IC". These chips were made by Harris Semiconductor.


text:
Using an external header file
I have a project that is part of a larger repository, and shares header files with non-Arduino C programs.
I know that it's possible to use these headers by copying them to the libraries folder, or the sketch folder, but I would rather use them with a relative path (which seems to not work), so I can avoid copying files around for every repository clone or update.
Is there a solution that doesn't involve moving/copying the header file?
EDIT:
Although there is no full solution for this question,
I have since found that using the PlatformIO
IDE instead solves the problem.

symlinks maybe?

I tried that using cygwin on windows.  The IDE didn't like it.

I use links. I link a folder into libraries folder. mklink on Windows

You can use header files with an absolute name, like:
#include "c:\Temp\x.h"

Another way that might help is to make the include path like:
#include "q:\x.h"

And use Windows to map driver letter Q to the path you need.

I guess that's better than nothing, but requires the repository to be cloned to a specific location, or changes to the code each time.

@Photon ... I tried using a define inside the include path to make that path variable, but that does not seem to work. I added another solution (mapping a drive letter). Than you need only one change.

Thanks.  I'll mark it as an answer, because it provides the best that can be done under the IDE limitations.

Thanks; and yes, it seems like a limitation of the IDE.

I tried to do this, and looked into it, a few years ago, but it doesn't appear to be possible to do what you want to do. This guy was having the same issue, #include statement with relative path.
Seems like either Michel's suggestion or copying them (which is a pain) will work, from Can I include a header file that is not a library?:

If the include file is part of a single Sketch, instructions are
  here... http://www.arduino.cc/en/Hacking/BuildProcess [new
  link]
If the include file is meant to be shared by multiple Sketches then...

Close the Arduino IDE
Navigate to the {Arduino}\hardware\libraries directory
Create a subdirectory.  I suggest something like MyCommon.
In the new subdirectory, create a header file.  I suggest something like MyCommon.h.
Open the new header file, edit it as you wish, and save it
Open the Arduino IDE
Create or open a Sketch
Add a #include to the top of the Sketch that references your new include file

This is why relative paths are not supported, from Re: how to include header file from previous folder?

Enable verbose mode when compiling. Navigate to the Testing.cpp file that is created from the Testing .ino file. Go up one level. Do you see the files you are trying to include?

and from Re: how to include header file from previous folder? (emphasis is mine)

The reason for having you go look at the something
  like/AppData/Local/Temp/build/sketch folder was
  to make you think about what the build process is doing, and maybe
  think that you could google Arduino + Build to get more details.
The IDE copies your sketch, and stuff #included by your sketch to a
  build directory.
If you #include , the file header.h, and everything else in
  the directory it is in, will be copied to the build directory, too.
If you #include "header.h", the file header.h, and everything else in
  the directory it is in, will be copied to the build directory, too.
The difference between <> and "" is where the header.h file is looked
  for. "" looks in the current directory. <> looks in the library
  directories.
If the token between the <> or the "" is not found in the appropriate
  folder, you are not told that; nothing gets copied, though.
But, that explains why relative names are useless. A sketch directory
  might contain a file called header.h. It will not contain a file
  called ..\header.h, because ..\header is NOT a valid file name.
Note that I did NOT say that ..\header.h is not a valid NAME. I said
  that it is not a valid FILE NAME.
Only file names between the <> or "" are possible, as far as the IDE
  is concerned.
If you do not like that, you are free to not use the IDE.

Finally from Re: How to specify a path to a specific header file?

The Arduino system has some severe limitations in its ability to work sensibly with the file system - can be a real PITA.

BTW, If you create multiple libraries in libraries folder, you can use relative reference path i.e in all Header files, you can use #include "..\mylib2\xxxx.h.


text:
ESP Wemos D1 upload fails
I try to upload simple code (e.g. blink.ino) to my ESP8266-12 (I have the WeMos D1 breakout board). Until now, that worked without a problem: I had to pull GPIO0 down and then I could upload the compiled sketch.
Since today that does not work any more - but I did not change anything.
I get:

error: espcomm_upload_mem failed

(I know that here are some questions / github issues out there that have the same error, but that was often because GPIO0 wasn't pulled down and the ESP was therefore not in FLASH mode.)
My config is: ESP8266, 80MHz, DIO, 115200, 512K (64K SPIFFS), ck, Serial
When I reset my board, having GPIO0 pulled down, the ESP sends this serial info:

ets Jan  8 2013,rst cause:2, boot mode:(1,7)

The whole debug output is:
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM6
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 228624 bytes from D:\Users\myusr\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037d10 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    read 0, requested 1
    setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
error: espcomm_upload_mem failed

As I found out, GPIO0 has to be LOW AND GPIO2 has to be HIGH. It is very important to use pin D3 as GPIO0 and pin D4 as GPIO2 at the WeMos D1 board, because this "routing" is different for other boards and therefore other digital pins are often described.

Very useful, upvoted.

@black What exactly did you do to solve the problem. Because I have almost exact problem. It was working fine. Suddenly It started to give this error. So I plugged every cable on wemos just as it is plain. Then using the Blink sketch even it is not uploaded without this problem. So what did you do?

I was facing the same problem, I simply updated CH34x driver for esp8266 to v1.4 from v1.3 after that I was able to see a new port option named usbserial 1420 & wchusbserial 1420. after selecting wchusbserial 1420 I was able to upload program successfully. As  my MacOs running on Mojave


text:
Efficient algorithm/data structure to calculate moving averages
Currently I am developing a graphic LCD system to display temperatures, flows, voltages, power and energy in a heat pump system. The use of a graphic LCD means that half of my SRAM and ~75% of my flash have been used up by a screen buffer and strings.
I am currently displaying min/max/average figures for energy At midnight when the daily figure resets, the system checks if the consumption for the day is above or below the previous minimum or maximum, and stores the value. The average is calculated by dividing the cumulative energy consumption by the number of days.
I would like to display the daily average over the last week and month (4 weeks for simplicity) i.e. a rolling average. Currently this involves maintaining an array of values for the last 28 days and calculating an average over the whole array for monthly and last 7 days for weekly.
Initially I was doing this using an array of floats (as the energy is in the form "12.12kWh"), but this was using 28 * 4 bytes = 112 bytes (5.4% of SRAM). I don't mind having only a single decimal point of resolution, so I changed to using uint16_t and multiplying the figure by 100. This means that 12.12 is represented as 1212, and I divide by 100 for display purposes.
The size of the array is now down to 56 bytes (much better!).
There is no trivial way to reduce the figure down to a uint8_t that I can see. I could tolerate the loss of a decimal place ("12.1kWh" instead of "12.12kWh"), but consumption is frequently higher than 25.5kWh (255 being the highest value represented by a 8-bit unsigned integer). Consumption has never been below 10.0kWh or above 35.0kWh, so conceivably I could subtract 10 from the stored figures, but I know that one day we will exceed these limits.
I then tested code to pack 9-bit values into an array. This gives a range of 0-51.2kWh and uses 32 bytes in total. However, accessing an array like this is pretty slow, especially when you have to iterate over all values to calculate an average.
So my question is - is there a more efficient way of calculating a moving average with three windows - lifetime, 28 days and 7 days? Efficiency means smaller in terms of SRAM usage, but without the penalty of huge code. Can I avoid storing all values?

Do you want to calculate a moving average over specific windows or an estimate/approximation of the average would do?

I want a moving average over a 7 day and 28 day window.

you could use a resolution of 0.2kWh (divide and multiply with factor 5) and you still get 0-51.2kWh range in 8 bits

You might end up putting strings and other constants in external RAM or external Flash -- see "What can I do if I run out of Flash memory or SRAM?".

If your data has low standard deviation, then one method would be to sum values over the window, and then keep subtracting the mean from the sum, while adding the new value.
This would work well if there are no outliers, thereby leading to the aggregate error tending to zero over time.
//Pseudocode

count=0
while new_reading and count<7:
    sum += new_reading        //Calculate the sum of first 7 values
    count++

while new_reading:            //Loop till new readings available
    avg = sum / 7             //Calculate average
    sum -= avg                //Subtract average from sum
    sum += new_reading        //Add next reading to sum
    print avg

you can use a different method, you keep the current average and then do
average = (weight1*average+weight2*new_value)/(weight1+weight2);

it's not a true rolling average and has different semantics, but it may fit your needs nonetheless
for a more efficient calculation method for your 9 bits per value solution you could keep the 8 highest bits of the values in an array and separate out the least significant bits:
uint8_t[28] highbits;
uint32_t lowbits;

to set a value you need to split it out
void getvalue(uint8_t index, uint16_t value){
    highbits[index] = value>>1;
    uint32_t flag = (value & 1)<<index;
    highbits|=flag;
    highbits&=~flag;
}

resulting in 2 shifts an AND and an OR and a not
to calculate the average you can use various bit tricks to speed it up:
uint16_t getAverage(){
    uint16_t sum=0;
    for(uint8_t i=0;i<28;i++){
        sum+=highbits[i];
    }
    sum<<=1;//multiply by 2 after the loop
    sum+=bitcount(lowbits);
    return sum/28;
}

you can use an efficient parallel bitcount for the bitcount()

Can you explain more how this would allow me to calculate the 7 and 28 day average?

I've used this approach for smoothing noisy analog values before, and it was certainly fairly effective. I didn't need a lot of precision though, as the resulting values were being put through a very coarse quantiser. I also didn't need historical averages.

This doesnt allow calculating the average for a specific window.

@Cybergibbons you can use different weights to approximate the window so old values become insignificant earlier or later, or keep 7 days for the 7 day window and this moving average for the 28 day average

How about only storing the difference from the previous value? In electronics there is a similar concept called Delta Sigma converter, which is used for DA/AD converters. It relies on the fact that the previous measurement is reasonably near the current one.

Another interesting idea. Unfortunately I am not sure energy consumption will always be like this, as it is a heat pump system and one day could take 30kWh, the next 10kWh. I really need to gather data and see.

is there a more efficient way of calculating a moving average with
  ... 28 days and 7 days?
  ...
  needing to remember 27 days of history ... ?

You might get close enough storing 11 values rather than 28 values,
perhaps something like:
// untested code
// static variables
uint16_t daily_energy[7]; // perhaps in units of 0.01 kWh ?
uint16_t weekly_energy[4]; // perhaps in units of 0.1 kWh ?

void print_week_status(){
    Serial.print( F("last week's total energy :") );
    Serial.println( weekly_energy[0] );
    int sum = 0;
    for( int i=0; i<4; i++ ){
        sum += weekly_energy[i];
    };
    Serial.print( F("Total energy over last 4 complete weeks :") );
    Serial.println( sum );
    int average_weekly_energy = sum/4;
    int average_daily_energy = average_weekly_energy/7;
    Serial.print( F("Average daily energy over last 4 weeks :") );
    Serial.println( average_daily_energy );
}
void print_day_status(){
    Serial.print( F("Yesterday's energy :") );
    Serial.println( daily_energy[0] );
    Serial.print( F("average daily energy over the last 7 complete days: ") );
    int sum = 0;
    for( int i=0; i<7; i++ ){
        sum += daily_energy[i];
    };
    int average = sum/7;
    Serial.println( average );
}

In other words, rather than storing every detail of every day for the last 27 days,
(a) store 7 or so values of detailed daily information for the past 7 or so days, and also
(b) store 4 or so "summarized" values of total or average information for each of the past 4 or so weeks.

Why couldn't you just add the values together as soon as you obtain them. So what I mean is you get the value for day 1, you divide it by 1 and store it and the 1 somewhere. Then you multiply the 1 by the value and add it to the next value and divide them both by 2.
Doing this method would create a rolling average with two or three variable as I can think of. I would write some code but I am new to stackexchange so please bear with me.

I don't understand how this deals with the 7 day and 28 day window?

Keep track of the previous and next values and keep adding and subtracting them from your running average...

So then I am back in the state of needing to remember 27 days of history, surely?

I've been thinking and you are right. So that technically makes my answer incorrect. I'm investing some more time and patience into it. Maybe something out of the box. I'll let you know if I come up with something. We do something like this a lot at my workplace. Let me ask around. Sorry about the confusion.


text:
How can I adapt the DallasTemperature library to accept another 1-Wire class?
A commonly used library is the DallasTemperature library, used to access DS18B20 sensors on a 1-Wire bus. When creating a DallasTemperature object you pass a reference to a OneWire object. OneWire can create a 1-Wire bus on pretty much any port of an Arduino.
An example of this is like so:
// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

However, there are some issues with using OneWire to drive a 1-Wire bus, mainly around driving longer bus lengths, dealing with shorts, and other errors.
There is a commonly available chip called the DS2482-100 that can drive longer busses (hundreds of feet), deals with shorts and other errors. It is also less CPU heavy and it deals with a number of the slower aspects of 1-Wire.
For this reason, I would like to be able to pass a reference to a library that I have created instead. Currently, I am doing this by:

Calling the library OneWire
Replicating all the methods called by the DallasTemperature library
Swapping out the OneWire library for mine

This is relatively messy. I would ideally like to be able to pass either a reference to my library or a 1-Wire library, so that people can chose which interface to use.
How would I go about doing this?

This might be quite C++ and more appropriate for StackOverflow. But, in defence of this question, this is a very specific Arduino/hardware library, and in trying to solve it, I have come up against some other issues (http://arduino.stackexchange.com/questions/322/why-do-i-need-to-include-libraries-used-in-other-libraries) that seem specific to the Arduino environment.

What do you mean by "there are some issues with using OneWire like this"? How should it then be used actually? I find it hard to understand how the way to instantiate an object as in your code cn have a bad impact as you describe.

Clarified in original question.

Can't you just use the DallasTemperature library exclusively?

The typical way to achieve what you want would normally be to create your own subclass of OneWire class and override the methods you need to change, then pass a pointer to an instance of your class to the DallasTemperature constructor.
However, for this to work, the OneWire class must have been developed with extensibility (subclassing) in mind, i.e. use virtual methods that you can override.
Unfortunately, a quick look at OneWire.h shows that no method is virtual in there.
So that means in the end you will have to perform some hacks, just as you do now.
What you could potentially do (that's still a hack, but maybe a bit less dirty) is:

replace OneWire.h to make all methods virtual (at least those you need to override)
keep the original OneWire.cpp that should still compile with the newly adapted header file
create a new MyOneWire.h / MyOneWire.cpp to define your own OneWire subclass that overrides all necessary methods as you want

Then you can pass either a OneWire or a MyOneWire instance to DallasTemperature constructor.
NB: when I see my answer, this makes me think your question is more a general C++ question than an Arduino-related one.

Thanks. I think your hack is cleaner - and doesn't involve moving files in and out of the library folder. I'm coming to the realisation that the C++ aspects of Arduino aren't really used to great effect. Thankyou for a great answer - I will leave open for a while anyway.

I should add one point to the defense of OneWire library authors: there can be a reason to not use virtual methods in a class: performance of method calls and code size. I haven't tried yet to measure such impact on Arduino (on a PC this is of course negligible and unnoticeable).

The DS2482-100 is an I2C-to-1-Wire®bridge device that interfaces directly to standard (100kHz max) or fast (400kHz max) I2C masters to perform bidirectional protocol conversion between the I2C master and any
  downstream 1-Wire slave devices.

It uses a higher level protocol over I2C which does not directly match the bit-banged OneWire interface above.
A possible solution is to "only" reuse the OneWire interface and reimplement it. Sub-classing will not work as the member functions are not virtual. Unfortunately this will not work directly due to error handing, timing, etc. The DallasTemperature class will also need modifying.
Please see the DS2482-100 product description and protocol.
To achieve your goal of allowing either bit-banged or DS2482-100 based 1-Wire master would require 1) an abstract interface (class) used by 1-Wire master device drivers, 2) sub-classes for each implementation master variant.
As the 1-Wire protocol has a number of common commands a delegation pattern is more useful. Please see the Cosa OWI::Driver and DS18B20 device driver for an example of the delegation pattern.


text:
What overheads and other considerations are there when using a struct vs a class?
C on embedded systems has traditionally use structs to hold structured data.
Arduino brings C++ to the table, so we can use classes instead.
Lets say we have two different data structures which could be considered very similar:
typedef struct
{
    int valueOne;
    int valueTwo;
    int valueThree;
} value_t;

and:
class Value
{
    public:
        int valueOne;
        int valueTwo;
        int valueThree;
}

In terms of memory, what difference will this make?
I still see the struct technique being used heavily - why is this?

if I recall my C++ correctly there is no difference between struct and class besides the default visibility

I would assume structs are used primarily because the great majority of embedded hardware is coded in C, so anyone who spends a lot of time writing code for small MCUs probably knows C much better then C++, and automatically reaches for C idioms before C++ idioms. It's a programmer performance issue.

As taken from the accepted answer from When should you use a class vs a struct in C++?

The only difference between a class and a struct in C++ is that
  structs have default public members and bases and classes have default
  private members and bases. Both classes and structs can have a mixture
  of public and private members, can use inheritance, and can have
  member functions.
I would recommend using structs as plain-old-data structures without
  any class-like features, and using classes as aggregate data
  structures with private data and member functions.

Memory wise the access modifier makes no difference and given the memory constraints of the Arduino, people are less likely to use classes with complex hierarchies, but prefer the POD structs anyway.

Unlike C, an instance of a struct in C++ is an object in exactly the same way as an instance of a class. From the point-of-view of the compiled code, they are identical. Memory usage, alignment, access times etc. are exactly the same (i.e. there are no overheads).
From the programmer's point-of-view, there is a very minor difference. Members of a struct have public visibility by default, whereas members of a class have private visibility by default. Otherwise, all language features work the same on both, such as constructors/destructors, inheritance, polymorphism, templates, and operator overloading. You can even derive a struct from a class, and vice versa.
Despite the similarity, it's quite common to see people deliberately using a struct in C++ for very simple structures, e.g. where it only consists of a few data members, but no functions. A class would be used for anything more complex. This is purely a matter of convention or personal preference though, and can be used as a subtle indication of the structure's intended complexity.

As other answers have pointed out, your particular struct and class are indistinguishable performance wise (There are slight differences in the scopes of the type names, due to the way you defined your struct). The delineation in C++ is not between struct and class, but between types that are POD (plain old data) and types that are not, as explained in this discussion.

In terms of memory, what difference will this make?

None. Structs and classes are the same thing, differing only in protection levels, and instantiating either creates an 'object'.

still see the struct technique being used heavily - why is this?

Less typing if you're not trying to hide data members.

Note that
typedef struct { ... } Foo;

is obsolete in C++ and you should just use
struct Foo { ... };

It's not very clear in the answers but the other effect of structs is public inheritance by default vs private inheritance by default with classes.
As mentioned by others, using struct is generally a convention for POD types.
Also technically 'struct vs object' should be 'struct vs class' (as instantiating a struct or a class still gives an object).

Edited question object->class.


text:
Why do I need to include libraries used in other libraries?
I have a simple library which uses another library.
Here is the header:
#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <HardwareSerial.h>

class DerivedClass
{
private:
    HardwareSerial* serial;

public:
    DerivedClass();
};
#endif

And the CPP:
#include "DerivedClass.h"

DerivedClass::DerivedClass()
{

}

And the sketch:
#include <DerivedClass.h>

void setup()
{
}

void loop()
{
}

This works fine.
However, if I change the library header to this:
#ifndef __DERIVEDCLASS_H__
#define __DERIVEDCLASS_H__

#include <SoftwareSerial.h>

class DerivedClass
{
private:
    SoftwareSerial* serial;

public:
    DerivedClass();
};
#endif

The sketch fails to compile:

/Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: ISO C++ forbids declaration of 'SoftwareSerial' with no type
  /Users/andrew/Documents/Arduino/libraries/DerivedClass/DerivedClass.h:9:
  error: expected ';' before '*' token

If I change the sketch to:
#include <DerivedClass.h>
#include <SoftwareSerial.h>

void setup()
{
}

void loop()
{
}

i.e. including the SoftwareSerial library in the top level sketch, it compiles fine.
If I expand the library out so it actually performs actions, then if it compiles, it works.
Why is this? HardwareSerial is a built-in part of the Arduino, located in hardware/arduino/cores/arduino and SoftwareSerial is in libraries, but why would the build process differentiate between the two.

If I remember correctly this is in fact a limitation of the Arduino IDE.
If you use a better IDE (personally I use Eclipse with the Arduino plugin) it works as it should, i.e. if you include a library A that includes another library B, then in the end you won't get compile-time errors and both B and A will be included in the final binary.

Absolutely right. Just tried Stino and it works fine. I might retreat back to using command line. I can't understand why they would do this.

Indeed, they are trying to fix this in 1.5 https://github.com/arduino/Arduino/pull/1726


text:
Lowest power possible in Arduino
I have googled all around and I know about some tricks to make ATmega328 not being a power hog. I am using Arduino Nano V3.0.
However, I didn't find out what is the minimal consumption possible with it?
My project consists of an Arduino that will wake up each 10 seconds and, by bluetooth (BT) will scan for existing devices, and if one specific device is not listed, it will lit a LED for 5 seconds and then go to sleep again.
In sum:

Sleep for 10 secs
Wake up
Scan for BT devices
If device ABC is in the list go to 1.
Lit LED
Delay 5 secs
Go to 1.

For bluetooth I will use NRF8001, because it is the most efficient BT module I know so far.
Can you give me some ideas of what tricks should I use to make this ATmega328 and BT module last like one year with a 500mAh battery? Has anyone tried this that can share his experience? Is ATmega328 the right uC for this? I am using it just because I already have code/libraries for it.

Creating the new tag 'nrf8001' requires at least 150 reputation. Try something from the existing tags list instead.

The best I've seen on Arduino power consumption: http://www.gammon.com.au/power You can get the ATmega current draw down to 100 nA in "power down sleep mode"; the rest depends on the other parts of your circuit and what percentage of the time you can stay asleep. You may want to rethink your LED: If you light a 20 mA LED for five seconds out of every 10 seconds, 50% "on" time, the LED alone will drain 500 mAh in 50 hours. The guy in the link found that flashing a LED for 5-10ms once a second was enough to make it visible.

It's worth checking if you may do better with an nrf51822 which is a combination processor & BLE, and no ATmega.

One year = 8765 hours. So average drain for 1 year life from 500 mAh = 500 mAh/8765h = 57 uA average. | An efficient modern LED is usefully bright at 1 mA and probably at 0.1 mA. [Best LEDs are 30 Cd+ at 20 mA so 150 mCd mean at 0.1 mA and your eye-brain sees more like the peak.  | 0.1 mA at 1% duty cycle for one year = 8765 x 0.1 x 1/100 = 8.765 mAh or about 2% of your battery capacity.

The issues regarding efficiency of power are:

The CPU speed
The Voltage
The Power Regulator (not supply)
The Peripherals

Address each one of these and don't over look any of them. Or any sub component. But note that some are more impacting than others.

while it is possible to lower the speed, It is more practical to just sleep. As you have indicated you are going to do.
Running at 3V instead of 5V is a big savings. Note that the 328 can run as low as 1.8V
DON'T use Linear Regulators. Most all Arduino's have a 7-12V to 5V(or 3.3V) Linear Regulator. This just burns the difference between the supply (aka battery) and the VCC, used.
pay attention to the peripherals. Likely this means getting rid of not needed devices. Example the USB to Serial chip that exists on the Nano. What is the lowest voltage can the radio run at? Must it run at a regulated voltage. Use the largest possible resistor values. Such as on pull ups. A 500K pull up will draw less current than a 10K. Where if too big any capacitance may slow it down. Which is likely acceptable.

One of the biggest savings is running directly off of the Battery without a Linear Regulator. Where the ATmega328P can run from 3V down to 1.6V. It would be recommend to use the Brown Out detector.
Also note that ALL batteries have a self discharge rate.  This will determine the maximum possible life of the battery, then minus your devices consumption.

Read the link in @j-g-faustus 's comment - very thorough. http://www.gammon.com.au/power - it starts with a stock board running at 50milliAmps and ends up at 0.002 milliAmps.
You will also need to find out the power consumption for your BT module - this may dwarf the power arduino's power consumption. The same goes for the LED.
Normal LEDs run at about (ballpark!) 20 milliamps - this means that on the coin battery mentioned by @Omer, 200milliAmp-hours/20 milliAmps = 10 hours of led light.
You can measure the power draw with a multimeter; stick your probes between the + of the battery and whatever the battery would normally connect to (you will have to disconnect the battery of course) - if using a 9v battery, plug in the negative, disconnect the positive, turning the snap connector 90 degrees; then you can put one probe on the battery, the other on the (open) snap connector. Measure Arduino awake + led on + BT connected and sending data. Measure again with everything off/idle/sleeping. Work out how much time it will spend in each state; this will give you an average number of milliamp-hours.

These are essentially notes in support of other answers:
One year = 8765 hours.
So average drain for 1 year life from 500 mAh
= 500 mAh/8765h
= 57 uA average.
To get one year on a 500 mAh battery you need to have average drain under say 50 uA
An efficient modern LED
is usefully bright at 1 mA and
probably very acceptable at 0.1 mA.
Best LEDs are 30 Cd+ at 20 mA
so 150 mCd mean at 0.1 mA
and your eye-brain sees more like the peak.
0.1 mA at 1% duty cycle for one year
= 8765 x 0.1 x 1/100
= 8.765 mAh
or about 2% of your battery capacity.

Lowest possible power consumption for an Arduino is 0mA - just disconnect it's Vcc :)
And seriously, when there are many factors involved, it is hard to include all of them into the proper equations, considering different factors that affect the current consumption such as temperature, humidity, quality and distance of the wires etc. Best would be to perform measurements of the power consumption for, say, several cycles of steps 1 to 7, and do the average.
Remember that the ATmega chip will draw more current depending on the voltage, so you might want to keep voltage as low as possible.
Here is a nice project of an ATtiny (Arduino alike) that runs on a coin CR2032 battery (~200mAh) for 220 days until it died, while wirelessly broadcasting the results and the measurements of the battery discharge rate, so you could actually achieve pretty good results working with a 500mAh battery.

For simple applications like this, you might find it more convenient to use a smaller board/MCU from the Arduino system. For example the Digispark uses an ATtiny85 rather than the standard ATmega328P. It's not clear that the MCU itself would use much less power (it's pretty much the same CPU core, after all, though you are powering less RAM) but the board has only the one MCU and the regulator on it. You can still power it from and program it via USB (at 5 V) for development, but for production use you can (as others have mentioned) provide 1.8 V power on the VCC line, ignoring the regulator, and you will not have to worry about the power usage of things like the USB interface (an FT232 on the Nano, but a whole second microcontroller on some other boards!) and other parts on the Nano.