message:
Uploading sketch to ESP8266

I'm managing to upload a sketch to the ESP8266 01. I have been researching on internet but I'm not able to get it.

I have installed the libraries for Arduino IDE and my circuit is the ESP powered by 9V converted to 3.3V using a LD 3.3 converter. I tested the voltages and works fine. Also the led in ESP is on (red).
To connect to the computer I'm using a TTL USB cable without vcc connected only for tx and rx.

The commands for the ESP works fine (AT commands), but when I try to upload a sketch it shown the following error:

> espcomm_open failed

I also have connected to GP0 (ESP) a button to ground. The circuit is:

9V battery --> 3.3V converter --> ESP---> TTL

Anyone knows about that error and why could be? Because the AT commands works fine. Maybe I need to provide more information but not sure.

My goal is to do this tutorial:
https://learn.adafruit.com/downloads/pdf/esp8266-temperature-slash-humidity-webserver.pdf

Another problem that I have following that tutorial is that in Arduino IDE, I cannot setup esptool as programmer, because isn't there. I loaded the same library for esp

body:
Following on from user1637451 the following sequence has always worked for me:

 1. Before download, pull both GPIO0 and RST to ground.
 2. Release the pull down on RST, but keep GPIO0 low.
 3. When the IDE has finished downloading, release GPIO0 from low.

I usually have pull-up resistors (10K) on both RST and GPIO0.

As to the IDE problem. I used the tutorial from Sparkfun entitled "ESP8266 Thing Hookup Guide" and then the section "Installing the ESP8266 Arduino Addon". Because I used a different ESP8266 board to them I set the IDE to use the "generic ESP8266 board". This worked for me.


sender: user

message:
Getting a binary string and convert it to decimal

I have a 4 dipswitch to get a 1 or a 0, try to get that into a string and from that get a decimal, therefor if I get for example a 0011 a 3.

so, I know that from the variations of 0000 to 1111 is a decimal from 0 to 15, I already have my string but how do I convert the "binary string" to decimal?

to get the string I'm using this (the I is at 5because there is where is the dipswitch):

          for(int i = 5; i <= 9; i++){
               Serial.println(digitalRead(i));
               Dstate = Dstate + digitalRead(i);
          }

sender: assistant

body:
What you want are the bit-shifting operators << and >>, and the OR operator |:

    for(int i = 0; i < 4; i++) {
        Serial.println(digitalRead(5 + i));
        Dstate = Dstate | (digitalRead(5 + i) << i);
    }

You'll notice I changed the loop so it runs from 0 to 3 instead of 5 to 9 - it makes other parts easier if you start counting from 0.

Then the line:

    Dstate = Dstate | (digitalRead(5 + i) << i);

is where all the magic happens.  Let's break it down:

    digitalRead(5 + i)

That of course gives you a 0 or 1 for pins 5, 6, 7 and 8 in turn.

    << i

That shifts the value returned by `digitalRead()` left `i` bits.  For instance, if `digitalRead()` returns 1 and `i` is 0 then `1` is left shifted 0 times so remains as 0b0001.  If `i` is 1 then it left shifts one bit, so the value becomes `0b0010`.  If `i` is 2 then it shifts two bits, so you get `0b0100`.

Finally the result is combined with the current value of `Dstate` with OR, so the four values basically get laid over the top of each other.

So say you have the four switches in the positions ON-OFF-ON-OFF and `Dstate` starts off as 0, then the sequence would be:

    i = 0, digitalRead = 1, shifted = 0b0001, OR = 0b0001
    i = 1, digitalRead = 0, shifted = 0b0000, OR = 0b0001
    i = 2, digitalRead = 1, shifted = 0b0100, OR = 0b0101
    i = 3, digitalRead = 0, shifted = 0b0000, OR = 0b0101


message:
Arduino Leonardo bugs and lack of removable microcontroller

Following one of the [article][1] from 2013 :

> Before you start hammering that “add to shopping cart” button, note
> that the general impression around the web seems to be that the
> Leonardo still has a few bugs that need ironing out, and isn’t quite
> as beginner friendly as the Uno. For builders already familiar with
> Arduino, this is the better deal.

The question is if Leonardo is still buggy and may cause any confusion to newbie Arduino programmers. Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

  [1]: http://www.tested.com/tech/robots/456466-know-your-arduino-guide-most-common-boards/

body:
> The question is if Leonardo is still buggy

Probably.

> and may cause any confusion to newbie Arduino programmers.

Definitely.  The whole way the Leonardo works is very different to the likes of the Uno. Transitioning from one to the other, if you don't know what the differences really mean, can be confusing.

> Furthermore, Leonardo doesn't have removable chip, so how can one transfer the project into a separate processor and use Arduino to the other project?

You build your circuit on a PCB and you provide an ICSP header.  ICSP stands for *I*n *C*ircuit *S*erial *P*rogramming.  You then use a hardware programmer to install either the Leonardo bootloader, which can then be used to install sketches through USB, or install a sketch direct without the bootloader.

Or, if you're making thousands of them you send your code to Atmel and they burn it to the chip in the factory for you - at a price of course.


message:
Turning on led every half hour

How can I make my program so that every half hour LED lights on and work for 5 minutes and than go off and the process should repeat

I made code but it does not works. Can someone help me?

    void setup() {
      pinMode(8,OUTPUT);

    }
    void loop() {
      digitalWrite(8,HIGH);
      delay(300000);
      digitalWrite(8,LOW);
      delay(1800000);

    }

body:
I see that the code is OK,
are you sure that the led pis is 8 ?
what is your input voltage ? (is it between 7 to 12 ?)
did you tried lower time values ? (like 1:2 minuts ?)
if you answer to all of these questions is "yes" then probably the arduino board is broken.


body:
You need to make sure that the LED is connected with the right polarity, you need to connect the negative to Ground and the positive to the digital pin 8.

Try the led by connecting 3.3v and GND so you are sure that the led is not broken.


body:
 1. Test the LED: Connect it between +5v and ground _with_ its current-limiting resistor. Make sure the cathode is connected to ground and not the other way round. Inside the plastic bubble are two tiny bits of metal. The larger one is the cathode. Does it light? If not, the LED is faulty or the resistor is too high.

 2. Reconnect the LED to pin 8, which is physical pin #14. (In case you got confused and used physical pin 8, no harm was done - physical pin 8 is another ground!) Reduce the delay times to 1 second on, 1 second off. Again be sure to connect its cathode side to ground. Does it blink? If not, perhaps Arduino's pin 8 driver is faulty.

 3. Try the same thing on a different pin (adjusting your code, of course). If it still doesn't blink, there is probably an issue with either the MCU chip or the power you're supplying to it. Assuming you used the board's +5v and ground in test (1.), then the power is OK and the chip is likely the cause.


message:
what is the difference between providing 7 volts or 12 volts to arduino uno?

according to [this][1] the recommended input voltage is between 7 and 12 volts.
The question is what is the difference between providing 7 volts(minimum recommended volts) and 12 volts(maximum recommended volts) ?.

  [1]: https://www.arduino.cc/en/Main/ArduinoBoardUno

body: The amount of heat dissipated by the voltage regulator.  The higher the voltage you supply the hotter the regulator will get.


message:
Why atmega168/328p starts to reset?

First we set fuse bits:

    avrdude -c usbasp -p atmega328p -U lfuse:w:0xFF:m -U hfuse:w:0xDF:m -U efuse:w:0x07:m # same for atmega168

In the following examples we use the following commands to compile and burn all the programs:

    avr-gcc -Os -mmcu=atmega328p -c -o serial.o serial.c
    avr-ld -o serial.elf serial.o
    avr-objcopy -O ihex serial.elf serial.hex
    avrdude -c usbasp -p atmega328p -U flash:w:serial.hex

Let us burn the following program:

    #define F_CPU 16000000UL
    #include <avr/io.h>
    void main (void) {
      DDRB |= (1<<PB5);
      PORTB |= (1<<PB5);
      while (1);
    }

It makes the led to be on constantly. And it stays so for infinite period of time.

Then we burn the following program:

    #define F_CPU 16000000UL
    #define BAUD 9600
    #include <avr/io.h>
    char data = 0;
    void main(void) {
      // Initialize USART:
      #include <util/setbaud.h>
      UBRR0H = UBRRH_VALUE; // set the speed (Higher bit)
      UBRR0L = UBRRL_VALUE; // set the speed (Lower bit)
      UCSR0B |= (1<<RXEN0); // enable receiver
      UCSR0C |= (1<<UCSZ01)|(1<<UCSZ00); // set mode (8N1)
      DDRB |= (1<<PB5); // enable output on pin PB5 (default led on arduino)
      while(1) {
        while(!(UCSR0A&(1<<RXC0))); // wait until a byte is received
        data = UDR0; // read it
        if (data) PORTB |= (1<<PB5); // set the led on
      }
    }

Then we open a terminal (9600,8N1) and press several keys, until the led turns off.
Now we burn the first program again and the led is constantly blinking. The reason for this is that watchdog times gets started when we press the keys in terminal. But why and when WDT gets started? How to make so that it will not start?

It should be noted also that we can disable the blinking only with complete poweroff/poweron - only after that the led lights constantly without blinking, as necessary.

This happens on atmega168 and atmega328p, 100% reproducible.

avr-gcc version 4.8.1 avrdude version 6.1

**NOTE:** bootloader is not used at all.

body:
WDT settings will remain unchanged, even after a reset. So the timer will keep running and therefore keep resetting the device. Which causes the blinking. Power cycling will clear the WDT settings.

PS I didn't read the code, as uncommented register writes are pretty much unreadable.


body:
The problem code was reduced to this:

    #define F_CPU 16000000UL
    #include <avr/io.h>
    char data;
    void main(void) {
      UBRR0H = 0x00;
      UBRR0L = 0x67; // baud=9600
      UCSR0B = 0x10; // 00010000
      UCSR0C = 0x06; // 00000110
      DDRB |= (1<<PB5);
      PORTB |= (1<<PB5);
      while(1) {
        data = UDR0;
      }
    }

This is the code which works:

    #define F_CPU 16000000UL
    #include <avr/io.h>
    void main(void) {
      char data;
      UBRR0H = 0x00;
      UBRR0L = 0x67; // baud=9600
      UCSR0B = 0x10; // 00010000
      UCSR0C = 0x06; // 00000110
      DDRB |= (1<<PB5);
      PORTB |= (1<<PB5);
      while(1) {
        data = UDR0;
      }
    }

But I don't know how to explain that char inside main makes the problem disappear...

**EDIT**
Just for the record, here are two more examples. The first example works with both compilation methods. The second example works only with the second compilation method. The examples differ only with that in the first direct code is used, and in the second it is used via functions.

    #define F_CPU 16000000UL
    #define BAUD 9600

    #include <avr/io.h>
    void main(void) {
      char data;
      #include <util/setbaud.h>
      UBRR0H = UBRRH_VALUE;
      UBRR0L = UBRRL_VALUE;
      UCSR0B = (1<<RXEN0)|(1<<TXEN0);
      UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
      DDRB = (1<<PB5);
      while (1) {
        PORTB ^= (1<<PB5);
        while(!(UCSR0A&(1<<RXC0)));
        data = UDR0;
        UDR0 = data;
        while(!(UCSR0A&(1<<TXC0)));
      }
    }

