Arduino Yun Python ImportError: No Module named mime.multipart So, I have an Arduino Yun, and I'm trying to send an email with python. I have this code that I got from https://github.com/amicojeko/YouCantTouchThis

But when I try to call the file with $python sendemail.py test.png, it returns me an error:

ImportError: No module named mime.multipart

I already tried to change to lowercase the imports, but it keeps showing the same error. The python version in the Arduino is 2.7. I've read something about module reorganization but even with the changes the error keep showing. Here is the code:

# coding=utf-8
# Copyright (C) 2014  Stefano Guglielmetti

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.

import smtplib, os, sys
from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders

#From address, to address, subject and message body
from_address    = 'FROM_ADDRESS@EMAIL.COM'
to_address      = ['YOUR_ADDRESS@EMAIL.COM']
email_subject   = 'Alert!!! Zombies!!! Ahead!!!'
email_body      = 'A non dead intruder has been detected and needs to be eliminated!'

# Credentials (if needed)
username = 'EMAIL_LOGIN'
password = 'EMAIL_PASSWORD'

# The actual mail send
server = 'smtp.gmail.com:587'

def send_mail(send_from, send_to, subject, text, files=[], server="localhost"):
    assert type(send_to)==list
    assert type(files)==list

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach( MIMEText(text) )

    for f in files:
        part = MIMEBase('application', "octet-stream")
        part.set_payload( open(f,"rb").read() )
        Encoders.encode_base64(part)
        part.add_header('Content-Disposition', 'attachment; filename="%s"' % os.path.basename(f))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.starttls()
    smtp.login(username,password)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

send_mail(from_address, to_address, email_subject, email_body, [sys.argv[1]], server) #the first command line argument will be used as the image file name

mime.multipart isnt used in your code at all so you shouldn't be getting that error. The correct import statements for Python 2.7 are:

from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.encoders import Encoders

Study these examples in the Python 2.7 documentation.


Unable to connect to Linux Environment (Linino AR9331 Interface) in Arduino Yun I was trying to reset my Arduino Yun (WLAN button pressed for more than 30 seconds), but it just kept on blinking for about 10 minutes. Then I finally got impatient and restarted the Yun. After the restart, there was no WLAN (blue) or USB (white) LED blinking or glowing anymore. I am unable to connect through the Wifi network, the Yun does not create it's own Wifi network and unfortunately when connected via Ethernet, I can still not navigate to arduino.local or 192.168.240.1.

So I have a feeling that somehow only the AVR is still functioning (because I can still upload sketches) and nothing else.

I have updated the firmware to the latest version (OpenWrt-Yun 1.5.3). Is there a way to connect or reset, if the Ethernet does not work? Can I upload a sketch to check in the console if the Linino interface still functions.

Thanks in advance!

Try uploading YunSerialTerminal example, opening the serial monitor and pressing the YUN RST button. You should see the linux side starting.

If it starts but it looks somehow bricked, you could try following the http://arduino.cc/en/Tutorial/YunUBootReflash tutorial.


Do I need a bubble sort or something easier? I'm using an Arduino Leonardo and a GPSTiny++ library to parse NMEA strings from my GPS receiver. In this chunk of code I'm averaging all satellite SNR numbers for satellites which are locked (Being used for navigation). The avg value provides some general information on overall performance but I'm also really looking for the avg Top 4 values.

I believe I would need to do some sort of sorting algorithm. Increment through the top 4 and average those values.

Here's a snippet of my output window:
12/13 0.92 SNR=17 10 27 27 30 29 25 27 33 0 0 0 31 25.60 0.00

The second to last number is the average.

How do I get started?

int totalSNR = 0;
    float avgSNR = 0;
    int count = 0;
    Serial.print(F(" SNR="));
    for (int i = 0; i < MAX_SATELLITES; ++i)
      if (sats[i].active)
      {
        if (sats[i].snr > 0) {
          count++;
          totalSNR = totalSNR + sats[i].snr;
        }

        Serial.print(sats[i].snr);
        Serial.print(F(" "));
      }

    avgSNR = float(totalSNR) / float(count);
    Serial.print(avgSNR);

You could do a qsort. You haven't posted any data types so it is hard to answer with your specific code, however here is a sample of sorting numbers:

const int COUNT = 10;

int someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
int myCompareFunction (const void * arg1, const void * arg2)
  {
  int * a = (int *) arg1;  // cast to pointers to integers
  int * b = (int *) arg2;

  // a less than b?
  if (*a < *b)
    return -1;

  // a greater than b?
  if (*a > *b)
    return 1;

  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

Output:

-5
3
18
21
30
42
54
998
999
7342

Generic compare function with a template

Interestingly, you can make the compare function be a template which lets you compare any type -- that is, any type that supports direct comparisons. Change the compare function to:

// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

This change removes the reference to "a" and "b" being "int" and replaces them with T, which is the template type.

Now we can change the qsort line to be:

  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (int), myCompareFunction<int>);
  // -------add this----------------------------------------^^^^^

That gives the same results, but now we can also compare float, long, unsigned long, byte, all that sort of thing.

Compare floats

For example to compare floats:

const int COUNT = 10;

float someNumbers [COUNT] = { 7342, 54, 21, 42, 18, -5, 30, 998, 999, 3  };

// callback function for doing comparisons
template<typename T>
int myCompareFunction (const void * arg1, const void * arg2)
  {
  T * a = (T *) arg1;  // cast to pointers to type T
  T * b = (T *) arg2;
  // a less than b?
  if (*a < *b)
    return -1;
  // a greater than b?
  if (*a > *b)
    return 1;
  // must be equal
  return 0;
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someNumbers, COUNT, sizeof (float), myCompareFunction<float>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someNumbers [i]);
  }  // end of setup

void loop () { }

The only change there was changing the word "int" to "float" (in two places) on the qsort line, and on the data declaration itself.

Compare String objects

You can even compare String objects (not C strings), for example the data is:

String someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

And the sort is:

  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (String), myCompareFunction<String>);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);

Compare C strings

We need to use strcmp in this case, but most of the work is done in that. We just have to dereference the pointer so strcmp gets the pointer to the string (not the pointer to the pointer to the string).

char * someStrings [COUNT] = { "the", "quick", "brown", "fox", "jumped",
                               "over", "the", "lazy", "dog", "ZOMG"  };

int myCompareFunction (const void * arg1, const void * arg2)
  {
  return strcmp (*(char **) arg1, *(char **) arg2);
  }  // end of myCompareFunction

void setup ()
  {
  Serial.begin (115200);
  while (!Serial) { }  // for Leonardo
  Serial.println ();
  // sort using custom compare function
  qsort (someStrings, COUNT, sizeof (char *), myCompareFunction);
  for (int i = 0; i < COUNT; i++)
    Serial.println (someStrings [i]);
  }  // end of setup

void loop () { }


Why can't the Atmel ATtiny family delay over a minute? I have some really simple code and tested on an 8 MHz ATtiny85 and ATtiny2313. It's basically a blocking blink:

int relayPin = 7;

long offPeriod = 1 * 60 * 1000;
long onPeriod = 1 * 60 * 1000;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delay(onPeriod);
  digitalWrite(relayPin, HIGH);
  delay(offPeriod);
}

When I assign onPeriod and offPeriod to be 1 * 1000 (1 second), the LED will blink as expected. When I add the 60 second multiplier in, it seems to fail.

For the ATtiny85 I use Arduino Pin 4 (physical pin 3) and for the ATtiny2313, I use Arduino pin 7 (physical pin 9).

I program through the Arduino IDE using boards manager to install the ATTinyCore library for the ATtiny2313 and this for the ATtiny85.

Am I doing something wrong here?

It looks like if I throw the delay in a function, and then invoke it with however many seconds I want, it will work. This is not good as it remains blocking. So perhaps the correct way to do this is to grab timestamps.
Here's the somewhat working code:

int relayPin = 4;
unsigned long offPeriod = 60;
unsigned long onPeriod = 60;

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

void loop()
{
  digitalWrite(relayPin, LOW);
  delaySeconds(onPeriod);
  digitalWrite(relayPin, HIGH);
  delaySeconds(offPeriod);
}

void delaySeconds(int s) {
  for (int i = 0; i < s; i++) {
    delay(1000);
  }
}

This is absolutely nothing to do with "why can't the atmel attiny family delay over a minute?". It is all to do with the way that C++ works.

See my page about Integer arithmetic and overflow.

To excerpt from that:

On the Arduino (Uno) platform, what do you think will be printed here?

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

  Serial.println (30000 + 30000); // twice 30000
  Serial.println (60 * 60 * 24);  // seconds in a day
  Serial.println (50 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Did you guess:

60000
86400
500

Nope!

It prints:

-5536
20864
0

This is because of integer arithmetic. If the compiler can, it treats an numeric literal (like 60) as an int type, which means it has the range -32768 to +32767.

And, arithmetic is done using the type of the largest argument, which means the arithmetic in each case is done as 16-bit arithmetic, and thus it overflows once it reaches 32767.

For example, 30000 + 30000 = 60000 which is 0xEA60 in hex. Unfortunately, 0xEA60 is exactly how -5536 is stored in an int type, which is why it prints -5536.

Meanwhile, 60 * 60 * 24 = 86400 which is 0x15180 in hex. As that doesn't fit in 16 bits, it is truncated to 0x5180 which is 20864 in decimal (as printed).

Finally, in integer arithmetic 50/100 is zero, multiply zero by 1000 and you still get zero, which is why the final result is zero.

Solution

First, you can add a suffix to numeric literals (eg. L for long, or UL for unsigned long), and add a decimal place to floats, like this:

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

  Serial.println (30000L + 30000); // twice 30000
  Serial.println (60L * 60 * 24);  // seconds in a day
  Serial.println (50.0 / 100 * 1000); // half of 1000
  }  // end of setup

void loop () { }

Now we get:

60000
86400
500.00