<!-- -->

    #define F_CPU 16000000UL
    #define BAUD 9600

    #include <avr/io.h>
    void serialSetup(void) {
      #include <util/setbaud.h>
      UBRR0H = UBRRH_VALUE;
      UBRR0L = UBRRL_VALUE;
      UCSR0B = (1<<RXEN0)|(1<<TXEN0);
      UCSR0C = (1<<UCSZ01)|(1<<UCSZ00);
    }
    void serialSend(char data) {
      UDR0 = data;
      while(!(UCSR0A&(1<<TXC0)));
    }
    char serialGet(void) {
      while(!(UCSR0A&(1<<RXC0)));
      return UDR0;
    }
    void main(void) {
      char data;
      serialSetup();
      DDRB = (1<<PB5);
      while (1) {
        PORTB ^= (1<<PB5);
        data = serialGet();
        serialSend(data);
      }
    }


body:
One thing that I found whilst experimenting with command line compilation is that for some strange reason no startup code was being linked with my code, so it all went completely screwy.

I finally tracked the problem down to a missing command line flag while linking.

First, you need to link with `avr-gcc` not `avr-ld`.  Second, you need to pass the `-mmcu=atmega328p` flag to the link command so that it knows which startup code to link in.

This is my complete command line sequence for compiling a simple blink program:

    avr-gcc -g -mmcu=atmega328p -ffunction-sections -fdata-sections   -c -o blink.o blink.c
    avr-gcc -mmcu=atmega328p -Wl,--gc-sections -o blink.elf blink.o
    avr-objdump -S blink.elf > blink.dis
    avr-objcopy -O ihex -R .eeprom blink.elf blink.hex

You notice I'm making function and data sections too, and then garbage collecting the unused ones - good practice since it can very much reduce the size of your finished program.

I am doing this through a Makefile, which looks like this:

    PREFIX=avr-
    CC=${PREFIX}gcc
    CXX=${PREFIX}g++
    LD=${PREFIX}ld
    AS=${PREFIX}as
    OBJCOPY=${PREFIX}objcopy
    OBJDUMP=${PREFIX}objdump

    BIN=blink
    MCU=atmega328p
    OBJS=blink.o

    CFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections
    CXXFLAGS=-g -mmcu=${MCU} -ffunction-sections -fdata-sections -fno-exceptions
    LDFLAGS=-mmcu=${MCU} -Wl,--gc-sections

    ${BIN}.hex: ${BIN}.elf
     ${OBJCOPY} -O ihex -R .eeprom $< $@

    ${BIN}.elf: ${OBJS}
     ${CC} ${LDFLAGS} -o $@ $?
     ${OBJDUMP} -S $@ > ${BIN}.dis

    install: ${BIN}.hex
     avrdude -c usbasp -p ${MCU} -U flash:w:${BIN}.hex -qq

    clean:
     rm -f *.o *.elf *.hex

    fuses:
     avrdude  -c usbasp -p ${MCU} -U lfuse:w:0xff:m -U hfuse:w:0xd6:m -U efuse:w:0x05:m -qq


message:
Algorithm to detect motion using ultrasonic sensor

I have a PIR sensor which sometimes give false readings and I have added a ultrasonic sensor to compensate for that. I think my algorithm can work, however currently it is very prone to give false positives.

## Algorithm theory ##

My idea is to have an arduino which will obtain six samples and wait 25 milliseconds between each sample and then calculate the [variance](http://www.mathsisfun.com/data/standard-deviation.html). If the variance exceeds a specific threshold, which I have set to a thousnad, it will send an motion event over the serial bus.

## Problem with the algorithm ##
Ultrasonic sensors can give faulty responds which usually isn't hard to detect. My HC-SR04 sensor can only accurately read the distance between 2 cm and 400 cm. All the faulty readings are usually way over 400 cm or lower than 2 cm, therefore if is not within these boundaries a new try will be made to get a value within the boundaries, if it fails for three times it will assume the distance is exactly 400 cm.

It is redundant to wait for more than 23280 µs because 400*29.1*2 is the corresponding microseconds it would take for the distance to be 400 cm. `pulseIn` has a timeout value which can be used for this.

In theory this sounds great to me but very often this algorithm will erroneously send motion events. My belief for this is that when the ultrasonic sensor transmitts a wave and wait for it come back, `pulseIn` will timeout and retry and yet again ask the sensor to send a wave. This happens before the first wave has come back thus the distance will be incorrect and vary from time to time making the variance higher than my threshold.

If the distance is much lower than 4 metres my algorithm works very well.

## What I tried ##
I figured I might be able to block for some time until the *echo* pin on the ultrasonic sensor turns low or a time of 100ms has passed. The code hanged and I couldn't communicate with my arduino any more. I can't see the problem with my code to obtain the distance pursuant to the ultrasonic sensor.

    for(tries=3;tries;--tries) {
      digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
      delayMicroseconds(2); // Let signal settle.
      digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
      delayMicroseconds(10);
      digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
      unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
      unsigned long time = micros();
      while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
        if((micros() - time) >= 100000) {
          continue;
        }
      }
      if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
        return ((float)(duration)/2.0) / 29.1;
      }
    }
    return 400.0f;

This just blocks my program indefinently and I had to upload a new program removing that code for my arduino to respond again.

So my question boils down to: how can I resolve this issue where my algorithm very frequently sends motion events erroneously? Is there a better way to detect motion with an ultrasonic sensor?

(**EDIT:** I was really tired when I wrote the code above and Majenko corrected me, I changed the code for this

    for(tries=3;tries;--tries) {
      digitalWrite(TRIG_PIN), LOW); // Set trigger pin low.
      delayMicroseconds(2); // Let signal settle.
      digitalWrite(TRIG_PIN, HIGH); // Set trigger pin high.
      delayMicroseconds(10);
      digitalWrite(TRIG_PIN, LOW); // Ping has now been sent.
      unsigned long duration = pulseIn(ECHO_PIN, HIGH, 23280); // Duration is in microseconds
      unsigned long time = micros();
      while(PINB & 0b00000010) { // ECHO_PIN is PB1 or digital pin 9
        if((micros() - time) >= 100000) {
          goto retry;
        }
      }
      if(duration >= 116L && duration <= 23280L) { // Is duration within boundaries?
        return ((float)(duration)/2.0) / 29.1;
      }
      retry:
      continue;
    }
    return 400.0f;

body:
The main blocking part of your code is this bit:

    while(!(PINB & 0b00000010)) { // ECHO_PIN is PB1 or digital pin 9
      if((micros() - time) >= 100000) {
        continue;
      }
    }

That is saying "While the echo pin is low, check the time.  If too much time has passed then carry on with the loop".

So basically that will loop until the echo pin goes high, regardless of the time.

The `continue` command means to jump back to the beginning of the loop that it's in, be that a while, for, or do loop.  In this case it jumps back to the beginning of the while loop it's in.

Instead you should consider using `break`, which means "Terminate this loop and carry on with what comes next".

----

Ultrasound sensing with `pulseIn()`, while simple to perform is rarely particularly accurate.  Any interrupts that occur during the sensing will affect the outcome, and it's only as accurate as the micros() function allows it to be.

If you need a more precise and reliable measurement you should consider using one of the *Input Capture* modules in the ATMega.  I don't know if there is a library to do it off hand, but programming it through the registers shouldn't be that difficult - just read the datasheet to find out how it all works.

Briefly the operation of IC is:

1. Send trigger pulse
2. Start IC timer counting
3. Pulse arrives
4. IC stops counting automatically and interrupt is triggered
5. Read counter value and convert to microseconds.
6. Set flag to indicate a result is available

The timing source is the main system clock and counting happens in the background completely parallel to the operation of the CPU, so nothing can interrupt it or delay it. Even if the execution of the IC interrupt routine is delayed by another interrupt running the counter value will have already stopped incrementing, so it will have been "captured" and give the correct result every time.


message:
Using GPS Module ET314AC With arduino Mega

Can I use GPS Module ET314AC with Arduino Mega? Here is the datasheet of ET314AC            [ET314AC Datasheet][1]

  [1]: https://www.google.com.pk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=4&cad=rja&uact=8&ved=0CC0QFjADahUKEwil6qrq4vnIAhVBhRoKHQePBOM&url=http://www.szstoton.com/res/stotongps/pdres/201203/20120320163340251.pdf&usg=AFQjCNFOZ31eexhFJWxNYqHvN-QWt4GoEA

body:
yes you can, the datasheet is saying that you can read from a serial port which is what you want to do.

Connecting the serial port to TX and RX pins of the Arduino, ground and power, you should be able to talk to the module.

I cant find a breakboard for this module so I suppose you are going to solder it or you can give us the link where you bought it.

I suggest you to try with TinyGPS library to decode the data, after you are sure that the module is talking to the Arduino correctly.


message:
Arduino Nano v3.0 with ESP8266

I am attempting to connect and use an ESP8266 board with my Arduino nano v3.0 and I am not have much luck.

I have read a bunch of tutorials and articles, the most recent is [http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html][1]

Any help would be greatly appreciated.

I have connected it like below and am using some simple code to try and get it working.

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

Code:

    #include <SoftwareSerial.h>

    SoftwareSerial esp8266(10, 11);

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

      Serial.flush();

      esp8266.print("AT+RST\r\n"); // reset for esp8266
      delay(500);
      esp8266.flush();//clear serial1
      // Check AT
      esp8266.print("AT"); // reset for esp8266
      esp8266.print("AT+CIFSR\r\n");// learn the ip which token for esp8266
      delay(500);
      if (esp8266.find("ready"))
      {
        esp8266.flush();
        esp8266.print("AT+CIFSR\r\n");
        delay(500);
        Serial.println("CIHAZ IP ADRESI:" + esp8266.readString()); // print esp8266 ip

      }
      else
      {
        Serial.println("there is no internet connection");
      }
      esp8266.print("AT+CIPMUX=1\r\n");//ser mux 1 so we want to connect as multiple users
      delay(500);
      if (esp8266.find("OK"))
      {
        Serial.println("Mux ok");
      }
      else
      {
        Serial.println("MUX failed");
      }
      esp8266.print("AT+CIPSERVER=1,23\r\n");// set esp8266 as server
      delay(500);
      if (esp8266.find("OK"))
      {
        Serial.println("SERVER started");
      }
      else
      {
        Serial.println("SERVER failed");
      }

    }
    void loop()
    {

      if (esp8266.available())
      {
        Serial.print(esp8266.readString()); // get message which comes from clients.
      }
    }

  [1]: http://elektro-blogger.blogspot.co.nz/2015/07/arduino-and-esp82666.html
  [2]: https://i.stack.imgur.com/6j8ZG.jpg

body:
The Esp8266 module has different firmware, the old one was running at 9600 and the new one is running at 115200.

Try to upload this code on  your arduino Nano and send AT commands over the Serial monitor of the Arduino.

If you send AT it should returns "OK", if not, try to swap RX to TX and try to play around with the baudrate 9600, 57600, 115200.