You only need to help out with the first literal, once the compiler knows we are using longs (or floats) it sticks with them for the expression.*

* It's actually somewhat more complex than that as this link explains: Understand integer conversion rules.

The compiler "promotes" a value in an expression to match another "higher-ranked" type, under certain circumstances. For example, adding an int and a long will result in the int being promoted to a long (regardless of whether it appears first in the expression or not). However if an int is being added to another int, it will not promote them to a long, even though the result may not fit into an int.


Sending data from Arduino to the server where arduino (sketch) acts as a client I want to make simple client-server program where arduino behave as a client. For example I have a LED connected in arduino board that is controlled by a switch. With the switch I can turn off and on the LED. Now I want to send the status of that LED to another computer wirelessly (let's say within the Local network). That computer will act as a server and update the change as soon as the LED changes its status. I am not expecting any complete code, I just want to know how could it be done in general? May be some links can help me? Because this is my first time working with client-server in arduino sketch, I need some kind of guidelines. Thank you.

A simple HC-05 module will give you a wireless bluetooth connection.  They're fairly simple to setup, and you can write data to them the same as one would the Arduino serial console.  Obviously they can read data too.

SoftwareSerial bt_serial(2, 3); // RX | TX
bt_serial.begin(9600);

[...]

if (led_state != last_led_state)
{
    if (led_state == HIGH)
        bt_serial.print("1");
    else
        bt_serial.print("0");
    last_led_state = led_state;
}

On the "server" side, a simple program reading the mapped bluetooth serial port would do the job.  For example, some python code:

import serial
import sys

serial_port = serial.Serial(port='COM8:', baudrate=9600, bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE)

try:
    serial_port.open()
except:
    print("Failed to open port")
    sys.exit(2)

while (True):
    try:
        led_state = serial_port.read()
        if (led_state != 0):
            print("LED is on")
        else:
            print("LED is off")
    except:
        pass

serial_port.close()   # yes, it never gets here


Servo jitter with Arduino We're complete beginners with Arduino and we're working on a project that moves a pointer based on a color sensor reading.

We used two servo motors each: one performs a specific task, the small servo works pretty fine. The problem is with the larger one.

We used this servo motor model: (towardpro MG996R), Arduino Uno and a color sensor. Because the motor is large we connect it to a 9 V power supply.

But when we run the code it just vibrates in place and the arm won't move :(

Is there anything else we need to add to the circuit like a resistor or some thing?

#include <Servo.h>
Servo largeServo;

void setup() {
  largeServo.attach(6);
  largeServo.write(0);
}

void loop() {
  largeServo.write(0);
  delay (2000);
  largeServo.write(30);
  delay (2000);
  largeServo.write(60);
  delay (2000);
  largeServo.write(90);
  delay (2000);
}

According to (MG996R)'s datasheet
You must connect a 6 volts - 2.5 amps power supply for it's best performance (max. Torque)
Maximum voltage of this servomotor is 6 volts
And be careful, exceeding that voltage can be cause of some damage to it's control board
Try 6 volts 2.5 amps power supply and if doesn't work maybe your servomotor's control-board is damaged by over-voltage.


Power Supply Ticking, Light Flashing My Arduino came with a 9V 1A power supply to use with it.  I decided to test it out with my multimeter.  I put the red lead in the connector and the black on the outside.  Sure enough I read 9V.  However when I tested the amps this did not work.  The meter read a low value and the power supply started making a ticking noise and a light started flashing on it.

I did have the multimeter on the correct settings.  Looking online I now realize that you cannot test the amps this way and as I was essentially testing a circuit with no load on it.

What I would like to know is what the power supply was doing when it was ticking and flashing.  It is alive and well so I suppose it was some sort of internal protection.

It was "hiccuping" in order to prevent damage from the short circuit condition. Once the short circuit condition is removed, the PSU restores normal operation.

From the reference:
"The operation of hiccup is as follows. When the current-sense circuit sees an over-current event, the controller shuts off the power supply for a given time and then tries to start up the power supply again. If the over-load condition has been removed, the power supply will start up and operate normally; otherwise, the controller will see another over-current event and shut off the power supply again, repeating the previous cycle."


Communication between 2 arduino boards I am not really 100% too sure how to do this but I am trying to make my arduino UNO communicate with my arduino MEGA. The reason why I needed to do this was because I was using the RFID module along with a TFT display and the problem I faced is that on the arduino mega they both needed pin 53. Luckily I have an arduino UNO so I just went for that instead for the display. I am trying to use the analogWrite() function to send analog signals from my MEGA over to the UNO so that the TFT display on the UNO can display the results. The UNO would also read the analog inputs coming from the MEGA. This did not work very well. The analog inputs are being sent from the MEGA but the UNO is not reciving them. I am using a PWN pin on the MEGA to send the analog output to the UNO.
This diagram shows what I mean:

These are the 2 compotents I am using:
https://i.stack.imgur.com/CqXdB.png
TFT display

RFID

This shows how the libary sets out the pins. I am only a beginner so I personally don't want to mess around with the libary.

Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).
You cannot transmit information with analogWrite() since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.


How to control Neopixel LEDs in parallel? Imagine a collection of LEDs (Neopixel or otherwise) labeled 2 through 12. There may be more than 11 LEDs, so repeat numberings are allowed. I want a simple way to control them from a single Arduino based on their label. So e.g. I should be able to implement a function whose arguments are a label value and an RGB value, and which turns all LEDs of that label value to the given RGB value. Most importantly, the solution has to be order-independent; that is, I should be able to re-wire the LEDs (or equivalently, scramble around the hex labels) in any manner, and still have everything work without rewriting any code. (For context, my goal is to make a custom Settlers of Catan edition, where the labels on each hex light up when their die value is rolled.)

I know I can't just use Neopixels out of the box, since the addressing depends on the order in which they're wired. So I assume I need to hack together a way for each LED to "know" its label, wire them all in parallel, and then write a custom library to . But I have no idea how to get each LED to know its label without having an entire Arduino for each LED, which would take up way too much space. (I'd like to fit everything in roughly the volume of a typical Catan hex label; think 2-3 quarters stacked together.)

I'm fairly comfortable with Arduinos, but I'm an electronics noob. Is it possible to reprogram the Neopixel controller? Or is there a tiny logic board I can hook up to a Neopixel or dumb LED that would do the job? Anything else I'm missing?

It will not be easy to “re-wire the LEDs [...] and still have everything
work without rewriting any code.” Those LEDs are not that smart, and the
only way to address them is by the order in which the color data is sent
through the data line.

What you can do, however, is write the code is such a way that rewiring
requires only a minimal change in the code. I would use an array to
map the LED indices to their labels. Something like this:

const uint16_t LED_COUNT = ...;

// Map LED indices along the strip to hex labels.
const uint8_t ledLabels[LED_COUNT] = {
    2, 2, 2, 2,  // LEDs 0 to 3 are labeled "2"
    8, 8, 8, 8,  // LEDs 4 to 7 are labeled "8"
    // etc...
};

Then, assuming your LED strip is declared as follows:

const uint8_t LED_STRIP_PIN = ...;
Adafruit_NeoPixel ledStrip(LED_COUNT, LED_STRIP_PIN);

the “function whose arguments are a label value and an RGB value, and
which turns all LEDs of that label value to the given RGB value” can be
quite easily written:

// Turn all the LEDs sharing that hex label to the given color.
void setHexColor(uint8_t label, uint32_t color)
{
    for (uint16_t n = 0; n < LED_COUNT; n++)
        if (ledLabels[n] == label)
            ledStrip.setPixelColor(n, color);
    ledStrip.show();
}

Now, if you rewire the strip, you just need to update the ledLabels
array and recompile. If you can manage to send that information to your
Arduino while it's running (a serial connection, an IR link, an SD card
inserted in an appropriate socket, whatever...), then you could even
have a procedure where the Arduino updates the array itself. Obviously
the const qualifier should then be removed. But you now have to devise
a way to “tell” the Arduino about your wiring.


How to control the power of attiny13a via pin change interrupt? I'm trying controll the power of attity13a and turn off/turn on the led.
I'm going to goals:

After to click on the button0
led will blicking 5 second nad then the attiny13a going to sleep.
After to click on the button1 then wake attiny13a up and then led will shane.

The button0 to sleep and blink the led.
the button1 to wake up and turn on the led.
Could you explain what is wrong in this sketch, please?
thank you for your answers.

code:

    #define F_CPU   1200000UL
    #define LED     PB2 // PB2
    #define BUTTON1 PB1 // PCINT1
    #define BUTTON0 PB0 // PCINT0

    #define HIGH         1
    #define LOW          0
    #define INPUT        0
    #define OUTPUT       1
    #define INPUT_PULLUP 2
    #define FALSE        0
    #define TRUE         1
    #define _BV(bit)    (1 << (bit))

    #include <avr/io.h>
    #include <avr/interrupt.h>
    #include <avr/sleep.h>
    #include <util/delay.h>

    void pinMode(uint8_t pin, uint8_t mode)
    {
        if(mode == OUTPUT) // Pin as output
            DDRB |= _BV(pin);
        else // Pin as input or input pullup
        {
            DDRB &= ~_BV(pin); // Set pin as input
            if(mode == INPUT_PULLUP)
                PORTB |= _BV(pin); // Enable pullup resistors
        }
    }

    void digitalWrite(uint8_t pin, uint8_t val)
    {
      if(val)
        PORTB |= _BV(pin);  // Set pin high
      else
        PORTB &= ~_BV(pin); // Set pin low
    }

    uint8_t digitalRead(uint8_t pin)
    {
      return !!(PINB & _BV(pin));
    }

    // go to sleep
    ISR(PCINT0_vect)
    {
       if(digitalRead(BUTTON0)){
            int i=0;
            while(i<10){
                blink();i=i+1;
            }
            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_enable();
            sleep_cpu();
        }
    }

    //wake up
    ISR(PCINT1_vect){
       if(digitalRead(BUTTON1)){
        digitalWrite(LED, HIGH);
       }
    }

    void blink(){
        digitalWrite(LED, LOW);
        _delay_ms(500);
        digitalWrite(LED, HIGH);
        _delay_ms(500);
    }

    int main(void)
    {
        pinMode(BUTTON0, INPUT_PULLUP);
        pinMode(BUTTON1, INPUT_PULLUP);

        pinMode(LED, OUTPUT);
        digitalWrite(LED, LOW);

        // Sets the Pin change interrupt mask PB0, PB1
        PCMSK |= _BV(PCINT0)|_BV(PCINT1);

        //Enables Interrupts globally after setup
        //sei();
        SREG |= _BV(SREG_I);

        while(TRUE){}
    }