It might be that your Wifi module doesnt have any firmware loaded which might need to be done.

    #include <SoftwareSerial.h>

    SoftwareSerial wifi(10,11); // RX, TX

    void setup()
    {
    Serial.begin(9600); // FTDI
    wifi.begin(9600); // GPS; 9600 first time, 38400 second time
    }

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

    }


body: Remember that ESP8266 Uses 3.3v logic and arduino 5v. So use a voltage divider to get 3.3v at esp8266 rx pin. Also esp8266 must be connected rx->rx tx->tx to communicate with pc and rx->tx tx->rx to communicate with arduino.


body:
Do not Connect your ESP8266 Module Directly to an Arduino Board, Always try your best to use Divider resistors for better communication. you need to use Arduino IDE serial Monitor Window for ESP8266 setup instead of writing At Commands in Source Code. I successfully Setup My ESP8266 Module by using just Arduino Nano and Arduino IDE Serial Monitor.

[Download Simple Source Code and List of Necessary AT Commands][1]

[![USE D2 and D3 for TX and Rx ][2]][2]

  [1]: http://www.electronicslovers.com/2017/11/learn-how-to-setup-wifi-module-esp8266.html
  [2]: https://i.stack.imgur.com/Vb5an.jpg


message:
Battery Solution for ESP8266 and HC-SR04

I'm working on a project that includes an ESP8266 (requires 3.3v input (250 mA peak)) and a HC-SR04 (requires 5v 20 mA peak). I'm making it battery/solar powered.

I'm trying to keep costs down as well as make a system that works reliably and has good longevity.

I'll be waking the device every 15 minutes and keeping it in deep sleep at the other times.

Originally I was going to use a battery source over 6v, like a 6 cell AA rechargeable battery pack, a 10v or so solar panel, and a breadboard type voltage regulator that conveniently provides 3.3v and 5v on the same board. This seems to waste a decent amount of power though.

Right now I'm looking into using a 2 AA rechargeable NiMH batteries, a 5v solar panel, a 3.3v step up voltage booster, and a 5v step up voltage booster. 5v step up voltage boosters are everywhere and cheap because of their uses for portable cell phone chargers. 3.3v step up voltage boosters on the other hand are more expensive and harder to find.

Looking for any advice or affirmation that I'm on the right path. Thanks!

body: A time a go when searching for some circuit to provide power to ESP and also being capable of charging batteries I came across this reply [here](https://electronics.stackexchange.com/questions/36930/some-advice-on-charging-circuit-used-in-simple-ups/36938#36938). Is intended for usb charger/Li-Ion batteries but maybe it could suit your needs too and be adapted. In the output the circuit presented there, you could use some LDO like  [MCP1825S](http://ww1.microchip.com/downloads/en/devicedoc/22056b.pdf) (or even the MCP1825 with extra information possibilities). Never test the circuit yet, so can not provide any good answer about how long it provides juice to ESP.


message:
Using a library of sleeping with a combination of the WD and a physical INTERRUPT

I would like to use one of the nice libraries like :

 1. JEELIB
 2. ENERLIB
 3. SLEEP_N0M1
 4. NARCOLEPTIC
 5. ADAFRUITSLEEPY_DOG
 6. LOW_POWER_MASTER

<!-- -->

 1. But to use a X second interval of sleeping and in the same time to enable the option of an Interrupt on pin2 that will get me out of all this sleepy mode vector if there will be interrupt ! which library is better and easier for this situation?
 2. when I want more then 8 second , what is the mining of doing 2x8s when they wrote it in some of those libraries -what should it mean to do ?
 3. Is there an option to enable the interrupt for a wake up from the sleep not only by a LOW_mode but also by a CHANGE_mode of the pin2 ??

Thank you very much in advanced @!

body:
 1. "Best" is completely subjective. I've used Narcoleptic myself. it's easy to use and somewhat limited. For the needs of my project, it served well. You'll need to review the libraries' source code and descriptions to decide which library will best serve your application.

 2. The Watchdog timer has a maximum interval of 8 seconds. To sleep longer, you'll need a routine that counts enough 8 second sleeps, plus lesser sleep periods, to make up the total sleep time you want. There are other timers you can use, but not in Power Down sleep mode.

 3. See section 10, "Power Management and Sleep Modes" of the ATmega328p datasheet (or the datasheet for the chip your Arduino uses). There is a table of wake-up sources for each sleep mode. It says that, except from Idle mode, only a level-triggered interrupt can wake the chip. But note that section 10.5 says a pin-change interrupt can wake the CPU. It appears that either kind can wake it but "the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt." It does not mention the (obviously transient) pin-change interrupt. You may need to experiment.

Update:

> ...I cant get a sleep for more than 8 second but I can only get to a sleeping mode twice and by that to get almost a 16 second of sleeping ?

Yes, the longest Watchdog timer period is 8 seconds.

>I still didn't understand if there is an easy possible to get into a sleep with a routine periods of WD wakings and in the same time enabling a physical interrupt on pin2 that works parallel ?

From my reading of the datasheet, yes, you can use both timers in parallel. But it wasn't clear to me whether a pin-change can both wake the CPU and cause an interrupt (that is, vector into your interrupt routine). A level-interrupt can, if the level is held long enough (I believe they said 4 CPU cycles would be required).


message:
Unsure how to connect the anode in this circuit

I am making a game of X and O’s and ran out of pins on the Arduino. After searching on the internet I found out about connecting it in a grid connecting all the anodes in columns and the different colours in rows but I don't know how to connect the anodes so it only turns on only one of the LEDs rather than the other 2 in the grid if they are all connected to ground. The wires I am unsure to connect are the orange ones in the diagram below (bottom left corner). Note the Red on the RGBs are not used so don't need to be connected

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

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

body:
Firstly, you have made the classic rookie mistake with your circuit regarding your LED current limiting resistors.  You have one per LED group instead of one per LED within a group.  The arrangement you have at the moment means that *at best* some LEDs will be dim or not light at all, and *at worst* will result in LEDs burning out.

There should be a resistor in every red, green and blue wire in your diagram.

As for what to do with the three orange wires (once you have re-arranged the resistors) they connect to three spare IO pins on the Arduino - you then turn each column on or off as you need - only one column is on at a time.  If you need more than 20mA for a column (which is highly likely with up to 9 LEDs on at a time) then those lines should be connected to either +5V or GND (depending on if you are common anode or common cathode) via transistors and the transistors should be switched by the IO pins.


message:
Using 5V arduino with 12v solenoid lock

I wish to use an arduino like [this](http://www.snapdeal.com/product/arduino-uno-r3-board-with/566147335) with a 12v solenoid lock like [this](http://www.ebay.in/itm/331401195916?ssPageName=STRK:MEWNX:IT&_trksid=p3984.m1439.l2649). How can I do this. I am told that using [this](https://www.sparkpcb.com/development/l293-d-dc-motor-driver-board.html) might work, but I am also thinking I can use a transistor's amlification to do that. Can you tell which one is better and if transistor, how to do that?

body:
By sheer luck your lock solenoid looks very similar to [this one](https://www.adafruit.com/products/1512) (similar spec too "Draws 650mA at 12V") and they have a working circuit for it [over here](https://learn.adafruit.com/secret-knock-activated-drawer-lock) so look at that and see what they used to drive it. [Apparently](https://learn.adafruit.com/secret-knock-activated-drawer-lock/parts-and-tools) it's a TIP120, so the peak/draw current is probably higher than that ballpark figure, which I suspect is for the hold.

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

Overengineering the transistor by an order of magnitude or so (for a poorly spec'd solenoid part) ensures it doesn't go pop so easily. Also, a Darlington like TIP120 is very easy to drive from the arduino or some other microcontroller.

[A similar project](https://learn.adafruit.com/remote-controlled-door-lock-using-a-fingerprint-sensor-and-adafruit-io/setting-up-the-electronic-door-lock) using the same solenoid lock used an IRLB8721 (power MOSFET) instead, which is even more beefy in terms of load current it can handle.

  [1]: https://i.stack.imgur.com/PNupP.jpg
  [2]: https://i.stack.imgur.com/5ptTr.jpg


message:
What's Happened with my Arduino?

I am in a First Year Design class, and we are supposed to be making an autonomous robot. After hooking up some wind speed and temperature sensors to calibrate, I plugged in to my laptop (we have 2 arduino nanos) and ran a temperature code. I got the reading, but smelled something burning. Nothing was smoking, but I've found that when I plug my arduinos into my laptop, the light and the code indicate that they are not connected. This is odd because when I plug in the batteries, they show that the proper voltage is coming through, but they will still not connect to the laptop. Is it a problem with the micro-usb port?

I've included the code I'm using just in case that is cause for suspicion. It is notable that our instructors have written an API that allows us to code in Java for the arduinos.

    public static void main (String[] args)
    {
        robot = new ArduinoNano();
        robot2 = new ArduinoNano();
        robot.setPort("COM5");
        robot2.setPort("COM6");
        robot.connect();

        int reading = getThermistorReading();

        System.out.println("The probe read the value " + reading);
        System.out.println("In volts: " + (reading * (5.0/1023.0)));
        System.out.println();

        double temperature = (reading - 855.02) / -7.563;

        System.out.println("Temperature: " + temperature);

    }

    public static int getThermistorReading()
    {
        int sum = 0;
        int readingCount = 10;

        for (int i = 0; i < readingCount; i++)
        {
            robot.refreshAnalogPins();
            int reading = robot.getAnalogPin(3).getValue();
            sum += reading;
        }

        return sum / readingCount;
    }
}

body:
First, did the Arduino continue to respond and operate after you smelled the burning?

Just because there isn't smoke doesn't mean you didn't kill something on the board.

If your Arduino is not responding, there are two possibilites I can think of:

1. Your port is not working so simply switch to a different USB port

2. Somehow your laptop must have sent a large amount of amps/volts to the circuit and burned it out. If you have a multimeter you can use the sound setting to test whether or not wires are burned out, and if your nifty with an iron/heat gun, you can replace the part. Or you could buy a new one.

[![enter image description here][1]][1]
If the connection is good, you will hear a small beep. Oh, and these things don't work if there's a resistor in the way.

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


message:
Arduino ethernet shield not responding to every request because it is busy

I have a simple HTTP server that monitors a serial port and responds to HTTP requests by sending the value. The serial port constantly outputs data, so that apart from a brief moment when the device is initializing the Arduino always has data available. Once a value is retrieved from the RS232 connection it is stored in a buffer. The buffer is overridden when new values are received.

Occasionally the server does not respond to a request. Monitoring through Chrome developer tools reports net::ERR_CONNECTION_RESET
Could it be that the Arduino is busy with processing the serial port when the connection request is made? What I find very difficult to understand is that once in a while the code below will display "Not available". This shouldn't happen because, as stated above, the buffer is always available.

        client.println("HTTP/1.1 200 OK");
        client.println("Content-Type: text/html");
        client.println("Connection: close");
        client.println("Cache-Control: no-cache, no-store, must-revalidate");
        client.println("Pragma: no-cache");
        client.println("Expires: 0");
        client.println("Refresh: 5");
        client.println();
        client.println("<!DOCTYPE HTML>");
        client.println("");
        client.println("");
        client.print("Value: ");
        if (valueReady()) {
          client.println( getValue() );
        } else {
          client.println( "Not available" );
        }
        client.println("");
        client.println("");

The "Not available" message is really confusing because that should only occur when the Arduino starts. valueReady() will only return false when power is first applied.

The LEDs on the Ethernet shield do not indicate that the Arduino is being reset, but it seems as if the sketch is periodically restarting. Is it possible for a buffer overrun to cause the Arduino to reboot?

body: The delay was occurring because, in some cases, I was storing the RS232 data into a character array past the initialized length. It looks like it was causing the Arduino to reboot.


message:
Counting minutes in arduino

I have a dipswitch of 4 steps to get a binary number that will turn out to decimal from 0 to 15, So I need to get that number and make it the ammount of minutes to make something and also be aware of some input while the time runs out.

So I was thinking of having a variable being equal to millis() and then dividing it by 60,000 which is a minute in millis and If I get an integer that must mean a minute has passed, the problem is that I don't know how to check if the result is an integer or a float.

any advice?

body:
Your method is completely wrong.

You need a variable that contains the value of millis() at the start of your period, whenever that may be (when the switches change? when a button is pressed? since the Arduino was powered up?) and compare that value to the current value of millis().  When the difference between them is greater than or equal to `60000 * 15` then 15 minutes have passed.

Look at *BlinkWithoutDelay* in the Examples menu in the IDE - it showcases the technique for you.


body:
To my understanding you want to make some sort of device that will count X min. To get X you configure the 4 dip switches to get the time (0000 - 1111 or 0 - 15). The easiest way is to configure 4 pins to INPUT_PULLUP then you wire your switch to those pins and to ground. If the pin is grounded (switch in the on state) it will register a 0 and if the pin is NOT grounded (switch in the off state) it will register a 1.

note: if all switch are "off" you will get a max value of 15 based on my example.

    long startTime;
    void setup(){
        pinMode(7, INPUT_PULLUP); //8bit
        pinMode(6, INPUT_PULLUP); //4bit
        pinMode(5, INPUT_PULLUP); //2bit
        pinMode(4, INPUT_PULLUP); //1bit

        startTime = millis();
    }

    void loop(){
        long inputTime = 0;

        if(digitalRead(7))
            inputTime += 8;

        if(digitalRead(6))
            inputTime += 4;

        if(digitalRead(5))
            inputTime += 2;

        if(digitalRead(4))
            inputTime += 1;

        inputTime = 60000*inputTime;

        if(millis() - startTime <= inputTime){
            //X min has passed -- Do something here if you like

            startTime = millis(); //reset the timer
        }else{
            //Time not yet reached -- Do something here if you like
        }
    }


message:
arduino PWM temperature inexpected results

I am making a system which regulates the temperature of a plate.
using the PID library
I programed the system as followed:

    /********************************************************
     * PID Basic Example
     * Reading analog input 0 to control analog PWM output 5
     ********************************************************/

    #include <PID_v1.h>
    #include "math.h"

    int val, output2;
    //Define Variables we'll be connecting to
    double Setpoint, Input, Output;
    //Specify the links and initial tuning parameters
    PID myPID( &Input, &Output, &Setpoint,0,20,20, DIRECT);

    void setup()
    {
      //initialize the variables we're linked to
      Setpoint = 37; //temperature a reguler

      //turn the PID on
      pinMode(9, OUTPUT);
      myPID.SetOutputLimits(-100, 100);
      myPID.SetMode(AUTOMATIC);
      Serial.begin(57600);
      while (!Serial);
    }

    void loop()
    {
      // phase haute
      //delay(100-output2);
      val = analogRead(1);
      float mv = ( val/1024.0)*5000;
      Input = mv/10;
      myPID.Compute();
      {   output2 = map(Output, -100, 100, 0, 200);
          Serial.print("output is :");
          Serial.println(output2);
          digitalWrite(9,HIGH);
          delay(output2);
          // phase basse
          digitalWrite(9,LOW);
      }
      //analogWrite(5,Output);
      //Serial.print("input temperature is :");
      //Serial.println(Input);
      // Serial.println(Output);
      // Serial.println(Input);

    }
As you can see in the code the output result is between 0 and 100.
the temperature desired in the plate is 37 degre. and the actual temperature is 24 degre. consequently, the program supposes to set the value of the output to the max value to reach to 37 degre.
But the problem is my output is setting to different values as you can see here: [![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/yVt8T.png
what can be the problem here ? thank you in advance

body: As Gerben said in a comment, you should add the value of Input to the serial print, to facilitate problem diagnosis.  As your question stands, one can only speculate about what the problem might be.  My speculation is that the system is unable to cope with parameters (Kp, Ki, Kd) = (0, 20, 20), ie, that it's unstable and unresponsive without proportional control.


message:
Arduino Mega failure after first use of Mega Shield power connector

I have an XDRduino Mega [clone][1] with ATmega2560 and ATmega16U2 USB support chip.  I also have a Sensor Shield (same vendor), which provides screw terminals to Vin and Ground.

I connected the board with USB, loaded "Blink", and then changed the time interval.  Next I connected a 20x4 LCD using the Sensor Shield and a breadboard and loaded LCD "Hello world".  All seemed fine with the new board.

Each time I powered on or reset the Mega, the TX and RX LEDs flashed a couple of times and then my sketch started running.

Then I disconnected it from the PC (no USB for power anymore) and connected a (working from another project) [S-60-12][2] power supply, DC Output 12V 5A to the shield screw terminals.  I verified polarity -V to GND, +V to VCC.

OK, I swear I hooked it up correctly.  But if you tell me that hooking it up backwards would explain all the symptoms below, then yes I'll believe you that I screwed up {sob}.

(And yes, you're right, there is no diode protection on Vin, just on the dc power jack.  Dummy me.  Double dummy me, as there was a screw type power plug laying unused on the bench {groan}.)

About 4 seconds later, I heard a snap and immediately pulled the plug on the power supply.  Yes, something probably smoked, but let's refine at bit, please.

I moved the Mega to my PC, (disconnecting the external power supply so to use only USB for power).  It is no longer recognized as a USB device, and the Arduino IDE (1.6.5) no longer finds the USB serial port.

Voltages at 3.3V pin and 5V pin are correct.  I've also probed the regulator and comparator and all looks well for the power circuitry. F1 is not blown (or there would be no power as USB is the only source).

Item: The TX and RX leads are on solid.  I expected them to flash then turn off.  (Power LED is on solid, which is normal.)

Item: The reset pin for the Mega reads 1.41 V.  It's connected through a 10K pullup to +5 V (reads 4.63 at USB pin, 4.53 at the 5V pin).  ***This seems way too low.***

Item: The reset pin for the 16U2 reads V+ (4.35) and is has a 10K pull-up.

Item: AREF is 50 mV.  I believe it should be 1.1 V or 2.56 V.

Question: Is it reasonable to think the 2560 may be dead, and the LEDs are on because the 16U2 can't talk to it?  **Any way to test this theory?**

(If the 16U2 were bad, it would still be possible to program the 2560 via the ICSP header, thus salvaging something...)

Question: The 16U2 won't do the USB connection dance with the PC because the 2560 is dead?  **Should the 16U2 to try to connect no matter what the state of the 2560?.**

Question:  **If the 16U2 is dead, should TX and RX LEDs be lit?**

Question:  **If I had reversed the hookup, should not the regulator (P1117 chip) have saved me?**

Question:  **Has anyone else had a failing component** (other than the 2560 & 16U2) **with these symptoms?**

  [1]: http://yourduino.com/sunshop2/index.php?l=product_detail&p=387
  [2]: http://www.alliedelec.com/mean-well-usa-s-60-12/70069551/

body:
If what i read is correct, then you've probably cooked your duino.

As for what exactly failed, i'm going to guess from your description, that one or both of the capacitors failed. Usually when they blow, you'll hear a loud snap like you describe.

I would suggest testing those, and replacing them if they are faulty.. This is no guarantee that other components weren't damaged, but it's a good place to start.

As for why the LED's may still light up, that could be any number of reasons really, and not a particularly good indicator of what exactly failed.


body:
I want to make this obvious to the casual reader:  Mega Sensor Shields -- all versions I've data on -- run the power connector to +5V.

The power connector ***is not power in***, as defined by the base board.  In fact, there is no direct way to get to the base board regulator from the shield.  (A pin exists for Vin, but it isn't connected to anything on the shield.  It's mechanical support.)

It's intended to supply more current to devices connected via the shield than the base board does.

There is a jumper that disconnects the sensor shield +5 rail from base board power to allow independent ***+5 volts distribution*** to the shield attached devices.


message:
Stop Arduino from powering LED strip when connected to USB

I have a WS2812B LED strip that is controlled by an Arduino. Normally, both the Arduino and LED strip are powered by the same 5V power supply. The 5V and GND pins of the Arduino and LED strip are connected together. If I want to reprogram the Arduino, I have to disconnect the LED strip or else it might want to try and draw power from my computer's USB.

I have a bunch of (assorted) transistors, (schottky, zener) diodes and resistors. Is there something I can build that will allow the power supply to power both the Arduino and LED strip, while the Arduino's USB can only power the Arduino itself?

I've thought about using a diode between the 5V of the Arduino and 5V of the power supply and using a resistor to pull the 5V terminal of the power supply pin low (when the power supply is not connected) but I'm not sure how stable that will be: once the diode starts conducting the resistor will have no chance to pull the pin low again and I'm not sure if the Arduino will like the voltage drop across the diode.

Obviously the external power would be disconnected before plugging the Arduino into USB. Since the LED strip runs on 5V I can't use the VIN pin.

body:
I'd try powering the led strip for the power-supply directly, and the arduino board via a (schottky) diode.

That way the led strip will have no power when only usb is plugged in.

The Arduino won't mind that it receive a bit less that 5v because of the voltage drop of the diode.

The only thing to look out for it sending a 5v signal to a WS2812B chip that has no power. According to the datasheet this is not allowed.

So you either need to buffer the output of the arduino going to the input of the WS2812B (e.g. using some transistors, or a [simple pull-up with diode](http://elinux.org/images/6/61/EOMA68-UART-RX-DIODE-PROTECT.png)). Or, since you are not hot-plugging the usb, have the 5v from the power supply go (via a resistor) to an input on the arduino, so you can detect this in your setup routine, and have it block the rest of the code, or something.


message:
How to read a higher voltage digital input?

Lets suppose I have a circuit with a car battery, a switch and a led. The led will turn on when the switch is closed, and turn off if it's not. I want to remove the led from the circuit and put an Arduino in that place to "read" when the circuit is closed or open.

I'm a good programmer, so the code is not the real problem. I only want to know how to do this without damaging the board.

How can I do this?

body:
As @Gerben says, voltage dividers are a good place to start. To elaborate on the topic, you can use a combination of voltage dividers, zener diodes and clamping diodes.

This [EE.SE post][1] has some good info about this, related to ADC, but still the same.

First off, a voltage divider circuit is easily found on the internet,

 1. [Google][2]
 2. [Wikipedia][3]

This circuit from [Hyperphysics][4] shows the basics:
[![Hyperphysics][5]][5]

----------

To add more protection to this so as not to go over the max I/O voltage of the MCU, you can add a zener diode on the **Vout**.
That would give you something like this([Olins][6]):

[![credit to Olin][7]][7]

This will give you the desired range to give legitimate High and Low on an I/O.

----------

If you wanted to forgo the voltage divider and zener you can use [clamping diodes][8] to the microcontroller supply voltage Vcc. This will give a range that will not damage the I/O.

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

The 10k resistor is there to limit the current through the diodes, which are Schottky diodes.

----------

Another method, which I have used before and is reliable, is to use a diode and two resistors like below:

![enter image description here][9]

The logic is that, when the input `IN` is > Vcc(5V) the signal on the I/O `_IN` will be the voltage of the pull_up resistor `R2`, if it is low or floating the signal will be low. R1 also gives a known logic state if the input floats.

*Edit*: Changed the image to proper logic flow.

  [1]: https://electronics.stackexchange.com/questions/35807/how-would-i-design-a-protection-clipper-circuit-for-adc-input
  [2]:https://www.google.com/search?q=voltage+divider&ie=utf-8&oe=utf-8
  [3]: https://en.wikipedia.org/wiki/Voltage_divider
  [4]: http://hyperphysics.phy-astr.gsu.edu/hbase/electric/voldiv.html
  [5]: https://i.stack.imgur.com/cLmul.gif
  [6]: https://electronics.stackexchange.com/a/48317/46355
  [7]: https://i.stack.imgur.com/CSQ5O.gif
  [8]: https://en.wikipedia.org/wiki/Clamper_(electronics)
  [9]: https://i.stack.imgur.com/uDj4f.png


message:
Get csv field values

I am uploading data using Thingspeak and I would like to get only values stored in a field. Is there any way to get this in a cvs http request?

When you call a cvs http url, you get:

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

What I am trying to get is just the value in field2: 10,10,12,12,16 without the headers.

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

body:
You can use this format to achieve what you described:

    http://api.thingspeak.com/channels/(channel_id)/field/(field_id).(format)

Source: http://community.thingspeak.com/documentation/api/

**Edit:** It seems that there are no available options that can do what you want. But, you can tweak the response like in this example:

      int i;
      String response = "created_at,entry_id,field2 2015-10-22 19:30:00,14878,5";

      for (i = response.length()-1; i >= 0 ; i--)
      {
        if (s.charAt(i) == ',') break;
      }
      String value = response.substring(i+1);
      Serial.println(value); // This will show only 5


message:
Occasional incorrect time returned by NTP

I have an Uno with CC3000 wifi shield and am trying to use the sntp.h library to get NTP time. I have been experimenting with a modified version of the ntpTest code from the library which fetches the time every minute. In the serial monitor I get the correct time MOST of the time. However at random intervals, the time will display 3 hours and 14 minutes ahead of the current MST time.

the SNTP client constructor looks like this:

    sntp mysntp = sntp(NULL,"time.nist.gov", (short)(-7 * 60),(short)(-7 * 60), true);

The time will display correctly for two to ten minutes and then display one of the erroneous times once then revert to correct time.

**EDIT**
Here is the pared down code from the [Adafruit CC3000 WIFI shield ntpTest][1] example. Note that the only reason I was getting the time so often was just teaching myself how it worked and I noticed this odd behavior. My intent was not to make an application that would, in the end, access NTP servers more than once per day.

        /***************************************************
      This is an example for the Adafruit CC3000 Wifi Breakout & Shield

      Designed specifically to work with the Adafruit WiFi products:
      ----> https://www.adafruit.com/products/1469

      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Kevin Townsend & Limor Fried & Rick Lesniak for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    /*

    This example does a test of the SNTP (Simple Network Time Protocol) client:
    * Initialization
    * SSID Scan
    * AP connection
    * DHCP printout
    * SNTP time synchronization
    * Extract and print current time and date information

    */

    #include <Adafruit_CC3000.h>
    #include <ccspi.h>
    #include <SPI.h>
    //#include "utility/NetTime.h"
    #include <string.h>
    #include "utility/debug.h"
    #include "sntp.h"

    // These are the interrupt and control pins
    #define ADAFRUIT_CC3000_IRQ   3  // MUST be an interrupt pin!
    // These can be any two pins
    #define ADAFRUIT_CC3000_VBAT  5
    #define ADAFRUIT_CC3000_CS    10
    // Use hardware SPI for the remaining pins
    // On an UNO, SCK = 13, MISO = 12, and MOSI = 11
    Adafruit_CC3000 cc3000 = Adafruit_CC3000(ADAFRUIT_CC3000_CS, ADAFRUIT_CC3000_IRQ, ADAFRUIT_CC3000_VBAT,
                                             SPI_CLOCK_DIVIDER); // you can change this clock speed but DI

    #define WLAN_SSID       "CompsciWifi"   // cannot be longer than 32 characters!
    #define WLAN_PASS       "005276DA"
    // Security can be WLAN_SEC_UNSEC, WLAN_SEC_WEP, WLAN_SEC_WPA or WLAN_SEC_WPA2
    #define WLAN_SECURITY   WLAN_SEC_WPA2

    //Arguments to SNTP client constructor:
    // 1 - Primary Network Time Server URL (can be NULL)
    // 2 - Secondary Network Time Server URL (also can be NULL)
    // 3 - Local UTC offset in minutes (US Eastern Time is UTC - 5:00
    // 4 - Local UTC offset in minutes for Daylight Savings Time (US Eastern DST is UTC - 4:00
    // 5 - Enable Daylight Savings Time adjustment (not implemented yet)
    //
    //sntp mysntp = sntp(NULL, "time.nist.gov", (short)(-7 * 60), (short)(-7 * 60), true);
    sntp mysntp = sntp(NULL, "time-a.timefreq.bldrdoc.gov", (short)(-7 * 60), (short)(-7 * 60), true);

    // Type SNTP_Timestamp is 64-bit NTP time. High-order 32-bits is seconds since 1/1/1900
    //   Low order 32-bits is fractional seconds
    SNTP_Timestamp_t now;

    // Type NetTime_t contains NTP time broken out to human-oriented values:
    // uint16_t millis; ///< Milliseconds after the second (0..999)
    // uint8_t  sec;    ///< Seconds after the minute (0..59)
    // uint8_t  min;    ///< Minutes after the hour (0..59)
    // uint8_t  hour;   ///< Hours since midnight (0..23)
    // uint8_t  mday;   ///< Day of the month (1..31)
    // uint8_t  mon;    ///< Months since January (0..11)
    // uint16_t year;   ///< Year.
    // uint8_t  wday;  ///< Days since Sunday (0..6)
    // uint8_t  yday;   ///< Days since January 1 (0..365)
    // bool  isdst;  ///< Daylight savings time flag, currently not supported
    NetTime_t timeExtract;

    #define pF(string_pointer) (reinterpret_cast<const __FlashStringHelper *>(pgm_read_word(string_pointer)))

    const prog_char   janStr[] PROGMEM = "January";
    const prog_char   febStr[] PROGMEM = "February";
    const prog_char   marStr[] PROGMEM = "March";
    const prog_char   aprStr[] PROGMEM = "April";
    const prog_char   mayStr[] PROGMEM = "May";
    const prog_char   junStr[] PROGMEM = "June";
    const prog_char   julStr[] PROGMEM = "July";
    const prog_char   augStr[] PROGMEM = "August";
    const prog_char   sepStr[] PROGMEM = "September";
    const prog_char   octStr[] PROGMEM = "October";
    const prog_char   novStr[] PROGMEM = "November";
    const prog_char   decStr[] PROGMEM = "December";

    PROGMEM const char* const monthStrs[] = { janStr, febStr, marStr, aprStr, mayStr, junStr,
                                              julStr, augStr, sepStr, octStr, novStr, decStr};

    const prog_char   sunStr[] PROGMEM = "Sunday";
    const prog_char   monStr[] PROGMEM = "Monday";
    const prog_char   tueStr[] PROGMEM = "Tuesday";
    const prog_char   wedStr[] PROGMEM = "Wednesday";
    const prog_char   thuStr[] PROGMEM = "Thursday";
    const prog_char   friStr[] PROGMEM = "Friday";
    const prog_char   satStr[] PROGMEM = "Saturday";

    PROGMEM const char* const dayStrs[] = { sunStr, monStr, tueStr,  wedStr,
                                            thuStr, friStr, satStr};

    /**************************************************************************/
    /*!
        @brief  Sets up the HW and the CC3000 module (called automatically
                on startup)
    */
    /**************************************************************************/
    void setup(void)
    {
      Serial.begin(115200);
      Serial.println(F("Hello, CC3000!\n"));

      //Serial.print("Free RAM: "); Serial.println(getFreeRam(), DEC);

      /* Initialise the module */
      Serial.println(F("\nInitialising the CC3000 ..."));
      if (!cc3000.begin())
      {
        Serial.println(F("Unable to initialise the CC3000! Check your wiring?"));
        while(1);
      }

      /* Optional: Update the Mac Address to a known value */
    /*
      uint8_t macAddress[6] = { 0x08, 0x00, 0x28, 0x01, 0x79, 0xB7 };
       if (!cc3000.setMacAddress(macAddress))
       {
         Serial.println(F("Failed trying to update the MAC address"));
         while(1);
       }
    */

      /* Delete any old connection data on the module */
      Serial.println(F("\nDeleting old connection profiles"));
      if (!cc3000.deleteProfiles()) {
        Serial.println(F("Failed!"));
        while(1);
      }

      /* Attempt to connect to an access point */
      char *ssid = WLAN_SSID;             /* Max 32 chars */
      Serial.print(F("\nAttempting to connect to ")); Serial.println(ssid);

      /* NOTE: Secure connections are not available in 'Tiny' mode! */
      if (!cc3000.connectToAP(WLAN_SSID, WLAN_PASS, WLAN_SECURITY)) {
        Serial.println(F("Failed!"));
        while(1);
      }

      Serial.println(F("Connected!"));

      /* Wait for DHCP to complete */
      Serial.println(F("Request DHCP"));
      while (!cc3000.checkDHCP())
      {
        delay(100); // ToDo: Insert a DHCP timeout!
      }

      /*Serial.println(F("UpdateNTPTime"));
      if (mysntp.UpdateNTPTime())
      {
        Serial.println(F("Current local time is:"));
        mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);*/

        /*Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min); Serial.print(F(":"));Serial.print(timeExtract.sec); Serial.print(F("."));Serial.println(timeExtract.millis);
        Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
        Serial.println(timeExtract.yday + 1);
      }

      /* You need to make sure to clean up after yourself or the CC3000 can freak out */
      /* the next time you try to connect ... */
      /*Serial.println(F("\n\nClosing the connection"));
      cc3000.disconnect(); */

        mysntp.UpdateNTPTime();
        mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
        Serial.print(pF(&dayStrs[timeExtract.wday])); Serial.print(F(", ")); Serial.print(pF(&monthStrs[timeExtract.mon])); Serial.print(F(" ")); Serial.print(timeExtract.mday); Serial.print(F(", "));Serial.println(timeExtract.year);
    }

    void loop(void)
    {
        mysntp.UpdateNTPTime();
        mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
        Serial.print(timeExtract.hour); Serial.print(F(":")); Serial.print(timeExtract.min);

        delay(60000);
        Serial.println();
    }

  [1]: https://learn.adafruit.com/adafruit-cc3000-wifi/ntptest

body:
The updated NTP test sketch assumes that the communication with the NTP server will not fail but as the NTP protocol is based on UDP the reply package can be lost. A possible correction to the updated sketch is to check the return value from `UpdateNTPTime()`.

    void loop(void)
    {
        if (mysntp.UpdateNTPTime()) {
            mysntp.ExtractNTPTime(mysntp.NTPGetTime(&now, true), &timeExtract);
            Serial.print(timeExtract.hour);
            Serial.print(F(":"));
            Serial.println(timeExtract.min);
            delay(60000);
            Serial.println();
        }
    }

Cheers!


message:
Help to decode xbee S2 API packet

I'm new at using Xbee and I would like to get some help on how to interpret API packets. Me setup consists of two arduino unos, two xbee S2, two [xbee shields][1] and a one magnetometer sensor HMC5883L.  The sensor is connected to the arduino via I2C and transmitting the data to the xbee (router) using serial communication. On the other side (coordinator) I'm reading and displaying the data on the serial monitor. I have read the data sheet of the xbee but I still can't figure how to interpret the packet. Here is a screen shot of the values that I'm getting on the serial monitor on the router and the corresponding packets on the coordinator's serial monitor.
[![enter image description here][3]][3]

There are four bytes that are changing each time so how can I translate them to an integer value. Any help would be greatly appreciated.

  [1]: http://q.lnwfile.com/_/q/_raw/gn/ta/2w.jpg
  [3]: https://i.stack.imgur.com/ugIDP.jpg

body:
You have a bunch of "stuff", followed by the data you sent, followed finally by another bunch of "stuff".  I don't know what the "stuff" is, but I can see and decode your data easily enough.

I suspect you transmitted the data using `.println(...)`.  That will send an ASCII representation of the data.

So to take the line: `-196.88<CR><LF>`, if we find the ASCII values and represent them as hexadecimal we have:

> 2D,31,39,36,2E,38,38,D,A

Which I am sure you can find in one of those lines - maybe this one:

> 0,15,90,0,13,A2,0,40,C1,A8,2E,98,8D,1,**2D,31,39,36,2E,38,38,D,A**,3B

So you have 14 bytes defining something interesting about the packet (I'm sure Google can tell you what - source and destination maybe, probably a packet length too), then your data, and finally what looks like it's probably a checksum.


message:
Is it possible to run emulator from IC? and how?

I have an Emulator and Roms I would like to create a portable device to allow me to connect via RCA to a TV and play. Only I have no prior knowledge of how Integrated Circuits function or what they are capable of. If a IC would work, how does one go about programming one to load up the emulator? What other components aside from RCA and USB would I need? Any direction with this would be great and sorry in case I am not asking the proper questions.

I figured arduino is similar to what I am building in regards to circuitry/ electronics. Thanks in advance.

This is the only bit of information I have found online in 4 days thats not store bought.   [CLICK HERE][1]

  [1]: http://www.voja.rs/PROJECTS/GAME_HTM/2. Hardware.htm#Schema

body:
Not a chance, I am afraid.  The Arduino cannot do what you think it does.

Yes, you could *program* the Arduino to act like some of the simple old video games, but there is no way it can run a pre-existing emulator program like your computer can.

You need something more like a Raspberry Pi - in fact there is an interesting project that might be just what you want: [RetroPie](http://blog.petrockblock.com/retropie/)


message:
Why won't the slide switches control the motor in this 123d simulation?

int guard = 7;
    int switchPin = 6;
    int motorPin = 9;

    void setup(){
      pinMode(guard,INPUT);
      pinMode(switchPin,INPUT);
      pinMode(motorPin,OUTPUT);
    }

      void loop(){
       if (digitalRead(guard==HIGH)&&digitalRead(switchPin==HIGH))    //&&

       {

         digitalWrite(motorPin,HIGH);
        delay(500);
        digitalWrite(motorPin,LOW);
        delay(1000);
       }
            else {

         digitalWrite(motorPin,LOW);
       }

      }

[![123dsimulation image][1]][1]

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

body:
This should be written like this:

    if ( digitalRead(guard)==HIGH && digitalRead(switchPin)==HIGH ) {

    // Rest of the code..

    }


message:
The difference between "time_t" and "DateTime"

I've run into an issue trying to combine 2 different Arduino timer projects I've found online.

For both projects I'm using a DS3231 RTC, but have been able use the DS1307 library just fine in my code.

The first set of code I picked up started with:

    #include <DS1307RTC.h>

The second set of code I tried to combine did not have this 'include', but instead used

    RTC_DS1307 RTC;

as found here:

https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit/understanding-the-code

As a novice coder, I'm not really sure what the difference between the above two ways to call this library. But I do know the first way using "include", if I want to access the current time on the RTC I use

    RTC.get();

as opposed to the second method which requires:

    RTC.now();

And while it was easy to find documentation to sync the RTC to computer time over the USB cable using this handy bit of code:

    // Notify if the RTC isn't running
        if (! RTC.isrunning()) {
        Serial.println("RTC is NOT running");
      }

       // Get time from RTC
      DateTime current = RTC.get();
      DateTime compiled = DateTime(__DATE__, __TIME__);
      if (current.unixtime() < compiled.unixtime()) { //CHECKS AGAINST COMPUTERTIME
        Serial.println("RTC is older than compile time! Updating");
        RTC.adjust(DateTime(__DATE__, __TIME__));  //UPDATES FROM COMPUTER IF OLD TIME IS OFF
      }

I can find no easy alternative using "#include DS1307RTC"

I first thought that the difference between RTC.now() and RTC.get() was just a matter of word substitution. But later on when I want to use a "time_t" call after initializing with "RTC_DS1307 RTC;"

     time_t timeNOW = RTC.now();

I get the error "cannot convert 'DateTime' to 'time_t {aka long unsigned int}' in initialization"

So I'm assuming one method uses "DateTime" and one method uses "time_t". But I'm not sure if this is the case, and if so, how to convert a "DateTime" value to a "time_t" value.

I have two goals in writing this post.

1- Can someone please explain to me the difference between "#include DS1307RTC.h" and "RTC_DS1307 RTC;" and how it impacts my code.

2- I'd like to stick with using ""RTC_DS1307 RTC;", only because it seems easy to sync my RTC to my computer. But if I do, I get the above error. So can someone please tell me how to convert a "RTC now()" call to a "time_t" value? Or is the issue more complicated than just a mere conversion between data types?

body:
A `DateTime` is a full class with lots of methods to it - a `time_t` is just an unsigned long.

`time_t` is used to store the number of seconds since the *epoch* (normally 01/01/1970)

The Arduino *Time* library returns a `time_t` to the `now()` function - but RTCLib return s a DateTime object.

The DateTime object, though, has a `unixtime()` method which will return a `time_t` representation of the time stored in the DateTime object.

So you can do:

    DateTime dt = RTC.now();
    time_t time = dt.unixtime();


message:
Interfacing Arduino UNO with TFT LCD and WiFi Shield

I'm trying to interface my Arduino UNO with both a 1) TFT LCD screen and 2) WiFi Breakout board/shield.
The WiFi breakout board uses many of the same Digital pins as the LCD screen so is it possible for the arduino to interface with both devices simultaneously?

I also noticed that the shield goes over the arduino, but covers the header pins. Does this mean that I can't use these pins?

I've never worked with shields or breakout boards and would like some advice before I purchase either component.
If neither of these solutions will work, please provide me with alternate methods.

Your time/feedback is greatly appreciated :)

-Vip

body:
I agree with Chris on this. The uno is limited where it comes to pins and and ram, you should probably look at a mega, or similar.

As far as running both at once, i don't think it would be possible with the uno, with the ram limitations, as well as pin limitations, you'll be hard pressed to get them going at the same time, within the same sketch.

While technically it is possible to use alternative pins, i doubt there will be enough unused pins to shift an entire shield over to on the Uno

If you're looking for a cheaper rout, you may look at adding a secondary Uno to run the wifi, and send any data you need displayed to the uno running the tft via serial coms.


message:
Instead of 1 and 0, make display say On or Off

So for my project, I am making a button that turns on and off an LED, but also display the state of the led on an LCD and by Serial.  But my issue is, I don't want it to just show a 0 or a 1, I want it to say On or Off.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

    int inPin = 22;         // the number of the input pin
    int outPin = 13;       // the number of the output pin

    int state = HIGH;      // the current state of the output pin
    int reading;           // the current reading from the input pin
    int previous = LOW;    // the previous reading from the input pin

    // the follow variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    void setup(){
        // set up the LCD's number of columns and rows:
        lcd.begin(16, 2);
        // Print a message to the LCD.
        lcd.print("System Activated");
        //
        lcd.setCursor(0, 1);
        lcd.print("Ready...");

        pinMode(inPin, INPUT);
        pinMode(outPin, OUTPUT);

        Serial.begin(9600);
        Serial.println("System Activated");
        Serial.println("Made by Mateo Holguin");
        Serial.println("0 = Light is Off | 1 = Light is On");
        Serial.println("=======================================");
    }

    void loop(){
        reading = digitalRead(inPin);

        if (reading == HIGH && previous == LOW && millis() - time > debounce) {
            Serial.println("Button Switch State Change:");
            if (state == HIGH)
                state = LOW;
            else
                state = HIGH;

            Serial.println(state);
            Serial.println("");
            lcd.clear();
            lcd.print("State: ");
            lcd.print(state);

            time = millis();
        }

        digitalWrite(outPin, state);

        previous = reading;
    }

body:
Put the strings to display in an array, and output them instead.

    char const * const stateDisplay[] = {"Off", "On"};

     ...

    lcd.print(stateDisplay[state]);


body:
Another option: use the "inline" *if* construct:

    lcd.print(state ? F("On") : F("Off"));

The format is:

    <if comparison> ? <true result> : <false result>

Note the use of `F(...)` to force the strings to stay in flash memory.


message:
HX711 Load Cell application strange behaviour

I have an application where an HX711 ADC is used with 4 load cells. (in wheatstone bridge configuration, rated at 50kg each).

The thing is that I am trying to sense 30~ish gram changes with it accurately, while the cells will be loaded with 10 to 40 kilograms.

I have built up the circuitry and placements properly, calibrated and tested etc. but I have 2 questions that I couldn't come up with a solution.

**1st question:**
When powering arduino from USB cable the readings are much more stable (they are fluctuating like +-5 grams only) but when I connect a 12V power source (with 5A output) to the arduino, the readings start to fluctuate much more. (+-30 grams or so). The HX711 is powered from arduino 5v out pin but even though i tried to power it from a 5v adapter the fluctuations seemed to happen.

I should also note that the HX711 is connected to the analog pins A0 and A1, and there are 8 other sensors connected to the pwm pins of the arduino.

Now any ideas why does that happen? Any way to prevent this fluctuation?

**2nd question:**
If I calibrate with a load close to the max. weight (as suggested in many papers) the small changes seems to be very unreliable. If I calibrate it with a small weight (like around 200g) I can sense small weights properly but this time when a 2 kg weight is put it is read like 2.3kg or something. Is this normal?

I know that my load cells are not the proper ones for the application but I would like to push them as much as i can.

Thanks for your time

body:
1) Put your power source on an oscilloscope and check it. I assume what's happening is you don't have a clean sine, and the power fluctuates, whereas power from a PC USB port is usually very well regulated. This may be causing issues in your sensor due to under/over voltage at a minuscule level.

2) Because you're pushing your sensors to the edge of their capabilities, you're going to have to work around them, so the normal scenario's don't really offer much help, as they are usually based on working within the middle ground of capabilities.

You said that factoring based on low load vs high load created unreliable  variances in your measurements, i would personally suggest calibrating not for max load, nor min load, but 2/3 of max, or 1/3 max, and see if that stabilizes you, or at least gets you somewhere to the middle of the road where your differences are nominal, or something you can live with.


message:
RS-232 is a protocol or a cable?

RS-485 and RS-232 are a type of communication protocol or a type and cable?

I studying these serial communication protocols and each place refers to the RS-232 / RS-485 in different ways. Some articles mention that it is a cable, the other a protocol, so I was in doubt.

body:
RS-232 etc mean different things in different contexts.  More specifically it is called TIA/EIA-232.

It refers to both the electrical characteristics of an NRZ signalling system, and at the same time it refers to the packet format for the transmission of data through such a system.

It also refers to the connectors that are used with such a system and, by extension, the cables that have those connectors on them.

> The standard defines the electrical characteristics and timing of signals, the meaning of signals, and the physical size and pinout of connectors. The current version of the standard is TIA-232-F Interface Between Data Terminal Equipment and Data Circuit-Terminating Equipment Employing Serial Binary Data Interchange, issued in 1997.

RS-485, or TIA/EIA-485, in contrast *only* specifies the electrical characteristics and not the data that is sent down the line. It doesn't specify any connectors to use, nor what format the data should take. For instance you can use RS-232 formatted packets, or you could use a MODBUS-RTU format that uses completely different packets. It only refers to the drivers and voltages used.

> TIA-485-A, also known as ANSI/TIA/EIA-485, TIA/EIA-485, EIA-485 or RS-485, is a standard defining the electrical characteristics of drivers and receivers for use in balanced digital multipoint systems.


message:
Arduino Due uploading error using Eclipse plugin "avrdude: stk500_recv(): programmer is not responding"

I have a Arduino Due that I'm trying to upload a sketch to. I follow the tutorial http://playground.arduino.cc/Code/Eclipse to get the board running with the Eclipse plugin.

However uploading the sketch gives me the error

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03
If I use the Arduino IDE everthing works fine. I'm using Eclipse mars with Arduino 1.6.5

What could have gone wrong?

body:
> avrdude: stk500_recv(): programmer is not responding
> avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

There's your clue.
1) programmer is not responding - This usually means the device isn't connected, or powered, or reachable by the IDE, make sure you have eclipse configured correctly for your device, and it's location.

2) not in sync - This is a redundant, or overlapping error, of course it's not going to sync if it can't connect.


body:
You are using the wrong upload tool.

The due is not using avr dude as upload tool.
You need to use bossac.

If you turn on verbose upload in the arduino ide preferences you will see

    ...arduino\tools\bossac\1.6.1-arduino/bossac.exe ...


message:
Matlab and Arduino Serial communication

I'm new to Arduino and am learning how Serial communication works. I am trying to send a value from Matlab to Arduino, but it seems to be partly fruitful. If anyone can explain the difference between the acquiring input and predefined strings in Matlab
Here is the program I tried, and it is successful.
Arduino :

     %This program receives an array of chars and stores them in array and transmits them back

     const int no_of_fields = 3;
     int field_index = 0;
     int vec_to_hold[no_of_fields]; //Array to hold the numbers

    void setup()
    {
       Serial.begin(9600);
    }
    void loop()
    {
       if(Serial.available())
        {
         char ch = Serial.read();
         if(ch >= '0'&& ch<= '9') //check if the received chars are digits
          {
             if(field_index<no_of_fields)
               {
                  vec_to_hold[field_index] = (vec_to_hold[field_index] * 10) + (ch -'0'); //accumulate values to form and integer
               }
          }
         else if(ch == ',')
         {
           field_index++;
         }
         else if(ch == '\n')
         {
            for (int i = 0;i<min(no_of_fields,field_index+1);i++)
             {
             Serial.print(vec_to_hold[i]);
             vec_to_hold[i] = 0;
             }
            Serial.println();
            field_index = 0;
          }
       }
    }

Here is the Matlab side of Code :

    delete(instrfindall)
    S = serial('COM3', 'BaudRate', 9600,'Terminator','LF'); 8400
    fopen(S);
    pause(0.1);
    vec_sent = input('Enter : ','s');
    fprintf(S,'%s\n',vec_sent);
    pause(0.1);
    t_value = fscanf(S,'%d');
    disp(t_value);
    delete(instrfindall)
The above code is working, but what if i don't want to enter the string. I want to be predefined.
For example in the above matlab code

    vec_sent = '200,300,400';
If i convert this line

     vec_sent = input('Enter : ','s');
to

     vec_sent = '200,300,400';
it does not work. The RX pin on the Arduino blinks indicating something is coming on the serial, but TX pin is not at all blinking, and nothing appears in MATLAB except an error stating

     Warning: Unsuccessful read: A timeout occurred before the Terminator was reached..

I would be grateful if anybody points out what I am doing wrong.
Thanks in advance.

body:
The Arduino parsing code seems to function correctly. If I just use the IDE Serial Monitor window and enter "200,300,400", the Arduino replies "200300400".

The error message says that you either did not get the LF, or the LF did not arrive within 0.1 seconds.

One thing to try, as I do not have MATLAB, is to change how the Arduino replies.  On the Arduino, `Serial.println` will send a CR and a LF at the end.  Perhaps you should just do the LF explicitly instead:

    for (int i = 0;i<min(no_of_fields,field_index+1);i++)
    {
      Serial.print(vec_to_hold[i]);
      vec_to_hold[i] = 0;
    }
    Serial.print( (char)10 ); // just LF, not CR/LF with println
    field_index = 0;

This will test whether the CR is causing a line termination problem in MATLAB.

Another possibility is that the `pause(0.1)` is too short.  The documentation states that this is highly dependent on the OS timer resolution.  Try `pause(1)`.  This will test whether the time is too short.  At 9600, 0.1s is only 100 character times.


body:
To confirm that the cause of the connection problem is not the software, you can try to connect using reliable software. Do do this, download and install the MATLAB support package for Arduino hardware: [http://www.mathworks.com/hardware-support/arduino-matlab.html][1]

  [1]: http://www.mathworks.com/hardware-support/arduino-matlab.html


message:
Read Voltage at PWM off time, and Current at PWM on time

For a battery charging project, i am using an ARDUINO UNO which is driving a buck converter to provide the battery with the charging current. I am using external ADCs to measure the battery's charging voltage and current. The test setup is working fine, but right now i am just measuring the voltage and current at random time instants. However to measure it correctly, battery voltage reading should be done at an instant when the controller's PWM output is LOW (OFF duty cycle), and battery current reading should be done when PWM output is HIGH (ON duty cycle). So i was thinking how i can do that, since i am using analogueWrite() function to give PWM output, i thought if i could access analogueWrite() fucntion, may be i could there insert the function of read_ADC_Voltage() during the LOW time, and read_ADC_Current() during the HIGH time.

Is my approach right ? If yes then can please anyone tell me how can i access and use this analogueWrite() function ? And if someone has any other idea to do the readings correctly, please suggest. I shall be grateful.

body:
No, in my opinion changing functions in the Arduino Core is not a good approach. You would have to change it back for any other project you are going to do and secondly, if you insert a function in the part where analogWrite is low it will result in a change in the duty cycle. Which may not be a big problem, but just don't.

My advice would be to use a timer to run a callback function every x seconds. Then in that function temporarily set the PWM to 0 and read your values. This is indeed not the most efficient approach, but we're talking about microseconds here... This approach is completely intterupt driven so you could run other things while it is running it's PWM and checking the voltage periodically.

It sounds as if you have gotten pretty far by yourself, so I'm not going to write you example code. You can a tutorial on how to use a timer to periodically call a function [here][1].

  [1]: http://playground.arduino.cc/Code/ArduinoTimerObject


body: Add a pin-change-interrupt (PCI) handler (See eg [PinChangeInt](http://playground.arduino.cc/Main/PinChangeInt) at arduino.cc); clear the flag and enable the interrupt whenever you want to take readings, and disable that PCI after you have the reading.  As noted in the link, PCIs are available on all signal pins (possibly not on A6 and A7 on the 328), so are available on any of the PWM pins.


body:
P.S I am writing it as an answer since my code wont fit in comment

I looked into interrupts and learned about them that there are 2 types of interrupts in Arduino namely "external", and "pin change". So i downloaded the "PinChangeInt Library" to test it. I wrote a small program where a PWM of 62.5kHz is being generated on pin3, and i am calling rising and falling edge triggered interrupts on this pin, i.e to display one value when rising edge occurs, and other value when falling edge occurs. My code looks like following:

        #include <PinChangeInt.h>
        #define pw 3
        int pwm;

        void setup() {
          // put your setup code here, to run once:
          pinMode(pw, OUTPUT) ;
          pwm_setup();             // Set PWM to a frequency of 62.5kHz

          PCintPort::attachInterrupt(pw,rise,RISING);    // call void rise() when PWM is HIGH
          PCintPort::attachInterrupt(pw,fall,FALLING);   // call void fall() when PWM is LOW

          Serial.begin(9600);
        }

        void loop() {
          // put your main code here, to run repeatedly:
          pwm = 127;                                                // 50% duty cycle
          pwm_on(pwm);

        }
        void pwm_setup()
        {

          TCCR2A = 0x23 ;
          TCCR2B = 0x09 ; // mode 7, clock prescale by 1
          OCR2A = 256-1 ;  // 256 clock periods = 16us per cycle
          OCR2B =0 ;
          TCNT2 =0 ;

        }
        void pwm_on(double)
         {
            OCR2B = pwm ;
         }

        void rise()
        {
          Serial.println("RISE");
        }

    void fall()
    {
      Serial.println("fall");
    }

But it is not working the way i think it should. It keeps on displaying "fall" every time, whereas according to me it should display "RISE" and "fall" alternatively, right ? However if i remove the "PCintPort::attachInterrupt(pw,fall,FALLING); " line, it starts to display "RISE" as it is supposed to.

Since its my first time programming with Arduino, and i am just a beginning level programmer, i might be making some stupid mistake here. So can you point it out please ?


message:
In what situation would the Vin pin be attached to any of the I/O pins?

Also, in what situation would the Vin pin be attached to an external circuit?

body:
Vin is exactly the same as using the barrel jack (DC in) on the Arduino.  You can use it when you want to power your Arduino from an external source and you don't want to have the bulk of a big power plug.  It can also be used as a power output when you are using the barrel jack, for instance for powering relays or motors.  It just saves on having to splice wires into the cable of a wall wart, for example.

The voltage you feed in to the Vin pin should be of the same specification as the barrel jack - that is, between 7 and 12V.  From there, just like the barrel jack, it goes to the 5V regulator to provide the 5V for the board, and then on to the 3.3V regulator for low powered peripherals.

If, at any time, you power the board from the USB and have something connected to the Vin pin that consumes power you risk damaging the 5V regulator on the Arduino since power will flow backwards through it form 5V to Vin, which it really isn't meant to do.  In these situations it is good to connect a diode between 5V and Vin such that the anode is on 5V and the cathode on Vin - so that if the 5V is higher than the Vin voltage then the current will bypass the regulator safely.


body:
Vin connected to an IO pin: If you want to damage your Arduino.

Hypothetically, I could imagine a misguided attempt to detect if it's being powered from a barrel jack or from USB, but the higher voltage (and it will ALWAYS be a higher voltage if powered from that rail) is likely to damage the chip

To do that safely/correctly, you would need a voltage divider, to reduce both the voltage to a level below the +5v level.

Vin to an external circuit is very reasonable. If you have, for example, a motor that needs +12v, and your Vin is 12v, then you can provide the power for the motor from Vin, and still control it from the Arduino - you would use a transistor to turn the +5v from one of the digital pins (set to output) to 12v from Vin. This is typically what happens on a "motor driver" - for example, see http://www.hobbytronics.co.uk/image/data/tutorial/bipolar-stepper-drive.jpg - on the left-hand side, you will see "motor supply" - this runs at a higher voltage (and is isolated from +5v and Arduino pins), and if your motor needs what the barrel jack supplies (and is no more than 12v), then Vin is perfect.

The other situation is that you can put +7v to +12v INTO the Vin, instead of using the barrel jack - this will power your Arduino.


message:
ESP 8266 does not respond at all

I have a ESP8266_01, and I wired up. It does not work for me.

I have connected the ESP to an Arduino Uno. I am using a 5V pin from uP with a 3.3V regulator, and I have a voltage divider between RX(ESP) and TX(uP). And I am sure that the wiring is correct. The thing is, I am not getting anything back from ESP, not even errors. And I tried to use different baudrates as well. There is a blue LED flashing from ESP only when I am using 115200, and red LED lights up constantly at any other baudrate.

What have I done wrong here?

I did 4 hours of research already and don't know what else I can do now.
If you have any idea, please leave me a word.

body:
Start by uploading blink sketch to your Arduino then connect it to your ESP8266 like this: TX-TX and RX-RX.

Now open Serial Monitor and send AT command and see if it responds. If so then you can control it using your Arduino by wiring it back to TX-RX and RX-TX.

PS: Don't forget to set the line ending in the Serial Monitor to Newline or Carriage Return.

**Edit:** Use this code to connect to ESP8266:

    #include <SoftwareSerial.h>

    const byte rxPin = 2; // Wire this to Tx Pin of ESP8266
    const byte txPin = 3; // Wire this to Rx Pin of ESP8266

    // We'll use a software serial interface to connect to ESP8266
    SoftwareSerial ESP8266 (rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      ESP8266.begin(115200); // Change this to the baudrate used by ESP8266
      delay(1000); // Let the module self-initialize
    }

    void loop() {
      Serial.println("Sending an AT command...");
      ESP8266.println("AT");
      delay(30);
      while (ESP8266.available()){
         String inData = ESP8266.readStringUntil('\n');
         Serial.println("Got reponse from ESP8266: " + inData);
      }
    }

Since the Hardware Serial interface will be busy when connected to Computer, then you have to use another Serial interface to communicate with your ESP8266. In this case, Software Serial comes handy.


message:
Uno pin 13 LED mysteriously always ON at 0.14V unless pinMode OUTPUT

- I upload a blank sketch: pin 13 LED is on. Why?
- I connect pin 13 to GND: it turns off until I remove the connection
- I connect multimeter between pin 13 and GND: measures 0.14V and LED turns off until multimeter is removed
- I press hard reset: LED blinks a few times, turns off for a second then turns on
- I upload a sketch that on setup sets pinMode(13, INPUT): pin 13 LED is on
- I upload a sketch that on setup sets pinMode(13, OUTPUT): pin 13 LED is off 0.01V
- I upload a Blink example: Everything works fine, LED cycles from 4.84V to 0.01V

Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?
I swear it wasn't like this a few days ago.

body:
Apparently it's normal. Although random. Sometimes the default voltage of the pin is high enough to make the LED light up because of the op-amp. Sometimes it isn't.
Source: https://electronics.stackexchange.com/a/39707


body:
The LED is driven by an op-amp (see the schematic). When the pin is configured as input the op-amp has an undefined input (floating input). Thus it may or may not turn on the LED. If you configure it to an output the op-amp is driven in a known way.

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

> Why is the LED on unless I set pinMode to output? Have I broken my UNO or is this normal?

It's perfectly normal.

---

I think they did this to stop the LED "loading" the SCK pin (pin 13), particularly if you have it configured as an input and are trying to measure something, the 1k resistor and LED would throw out the measurement.

You could conceivably have a pull-down resistor from SCK to GND, but that would load the pin as well.

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


body: If SCK is set as an input then pin 5 of the op amp goes high (pnp transistor input stage) and the op amp output goes high turning on the LED.


message:
Understanding transistor datasheets

I'm trying my best to understand and utilise questions that already exist as well as other websites, however I just wanted to check the circuit I've come up with (which is a very simple switch circuit) will work.

I plan on using a [BD139][1] transistor, although I haven't purchased anything yet, so can change to anything really.

The fans are each 0.09A at 12V. I've calculated that R1 should be 360ohms. The 5V control will be coming from an Arduino. I believe it's within the specs of the transistor. Ic max is 1.5A.

Does the circuit look correct? Are there any changes I should make?

![](https://i.stack.imgur.com/1CWRD.jpg)

  [1]: https://www.fairchildsemi.com/datasheets/bd/bd135.pdf

body:
For saturation you should assume hfe to be 10. This gives:

(5V − 0.85V) / ((0.09A ⋅ 3) / 10) = 154 Ω

Consider using a 150-220Ω base resistor instead. And since a fan is an inductive load, don't forget the flyback diode from the collector to the +12V rail. A 1N4000 series diode should be fine for this small a load.


message:
SIM900 Modem is not responding

I'm working with arduino nano and it has interfaced with SIM900 GSM. I'm sending "AT\r" to GSM modem, but not getting response.

    void setup()
 {
   Serial.begin(9600);
   Serial.println("Setup is Ready");
 }

 void loop()
 {
    Serial.write("AT\r");
    delay(1000);
    if(Serial.available() > 0)
    {
      Serial.println("Data received");
      Serial.println(Serial.read());
    }

 }

Serial monitor:

Setup is Ready

ATATATATATATATATATATATATATATATATATAT

I've set the 9600 baudrate to modem and my rx and tx is connected correctly...
What is the problem?

Thanks

body: You aren't talking to the SIM900. You are just communicating with the serial monitor.


body:
You should not use the same Serial interface to debug and talk to your SIM900. You should use a SoftwareSerial interface to talk to the SIM900 and use the hardware Serial to send response back to your computer.

Try this code:

    #include <SoftwareSerial.h>

    const byte rxPin = 2; // Wire this to Tx Pin of SIM900
    const byte txPin = 3; // Wire this to Rx Pin of SIM900

    // We'll use a software serial interface to connect to SIM900
    SoftwareSerial SIM900(rxPin, txPin);

    void setup() {
      Serial.begin(115200);
      SIM900.begin(9600); // Change this to the baudrate used by SIM900
      delay(1000); // Let the module self-initialize
    }

    void loop() {
      Serial.println("Sending an AT command...");
      SIM900.println("AT");
      delay(30);
      while (SIM900.available()){
         String inData = SIM900.readStringUntil('\n');
         Serial.println("Got reponse from SIM900: " + inData);
      }
    }


message:
Assemble or typecast byte array to float

The serial port on my Arduino Mega is receiving 3 floats as bytes (total of 12 bytes, 4 per float) over serial. Unfortunately I cannot assemble the 4 Bytes in a float, as the serial monitor only displays

`0.00`

`0.00`

`0.00` etc.

Here is the code:

    void serialEvent2() {
      if (Serial2.available() > 11) {
        byte yawData[3];
        yawData[0] = Serial2.read();
        yawData[1] = Serial2.read();
        yawData[2] = Serial2.read();
        yawData[3] = Serial2.read();
        float yawAngle = *((float*)(yawData));
        Serial.println(yawAngle);

        byte pitchData[3];
        pitchData[0] = Serial2.read();
        pitchData[1] = Serial2.read();
        pitchData[2] = Serial2.read();
        pitchData[3] = Serial2.read();
        float pitchAngle = *((float*)(pitchData));

        byte rollData[3];
        rollData[0] = Serial2.read();
        rollData[1] = Serial2.read();
        rollData[2] = Serial2.read();
        rollData[3] = Serial2.read();
        float rollAngle = *((float*)(rollData));
      }
    }

I made sure the data coming to Serial2 is not `0`.

**UPDATE:** The initial mistake was my byte array not being sized correctly. I fixed it. The values I print are fine until after about a second, they get totally weird. Dropped bits/Bytes maybe? Seems odd because a sample sketch written in Processing works perfectly while taking the exact same input.

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

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

body:
If you must do it that way I'd recommend using a `union`:

    typedef union {
        float val;
        uint8_t bytes[4];
    } floatval;

    floatval v;
    v.bytes[0] = Serial2.read();
    v.bytes[1] = Serial2.read();
    v.bytes[2] = Serial2.read();
    v.bytes[3] = Serial2.read();
    Serial.println(v.val);

A better solution is to just write and read the raw float data:

    // Sender:
    Serial.write((const char *)&myfloat, sizeof(float));

    // Receiver
    Serial2.readBytes((char *)&myfloat, sizeof(float));

Even better still is to define a `struct` which is the packet of data you wish to send:

    typedef struct {
        float yaw;
        float pitch;
        float roll;
    } attitude;

    attitude myatt;
    myatt.yaw = 14.9;
    myatt.pitch = 23.4;
    myatt.roll = 11.49;

    Serial.write((const char *)&myatt, sizeof(attitude));

    // receive:

    attitude myatt;
    Serial2.readBytes((char *)&myatt, sizeof(attitude));
    Serial.println(myatt.yaw);
    Serial.println(myatt.pitch);
    Serial.println(myatt.roll);


body:
try use memcpy, i think it might work:

    void serialEvent2() {
      if (Serial2.available() > 11) {
        byte yawData[4];
        float yawAngle = 0;
        yawData[0] = Serial2.read();
        yawData[1] = Serial2.read();
        yawData[2] = Serial2.read();
        yawData[3] = Serial2.read();
        memcpy(&yawAngle, &yawData,sizeof(float));
        Serial.println(yawAngle);

        // same for others ...
      }
    }