#define F_CPU   1200000UL

#define LED     PB2 // PB2
#define BUTTON1 PB1 // INT0
#define BUTTON0 PB0 // PCINT0

#define HIGH         1
#define LOW          0
#define INPUT        0
#define OUTPUT       1
#define INPUT_PULLUP 2
#define FALSE        0
#define TRUE         1
#define _BV(bit)    (1 << (bit))

#include <avr/io.h>
#include <avr/interrupt.h>
#include <avr/sleep.h>
#include <util/delay.h>

void pinMode(uint8_t pin, uint8_t mode){
    if(mode == OUTPUT) // Pin as output
        DDRB |= _BV(pin);
    else // Pin as input or input pullup
    {
        DDRB &= ~_BV(pin); // Set pin as input
        if(mode == INPUT_PULLUP)
            PORTB |= _BV(pin); // Enable pullup resistors
    }
}

void digitalWrite(uint8_t pin, uint8_t val){
  if(val)
    PORTB |= _BV(pin);  // Set pin high
  else
    PORTB &= ~_BV(pin); // Set pin low
}

uint8_t digitalRead(uint8_t pin){
  return !!(PINB & _BV(pin));
}

//wake up
ISR(INT0_vect){
   sleep_disable();
   //cli(); // Turn off global interrupts
   digitalWrite(LED, HIGH);
}

void blink(){
    digitalWrite(LED, LOW);
    _delay_ms(1000);
    digitalWrite(LED, HIGH);
    _delay_ms(1000);
}

// go to sleep
ISR(PCINT0_vect)
{
   //cli(); // Turn off global interrupts
   if(!digitalRead(BUTTON0)){
        cli(); // Turn off global interrupts

        blink();

        digitalWrite(LED, LOW);

        sei(); // Turn on global interrupts
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        sleep_cpu();
    }
}

int main(void)
{
    //enabled external interrupt
    MCUCR=0;
    //MCUCR=0b00000000;
    GIMSK|=_BV(INT0); // enabled external interrupt INT0 - PB1

    // Sets the Pin change interrupt mask
    GIMSK|=_BV(PCIE);
    PCMSK|=_BV(PCINT0);//PB0

    pinMode(LED, OUTPUT);
    digitalWrite(LED, LOW);

    pinMode(BUTTON1, INPUT_PULLUP);//INT0 - PB1
    pinMode(BUTTON0, INPUT_PULLUP);//PCINT0 - PB0

    //Enables Interrupts globally after setup
    //SREG |= _BV(SREG_I);
    sei(); // Turn on global interrupts
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    sleep_enable();
    sleep_cpu();

    while(TRUE){}

    return 0;
}


Arduino ethernet shield not getting correct IP I have a very simple sketch which I'm using to (try to) prove out an ethernet shield. The complete sketch is below. When I upload the sketch, the IP address that the shield gets is 0.140.140.140, which is incorrect. I just received the shield today from SparkFun, it is this one. Am I doing something wrong, or is my shield  and/or Arduino broken? The Arduino is an Uno R3. The sketch works otherwise (the LED blinks as expected).

Sketch:

#include <SPI.h>
#include <Ethernet.h>

// Network information
byte mac[] = {0xDE, 0xAD, 0xBE, 0xCF, 0xFE, 0xEE };
byte ip[] = { 172, 31, 42, 201 };

void setup() {
  pinMode(4,OUTPUT);
  digitalWrite(4, HIGH);
  delay(1);

  // initialize serial:
  Serial.begin(9600);
  Serial.println("Starting sketch...");
  Ethernet.begin(mac,ip);
  delay(1000);
  Serial.println(Ethernet.localIP());
  Serial.println("Setup done.");
  pinMode(13, OUTPUT);
}

void loop() {
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
  delay(1000);
  Serial.println(Ethernet.localIP());
}

The sketch you have written works perfectly with a cheap Ethernet Shield clone from eBay.  Those (and the older Arduino Ethernet Shields) use the Wiznet W5100 chip.

The new shields, of which you have one, use the newer, more powerful, Wiznet W5500 chip.

You can't use the old Ethernet library with the new Wiznet W5500 chip.  It doesn't work.

You have to use the "Ethernet 2" library as described here:

http://labs.arduino.org/Ethernet+2+Library

  Note: this library is used to work with the new Ethernet shield (version 2) and Leonardo Eth that uses a new Controller W5500.

That page is linked from the product page you link to above.  If you had read the product page you would already know this.


Adding Library to my sketchbook Hey so basically I have my Arduino uno r3 setup with my RFID-RC522. I am looking to add this library to so I can use the examples alongside the ones I already have.
https://github.com/BoolLi/RC522_RFID_NFC_Utilities

I haven't been able to add them correctly and hope someone can help me out doing this. I currently have these ones already added and working correctly:
https://github.com/miguelbalboa/rfid

Download https://github.com/BoolLi/RC522_RFID_NFC_Utilities/archive/master.zip
Copy the folder RC522_RFID_Utilities from the downloaded file to {sketchbook folder}/libraries. You can find the location of your sketchbook folder in the Arduino IDE at File > Preferences > Sketchbook location.
If you're using Arduino IDE 1.6.5-r5 or older restart the Arduino IDE. If using a newer version no restart is necessary.

The other three folders in the downloaded file are example sketches, not libraries. After installing the RC522_RFID_NFC_Utilities library following the instructions above you will be able to use them. You can store those folders anywhere you like but you should not put them directly under the libraries folder as this will cause warning messages about invalid libraries on every compilation. If you do want to bundle them with the RC522_RFID_NFC_Utilities library, as is customary, you can do this:

Create a folder named examples in {sketchbook folder}/libraries/RC522_RFID_NFC_Utilities
Copy the example sketch folders (NDEFFormattingExample, etc) from the downloaded file to the examples folder you created.
Restart the Arduino IDE if it's running.

The example sketches will now be accessible via File > Examples > RC522_RFID_NFC_Utilities.


External vs internal pullup There are two ways of pulling the pins in Arduino – using internal and external resistor. I wonder when I should use external resistor instead of INPUT_PULLUP.

You can use either the internal or external resistor in normal application.

Each method has each own advantages:

Internal resistor

Pros: flexible to change by changing the code
Pros: Reduce PCB size
Pros: Reduce cost (very small)
Cons: It may make MCU hot

External resistor

Pros: Reduce heat for MCU
Cons: Not easy to replace when it is built-in PCB
Cons: Increase PCB size

Besides, Pull-up and pull-down resistors are not only used for INPUT port but also for OUTPUT port. In the case of OUTPUT port. The external resistor has another advantage:  flexibility in connecting devices with different I/O voltages. For example, in I2C hardware see I2C at the Hardware Level.

NOTE: As far as I know, at the writing time, Arduino library does NOT support INPUT_PULLDOWN


Arduino with ATmega32U4 low power but keep Serial1 working I am looking for a low power solution for my ATmega32U4. It uses Serial1 to communicate with Bluetooth, so I need to have it active. When I receive data from Serial1, I want to power up the Arduino, do some magic, and then power it off...

For Power Down/Standby Mode you would have to use an Interrupt Pin to reactive the MCU. If you do not mind possible loss of the first character you could connect an Interrupt Pin to Serial1 RX and wake up on the first start bit.

The startup delay (i.e. time until UART is up and working) may impact the first character received. You could always start off by sending a number of null character as a "wake up call"; classical break sequence.

Cheers!

Ref. ATmega16/32U4, Chap. 7. Power Management and Sleep Modes.


Using TMRpcm object, why is the SD Card failing to be found by arduino? I am using this micro-sd card reader, and my wiring configuration is as follows (double and triple checked):

3.3v goes to 3.3v on the Arduino UNO
GND goes to Ground on Arduino UNO
D0 goes to pin 12 on Arduino UNO
D1 goes to pin 11 on Arduino UNO
CLK goes to pin 13 on Arduino UNO
D3 goes to pin 4 on Arduino UNO

When I run the 'basic' example from the TMRpcm library, everything compiles and uploads properly with no warnings. Looking at the Serial Monitor, I get "SD Fail", which, according to the comments, means that the SD card failed to initialize. The card is present, and works in my computer. Do I have something wired wrong, or is there another issue?

EDIT

I have tried using a different pin for D3, and changed the code as needed. Still no luck.

See  https://github.com/greiman/SdFat

Ensure it works with the sdinfo example, and then you can just use the sdformatter example to format the card.


Arduino WIFI compiler error Just bought an ESP8266 module to try it using my arduino uno R3. I have connected my WIFI module correctly, anyways evenb if i disconnect it, the error occur.

While trying to upload the WIFI (connect with wpa) sketch i get several errors.

First i tried uploading the hole sketch, i got those errors:

/usr/share/arduino/libraries/WiFi/WiFi.cpp: In member function ‘uint8_t* WiFiClass::macAddress(uint8_t*)’:
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: unable to find a register to spill in class ‘POINTER_REGS’
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112:1: error: this is the insn:
(insn 35 25 26 2 (set (reg:QI 23 r23)
    (mem/c:QI (plus:HI (reg/f:HI 28 r28)
            (const_int 2 [0x2])) [3 S1 A8])) /usr/share/arduino/libraries/WiFi/WiFi.cpp:110 28 {movqi_insn}
     (nil))
/usr/share/arduino/libraries/WiFi/WiFi.cpp:112: confused by earlier errors, bailing out

After that i tried to only import just the libraries and try to compile it. Even with this method i get errors

Code

#include <WiFiServer.h>
#include <WiFiClient.h>
#include <WiFi.h>

error:

In file included from /usr/share/arduino/libraries/WiFi/WiFiServer.h:8:0,
                 from sketch_oct20b.ino:1:
/usr/share/arduino/hardware/arduino/cores/arduino/Server.h:4:29: error: expected class-name before ‘{’ token
In file included from sketch_oct20b.ino:1:0:
/usr/share/arduino/libraries/WiFi/WiFiServer.h:14:3: error: ‘uint16_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:17:22: error: field ‘uint16_t’ has incomplete type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:24: error: ‘uint8_t’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:20:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:21:11: error: ‘size_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:22:3: error: ‘uint8_t’ does not name a type
/usr/share/arduino/libraries/WiFi/WiFiServer.h:24:9: error: ‘Print’ has not been declared
/usr/share/arduino/libraries/WiFi/WiFiServer.h:18:42: error: ‘NULL’ was not declared in this scope

I can just figure out some syntax errors, but my c is not good enough to understand much of it.

Can anyone tell me what am i doing wrong and show me how it will be done?

The WiFi libraries (such as Wifi.h, WifiClient.h, and WiFiServer.h) are used for interfacing with the official Arduino WiFi shield. Interfacing with an ESP8266 module is typically done by issuing AT commands via UART (i.e. Serial.write(), etc.)


Trying to make a heart rate analyser with Arduino that will calculate the BPM of a person I am trying to make a heart rate analyzer device using an Arduino board that will calculate the BPM of a person by using raw sensor signals greater or equal to the threshold value to calculate pulses/heartbeat in 10 seconds and then multiply the number of pulses by 6.

The circuit is fairly simple: it has a led that is going to flash on the finger of the person. In-front of the finger there is going to be a photoresistor that is going to read changing values of light falling on it. The values will be varying because of the blood flowing through the finger. When there is going to be a  pulse/heart-beat the amount of light falling on the photoresistor will increase, hence the reading of the photoresistor will also increase.

If the raw values read by the sensor are equal to or greater than the threshold value the code will increment the number of pulses by 1. To calculate the heartbeat rate we will have to count the number of pulses/heart-beats for 10 seconds and then multiply the count by 6.

In short the code that I will use will convert raw analog sensor data into BPM (Beats Per Minute) so that a user can get a standard measurement of his pulse rate.

I took the code that I am going to use from a website. Here is a link to page so that you can also have a look at the code.

I had some problem in the code and was wondering if anyone could help me with it. The full code is given below:

int sensorValue = 0;
int sensorValue = 0;
// variable to store the value coming from the sensor
int count=0;
unsigned long time1=0; // store the initial time
unsigned long time2; // store the current time

void setup() {
  // declare the ledPin as an OUTPUT:
  pinMode(sensorPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // read the value from the sensor:
  if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();
  }
}

void increment() {
  count++;
  while(sensorValue>156) {
    Serial.print("Sensor value is greater than .75V\n");
  }
}

void counter() {
  count=count*6;
  Serial.print("Heartbeat rate is ");
  Serial.print(count);
  Serial.print(" per min\n");
  time1=0;
  time2=0;
  count=0;
}

Part of the code I'm not able to understand. This is located at the very top of void loop():

[note: i pretty much understand how increment and counter functions work but i am not able to understand how the program is able to take input for 10 seconds.basically how the counter function runs for 10 seconds]

 if(count==0) {
    time1=millis();
  }
  time2=millis();
  sensorValue = analogRead(sensorPin);
  if(sensorValue>156) {
    increment();
  }
  if(time2>=time1+10000) {
    counter();

Although I know that this part of the code that I am not able to understand counts the pulses for 10 seconds by taking raw sensor values and checking if these values are above or equal to the threshold value, I am not able to understand how it is working.

I would be highly obliged if anyone could help me with this problem of mine.

// Record the start time into time1
if(count==0) {
  time1=millis();
}

// Set time2 to the current time
time2=millis();

// Read the sensor
sensorValue = analogRead(sensorPin);

// If the sensor value is high enough, increment the beat counter
if(sensorValue>156) {
  increment();
}

// If the current time is greater than, or equal to, the start time
// plus 10,000 milliseconds (10 seconds), show the heart rate
if(time2>=time1+10000) {
 counter();
}


Using Raspberry Pi to Receive Float from Arduino using NRF24L01 Good day. I've been learning on how to transfer data from Arduino to Raspberry Pi wirelessly using NRF24L01 based on the following reference:
Raspberry Pi 3 Tutorial 14 – Wireless Pi to Arduino Communication with NRF24L01+.

The reason why I want to do this is to log temperature and humidity data wirelessly using DHT22 sensors.

The Arduino code is shown below:

//SendReceive.ino

#include<SPI.h>
#include<RF24.h>

// CE, CSN pins
RF24 radio(9, 10);

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

    radio.begin();
    radio.setPALevel(RF24_PA_MAX);
    radio.setChannel(0x76);
    radio.openWritingPipe(0xF0F0F0F0E1LL);
    const uint64_t pipe = (0xE8E8F0F0E1LL);
    radio.openReadingPipe(1, pipe);

    radio.enableDynamicPayloads();
    radio.powerUp();

}

void loop(void){
    radio.startListening();
    Serial.println("Starting loop. Radio on.");
    char receivedMessage[32] = {0};
    if(radio.available()){
        radio.read(receivedMessage, sizeof(receivedMessage));
        Serial.println(receivedMessage);
        Serial.println("Turning off the radio.");
        radio.stopListening();

        String stringMessage(receivedMessage);

        if(stringMessage == "GETSTRING"){
            Serial.println("Looks like they want a string!");
            const char text[] = "Yo wassup, haha";
            radio.write(text, sizeof(text));
            Serial.println("We sent our message.");
        }
    }
    delay(100);

}

Meanwhile, the Raspberry Pi code is shown below:

import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import time
import spidev

GPIO.setmode(GPIO.BCM)

pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]

radio = NRF24(GPIO, spidev.SpiDev())
radio.begin(0, 17)

radio.setPayloadSize(32)
radio.setChannel(0x76)
radio.setDataRate(NRF24.BR_1MBPS)
radio.setPALevel(NRF24.PA_MIN)

radio.setAutoAck(True)
radio.enableDynamicPayloads()
radio.enableAckPayload()

radio.openWritingPipe(pipes[0])
radio.openReadingPipe(1, pipes[1])
radio.printDetails()
# radio.startListening()

message = list("GETSTRING")
while len(message) &lt; 32:
    message.append(0)

while(1):
    start = time.time()
    radio.write(message)
    print("Sent the message: {}".format(message))
    radio.startListening()

    while not radio.available(0):
        time.sleep(1 / 100)
        if time.time() - start &gt; 2:
            print("Timed out.")
            break

    receivedMessage = []
    radio.read(receivedMessage, radio.getDynamicPayloadSize())
    print("Received: {}".format(receivedMessage))

    print("Translating the receivedMessage into unicode characters")
    string = ""
    for n in receivedMessage:
        # Decode into standard unicode set
        if (n &gt;= 32 and n &lt;= 126):
            string += chr(n)
    print("Out received message decodes to: {}".format(string))

    radio.stopListening()
    time.sleep(1)

Based on the Arduino code above, the code that shows the data that is transmitted is shown below:

const char text[] = "Yo wassup, haha";

Based on the Raspberry code above, the codes that decode the received data from Arduino are shown below:

for n in receivedMessage:
    # Decode into standard unicode set
    if (n &gt;= 32 and n &lt;= 126):
        string += chr(n)

However, these decoding code only works if I transmit string or integer from Arduino to Raspberry Pi. It doesn't work if I transmit float. Since DHT22 records temperature and humidity up until 1 decimal point, it is required for me to transmit float. Can anyone here please teach me how to decode the float values?

Thank you very much.

If you say you only need one digit, why not multiplying your value with 10 (with rounding), transmit it as a 4 byte (unsigned?) integer, and divide by 10 after receiving.

You only need to check if you have little or big endian conversion needed (swapping MSB/LSB 2 byte or single byte). But you see this very fast if you print the values in hex format.


can't return float value from function I want to put a 2 seconds delay to temperature reading but the millis() delay is not applying.

#include <OneWire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
#include <DallasTemperature.h>

#define ONE_WIRE_BUS 2

Time t;
LiquidCrystal_I2C lcd(0x27, 16, 2);
DS3231  rtc(SDA, SCL);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

const int OnHour = 23;
const int OnMin = 42;
const int checkTemp = 2000;
const int checkTempinterval = 0;

void setup() {
  Serial.begin(115200);
  pinMode(3, OUTPUT);
  lcd.begin();
  lcd.backlight();
  rtc.begin();
}
void loop() {
  t = rtc.getTime();
  float testTemp;
  testTemp = temperature();
  lcd.setCursor(0,0);
  lcd.print(testTemp);
  lcd.print("   ");
  lcd.print(rtc.getTimeStr());
  lcd.setCursor(0,1);
  lcd.print(rtc.getDOWStr());
  lcd.print("   ");
  lcd.print(rtc.getDateStr());
  if(testTemp >= 28){
    digitalWrite(3,HIGH);
  }else{
    digitalWrite(3,LOW);
  }
//  if(t.hour == OnHour && t.min == OnMin){
//    digitalWrite(3,HIGH);
//  }else{
//    digitalWrite(3,LOW);
//  }
}
float temperature(){
  unsigned long currenttime = millis();
  if(currenttime - checkTempinterval >= checkTemp){
  sensors.requestTemperatures();
  float testTemp = sensors.getTempCByIndex(0);
  currenttime = checkTempinterval;
  return testTemp;
  }
}

I see 2 problems with your code:

Returning a value from a function: If you want to return a value from a function, you will have to make sure, that in any case the return x statement is executed inside the function in the temperature() function you currently have this if statement:

if(currenttime - checkTempinterval >= checkTemp){

Inside of it is the only return statement. That means, if the function is called before the next measurement time, the function will not return anything. Normally the compiler gives you at least a warning about that (maybe you have to turn the warnings on in the settings of the Arduino IDE).

Here you also have to think about, what you want to return, if no measurement was actually executed. Do you want to return an error value (for example -300; the error value should not be found inside valid data)? Then do so after the if statement. Or do you want it to simply return the last measured value? Then declare a variable (either at global scope, meaning outside of any function, or at local scope, meaning inside the function, but static, which means that the value will be retained between the functions executions). Save the measured temperatures to this variable and return it after the if statement.

If you do this, also consider what that means for the rest of your code. For example, if you return an error value, currently it will also be displayed by your code.
Doing the millis() code correctly: What you are doing wrong here, it that you update the wrong variable inside the if statement. Currently you write the value of checkTempinterval (which is the time of the last measurement) to the variable currenttime. The variable currenttime was declared locally (meaning inside the function) by using

unsigned long currenttime = millis();

Local variables are only present during the execution of the function, that they are declared in. When the microcontroller has executed the return statement, it will throw all local variables away, making the RAM free for other variables. That means currently you are saving a value inside a variable, that get's thrown away directly after it.

What you actually meant to do, was to do it vice versa:

checkTempinterval = currenttime;

checkTempinterval is a global variable. It will stay in RAM during the whole program execution. Since it holds the last measurement time, you write the currenttime to it, when you measure.

Very important: Currently checkTempinterval is defined as const int meaning constant integer. This variable must not be constant, since we want to change the value (update the time of the last measurement). Also you should not use int here, because it's value range goes only up to 32767, which is 32 seconds when used with millis(). After that, it will overflow to negative values. Better use the type of millis() return value: unsigned long. It has 4 byte (instead of ints 2 byte) and will only overflow after 49 days. If you only use this variable type for things with millis(), even this overflow will not be a problem.


Controlling LED and Button with single pin I am trying to use an ATTINY85/Ardunio Uno to turn an LED on and listen to a button input. I don't mind if the LED turns on when the button is used.

I am have found this thread from a couple of years ago however it doesn't seem to work at low voltage (3V) due ending up with floating pins due to the forward voltage of the LED. I was wondering if anyone had a soltion or if they could check to see if my solution would be suitable.

Many Thanks

simulate this circuit – Schematic created using CircuitLab

I think this is what you want...

simulate this circuit – Schematic created using CircuitLab

To check for button, set pin to INPUT and enable pullup. If pin is LOW, then the button is pushed.

To light LED, set pin to OUTPUT and LOW.


What is the best way to get started? I am interested in learning about arduino.  What is the quickest and cheapest way to find out if this is something I can and want to do?

The starter kit would get you everything you need to do a whole set of projects. Alternatively there is a PDF on the Arduino site with a whole set of projects in it. You could go through it, put together an inventory of the parts you need, and order those parts from an electronics supplier like Mouser, DigiKey, Jameco, etc, and save some money.

The starter kit is probably worth the extra money, though, because it has everything you need, plus an organized set of lessons that teach you the various skills you'll need.


Can't upload sketches to breadboard Arduino I have an ATmega328 chip with the boot-loader installed.
I also have an Arduino Uno with the ATmega328 chip removed.
I hooked this chip up to a breadboard with the proper 22pF caps, 16MHz crystal, and 10kΩ pull-up resistor.
The LED flasher was loaded prior, and this works fine when I hook an LED and resistor up to pin 19. I have confirmed my external crystal works by disconnecting it, and the flashing stops, when I reconnect the crystal, the flashing continues.
Power is fed from my Arduino Uno 5 V out to the DIY Arduino
I connected the reset wire, and data wires, ensuring pin 2 went to RX and pin 3 to TX.

In the software

First to confirm everything works, I removed the chip from the breadboard and placed it in the Arduino. The sketch uploaded successfully using the settings:  Arduino Uno as board and AVRISP mkll as programmer.

Now I move the chip to the breadboard, and ensure all the wires are connected. The LED starts to blink again, but when I try to upload the sketch, I get an error:

avrdude: stk500_recv(): programmer is not responding

I ensure continuity between the reset, TX, RX, and power connections and try different settings like Arduino as ISP and different boards under settings including the Duemilanove and nano but nothing seems to be working.

Any suggestions on what to try next?

Answered by Skyler440:

  Never mind, found the problem. My software switched to the bluetooth for some reason after I changed some other settings.

Converted to answer to reduce unanswered questions.


Global Variable does not Change when Value is set within Boolean Function I have a boolean function which contains a string. In my main project this string is extracted from a website using an ESP8266 which is compatible with the Arduino IDE. I need to convert this string to a char* type of which is to be used in the loop() section of the code. The issue which I have faced is related to the setting of the mPass global variable, which does not change when it is done in the restoreConfig() Boolean function, meaning it remains blank when called for in the loop.

I do understand that this problem is related to the fact that I am defining the mPass within the Boolean function, however I am unsure as to the process in which I can change the global variable without errors.

I have tried resolving this problem through moving the mqttpass, mqttpasslen and mPass variables out of the restoreConfig() function, however it creates significantly more problems than that which I have at the moment. As a result I have only presented the code without any adjustment below:

char* mPass = "";

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

void loop() {
  if (restoreConfig()) {
    Serial.println(mPass);
    Serial.println("ABOVE IS mPass IN LOOP");
  }
  delay(1000);
}

boolean restoreConfig() {
  String mqttpass = "DOGS";
  int mqttpasslen = mqttpass.length() + 1;
  char mPass[mqttpasslen];
  mqttpass.toCharArray(mPass, mqttpasslen);
  Serial.println(mPass);
  Serial.println("ABOVE IS mPass IN BOOLEAN");
  return true;
}

My current output from this is:

DOGS
ABOVE IS mPass IN BOOLEAN

ABOVE IS mPass IN LOOP

You have local variable mPass in the function restoreConfig. It 'shadows' the global variable.


Chain of, or one big if sentence (This might be more of a common C question)

I want to test several conditions in an IF-sentence

if(variable) {            // fastest check
  if(register) {          // a bit slower
    if(read_peripheral) { // very slow check
      // [do something]
    }
  }
}

It seems obvious that I want to start with the fastest check, and move on to the slower ones afterwards, potentially avoiding to check them if the above was false.

Now since I need to check quite a few conditions, I'd like to know if the following is the same, or if all conditions will be evaluated prior to making a decision?

if(variable && register && read_peripheral) {
  // [do something]
}

Putting them all in a single condition like that is absolutely fine. C/C++ uses "short circuit evaluation" which means it will stop as soon as it's determined the outcome. If everything is combined using logical AND operators (&&) then that means it will stop as soon as one of them evaluates to false.

For example:

 if (blah() && foo()) { ... }

If blah() returns false, it will never call foo() at all because it already knows the overall outcome is false.

The reverse happens with the logical OR operator (||):

 if (blah() || foo()) { ... }

If blah() returns true in this case, it won't call foo(). That's because it already knows the overall outcome is true.


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 ?

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.


Arduino controlled LCD 16x2 is very very dim I was testing out whether my 16x2 LCD works. I hooked it up to the arduino.

Some white box appeared which probably meant it works fine, but the box and the blue background looked very dim even when the potentiometer was turned to the maximum, and did not have the bright blue background which I saw on google.

FYI I soldered copper wire on the LCD and shoved them onto the breadboard since I did not have any pin headers. Would this be a cause of the problem?

I suggest you invest a dollar or so and get some proper wires. Those bare wires, which don't look soldered on, from the top view, just don't cut it. It also looks like the individual wires would short with each other (or are actually shorting).

It will light up when the backlight is correctly connected, which is impossible to tell from your photo.


Power motor with Uno I am trying to power a small peristaltic pump using an UNO R3. I have it powered using usb, and I tried running the blink program to see if I could power it using digital write, and extended the delay to troubleshoot voltages using a multimeter. The motor doesn't do anything connected to the digital pins even when the digital write is set to high. If I connect the motor to the 5 V power pin the motor turns on so I know 5 V is enough voltage. I've looked at tutorials for DC motors and they explain how to set it up with motor reversing using components I don't have, and I don't need it to reverse. How can I get the motor to turn for a specific length of time?

Most likely the motor you are trying to drive requires much higher current than what the UNO can provide through its digital outputs.

Check out this summary to find out detailed specs for the I/O ports.

What you could do is to draw power from the 5V line provided by the Arduino. If that can drive your motor, then use the line to power an output stage, driven by the digital I/O. See this example.
In general, the idea is that the digital I/O provides the control logic, while the output stage provides the power required by the specific load.

The typical loads that can be driven directly by GPIOs are low power LEDs.
Anything that involves moving parts is generally out of reach, power-wise.


Esp8266 server unreachable. Port doesn't open I have followed all the instructions provided on  http://allaboutee.com/2015/01/20/esp8266-android-application-for-arduino-pin-control/

I have got the correct setup, I have got the message "Server Ready" in the serial monitor, i have an app similar to this, means the only thing i have done different from the web page is removing two buttons from the app.

But then also whenever i use my app to send request parameters to arduino it says "connection to 192.168.x.x:xx refused" , when i put the same ip and port in chrome, it says Server not reachable, the website may be down, What to do ? , Please help...

The ESP module is not that difficult to work with, if you send the correct parameters to it AND you have the correct power it should work as expected.

My main suspicions will be cabling (just triple check that connections are as expected) and power source (the ESP is VERY power hungry, if you are powering the ESP from the Arduino that is your problem, you need a very good and stable power for the ESP to work (it might show up on your network but will not have enough power to actually send anything and it will disconnect (that will still show up on your router, it depends on how fast it connects/disconnects but won't be able to send anything).

This link can provide some good information about this subject:

http://bbs.espressif.com/viewtopic.php?t=133


Unable to type in Arduino IDE running on OS X I'm trying to use the Arduino IDE (1.6.8 downloaded from arduino.cc) on a MacBook running OS X (10.11.5 beta).

The IDE seems to run and I can open and upload the examples and they run. But…

I can't type in the editor window of the IDE – either with the examples or with the new sketch that opens when you launch the IDE.

I have a similar problem with the version of the IDE distributed with mBlock (1.6.5) if I use the Edit in Arduino IDE button. I also tried the 1.6.9 hourly version. All to no avail. So I'm thinking that this is a OS X problem, or maybe an issue with version of Java (1.8.0).

Any ideas or troubleshooting suggestions?

Make sure that in preferences the option Use external editor is not checked.


How Arduino IDE works? You know , a simple arduino sketch has no main function , no include preprocess cmds,so I just want to know how arduino IDE convert a sketch to normal C/C++ source code,and what is the source code looks like.

If possible,I also want to use cmd like  g++ -E   to see the .i file genetated after preprocess.How to do it?

ps: my English is poor.

You can turn on verbose compiling.
This will show all the compiler commands used by Arduino IDE.

The ino file is converted to a .cpp file (which you can see in the verbose output). Basically the conversion is as follows:

merge all .ino files into one big .ino file with the [project].ino
file first
Add arduino.h
Add all function declarations of methods defined in the .ino files
Save as .cpp file

As to the lack of main method.
The core contains a main.cpp file which defines main in avr world this looks like

int main(void)
{
    init();

    initVariant();

#if defined(USBCON)
    USBDevice.attach();
#endif

    setup();

    for (;;) {
        loop();
        if (serialEventRun) serialEventRun();
    }

    return 0;
}


ESP8266 sending GET Request and getting 408 Timeout error I am using esp8266 to send a GET Request but I am getting 408 Timeout error.

Here is a screenshot of my output.

I assume you're doing all this from the serial monitor. You can't use escape sequences like \r in the serial monitor entry box. Everything you enter is evaluated as a string of separate ASCII characters; \r is just a backslash character followed by lowercase r. To send a HTTP request, you make the serial monitor send the \r\n for you.

First set the serial monitor to BOTH NL & CR permanently; it will serve you well for commands and HTTP requests as it appends \r\n to everything you send.
Count the number of bytes in the your HTTP request, including the carriage return and newline characters. I count 61 characters in your request.
Use this count in AT+CIPSEND
Type the first line of your request, and stop right before the first \r\n, and click Send. Because of your setting, the monitor will now send what you typed with \r\n suffixed to it.
Type and send each line of the request, just like you sent the first line, until you've sent the last line.
Since there is an additional \r\n after the last line, you click Send again, without typing anything. And since the module requires \r to indicate the end of the data packet, you click Send one last time.

Hopefully, this should give you the right results.


Measure Natural Gas Pressure with arduino? I am looking to measure Gas pressure in order to turn off Gas Heater when there is low gas. As in Pakistan alot of deaths occur when flame turns off because of low pressure of gas and then gas comes back. People suffocate into CO2. So to measure that gas what kind of sensor should i use with arduino?
Thanks

This is a fantastic idea, but you should be a bit more informed before you start the project.

I do not think the people suffocate into CO2 because CO2 is not inflammable under normal conditions so it is not used to feed the heaters. It's produced by the heater while it burns. Most probably the heater uses methane (CH4), ethane (C2H6) or propane (C3H8).

To measure the pressure, you have to insert the sensor within the gas pipe. If this is done incorrect, there is much more danger. So you have to find a fool proved method to add the sensor.

The selection of the sensor depends also on the pressure that can be considered as normal. Another value you have to find out is: how much decreases the pressure if the burner (or more burners) are switched on. i.e at which pressure do you assume the burner's flame to go out. This value must be well known.

When you know the max and min pressure values, you can look for a sensor that can safely measure this values. It should also be included in an enclosing that can be attached to the gas pipeline.

Attention: If the pressure drops just for a small moment, the flame might go off and the sensors might not be aware of that event.

Do you know, there are alternatives to measure the pressure?

A Gas Sensor in the room checks, if there is methane, ethane or propane in the air in the room. ( this is the most secure method ) There are cheap gas sensors from china, (e.g. MQ-02), but I do not know much about them. You can also combine them with a CO2 and/or CO sensors to sense whether the chimney is clogged.

A high temperature sensor near the flame recognizes if the flame is out. But this is difficult to accomplish, because you have to build the sensor into the heater.

EDIT

I want to point you to the comment of @Gerben. Checking the light of the pilot flame or the flame might also be interesting.

Having thought about this a bit,  I still find that measuring the air with gas sensors and starting a acoustic signal is the best way of doing it. If you want to close a valve in case you detect gas, the Arduino can start a siren and control the valve.

Attention: Again, working with gas installations is nothing a beginner should do. You want to save life ...


How do you write to a specific register using I2C communcation? I am trying to write to a charging IC (BQ24193) and I am trying to figure out how to use I2C to write to a specific register so I can set up the charging IC properly. I have watched a few videos on the communication protocol, but I don't understand how to write to a register directly. Your help would be appreciated. Thanks.

Datasheet: http://www.ti.com/lit/ds/symlink/bq24193.pdf

The Arduino uses the Wire.h library to communicate on an I2C bus.

Writing to a register in I2C is usually done by sending two bytes to the correct I2C address.  The first byte is usually the register address, and the second is the value to place into the register:

#define CHIP_ADDRESS     0x6B
#define REGISTER_ADDRESS 0x12

Wire.beginTransmission(CHIP_ADDRESS);
Wire.write(REGISTER_ADDRESS);
Wire.write(0x18);
Wire.endTransmission();

Reading from a register is slightly more tricky, in that first you need to write to the chip to set the register address, then as a separate operation you need to read from that address:

Wire.beginTransmission(CHIP_ADDRESS);
Wire.write(REGISTER_ADDRESS);
Wire.endTransmission();
Wire.requestFrom(CHIP_ADDRESS, 1); // We want one byte
uint8_t val = Wire.read();


Use 2 DHT22 AND PASS THE DATA TO SD? I have the code to pass the data from dht22 to sd but for only one and i want to pass the data from 1 dht22 with one file and the data from other sensor to other file and logging in to sd. Anyone can help me?

#include
#include
#include "DHT.h"
#define DHTPIN 8
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
File data_file;

int CS_pin = 10;
long sec=00;
long mint=00;
long hr=00;

void setup() {
Serial.begin(9600);
pinMode(CS_pin, OUTPUT);
dht.begin(); //This command will start to receive the values from dht22
// SD Card Initialization
if (SD.begin())
{
Serial.println("SD card is initialized and it is ready to use");
} else
{
Serial.println("SD card is not initialized");
return;
}
}

void loop() {
data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
delay(1000);
}

void getData(){
for(long sec = 00; sec < 60; sec=sec+2){
float temp = dht.readTemperature(); //Reading the temperature as Celsius and storing in temp
data_file.print(hr);
data_file.print(":");
data_file.print(mint);
data_file.print(":");
data_file.print(sec);
data_file.print(", ");
data_file.println(temp);
Serial.print(hr);
Serial.print(":");
Serial.print(mint);
Serial.print(":");
Serial.print(sec);
Serial.print(", ");
Serial.println(temp);
if(sec>=58){
mint= mint + 1;
}
if (mint>59){
hr = hr + 1;
mint = 0;
}
data_file.flush(); //saving the file
delay(2000);
}
data_file.close(); //closing the file
}

Thanks

First you need to setup the second DHT sensor and a second file. Please replace the X by the number of the pin your second sensor is connected to after #define DHTPIN2

#define DHTPIN 8
#define DHTPIN2 X
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
File data_file, data_file2;

In setup() you need to also start the second dht sensor:

dht.begin(); //This command will start to receive the values from dht22
dht2.begin(); //This command will start to receive the values from dht22

In loop() you have to open the second data file in addition to the first one:

data_file = SD.open("data.txt", FILE_WRITE);
if (data_file) {
getData();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data.txt");
}
data_file2 = SD.open("data2.txt", FILE_WRITE);
if (data_file2) {
getData2();
}
// if the file didn't open, print an error:
else {
Serial.println("error opening data2.txt");
}

Although not the most efficient/elegant solution, this requires you to duplicate your void getData() function as void getData2() to work for the second sensor/file, by replacing dht by dht2 and data_file with data_file2.
This would do the logging on the two sensors in sequence.
If you want the logging in parallel you need to add the measurement and writing of the second sensor/file into the void getData() function.


Functions with string parameters Inside my main loop there is this string:

String string1;

I have a function that will take string1 as parameter, and use it to send this string as SMS.

sendSMS(string1);

This is the sendSMS() function (without parameters):

void sendSMS()
{ sms.beginSMS(remoteNumber);
  sms.print(finalstr);
  sms.endSMS();
  lcd.setCursor(0, 0);
  lcd.print("Message sent!");
  delay(10000);
}

My questions are:

How do I put the string input parameter in sendSMS?
Do I also need to use a function prototype for sendSMS()? (so that it appears three times, 1 in the prototype, 1 in the declaration and one in the call). Or I don't need to use function prototype before the main loop()?

Just change

void sendSMS()

to

void sendSMS(const String& thisIsAString)

You can then access the parameter inside the function with thisIsAString.
No, you do not need a prototype.


Writing serial data on a pin on Arduino I want to write some data (GPS) to a digital port on Arduino.  As far as I understand sending data via a pin as if it were USB is possible. But I don't know what function to use. digital.Write doesn't expect any data or strings. How do I write serial data on to a digital pin

Using the arduino library "software Serial" (https://www.arduino.cc/en/Reference/SoftwareSerial) you can use any pin to write/read serial data.


How to print a line with a variable in it? I want to know if there is a way to write like in C programming:

  printf("the num is %d",num);

I know that to print a line or a variable the command will be Serial.println
when I write:

 Serial.println("the num is %d",num);

It's not working.

Is there a way to write it in just one line?

I use:

Serial.println("The temperature is " + String(temperature) + " degrees C");

With this solution you can't format the variable's value but I find this quick and dirty for debug messages.


Can't read two bytes through Serial.read - Arduino I'm sending via Bluetooth with an Android App two bytes like this:

private void _sendCommand(byte command, byte arg)
{
    if (CONNECTED)
    {
        try
        {
            os.write(new byte[]{command, arg});
            os.flush();

        } catch (IOException e) {
            Log.e(TAG, "Error sending command: " + e.getMessage());

        }
    }
}

And this is the code I'm using to receive them with Arduino:

byte _instruction;
byte _arg;

void loop()
{
  while(Serial.available() < 2)
  {
    digitalWrite(LED_BUILTIN, HIGH);
  }

  digitalWrite(LED_BUILTIN, LOW);

  _instruction = Serial.read();
  _arg = Serial.read();
  Serial.flush();

  switch (_instruction)
  {

     ...

  }
}

I don't have any problems sending just one byte (modifying the code to receive just one), but I can't do the same with two bytes. It's always stuck in the while. Any idea of what I'm doing wrong?

EDIT: As ST2000 pointed out, there was a problem of syncronization, so this is the code working properly:

void loop()
{
  // Wait until instruction byte has been received.
  while (!Serial.available());
  // Instruction should be read. MSB is set to 1
  _instruction = (short) Serial.read();

  if (_instruction & 0x80)
  {
    // Wait until arg byte has been received.
    while (!Serial.available());
    // Read the argument.
    _arg = (short) Serial.read();

    switch (_instruction)
    {
      ...
    }
  }

  Serial.flush();
}

Thanks,

There may be a underlying problem with synchronizing the transmitter and receiver.  They both have to agree / know which is a command byte and which is a data byte.

In order to do this, some protocols sacrifice a bit. For example you could set the most significant bit for commands and not set the most significant bit for data. However, that does mean you can only send data in the range of 0 to 127. And it does restrict you to only 128 commands. If you need more, and want to stick to this "most significant bit" approach, you could break your data into chunks and only send 7 bits at a time. The possibilities are many. Use this one or make one up that fits your needs better.

In order to implement this approach, you will need to read and process each byte as it arrives.  You can not wait until you accumulate the expected number of bytes as this assume you are always in sync with the transmitter. Which may not be the case.


4 Bit Counter up and down we are asked to create an Arduino code that would run a 4 Bit Binary UP counter once a push button switch is pressed and then 4 Bit Binary Down counter on the second click. Then vice versa. This should be done using only one switch. I figured out the Count up portion but I don't know how to add the count down code for the same switch. Can someone help me with this. Thank you.
please see below for my program

int buttonState = 0;
int timer = 300;
int pin8 = 8;
int pin9 = 9;
int pin10 = 10;
int pin11 = 11;

void setup()
{
pinMode(7,INPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);

}

void loop()
{
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
buttonState = digitalRead(7);

if(buttonState == HIGH)
{
digitalWrite(pin8, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
delay(timer); //bit 1
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
delay(timer); //bit 2
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
delay(timer); //bit 3
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
delay(timer); //bit 4
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 5
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 6
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 7
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin11, LOW);
delay(timer); //bit 8
digitalWrite(pin8, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 9
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 10
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 11
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 12
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 13
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 14
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 15
}
}

Currently you are just setting the LEDs manually one after another in your code. That is not actually a binary counter (as it is most likely wanted by the exercise), but only looks like one.
First you need to understand, what a counter really is: Basically it is just a variable, that holds a number. Where exactly this variable is saved, is not important. For your case you would use a variable in your code. The Counter/Timer hardware in the Arduino uses a fixed SFR (Special Function Register) for it.
That the counter is 4bit, means, that its value is hold by only 4 bits. That gives you a value range from 0 to 15 (2^4 values). So a 4bit counter variable would count from 0 to 15. You could just have a counter variable, that you could increment or decrement (depending on the direction, that you want to count).
// Declare counter variable and initialize with zero
int counter_variable = 0;
// Increment
counter_variable++;
// or Decrement
counter_variable--;

For the "binary" part: Here it is important to understand, that the decimal number from 0 to 15 is already saved in the variable as binary (since microcontrollers/computers only know binary, nothing else). So you can write out the state of the 4 least significant bytes of the counter variable:
digitalWrite(pin8  ,counter_variable & 0b0001);
digitalWrite(pin9  ,counter_variable & 0b0010);
digitalWrite(pin10 ,counter_variable & 0b0100);
digitalWrite(pin11 ,counter_variable & 0b1000);

The & is a bitwise AND. The result of the operation will only leave bits set, when they are set on both sides. So here we are isolating the corresponding bits. digitalWrite() will interpret anything but zero as HIGH. Thus the pin is set HIGH, if the corresponding bit is set in counter_variable. But you see, that we are repeating us here. We could use a for loop and define our pins in an array:
// at global scope
int led_pins[4] = {8, 9, 10, 11};

// in the button if statement
for(int i=0; i<4; i++){
    digitalWrite(led_pins[i], counter_variable & (1 << i));
}

We have organized the pins of the LEDs in an array, so they can be easily indexed. Then we are looping through the pins array and setting the pins similar to the last version. But now we are using (1 << i). The << operator shifts the bits of the number before it by the number of digits, that comes after it. Decimal 1 is binary 0b0001. So, when i is 2 (for example), this would shift the bits 2 digits to the left, giving you 0b0100. We are just generating the same bit patterns as in the last version.
But we can even optimize further via direct port manipulation. Inside the microcontroller the output pins are controlled via simple Special Function Registers. They work somewhat like a variable. All output pins are organized into socalled "Ports" (groups of up to 8 pins). Each port has one PORTx registers (where x stands for the character associated with that port), which sets the state of the pins, if they are in output mode. Setting the corresponding bit in the correct PORTx register will set the pin to HIGH. Clearing the bit (setting to zero) will set the pin to LOW.
You are using the Arduino pins 8 to 11. If you look at a pinout diagram of the Arduino Uno, you will see, that these pins are also marked as PB0 to PB3, which stands for "Port B, pins 0 to 3 (inside that port)". The corresponding PORTx register is PORTB. So we can set all pins of the port at once by assigning a new value to that register. The following code would set an alternating on/off pattern for all 8 pins of PORTB:
PORTB = 0b10101010;

Now we only want to use the lowest 4 bits and set them to the values, that our counter variable has. So we are masking away the 4 higher bits with the bitwise AND operator and then assign that value to the register:
PORTB = counter_variable & 0b00001111;

So now the if statement in void loop() might look like this (using a for loop):
if(buttonState == HIGH){
    // count up counter variable
    for(int counter_variable=0; counter_variable < 16; counter_variable++){
        // write out to the pins
        PORTB = counter_variable & 0b00001111;
        // delay a bit to show the value
        delay(timer);
    }
}

And now we want that each consecutive button to count in the other direction than before. So we can declare another variable as direction and then use another if statement, to switch between two for loops:
// On global scope
int direction = 1;

// in void loop()

if(buttonState == HIGH){
    if(direction == 1){
        // count up counter variable
        for(int counter_variable=0; counter_variable < 16; counter_variable++){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = -1;
    } else {
        // count up counter variable
        for(int counter_variable=15; counter_variable >= 0; counter_variable--){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
        // change direction
        direction = 1;
    }
}

Note:

This is probably not the most efficient way, but I think it is quite understandable (which is also important).
This still uses much delay() calls, just as your code. That will make your button unresponsive. The counter must first finish, before the button will react again. That might be ok for you. If not, you need to restructure the program for using a non-blocking coding style like in the BlinkWithoutDelay example from the Arduino IDE (using millis()). There are lots of tutorials about that on the web.
When using a non-blocking coding style, you also need to check the button for the transition to HIGH, instead for the state high. Otherwise the code would run only, while the button is pressed.
Buttons bounce, when being pressed. So there are many transitions between HIGH and LOW for a few ms, when the button is pressed. In the code above this is not important, because the started counter needs so long, that every bounce is finished after the counter finished. With code, that needs less than a few ms, you might get into problems there. I would suggest the Bounce2 library for that. It handles the bounce detection for you.


Nodemcu stops sending the messages to the API Here is my code which sends some data to the firebase cloud functions. The code works well and the nodemcu sends the data to the cloud for about half an hour and then stops sending the messages.

#include <OneWire.h>
#include <DallasTemperature.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>

#define ONE_WIRE_BUS 5

// Use WiFiClientSecure class to create TLS connection
WiFiClientSecure client;

OneWire oneWire(ONE_WIRE_BUS);

DallasTemperature sensors(&oneWire);
String data="";
const char* ssid = "***************";
const char* password = "**************";

const char* host = "**************************";
const int httpsPort = 443;

String url = "/getData";
float Celcius=0;
float Fahrenheit=0;
int sensor_light;
int sensor_temp;
int sensor_moist;
void setup() {
ESP.wdtDisable();
pinMode(16,OUTPUT);//moist
pinMode(0,OUTPUT);//light
Serial.begin(115200);  //Serial connection
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());

Serial.print("connecting to ");
Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
ESP.wdtEnable(WDTO_8S);
}
void loop()
{
 client.connect(host, httpsPort);
 int l,m,t;
 data=" ";
 l=get_light();
 t=get_temp();
 m=get_moist();
 if(WiFi.status()== WL_CONNECTED){
    data+="{";
    data+="\"";
    data+="Node-Id";
    data+="\"";
    data+=":";
    data+=1;
    data+=",";
    data+="\"";
    data+="light";
    data+="\"";
    data+=":";
    data+=l;
    data+=",";
    data+="\"";
    data+="temperature";
    data+="\"";
    data+=":";
    data+=t;
    data+=",";
    data+="\"";
    data+="humidity";
    data+="\"";
    data+=":";
    data+=m;
    data+=",";
    data+="\"";
    data+="Latitude";
    data+="\"";
    data+=":";
    data+=29.3589362;
    data+=",";
    data+="\"";
    data+="Longitude";
    data+="\"";
    data+=":";
    data+=79.5506528;
    data+="} ";
    Serial.println(data);
    client.print(String("POST ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n"+
           "Content-Length: " + data.length()+ "\r\n" +
           "Content-Type: application/json;charset=UTF-8\r\n\r\n"+
            data +"\r\n");
    //  Serial.println("Sent");
    String line = client.readStringUntil('\n');
    Serial.println(line);
    while(!client.connected())
        { client.stop();
          ESP.wdtFeed();
         }
     }
    delay(4000);
    }

    int get_light()
    {
    digitalWrite(0, HIGH);
    sensor_light=0;
    sensor_light = analogRead(A0);
    digitalWrite(0, LOW);
    delay(2000);
    return sensor_light;
    }
    int get_temp()
    {
    int  sum=0,i;
    for(i=0;i<10;i++)
      {
    sensors.requestTemperatures();
    Celcius=sensors.getTempCByIndex(0);
    delay(250);
    sum+=Celcius;
    }
    Celcius=sum/20;
    delay(2000);
    return Celcius;
    }

    int get_moist()
    {
     digitalWrite(16, HIGH);
    sensor_moist=0;
    sensor_moist = analogRead(A0);
    digitalWrite(16, LOW);
    delay(2000);
    return sensor_moist;
    }

If I do not use ESP.wdtFeed() and other similar functions then I am getting Soft wdt reset error. I am using the laptop to power it. Any help?

Remove the return in setup function and check. And set regular yield () statements to ensure smooth running of background tasks. And use if statement in the loop for !client.connected()


Debugging modified BlinkWithoutDelay I have some level of programming background, however never with Arduino's. I've just started hacking at the examples - I'm not even sure what language I'm currently writing. I presume it's C++.

Anyway, I figured I'd try out the pin 13 LED with the BlinkWithoutDelay example. I've got that running fine (which I was very excited about), however I've tried to modify it to blink out SOS in Morse code, but it doesn't appear to be working.

// constants won't change. Used here to set a pin number :
const int ledPin =  13;      // the number of the LED pin

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

// constants won't change :
//unsigned long interval = 1000;           // interval at which to blink (milliseconds)

// Number of times to blink
const long blinkMax = 10;
// Counter for number of times blinked
unsigned long blinkCount = 0;

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  int loopCount = 0;
  // S O S
  int values[] = {1000, 1000, 1000, 200, 200, 200, 1000, 1000, 100};
  blink(values[loopCount]);
  loopCount = loopCount + 1;
}

void blink(int interval)
{
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

As you can see, I've assigned the time values (1000 for long and 200 for short) to an array and had the loop function call my blink function each time. Every time it loops, it increments and goes to the next value.

I know it's able to pull values from the array fine, as I've tried manually modifying loopCount just before the blink() and it blinks at the specified timeout. I presume the loopCount increment is fine (I also did loopCount++; - no luck).

If someone could point me in the right direction, this would be great. Thanks!

Since it's blink without delay, the next loop will happen immediately. Not after the blink function is don't. So loopCount will increment continuously. You don't limit loopCount to 9, so it will after a few milliseconds try to access, e.g. values[12] which doesn't exist. (see @jfpoilpret's comment)

// constants won't change. Used here to set a pin number :
const int ledPin =  13;      // the number of the LED pin

// Variables will change :
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated
int blinkValues[] = {1000, 1000, 1000, 200, 200, 200, 1000, 1000, 100};
int loopCount = 0;

// constants won't change :
//unsigned long interval = 1000;           // interval at which to blink (milliseconds)

// Number of times to blink
const long blinkMax = 10;
// Counter for number of times blinked
unsigned long blinkCount = 0;

void setup() {
  // set the digital pin as output:
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  blink();
}

void blink()
{
  unsigned long currentMillis = millis();
  if(currentMillis - previousMillis >= blinkValues[loopCount]) {
    previousMillis = currentMillis;
    loopCount = (loopCount + 1) % 9;
    if (ledState == LOW)
      ledState = HIGH;
    else
      ledState = LOW;
    digitalWrite(ledPin, ledState);
  }
}

Also note that the blink function will toggle the led, after the interval. So you need to add intervals, for how long the led should be off between flashes. But I leave that for you to figure out.


How to get the weather kit with anemometer working using arduino (UNO)? I tried to build a weather station with anemometer and My setup is,
SwitchDoc Labs' anemometer kit (which is equivalent to sparkfun anemometer kit) connected to the grove weather-pi board with rtc clock DS3231 installed on which is connected to arduino UNO.

According to http://www.switchdoc.com/wp-content/uploads/2016/07/WeatherBoard_CurrentSpecification.pdf and their official tutorial https://www.switchdoc.com/2015/01/weather-arduino-weatherpiarduino/, if I use grove weather-pi board's JP2 connections to connect to the UNO/Mega2560 board then it suggests as following (in my case its UNO)

diagram 1
diagram 2

GroveWeatherPi_board    Mega        Uno     Units
    JP2/1 ->            A0          A0      WindVane
    JP2/2 ->            D2          D3      RainBucket
    JP2/3 ->            D5          D2      Anemometer
    JP2/4 ->            GND         GND     GND

And the supposedly working sketch/library is https://github.com/switchdoclabs/SDL_Weather_80422 which only compiles on arduino-IDE without issue if I use the fork https://github.com/soligen2010/Adafruit_ADS1X15 instead of the original https://github.com/adafruit/Adafruit_ADS1X15 with it but even then the wind-speed and wind-direction unit or to say the whole anemometer part just do not work or in other words, do not give any reading. I have tested the units individually up to the arduino pins with LED light on breadboard, they are sending signals/responding and also mounted the whole project on a Mega2560 as well but results remained unchanged.

I am assuming the pin-outs defined in the https://github.com/switchdoclabs/SDL_Weather_80422 are messed up then but how to redefine it in the sketch/library because in the ino sketch file, these are the pin-out definitions for primarily Mega2560

#define pinLED     13  // LED connected to digital pin 13
#define pinAnem    18  // Anenometer connected to pin 18 (not used in the diagram!) - Int 5 - Mega   / Uno pin 2
#define pinRain    2   // Anenometer connected to pin 2 - Int 0 - Mega   / Uno Pin 3
#define intAnem    5   // int 0 (check for Uno), according to the above two diagrams' comparison, for UNO this pin also goes to the pin 2
#define intRain    1   // int 1 (not used in the diagram! Then why? Its a TX pin)

Where the pinAnem and intAnem both indicates pin 2 for UNO according to the above two diagrams.

When I connect the I2C vcc pin from grove-weather-board to UNO's 5 volts instead of 3.3 volts as shown, the wind direction gets fixed but still no wind-speed reading.

So what are the corrections I need to do in the SDL_Weather_80422 library or in the connection diagram in this case?

According to the above setup only rain bucket unit works.

And as jsotola mentioned both the anemometer and the rain bucket sensors are simple switches, so a simple sketch can be written that reads the switch state and light LED (pin13) if the switch is activated and turns off LED if switch is not activated and that can be done for each of the switches separately.

But instead I took a shortcut.

Fixes:

The wind vane part (on analog pin A0) starts working only when I connect the I2C vcc pin to 5 volts pin instead of 3.3 volts pin of UNO.
Had to ditch the https://github.com/switchdoclabs/SDL_Weather_80422 library's wind_speed reading method and adopting and merging into the http://cactus.io/hookups/weather/anemometer/davis/hookup-arduino-to-davis-anemometer-wind-speed code and adding up the wind_gust function from https://github.com/sparkfun/Weather_Shield/blob/master/Firmware/Weather_Shield_Weather_Station_V12/Weather_Shield_Weather_Station_V12.ino makes the anemometer with rain-bucket with the exact same setup fully functional.


ToF VL53L1X sensor integrate with arduino I have this latest version VL53L1X time of flight laser distance sensor: http://www.st.com/en/imaging-and-photonics-solutions/vl53l1x.html

I study about this sensor, It says that sensor only Access with API(Application program Interface) how do I Integrate that API code in arduino or
how do I use Wire library to Integrate this sensor.

There's actually a library created by Pololu that is quite straightforward to use so you don't need to worry about any of that. I think it covers all available functionality.
https://github.com/pololu/vl53l0x-arduino

I was also a bit confused by the API comment and the datasheet.

I misread the device name so the above is not relevant.

In theory I think to use the API you can just #include the C code they provide into your sketch like a normal library. You can download the API code from the manufacturer ST here.
You'll need to give your name and email but it's free.
It's in C but you can probably understand it if you're familiar with Arduino/C++.

Before compiling you would also need to implement some I2C functions for which they provide prototypes (in the vl53l1_platform.c file). However, I think there are some additional steps when using C files that you will need to take to get this to compile, unfortunately I am not familiar with this so can't help - if anyone does then they can probably write a more complete answer.

The alternative is to write your own functions that replicate the functionality that is described in the API.
I would do this by looking at the basic process flow in the API User Manual, taking each function and working through the API files to see what it does.
The main thing you're looking for is the registers that you need to write (via I2C) in order to trigger a range measurement starting, and then the registers that you need to read to find out the result.
I would note that there are multiple levels of #defines for some of the register values and there is a lot of code that deals with managing the status of the device, so this might take a while.