text:
2.4Mhz clock for 3-wire SPI using Arduino Mega 2560
I am trying to develop an Arduino sketch for ADS8320 ADC IC, which is 3-wire SPI. I need a 2.4MHz serial clock for the SPI interface. I tried the code below, but I don't know how to generate clock pulses at 2.4MHz clock speed.
#define CLK 22
#define DBIT 24 // so
#define CS 26

#include <SoftwareSerial.h>

int v = 0;
float Ctemp, Ftemp;

void setup()   {
  Serial.begin(9600);
  pinMode(CLK, OUTPUT);
  pinMode(DBIT, INPUT);
  pinMode(CS, OUTPUT);
  digitalWrite(CS, HIGH);
  digitalWrite(CLK, LOW);
}

void loop()   {
  v = spiRead();
  if (v == -1)   {
    Serial.print("No sensor \n");
  } else   {
    Serial.println(Ftemp);
  }
  delay(100);
}

int spiRead() {
  int value = 0;
  digitalWrite(CS, LOW);
  delay(2);
  digitalWrite(CS, HIGH);
  delay(220);
  /* Bring CS pin low to allow us to read the data from
    the conversion process */
  digitalWrite(CS, LOW);
  /* 1st 5 clock cycles  */
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  digitalWrite(CLK, LOW);
  digitalWrite(CLK, HIGH);
  delay(1);
  /*
    Read bits 16-0 from ads8320 for the adc. Loop for each bit reading
    the value and storing the final value in 'adc'
  */
  for (int i = 16; i >= 0; i--) {
    digitalWrite(CLK, HIGH);
    value += digitalRead(DBIT) << i;
    digitalWrite(CLK, LOW);
  }
  // check bit D2 if HIGH no sensor
  if ((value & 0x04) == 0x04) return -1;
  // shift right three places
  return value >> 3;
}

'
i have added the code i tried with arduino spi library still i don't get any result
 // inslude the SPI library:
 #include <SPI.h>

 // set pin 10 as the slave select for the digital pot:
 const int slaveSelectPin = 10;

 void setup() {
 // set the slaveSelectPin as an output:
 pinMode(slaveSelectPin, OUTPUT);
 // initialize SPI:
 SPI.beginTransaction(SPISettings(2400000, MSBFIRST, SPI_MODE0))

 void loop() {
 while(1){
 spiread(slaveSelectPin);
 }
 }

 void spiread(int slaveSelectPin) {
 // take the SS pin low to select the chip:
 digitalWrite(slaveSelectPin, LOW);

 receivedVal = SPI.transfer(val);
// take the SS pin high to de-select the chip:
digitalWrite(slaveSelectPin, HIGH);
}

On an Arduino Mega and using the Arduino core the highest clock frequency by toggling a digital pin is approx. 70 kHz. The Arduino core is very slow. See GPIO library benchmark https://github.com/mikaelpatel/Arduino-GPIO/blob/master/examples/Benchmark/Benchmark.ino. It is possible to generate up to 4 Mhz clock but you need core or library that is optimized for performance. Also the SPI clock is scaled 8, 4, 2, ..., etc MHz. 2.4 Mhz would force you to select 2 Mhz.

The ADS8320 has to have a DCLOCK frequency of between 0.024MHz and 2.4MHz. Using primitive bit-banging with millisecond granularity delays is not going to get anywhere near even the lower end of that range (500Hz is all you could possibly get with a 1ms delay between each clock transition, also you're generating a pulse wave, not a square wave - nasty).
Even using smaller microsecond delays it's not going to give you good results.
Instead you should be using the hardware SPI port which generates a stable clock signal for defining the acquisition timing.
However you cannot get a 2.4MHz SPI clock on the Arduino. But, do you need a 2.4MHz SPI clock? That's the absolute top end of the sampling frequency. You can go much slower - all the way down to 0.024MHz (24kHz) and still be sampling.
On the Arduino SPI runs at a division of the system clock frequency. That is, 1/2, 1/4, 1/8, etc.  So with a 16MHz system clock you can run SPI at 1/8 that speed and get a 2MHz clock.
You will also need to do a certain amount of bit shifting and unpacking to get the 16 bit data from the 24-bit stream (more bits than you have now) since SPI can only work in 8 bit chunks.

Minimum 22 clock cycles required for 16-bit conversion. Shown are 24 clock cycles. If CS remains LOW at the end of conversion, a new datastream with LSB-first is shifted out again.
-- Datasheet: Figure 29. ADS8320 Basic Timing Diagrams

So you can just ignore what you get in the last two bits of a 24-bit stream.

It's hardly possible to generate a stable and exact frequency with your method.
Imagine you have an interrupt routine interrupting your spiRead() or any function called inside: Your clock will be extended by the ISR runtime.
Apart from this:

I'm not sure if your LOW phase is long enough (there's no delay between setting CLK from LOW to HIGH. If 2.4 MHz is the max frequency for the chip, it should be at least 208ns.
However:
If you are sure that the runtime of digitalWrite is always longer than 208ns, you could remove your delay() at all. The resulting frequency is the maximum possible you can achieve with your method.
The smallest delay() is 1ms, which leads to a maximum of something < 1 kHz (or even 0.5kHz for a 50:50 signal).
You should use delayMicroseconds() to get at least 500kHz.

But what I'm really wondering:
Why are you implementing bit banging instead of simply using the SPI library?

i did not find 3 wire spi example for sensor interfacing. how to use arduino spi library here. can you let me know basic functions for 3 wire spi? which sets 2MHz clock at least

@vassidefuk: For 3 wire SPI you could just leave MOSI unconnected. For the functions refer to the library documentation. What maybe is not so clear there: function "transfer" is byte oriented. As your sensor needs at least 22 bit for converting and sending one value, you would have to call "transfer" three times (24 bit; doesn't hurt) within CS = LOW

i have put another question can you have a look and tell whats is wrong with the code? [https://arduino.stackexchange.com/questions/39047/ads8320-with-arduino-mega-2560]

The Mega 2560 clock rate is 16 MHz. Your target SPI clock rate is 2.4 MHz. That leaves you with 16/2.4 = 6,67 clock cycles per SPI clock cycle, which means you have an available processing clearly insufficient for the task you intend. Your program will choke and will be unable to meet the hard time deadlines required. It will not work.
Instead, you should use another board with higher processing power, a slower SPI clock rate or a HW solution (instead of SW) for the SPI clock.


text:
Accidentally plugged in Arduino Uno before installing software, now it's not recognized by Windows 10, only powered by usb port
Just got a new Arduino Uno, accidentally plugged it in before installing the IDE and windows installed its drivers and had it under ports as a generic device on COM3 (it wasn't named Arduino Uno on device manager).
When I installed the IDE, I couldn't upload sketches to the board because it wasn't recognized. So I uninstalled the device from device manager and also the IDE. I pressed the reset button on the Uno, restarted my PC, reinstalled the IDE, then plugged in the Uno. Since then however, the device isn't read by Windows at all; device manager doesn't show it anywhere, nor does it even refresh when plugged in.
I tried this restarting/reinstalling process multiple times, it's also not a cable issue because I checked for that as well. The power LED is still on, and the pin 13 LED is blinking, but the Arduino isn't being recognized.
I've also tried using the Hardware Install Wizard, but that gives me

This Device Cannot Start (Code 10)

I've been trying to run this for a while now.

I'm running Windows 10, and Arduino IDE for more than  6 months now, 2 different systems, and, for me, UNOs always show as a generic USB device, and everything works just fine.

Last time something similar happened to me, it was caused by a crappy USB cable.

If it shows up as a COM port, you can select/program it through the Arduino IDE, what is the problem here?

you won't see the word "uno" in device manager. do you hear a "ding" when you plug in the Uno?

Also try another USB port.

Check serial communication device on the development board, sometimes the drivers it needs are not installed by default while installing IDE as clones come with different varieties of USB to serial ICs. Try to use different Arduino if you have.

You should not need to install drivers in Windows 10. Windows 10 has its own CDC/ACM drivers built in. What you had before you installed the drivers was correct - it was probably just the settings in the IDE breaking it (wrong port selected?)

There was another post on here recently that was showing error code 10.  I think it is still unresolved though.

You do not need to install drivers in Windows 10 (unless you have a CH340G based Chinese clone, in which case it wouldn't have detected before installing the drivers).
Windows 10 has its own CDC/ACM drivers built in - something every other operating system has had for years and Windows has only just caught up with them. That is why it detected COM3 fine before.
It should have worked fine without installing drivers. It may have been the IDE with the wrong port selected or something else interfering with the port that was stopping you using it.
Uninstall the Arduino drivers and revert to using the Windows built-in ones and work on diagnosing why it wasn't working with those.

You can always remove a unknown device in device manager (yellow exclamation point), reinstall the software, then plug the device in.

If you go to device manager and right-click the Arduino (it will probably have a yellow exclamation mark next to it). You can click update drivers. This fixed the problem for me.

source: Stack Exchange

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

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

sort: votes


text:
Air quality sensor reading meaning
So I got this air quality sensor running, and it's outputting some numbers.
I've read some tutorial online and it looks like the smaller the number the better the air quality.
But I don't understand what is the meaning of those number. Like what is the unit of measurement? For example, the temperature sensor gives you numbers in Celcius degree.
http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

One of those MQ gas sensors ? They are electrochemical sensors. They can be calibrated more or less with a known concentration of a certain gas. But since the are often sensitive to a number of gasses, you do not know the concentration of that specific gas that was used for calibration.
A number that is going up and down is what you have. You can make a graph with it to show the value for each hour or each day.
The MQ gas sensors have a "preheat" or "burn-in" time. It is often 24 hours. Keep the sensor on for 24 hours to get more stable output values.
A temperature sensor is completely different, it contains electronics inside and has been calibrated at the factory. The MQ gas sensors are just a few wires, a heater and some chemicals.
[ADDED]
That is a module with the MP503 gas sensor. It just like the MQ sensors a electrochemical gas sensor. According to the datasheet it is sensitive for alcohol and smoke and the "preheat" or "burn-in" is called "aging time" and can be up to one week! The module has a amplifier.
The detection of gasses is according to a certain curve. To calculate the concentration of gasses a calculation is needed (and a calibrated sensor). I don't see that calculation in the supplied library. So all you have is numbers that change according to the air quality. That's all. And that is normal for these sensors.
Read the information and pdf files on that seeed page about this Grove module. It clearly says that you can't measure the concentration of gas (not "quantitatively"), you can only tell if the air quality gets better or worse (qualitative).

This actually http://wiki.seeed.cc/Grove-Air_Quality_Sensor_v1.3/

I have found that they will give false positives immediately upon power-on, so if they are being used for alarms you might want to build a delay into your program to allow it to heat up.   -- The datasheet says it takes 24 hours to reach factory specifications, but you might try giving it a few hours and see if it working well enough for your particular project.  Ambient temperatures are an issue, of course.  The cooler the environment then the longer it will take to become accurate enough.

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


text:
PCM audio, PROGMEM sounds through speaker, multiple clips (using speaker_pcm)
I downloaded the PCM Audio speaker_pcm (see link below) and it worked easily with the supplied Mac startup chime. I also got my own sounds parsed properly via a combination of sox and wav2c incantations as described. However, when I tried to store and play two or more (very short e.g. 150ms, 8K) sound clips in sequence, I couldn't seem to get it to work. It only sounds like it is playing the last clip in order. I only modified the code (see below) from the original to address the multiple clips. My pointer dereferencing seems to be working (it plays the last clip in sequence), but it won't play a group of them. What am I doing wrong?
(You can download the 01.h 02.h 03.h files from my website, pete dot zelchenko dot com slash 2017 slash the file name. I can't post lots of links here. You can also create your own using the incantations about sox and wav2c in the documentation below, but it takes time. The three files are the words "one" "two" "three" and that's it.)
/*
 * (PCM Audio speaker_pcm downloaded from http://playground.arduino.cc/Code/PCMAudio)
 *
 * speaker_pcm
 *
 * Plays 8-bit PCM audio on pin 11 using pulse-width modulation (PWM).
 * For Arduino with Atmega168 at 16 MHz.
 *
 * Uses two timers. The first changes the sample value 8000 times a second.
 * The second holds pin 11 high for 0-255 ticks out of a 256-tick cycle,
 * depending on sample value. The second timer repeats 62500 times per second
 * (16000000 / 256), much faster than the playback rate (8000 Hz), so
 * it almost sounds halfway decent, just really quiet on a PC speaker.
 *
 * Takes over Timer 1 (16-bit) for the 8000 Hz timer. This breaks PWM
 * (analogWrite()) for Arduino pins 9 and 10. Takes Timer 2 (8-bit)
 * for the pulse width modulation, breaking PWM for pins 11 & 3.
 *
 * References:
 *     [links]
 *
 * Michael Smith <michael [at] hurts.ca>
 */

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 8000

    /*
     * The audio data needs to be unsigned, 8-bit, 8000 Hz, and small enough
     * to fit in flash. 10000-13000 samples is about the limit.
     *
     * sounddata.h should look like this:
     *     const int sounddata_length=10000;
     *     const unsigned char sounddata_data[] PROGMEM = { ..... };
     *
     * You can use wav2c from GBA CSS (OR use EncodeAudio? http://highlowtech.org/?p=1963):
     *     http://thieumsweb.free.fr/english/gbacss.html
     * Then add "PROGMEM" in the right place. I hacked it up to dump the samples
     * as unsigned rather than signed, but it shouldn't matter.
     *
     * [link deleted]
     * mplayer -ao pcm macstartup.mp3
     * sox audiodump.wav -v 1.32 -c 1 -r 8000 -u -1 macstartup-8000.wav
     * sox macstartup-8000.wav macstartup-cut.wav trim 0 10000s
     * wav2c macstartup-cut.wav sounddata.h sounddata
     *
     * (starfox) nb. under sox 12.18 (distributed in CentOS 5), i needed to run
     * the following command to convert my wav file to the appropriate format:
     * sox audiodump.wav -c 1 -r 8000 -u -b macstartup-8000.wav
     */

    //#include "sounddata.h"
    #include "toolow.h"
    #include "toohigh.h"

    #include "01.h"
    #include "02.h"
    #include "03.h"

    int      ledPin   = 13;
    int      speakerPin = 11; // Can be either 3 or 11, two PWM outputs connected to Timer 2

    volatile uint16_t sample;
    byte lastSample;

    int sounddata_length;

    /*int sounddata_length;
    signed char *sounddata_data[10000]; */

    void stopPlayback()
    {
        // Disable playback per-sample interrupt.
        TIMSK1 &= ~_BV(OCIE1A);

        // Disable the per-sample timer completely.
        TCCR1B &= ~_BV(CS10);

        // Disable the PWM timer.
        TCCR2B &= ~_BV(CS10);

        digitalWrite(speakerPin, LOW);
    }

    unsigned int sounddata_addr;

    // This is called at 8000 Hz to load the next sample.
    ISR(TIMER1_COMPA_vect) {
        if (sample >= sounddata_length) {
            if (sample == sounddata_length + lastSample) {
                stopPlayback();
            }
            else {
                if(speakerPin==11){
                    // Ramp down to zero to reduce the click at the end of playback.
                    OCR2A = sounddata_length + lastSample - sample;
                } else {
                    OCR2B = sounddata_length + lastSample - sample;
                }
            }
        }
        else {
            if(speakerPin==11){
                OCR2A = pgm_read_byte(sounddata_addr + sample);
            } else {
                OCR2B = pgm_read_byte(sounddata_addr + sample);
            }
        }

        ++sample;
    }

    void startPlayback(int clip)
    {

    signed char *sounddata_data[10000];

        switch (clip) {
          case   1:  sounddata_data[0] = &s_01_data[0]; sounddata_length = s_01_length; break;
          case   2:  sounddata_data[0] = &s_02_data[0]; sounddata_length = s_02_length; break;
          case   3:  sounddata_data[0] = &s_03_data[0]; sounddata_length = s_03_length; break;

        }

    sounddata_addr = sounddata_data[0];

        pinMode(speakerPin, OUTPUT);

        // Set up Timer 2 to do pulse width modulation on the speaker
        // pin.

    *  // Use internal clock (datasheet p.160)
        ASSR &= ~(_BV(EXCLK) | _BV(AS2));

        // Set fast PWM mode  (p.157)
        TCCR2A |= _BV(WGM21) | _BV(WGM20);
        TCCR2B &= ~_BV(WGM22);

        if(speakerPin==11){
            // Do non-inverting PWM on pin OC2A (p.155)
            // On the Arduino this is pin 11.
            TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
            TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2A = pgm_read_byte(&sounddata_data[0]);
        } else {
            // Do non-inverting PWM on pin OC2B (p.155)
            // On the Arduino this is pin 3.
            TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
            TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2B = pgm_read_byte(&sounddata_data[0]);
        }

        // Set up Timer 1 to send a sample every interrupt.
        cli();

        // Set CTC mode (Clear Timer on Compare Match) (p.133)
        // Have to set OCR1A *after*, otherwise it gets reset to 0!
        TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
        TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

        // No prescaler (p.134)
        TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set the compare register (OCR1A).
        // OCR1A is a 16-bit register, so we have to do this with
        // interrupts disabled to be safe.
        OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

        // Enable interrupt when TCNT1 == OCR1A (p.136)
        TIMSK1 |= _BV(OCIE1A);

        lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
        sample = 0;
        sei();
    }

    void setup()
    {
    // audio pins
        pinMode(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);

        startPlayback(01);
        startPlayback(02);
        startPlayback(03);

    }

    void loop()
    {
      loop();
    }

Which Arduino board ? Arduino Uno ?

I know I'm answering my own question. A lot of rules on stackexchange and dog only knows if this violates one. It looks as if I need to put enough delay after each clip that the clips don't walk on each other. It's that simple. Without the delays, it makes sense that they will just overlap and you'll just hear a high-pitched shriek. I put a delay(250) in for these short clips just to test, but you can calculate the necessary delay for each clip after startPlayback() of each clip, based on the length of the given clip.

I think it's just a case of startPlayback() being asynchronous. It doesn't block; it doesn't wait for playback to finish. It just sets up the 8000 Hz timer interrupt and returns.
The original code calls stopPlayback() when it runs out of samples. You could change that block (under if (sample >= sounddata_length)) to have it cycle on to the next clip, rather than stopping.
(Note: I'm the original author of the PCM sample but it's been quite a while so take this with a grain of salt. Surprised it still works with newer boards. Have fun!)

The Mega2560 apparently has to use pin 10 instead of pin 11 for PCM output.  It would be better if this were defined in the main sketch instead of the library.


text:
What not to do to an Arduino
I may have been working with my Arduino UNO board improperly,
because now it fails to upload sketches (says some programmer is not responding)
and when I press the cute little restart button, the green LED doesn't do its blink anymore. I am aware what that means, but what I really wonder is how should I properly care the board. I probably will have no other chances to buy more arduinos so this information follows to be of a great importance.

As an example I would give, is touching the arduino board with bare hands risky, how much shock-tolerant it is, what if I mistake some pins, are there pins that cannot be mistaken, what will happen if I declare a pin as an output, but use it for input and the contrary, is loading a PWM program onto TFT touch screen shield unhealthy and so forth and briefly - how should I properly care the arduino board.

A lot of things can happen to ruin an Arduino board, although so far I made mistakes and none has broken. However, possible causes can be:

Electrostatic energy, you can prevent it by buying an ESD mat/wristband, or if you don't want to spend money, touch regularly some 'earth' like the central heating
There should not be too much current on a pin ... so don't try to run too many leds or even a motor which is too big from a pin.
Watch out with external power supplies
Don't forget resistors where needed, because of the previous point
Shaking should not matter much, unless you shake so hard that breadboard components are touching each other
Running a program for something else (like PWM on touch screen) might be hard to explain ... it can ruin the device connected, and possibly the Arduino too.

Just some tips:

Whenever you change some hardware/wiring, remove the power
Check very carefully that everything is wired correctly
Keep the Arduino on a solid place (don't let the USB cable let it overthrow/fall on the floor)

I didn't mention about breadboards and it becomes a bit unclear for that reason. Otherwise, very accurate advices, thank you.
I think this is exactly how I broke my Ardu, PWM on a display shied, it was slowly blinking (dimming) back and forth and around that time, this was the last fortunate moment.

It's very hard to predict what happens when a different device is connected (maybe the VCC pin and GND were on different pins).

Yes, this particular tft ts display uses almost all pins and there is not hard to predict every possible combination of wrong placement, but it doesn't matter, I can not revive the board, but I can prevent this happening over again.. on the next 3$ board.

Luckily they are very cheap ... better luck next time

Thanks. Yes, they are affordable. By the way, I was connecting it hundreds of times properly, tested hundreds of programs, but at some point I just got tired, started to be careless and making mistakes. Then it happened.

Happens to me too sometimes ... luckily I just burned not an Arduino, just some LEDs and one 8x8 matrix (one led)

it is okay to use for simple experiments directly. But while you choose to opt for a complex tasks read the details about all the components and their wiring techniques.
specifically try to check soldering is done correctly or not while connecting the wires to any component or to other wire. wrong soldering may damage your parts and arduino as well.
Be careful while using power supply, more when it comes to use multiple sources.
read carefully before you do anything. Dont be afraid just be careful.


text:
Adafruit Gemma unrecognised USB device on Windows 10
I have a V2 Adafruit Gemma from the Gemma starter pack, and I'm running Windows 10 Home (version 10.0.14393), on a 64-bit laptop. Following the  Introducing Gemma guide I've installed the Adafruit drivers and I'm now trying to get it to connect via USB.
After connecting, the board shows the green power LED, but not the pulsing red LED, and Windows shows the 'USB device not recognised' message.
Tried so far

I'm definitely using USB 2 ports, and I have tried it connected directly to the PC and via a USB hub.
I'm pretty sure the cable is working correctly (It works for exchanging data on a phone, and I've tried a few different ones).
Under Device Manager, the board shows as 'USB Device (Device Descriptor Request Failed)'.
'Update driver software' > 'Search automatically...' reports that 'The best driver software for your device is already installed'.
If I do 'Update driver software' > 'Browse my computer...' and point it to the manual Adafruit driver files (available on the link to the guide), I get the same message.

Can anyone suggest anything to try? Do I need to (re)install the bootloader itself, and if so, can you point me in the direction of how I do this?
Update
As mentioned in the comments I have posted on Adafruit's own support forum but got absolutely nothing yet. I have also tried it on my work PC (Windows 10 Pro, 64-bit) and got exactly the same behaviour.
I'm keen to get this sorted so bounty added for anyone who can at least come up with some suggestions of what to try!

"USB Device (Device Descriptor Request Failed)" tends to indicate that the speed select resistor has been seen, but actual USB signalling failed.  This could be any number of problems.  The Gemma doesn't use a legitimate USB interface, but a rough approximation in software running on the ATtiny.  So it could be a compatibility issue, a lack of appropriate software loaded, or a bad board.   Given you've already tried with and without a hub, you should probably pursue this with Adafruit on their own support forums.

Yes I've posted on the Adafruit forums too and I've tried with and without the hub as above. I appreciate the message is vague but that's exactly my problem, I'm not sure where to go from there.

I think, you've pretty much done everything. If you could gain access to another board, and try that one you could figure out more. Otherwise your symptoms remind me of a something called an ESD (Electrostatic Discharge) caused malfunction. This basically means one of the system essential chips on the board have been fried. It is very easy to ESD a chip without protection, just walk on a carpet or put on a sweater, and than touch the chip. Chances are you were electrostaticly charged with thousands of volts. The chip does not stand a chance. To prevent this from happening, touch something made out of metal before touching the board.More on ESD: Electrostatic discharge


text:
Fade effect analog RGB strip and NodeMCU
I have an analog or dumb RGB strip that I control with HTTP commands. I want to be able to make the strip fade between different colours when I call http://XX.X.X.XXX/fade. I want it to do this infinitely until another colour is set or it turns on or off. I have tried doing this with a while loop but I can no longer change the state of the light from fading. Does anyone know how to do this? I'll link my code below.
//NodeMCU RGB-Controller for Homebridge & HomeKit (Siri)

#include <ESP8266WiFi.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel

#define max(a,b) ((a)>(b)?(a):(b))

WiFiServer server(80); //Set server port

String readString;           //String to hold incoming request
String hexString = "FFFFFF"; //Define inititial color here (hex value), 080100 would be a calm warmtone i.e.

int state;

bool fading;

int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "SSID";
const char* password = "PASSWORD";
IPAddress ip(XX,X,X,XXX);      // set a fixed IP for the NodeMCU
IPAddress gateway(XX.X.X.X);  // Your router IP
IPAddress subnet(XXX.XXX.XXX.X); // Subnet mask
////////////////////////////////////////////////////////////////////

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet); //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  server.begin();
}

void allOff() {
  state = 0;
  for (float fade = 1.0; fade >= 0.0; fade -= 0.01) {
    analogWrite(redPin, map((r * fade), 0, 255, 0, 1023));
    analogWrite(grnPin, map((g * fade), 0, 255, 0, 1023));
    analogWrite(bluPin, map((b * fade), 0, 255, 0, 1023));
    delay(2);
  }
  // Set r/g/b to 0 so fade in is possible
  r = 0;
  b = 0;
  g = 0;
}

//Write requested hex-color to the pins
void setHex() {
  const float STEPS = 100; // Change number of steps while fading (lower is faster)
  // Save old values of r/g/b
  byte oldR = r;
  byte oldG = g;
  byte oldB = b;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  float deltaR = (r - oldR) / STEPS;
  float deltaG = (g - oldG) / STEPS;
  float deltaB = (b - oldB) / STEPS;
  // Fade to new colour
  for (float f = 0; f < STEPS; f++) {
    analogWrite(redPin, map((oldR + (deltaR * f)), 0, 255, 0, 1023));
    analogWrite(grnPin, map((oldG + (deltaG * f)), 0, 255, 0, 1023));
    analogWrite(bluPin, map((oldB + (deltaB * f)), 0, 255, 0, 1023));
    delay(2);
  }
  state = 1;
}

//Compute current brightness value
void getV() {
  R = roundf(r/2.55);  //was (r/10.23);
  G = roundf(g/2.55);  //was (g/10.23);
  B = roundf(b/2.55);  //was (b/10.23);
  x = max(R,G);
  V = max(x, B);
}

//For serial debugging only
void showValues() {
  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);
  getV();
  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");
}

void setup() {
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
  WiFi.mode(WIFI_STA);
  WiFiStart();
  setHex();
}

void loop() {
  WiFiClient client = server.available();

  if (!client) {
    return;
  }

  while(client.connected() && !client.available()) {
    delay(1);
  }

  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: ");
          Serial.println(readString);

          //Send reponse
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            showValues();
            fading = false;
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
            fading = false;
          }

          //Fade
          if(readString.indexOf("fade") >0) {
            fade();
            fading = true;
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            showValues();
            fading = false;
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
          client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
          client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {
          getV();
          client.println(V);
          }

          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

void fade() {
  while(fading == true){
    hexString = "000000";
    setHex();
    hexString = "FFFFFF";
    setHex();
    hexString = "FF0000";
    setHex();
    hexString = "008000";
    setHex();
    hexString = "0000FF";
    setHex();
    hexString = "FFFF00";
    setHex();
    hexString = "1E1E1E";
    setHex();
   }
 }

get rid of the client.read() malarky using server.on() to handle your API outside of loop(). 2. move your setHex code to loop, and make enough of the control variables globals so that it performs as expected. 3. have your API modify the control variables, like step increment (which can be zero to pause/halt), current colors, etc.

The variable fading cannot ever change, once you are in that while loop, since your code doesn't do it and you don't use interrupts either (And I don't know, if the library is supporting this). So the Arduino is stuck forever in this loop and will not respond to any interactions but resetting.
There are basically there are 2 different options for you (not counting the usage of a hypothetical interrupt capability of the Wifi library, as I don't know enough about the library):

Adding Wifi code to the while loop: You can just add code, that watches the Wifi interface into the while loop and set the fading variable correspondingly. This is the easiest to program option.
Rewrite your code (especially the fade() function) to be non-blocking, which means it will not block the execution of other code, but will only do something, when it is time to do so, and otherwise return from the function. You can achieve this by using the millis() function, which returns the milliseconds since the last startup/reset to use as a time source. Refer to the BlinkWithoutDelay example of the Arduino IDE. Also you can google for millis(); there are a ton of tutorials out there. When writing non-blocking code you might also want to implement a Finite State Machine (FSM). It's simpler as it sounds. You basically define a simple variable, which sets your current state (for example the states fading, off, specific_color, ...). In your loop() function you make a switch(state_variable){ case statement, where you insert code for every state in it's own case. Outside of the switch statement you can then check the Wifi interface and set the state variable correspondingly. If everything is written non-blocking it should work like a charm.

Thank you. It worked when I made a switch case in the loop then made a new function called handleWifi() to handle the wifi code.

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


text:
How to fade out RGB strip?
I have a NodeMCU controlling an RGB strip. I have followed a guide and used this code:
#include <ESP8266WiFi.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel
#define max(a,b) ((a)>(b)?(a):(b))

WiFiServer server(80); //Set server port

String readString; //String to hold incoming request
String hexString = "FFFFFF"; //Define initial color here (hex value), 080100 would be a calm warm tone i.e.

int state;
int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "xxxxxxx";
const char* password = "xxxxx";
IPAddress ip(x,x,x,x);      // set a fixed IP for the NodeMCU
IPAddress gateway(x,x,x,x);  // Your router IP
IPAddress subnet(255,255,255,0); // Subnet mask

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);
  //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");
  server.begin();
}

void allOff() {
  state = 0;
  analogWrite(redPin, 0);
  analogWrite(grnPin, 0);
  analogWrite(bluPin, 0);
}

//Write requested hex color to the pins (10-bit PWM)
void setHex() {
  state = 1;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  r = map(r, 0, 255, 0, 1023);  //added for 10-bit PWM
  g = map(g, 0, 255, 0, 1023);  //added for 10-bit PWM
  b = map(b, 0, 255, 0, 1023);  //added for 10-bit PWM
  analogWrite(redPin, (r));
  analogWrite(grnPin, (g));
  analogWrite(bluPin, (b));
}

//Compute current brightness value
void getV() {
  R = roundf(r/10.23);  //for 10bit pwm, was (r/2.55);
  G = roundf(g/10.23);  //for 10bit pwm, was (g/2.55);
  B = roundf(b/10.23);  //for 10bit pwm, was (b/2.55);
  x = max(R,G);
  V = max(x, B);
}

//For serial debugging only
void showValues() {
  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);
  getV();
  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");
}

void setup(){
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
  setHex(); //Set initial color after booting. Value defined above
  WiFi.mode(WIFI_STA);
  WiFiStart();
}

void loop() {
  //Reconnect on lost WiFi connection (superfluous - will reconnect anyway)
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  while(client.connected() && !client.available()) {
    delay(1);
  }
  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: ");
          Serial.println(readString);
          //Send reponse
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            showValues();
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            showValues();
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
            client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
            client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {
            getV();
            client.println(V);
          }
          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

I have tried to fade out by putting my code below in the allOff() function, but it only fades out then comes back white. I would also be interested in fading between different colours in the setHex() function.
void allOff() {
  state = 0;
  for (int i=r; i <= 1023; i--){
  analogWrite(redPin, i);
  analogWrite(grnPin, i);
  analogWrite(bluPin, i);
  }
}

I would appreciate it if anyone could give me the right way to do this. Thank you.

for (int i=r; i <= 1023; i--){
    analogWrite(redPin, i);
    analogWrite(grnPin, i);
    analogWrite(bluPin, i);
    }

analogWrite expects a range of 0 to 255, not 0 to 1023.
In any case, why are you starting with the r value and decreasing that? What about b and g?
And why not stop at zero? Your code will reach zero, and then keep going down to -1, -2 etc. I think you mean i >= 0 not i <= 1023.
Let's assume that the previously set values of r, g and b are what you want to fade. Make a loop that decreases them at the same rate:
for (float fade = 1.0; fade >= 0.0; fade -= 0.01)  // 100 steps
    {
    analogWrite(redPin, (float) r * fade);
    analogWrite(grnPin, (float) g * fade);
    analogWrite(bluPin, (float) b * fade);
    delay (10);  // short delay so you notice it
    }

So how could I apply this code to fade between colours in my setHex function?

Well, fading to black is a special case of fading from one colour to another. To do it in (say) 100 steps you need to work out a "delta" - that is the difference, for each of r/g/b from the initial colour to the new one. So for example if the old red value was 10 and the new red value is 50, then the delta is 40 (50 - 10). So over your 100 steps you need to change the red value by 40 / 100. Using floating point arithmetic lets you handle numbers which aren't integers (in this case 40 / 100 would be 0.4). Example code:
  const float STEPS = 100;

  // save old values of r/g/b
  byte oldR = r;
  byte oldG = g;
  byte oldB = b;

  // calculate new values
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;

  // work out deltas
  float deltaR = (r - oldR) / STEPS;
  float deltaG = (g - oldG) / STEPS;
  float deltaB = (b - oldB) / STEPS;

  // fade from old to new
  for (float f = 0; f < STEPS; f++)
    {
    analogWrite(redPin, oldR + (deltaR * f));
    analogWrite(grnPin, oldG + (deltaG * f));
    analogWrite(bluPin, oldB + (deltaB * f));
    delay (10);
    } // end of for

Thank you this is exactly what I was looking for, I forgot about the b and g values when I was trying to just test how I could get one channel to fade then forgot. Thanks :)

How could I do the same with fading between colours in the setHex() function?

Will the float values get truncated to byte for the analogWrite? If so, then just decrement from 255 by 2 or 3, stop when get down to non-detectable level.

Yes, there will be truncation, but this method smoothly dims all three colours at the same rate (eg. R/G/B will at some point all be 50% of what they started). They don't necessarily start at 255, since he wants to dim whatever-colour-it-was he started with. If you just subtract (say) 2, and he starts with R=255,G=100,B=10 then blue will very quickly become zero and the hue will change.

So how could I apply this code to fade between colours in my setHex function(see my code).

See amended answer.

Thank you I tried doing something like this but it didn’t exactly work. Thank you for taking the time to explain it.


text:
Can upload programs to ESP8266 with Arduino Nano but not run them
I am trying to use my Arduino Nano to program my Generic ESP-01 Module. I want to use the module to control an RGB LED Light Strip but am not having much success, only errors....
These are my connections:
Esp-01 -------------------------------------------------- Arduino Nano
TX <------------------------------------------------------> TX
RX <-----------------------------------------------------> RX
VCC <----------------------------------------------------> 3.3v
CH_PD <------------------------------------------------> 3.3v
GND <---------------------------------------------------> GND

I have also grounded my reset pin on my Arduino and when programming I ground the GPIO0 on the ESP-01 to enter flash mode. Not too sure if this would cause a problem but just wanted to note that my Arduino Nano is a clone and runs on the CH340G USB drivers not FTDI. It successfully uploads the program with the Arduino IDE but not much after that. I have also tried uploading the Blink program and the CheckFlashConfig program but the same error on startup.
Here is the error:
ets Jan  8 2013,rst cause:2, boot mode:(3,6)

load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v09f0c112
~ld

I also decoded the stack that I sometimes get with ESP Exception Decoder:
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x402177a8: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104bd3: wdt_feed at ?? line ?
0x40104bb4: wdt_feed at ?? line ?
0x40104bcd: wdt_feed at ?? line ?
0x40104bca: wdt_feed at ?? line ?
0x4022bea0: cal_rf_ana_gain at ?? line ?
0x40228690: tx_cap_init at ?? line ?
0x4022d4cd: ram_rfcal_pwrctrl at ?? line ?
0x4022d37c: ram_rfcal_pwrctrl at ?? line ?
0x4022be18: cal_rf_ana_gain at ?? line ?
0x4022be3d: cal_rf_ana_gain at ?? line ?
0x4022be9c: cal_rf_ana_gain at ?? line ?
0x40228689: tx_cap_init at ?? line ?
0x40228690: tx_cap_init at ?? line ?
0x4022a600: chip_v6_initialize_bb at ?? line ?
0x40226237: phy_init at ?? line ?
0x40105eae: register_phy_ops at ?? line ?
0x4022b3b2: register_chipv6_phy at ?? line ?
0x4021a93e: wifi_station_set_default_hostname at ?? line ?
0x40201b39: __wrap_register_chipv6_phy at /Users/privitec/Library/Arduino15/packages/esp8266/hardware/esp8266/2.3.0/cores/esp8266/core_esp8266_phy.c line 261
0x4022f660: sleep_reset_analog_rtcreg_8266 at ?? line ?
0x4010564a: spi_flash_read at ?? line ?
0x402174c3: rijndaelKeySetupEnc at ?? line ?
0x40217b3c: user_uart_wait_tx_fifo_empty at ?? line ?
0x40217b17: user_uart_wait_tx_fifo_empty at ?? line ?
0x40104e90: wdt_feed at ?? line ?

Your help would be greatly appreciated.
Update:
I have tried reinstalling AT firmware version 0.9.2.2 with esptool. Again it successfully detects the ESP-01 and programs it. I still get the same error (sometimes instead of getting boot mode:(3,6) I get boot mode:(3,7)) when powering up and I have tried to input AT into the Serial Monitor and I get no response.

you need to go rx-tx, tx-rx...

Already tried... Still no luck.

I believe it has a program mode and a run mode (it has on some other ESP versions). You could Google around on that a little

I know that grounding GPIO0 puts it into flashing mode. I have also tried other combinations pulling other pins high and low but nothing has worked.

Possible duplicate of ESP8266 proper power circuit for avoid reset issue in that until the improper use of the Arduino's 50 mA rated 3.3v regulator to power the ESP's up to ~170 mA current requirement is corrected, it's not worth considering anything else.

you need to go rx-tx, tx-rx Actually in this case the Nano is only being used as a USB-serial adapter to directly program the ESP8266 and so RX-RX, TX-TX is the correct wiring.

I have tried to input AT into the Arduino IDE and I get no response. When you upload to the ESP8266 via the Arduino IDE the AT firmware is overwritten. "input AT into the Arduino IDE" is a very imprecise statement. Do you mean the Serial Monitor? Please make a better effort with your questions, otherwise they will be closed.

Sorry, yes I mean the serial monitor and this is even after erasing the ESP-01 then flashing AT firmware back to it with esptool.

I'd also say putting 5V (TX) into a 3.3V (RX) such as ESP-*-s might not be the best idea. Please use a level converter. The opposite is okay as 3.3V is detected as HIGH on an Arduino.

I have tried using a voltage divider with a 1k resistor and a 2.2k resistor but it makes no difference.


text:
Unable to upload sketch using Platformio (but Arduino IDE works)
I am using an Arduino Nano (Clone) which I was programming with the Arduino IDE (Version 1.8.5 on Mac OS X 10.10.5).
Using the Arduino IDE I need to re-plug the Nano before uploading, but after doing this everything works as expected and the sketch is being uploaded successfully.
I then tried to use Platformio core (CLI) and get the well-known not in sync error:
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xe0
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

As said, this error is well-known, esp. in relation to Arduino clones, and reported several times around the Internet with different solutions.
I just wonder how Arduino IDE is able to upload the code successfully, but Platformio is not since both Arduino IDE and Platformio CLI are just calling avrdude to upload the code.
Remark: Uploading the same code to an Arduino Uno works like a charm with both using Arduino IDE and Platformio.

Updates due to further investigation:
I enabled verbose output for both Arduino IDE and Platformio showing the exact avrdude command executed to upload the built hex-file. I adopted the call to avrdude from Arduino IDE with the path of the compiled Platformio code. This works as expected:
avrdude -v -p atmega328p -c arduino -b 57600 -D -P /dev/cu.usbserial-00000000 -U flash:w:.pioenvs/nano/firmware.hex:i

I then had a look at the command used by Platformio which is quite similar but provides an additional -C for a config-file:
avrdude -v -p atmega328p -C /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf -c arduino -b 57600 -D -P "/dev/cu.usbserial-00000000" -U flash:w:.pioenvs/nano/firmware.hex:i

Unfortunately, I am not able to run this command from the Terminal due to an error:
avrdude: Version 6.0.1, compiled on Dec 16 2013 at 17:26:24
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf"
avrdude: syntax error at /Users/Albert/.platformio/packages/tool-avrdude/avrdude.conf:1080

try to upload to Nano with Uno selected as board

@Juraj: Using Uno instead of Nano does not work as well.

has Platformio an "old bootloader" option for Nano?

There is a 'normal' and a 'new' option. Both not working. The only difference seems to be the baud rate at first glance. I might have a look at the upload scripts for further differences...

I've tried replicating this issue using a nano clone on mac os 10.12.6 using platformio IDE, and there were no issues. I would try two things: upload a simple blink sketch (or an empty loop) using arduino IDE to make sure the board doesn't try to connect over UART thus interfering with the upload process under platformio; and if this doesn't help, then I would re-flash the bootloader. Also, if platformio is not up to date, it is certainly a good idea to update it to make sure it uses the latest avrdude + config file.

@Im_Int: Updated to Arduino 1.8.7 and tryied to reflash boot-loader. Reflashing did not work with Arduino 1.8.7 but with 1.8.5. After that still not able to upload code using Platformio. Tried another Arduino Nano clone: Was able to upload code once with Platformio, but never again. Uploading with Arduino IDE 1.8.7 works, unable to re-flash bootloader to this board as well. There are several discussions around the Internet about the transfer protocol, the use of reset signal on Reset pin (RST) and a capacitor. So this might me a hardware/board-related issue due to cheap Arduino clones... :/

how do you flash the bootloader?

I used/tried to use an Arduino Uno as ISP since I do not have my original AVR ISP mkII on hand currently

and why did you do that? is it possible that you changed to different bootloader?

I'm having the exact same issue. I'm abandoning platform io because of this. It's rather more difficult than the arduino IDE.

Please use board = nanoatmega328new in your platformio.ini


text:
Reducing the noise of an SSD1306 display by reducing pre-charge in Adafruit SSD1306 library
I have issues with electrical noise on my board (>300mV switching noise on top of 3.3V rail, its quite a lot), which is generated by my I2C SSD1306 OLED display. After some research I found that the noise may be reduced by changing the pre-charge duration in the SSD1306 controller. I am using an Arduino IDE with Adafruit_SSD1306.h library to program my chip. As I understand the initialization bits should be passed via I2C to the controller.
I found the following command in the Adafrui_SSD1306.cpp:

And the relevant bit of datasheet:

The D9 register is defined as SSD1306_SETPRECHARGE in Adafruit_SSD1306.h:

I am using the following code:
void setup(){
...
display.ssd1306_command(SSD1306_SETPRECHARGE); //0xD9
display.ssd1306_command(0x11);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
}
...

I am trying to set to 0x11, so to give the pre-charge byte lowest value possible. I've also tried putting the same command into the loop. Nothing has any effect on the display brightness though, which from my understanding should decrease with decreasing the pre-charge value. The noise also stays exactly the same. It seems I fail to pass the values to the SSD1306 correctly. I also tried changing the value in the Adafruit_SSD1306.cpp file:

Still no change. The noise stays exactly the same as well as the brightness. It's clear to me I'm doing something wrong, or I misunderstand the effect of changing the pre-charge value completely. I couldn't find anything in adafruit documentation on this matter. What am I doing wrong?
UPDATE:
I used other commands, such as setcontrast, which did have an effect on the display, so I did pass the values to the controller. It seems that changing the pre-charge value do not have much of an effect. On the other hand I discovered that I2C bus might be introducing the unwanted noise. When bypassing the data of clock line to ground via a capacitor the noise decreases. It seems I was looking for an issue in the wrong place.

At the first glance ssd1306_commad1 should be wrapped in a transaction. This is missing in your code. Add the wrapping macros TRANSACTION_START and TRANSACTION_END or try using ssd1306_command instead.

Apologies, I was using ssd1306_command, forgot to edit it in here. I also discovered that my commands did update the values in the ssd1306 (using other commands like setcontrast etc.), but there was no visible difference when I changed the pre-charge value either in noise or in brightness.


text:
Can not receive data from UART with stepper motor
I am using an Arduino Mega2560
While my motor is moving I can not receive anything from the UARTs. When the motor ends movement, I receive data from UART.
How can I make my motor move without stopping the reception of data from UART?

Why should we take the time to help you if you won't make a little effort with your question? Edit your post to have proper spelling and punctuation. Format your code (hint: Tools > Auto Format if using the standard Arduino IDE).

If you look at AccelStepper.cpp code of the library you're using, you'll notice that runToNewPosition() is:
void AccelStepper::runToNewPosition(long position)
{
    moveTo(position);
    runToPosition();
}

which, in turns calls:
// Blocks until the target position is reached
void AccelStepper::runToPosition()
{
    while (run())
    ;
}

In turn, run() returns false only when the position is reached, as shown here:
boolean AccelStepper::run()
{
    if (_targetPos == _currentPos)
    return false;

    if (runSpeed())
    computeNewSpeed();
    return true;
}

As you can see, your program is blocked until the position is not reached.
Data can be still received by the serial port (until buffer is exceed), but you won't be able to read it until that while ends.
To make the motor running without blocking the program, you should implement the AccelStepper functions in the loop function, in a non-blocking way.
In particular, (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications), in rotate_motor() call only:
stepper1.moveTo(1100);

Then in the loop, write somewhere:
stepper1.run();

EDIT:
Hint for having the motor moving forward and then backward as in your original code:
Add a state variable (say you call it "m"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling stepper1.run(), check if you actually must move (if (m != 0)). When you call the stepper1.run() method, check if it returns false. In this case it means it reached the position, then you must change the value of m accordingly.

when I write stepper1.moveTo(1100); stepper1.run(); the motor do not make any movement . it is static. what problem??

Because, as you can see in the code, that method only sets the target position and compute the speed. (https://github.com/adafruit/AccelStepper/blob/master/AccelStepper.cpp). You must also write in the loop stepper.run(). That method is responsible for the actual movement, and it must be continuously called (in the loop function), as written in the cpp source.

ok . but I need to bring it to zero position when it finish rotate. in other words . go to 90 degree then go back to zero . that will be continuous

I wrote in the answer (I only help you to set the position to 1100. You'll make the effort to bring it back to 0, with small modifications).  :)
Hint: add a state variable (say you call it "m"), where you store if you need to move forward (e.g. 2), backward (e.g. 1) or stop (0). Then, before calling run, check if you actually must move (if (m != 0)). When you call the run() method, check if it returns false. In this case it means it reached the position, then you must change the value of m accordingly.
I added this on the answer.


text:
Arduino Pro Mini ATmega 328P: garbage output on serial console
Arduino Pro Mini ATmega 328P 3.3V 8MHz, connected to USB port via USB to Serial breakout board built around the FT232RL FTDI chip. JTAGenum project code uploaded to the Arduino. I opened terminal and tried to run test command (without connecting wires between target and Arduino), but terminal output show garbage values. The baud rate of the serial console has been set 115200, as specified in JTAGenum code. Not sure whether this issue can be related to CPU_PRESCALE defintions in code.

Most likely an incorrect F_CPU. Do you have the right board selected in the IDE?

I managed to upload sketch. I use Arduino Web Editor, I selected 'Board as Arduino Pro or Pro Mini', first it show red cross(disconnected) state, when click Change on menu, it stay connected, but when I check board type I noticed that FLAVOUR by default always selected '16MHz ATmega328', not '8MHz ATmega328'. When I select  '8MHz ATmega328' it show disconnected state, so I should press Change. Does this mean my OEM board is 16MHz, not 8MHz?

The IDE cannot know what your board is - that is down to you to tell it. If it's an 8MHz board and you tell the IDE 16MHz you will get garbage. If its a 16MHz board and you tell the IDE 8MHz you will get garbage. If you don't know which you bought, why did you buy it?

No. I think Arduino Web Editor (as part of Arduino IDE) capable automatically detect the kind of board and the port it is connected to without having to individually select them. That's why Arduino Web Editor by default always show '16MHz ATmega328' in FLAVOUR menu. But in my Pro Mini ATmega board description was stated its 328P 3.3V 8Mhz model.

I changed the terminal baud rate to 57600 and code works now. Due to presumably wrong bootloader installed, Arduino IDE detects board as 16MHz clock, not 8MHz which it actually is, so Arduino Plugin uses incorrect settings when uploading code into the board.

Garbage values on output is mostly due to the baudrate.
Try changing the baudrate on the output terminal to the baudrate in the code.
Try checking the output by changing different baudrates on the terminal.
 This must work for you :)


text:
Error when trying flash bootloader into Arduino Pro Mini 328P 8MHz 3.3V
I tried flash bootloader into Arduino Pro Mini 328P 8MHz/3.3V clone, but got error.
First I did test:
~$ avrdude -c usbasp -p m328p

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: safemode: Fuses OK (E:FD, H:D9, L:E2)

avrdude done.  Thank you.

~$ avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex

avrdude: Version 6.2
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/combox/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: reading input file "optiboot_atmega328_pro_8MHz.hex"
avrdude: error opening optiboot_atmega328_pro_8MHz.hex: No such file or directory
avrdude: can't determine file format for optiboot_atmega328_pro_8MHz.hex, specify explicitly
avrdude: read from file 'optiboot_atmega328_pro_8MHz.hex' failed

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:D9, L:E2)

avrdude done.  Thank you.

@combox:~$ cd Downloads
@combox:~/Downloads$ cd Arduino
@combox:~/Downloads/Arduino$ avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex

avrdude: Version 6.2
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/combox/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: NOTE: "flash" memory has been specified, an erase cycle will be performed
         To disable this feature, specify the -D option.
avrdude: erasing chip
avrdude: auto set sck period (because given equals null)
avrdude: reading input file "optiboot_atmega328_pro_8MHz.hex"
avrdude: input file optiboot_atmega328_pro_8MHz.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328_pro_8MHz.hex:
avrdude: load data flash data from input file optiboot_atmega328_pro_8MHz.hex:
avrdude: input file optiboot_atmega328_pro_8MHz.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328_pro_8MHz.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x7e00
         0x00 != 0x11
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as 0
avrdude: safemode: efuse reads as FE
avrdude: safemode: lfuse changed! Was e2, and is now fe
Would you like this fuse to be changed back? [y/n]

How to solve this?

First, I put the voltage jumper on USBASP programmer to 5V, to increase voltage.
Then I set correct default fuse bits values for this board:
Arduino Pro or Pro Mini (3.3V, 8 MHz) w/ ATmega328

Low Fuse:   0xFF
High Fuse:  0xDA
Extended Fuse:  0x05

avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U efuse:w:0xFD:m
avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U hfuse:w:0xDA:m
avrdude -c usbasp -p m328p -v -u -U lock:w:0x3f:m -U lfuse:w:0xFF:m

Note, that I used option -u when modifying the fuse bits, this switch tell avrdude we really mean modify it. It disables the default behaviour of reading out the fuses three times before programming, then verifying at the end of programming that the fuses have not changed. I put 0xFD value for Extended Fuse Byte in place of 0x05, due to a bug in avrdude. (0xFD and 0x05 are the same value)
After that I flashed correct bootloader:
avrdude -c usbasp -p m328p -v -U flash:w:optiboot_atmega328_pro_8MHz.hex -U lock:w:0x0f:m

Now it fully fixed and works.

It is locked/blown. Looks like you tried to flash it previously as an Arduino Nano or Uno.
Now the lock bits are set. Even in highVoltage programming mode you cannot discover it. Buy a new one.

@Harald - no, I managed to fix it, easily enough. I will edit my question to add the solution.


text:
Arduino UNO/Nano communication with SP1ML-868 module
Good evening, I'm trying to establish serial communication between an Arduino UNO/Nano (ATMega328P) and a SP1ML-868 RF radio module (http://www.st.com/en/wireless-connectivity/sp1ml.html). I can talk to the radio with an FTDI breakout board, connected directly to my PC, but I can't do it with the Arduino.
As the radio is 3.3V and the Arduino is 5V, I tried to use the logic level converter from Sparkfun in the RX/TX lines, but that didn't work as well.
Any idea as to what I might be doing wrong? Thanks!
EDIT
I was able to talk to the radio by uploading a blank sketch to my Arduino and using only the RX/TX pins and the FTDI chip on the board. When I configure the Serial port (i.e. Serial.begin), this no longer works, which leads me to believe the problem is in the ATmega USART configuration. For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.
As requested, below is the simple serial echo code I'm using, and an image with the wiring. This assumes the normal RX->TX and vice-versa connection. The module is powered through wires underneath its breakout board (3.3v).

void setup(){
  Serial.begin(115200);
}
void loop(){
  while(Serial.available() > 0){
    Serial.print((char)Serial.read());
  }
}

Please edit your question to include a complete minimal sketch that demonstrates the problem. Please edit your question to explain how you have the module wired to the Arduino board.

@per1234 There, does that help?

Not an answer to my question per-se, but I was able to solve my problem.
As mentioned on my comment on the last answer, the SP1ML module's serial communication is handled through an ARM microcontroller. So I got my hands on an Arduino Due, which has an ARM Cortex M3 MCU, and uploaded a serial echo code similar to the one on my question, only now using Serial3 to talk to the module:

void setup(){
  Serial.begin(9600);    // Connected to PC
  Serial3.begin(115200); // Connected to SP1ML, Rx-Tx connection
}
void loop(){
  if (Serial.available() > 0){
    Serial3.write(Serial.read()); // Echo to SP1ML
  }
  if (Serial3.available() > 0){
    Serial.write(Serial3.read()); // Echo to serial monitor
  }
}

I tried the exact same code on an Arduino Mega (same pins, ATmega2560 MCU) and it didn't work.
Obviously the MCUs are very different, but I have no idea one works and the other doesn't. A wild guess would be that the word sizes are different. In the Atmega, the word size is 16-bits, and in the ARM, the word size is 32-bits.

For some weird reason, this only works when the Arduino RX is connected to the module RX, and TX with TX.

This works because in that configuration you are actually using your Arduino as a USB-serial adapter. When you make the RX-RX, TX-TX connection you cannot communicate between the ATmega328P on your Uno but you are also making a RX-TX, TX-RX connection with the ATmega16U2 chip on your Uno that is used as the USB-serial adapter on the board.
I feel that it's problematic to try to use Serial (pins 0 and 1) for communication both with the computer and the module. Instead I would recommend using the SoftwareSerial library for communication between the Uno and the module.
SoftwareSerial doesn't work reliably at 115200 so you should first use the current working wiring to configure the module to communicate at a lower baud rate. 9600 is quite safe but if communications speed is a bottleneck for your application you can probably use a higher baud rate.
Next, wire the module to any unused pins on your Uno other than 0 and 1.
Finally, upload the following code to the Uno:
#include <SoftwareSerial.h>

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

void setup() {
  Serial.begin(115200);  // set this to the baud rate of the Serial Monitor
  SP1MLserial.begin(9600);  // set this to the baud rate of the module
}

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

This is the equivalent of the simple echo code you posted above and can be used to verify that everything is working before moving on to more complex code. I have arbitrarily chosen pin 10 for the Uno software serial RX pin 11 for the TX pin but you can modify the code to any pins that are convenient for you. You should make the connections with the module as RX-TX, TX-RX.

Thanks for the answer!  However, I tried your suggestions and it still does not work. I send a command to the module (i.e. "+++\r", to enter command mode) and get nothing in return. If it helps, this module's serial comm is done with an STM32L1 ARM MCU, which connects to the SPIRIT1 radio via SPI protocol. Maybe there is a mismatch between the SoftwareSerial protocol and the one used in the ARM?


text:
ESP8266 disconnects after relay switch
the aim of the project I'm working on is to water my bonsai automatically, depending on numerous sensor inputs. So basically I have Arduino Nano with huminity and light sensor, a relay to switch the water pump and ESP8266 wifi module, which I use to check the data from the sensors in the Blynk app on my phone. I use two isolated circuits. The first one is used only by the DC motor (water pump) and is supplied by a 5V 600 mA power source. The second takes care of the rest (arduino, ESP, sensors, relay) while it's supplied by a 5V 1A power source. I'm using this with the ESP8266 board.
Once I run the program, it connects to the Blynk server and I can read data from the sensors on my phone. The problem comes when I want to switch the relay from the Blynk app. Than the ESP8266 disconnects (nearly immediately, or after few seconds). I tried a different DC motor (not a water pump) and it worked fine. I also tried to switch the pump without using EPS8266, that worked as well (so the code should be ok). I think this has something to do with the current draw caused by the water pump, but that makes no sense - I'm using two independent circuits, the pump draws maximally 300 mA from the 600 mA source, while the rest of the electronics draws no more than 200 mA from the 1 A power supply. Neither different power supplies, nor another relay worked.
Here's my code:
#define BLYNK_PRINT Serial
#define BLYNK_DEBUG

#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>

#include <BH1750.h>
#include <Time.h>
#include <SoftwareSerial.h>

#define PUMP  10
#define SENSOR A0
#define BUTTON 2

char ssid[] = "XXXXX";
char pass[] = "XXXXXXXXXXXXXXXXXX";

SoftwareSerial EspSerial(11, 12);
ESP8266 wifi(&EspSerial);

BlynkTimer timer;
BH1750 lightMeter;
int humidity;
int light;
bool pressed = 0  ;
bool pump=1;
char auth[] = "XXXXXXXXXXXXXXXXXXXXXXXXXX";

void sendData(){
      humidity=analogRead(SENSOR);
      light=lightMeter.readLightLevel();
      Blynk.virtualWrite(V0,humidity);
      Blynk.virtualWrite(V1,light);
//      Serial.print("humidity: ");
//      Serial.println(humidity);
//      Serial.print("light: ");
//      Serial.println(light);
}
void checkConnection(){
  if(!Blynk.connected()){
    digitalWrite(PUMP,1);
    Blynk.begin(auth, wifi, ssid, pass);
  }
 }
void checkButton(){
  if(digitalRead(BUTTON) && pressed){
     Blynk.virtualWrite(V3,digitalRead(BUTTON));
     pump=!pump;
//      Serial.println("pump from button");
     }
  else if(digitalRead(BUTTON) && !pressed){
    pressed=1;
    }
  else{
    pressed=0;
    }
}
BLYNK_WRITE(V2)
{
    Serial.println("switching pump");
    pump=!param.asInt();
    digitalWrite(PUMP,pump);
}
void setup() {
  Serial.begin(9600);
  delay(10);
  EspSerial.begin(9600);
  delay(10);
  lightMeter.begin();
  pinMode(PUMP, OUTPUT);
  pinMode(BUTTON, INPUT);
  digitalWrite(PUMP, pump);
  Blynk.begin(auth, wifi, ssid, pass);
  timer.setInterval(5000L, sendData);
  //timer.setInterval(5L, checkButton);
//  timer.setInterval(2000L, checkConnection);
  }

void loop() {
  if (Blynk.connected()) {
      Blynk.run();
      timer.run();
    }
}

and the Blynk log:
[2631095] <[06|05|14|00|00]
[2631389] >[00|05|14|00|C8]
[2632112] <[14|05|15|00|08]vw[00]0[00]632
[2632280] <[14|05|16|00|07]vw[00]1[00]28
[2637109] <[14|05|17|00|08]vw[00]0[00]630
[2637214] <[14|05|18|00|07]vw[00]1[00]28
[2641393] <[06|05|19|00|00]
[2651445] Cmd error
[2656470] Cmd skipped:20
[2656471] Cmd skipped:20

[EDIT] and the circuit:

Your question does not have any schematic or other details regarding the hardware.  Optical relay?  Mechanical relay?  If mechanical did you use a fly-back diode? Or mechanics.  Were you testing the motor under load? (For example with water in the pump?)  Or did you try it with no load?  (For example, dry?)  Are the power supplies floating?  Did you share a common ground?

@st2000 Hi, thanks for your response. I added the circuit to my post. I'm using this 1 channel relay from ebay. The motor was tested under load. I'm sharing a common ground. Neither of the power supplies is connected to the ground pin in the power socket (so they're both floating, I guess).

Separate your grounds.  The relay provides isolation.  The optical coupler even more.  I see you may be driving the EPS8266 with a 5 volt signal.  Yet it is power from a 3.3 volt source.  This is not a good arrangement.  Unless the EPS8266 has over voltage protection on its input, this could lead to unexpected results.  The relay in your schematic is very confusing.  I am hoping that it actually is something very different from the symbol.

Separating the grounds really did the thing - thanks a lot! I just don't understand why? And is there any way I could power both the electronics and the water pump from only one power supply?
@st2000 As I mentioned in my question, I'm using this board with the ESP8266. Regarding the relay - I used the symbol I found in Fritzing. Link to the relay I'm actually using is mentioned in my previous comment.

Not absolutely sure w/o testing why separating the grounds works.  However, it is likely you are still (and this still might the the root cause of your problems) driving a 3 volt powered ESP8266 with a 5 volt serial port signal.  This is not good.  You might, at the very least, look into a resistor divider circuit to reduce the serial port voltage down to 3 volts.

The problem was hidden in a wrong relay wiring. Once I'm using only COM and NO PIN as it is showed in this article, not only that the whole system is stable and the ESP8266 is not disconnecting any more, but I can also power the circuit using only one 5V 2A power supply.
Here's my updated schematics


text:
Multiple SPI device
I want to connect Ethernet board (W5100 HR911105A) to Arduino Leonardo with SPI and I also want to connect SD reader.
When I test these boards separately everything working. But when I connect them  on the same board the program fails at Ethernet.begin();
#include <SPI.h>
#include <Ethernet.h>
#include <SD.h>

#define SS_SD_CARD  4
#define SS_ETHERNET 10

const char CONFIG_FILE[] = "system.cfg";

byte C_MAC[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
IPAddress S_IP(192,168,0,19);
IPAddress C_IP(192, 168, 0, 177);
const uint16_t  S_PORT = 8090;

EthernetClient client;

void setup() {
  Serial.begin(9600);
    while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }
    pinMode(SS_SD_CARD, OUTPUT);
    pinMode(SS_ETHERNET, OUTPUT);

    digitalWrite(SS_SD_CARD, HIGH);
    digitalWrite(SS_ETHERNET, HIGH);

    digitalWrite(SS_SD_CARD, LOW);
    SD.begin(SS_SD_CARD);
    digitalWrite(SS_SD_CARD, HIGH);

    Serial.println("Setup ethernet");
    digitalWrite(SS_ETHERNET, LOW);
    if (Ethernet.begin(C_MAC) == 0) {
      Serial.println("Failed to configure Ethernet using DHCP");
      Ethernet.begin(C_MAC, C_IP);
    }
    delay(100);
    Serial.println("connectin...");
    bool result = client.connect(S_IP, S_PORT);
    Serial.println("connected");
    digitalWrite(SS_ETHERNET, HIGH);
}

void loop() {
  Serial.println("loop...");
  delay(1000);
}

I tried on Leonardo and Mega 2560.

So are you saying that if you have only the W5100 connected to the Leonardo it works fine but once you connect the SD reader it doesn't work? Also, it's SPI, not ISP. ISP stands for In-System Programmer, which is something completely different.

Yes this is what I am saying. When I connect both device to SPI only the card reader working and read data from the card, and the ethernet fail at the mentioned point. But if I only connect the ethernet it is working.

When you test individually as you describe, are the SS pin numbers the same (4 and 10)?

What SD reader are you using? Can you describe the exact wiring?

Some card reaaders (as well as display boards with built-in sd socket) use 10-kOhm resistors in series to the CS, DIN and CLK lines, to perform a cheap 5V to 3.3V level translation. This is really not the best solution, especially in terms of speed (we verified that typically this limits the maximum SPI speed to about 1 MHz).
Other cards readers (such as this one http://modtronix.com/mod-sdcard-l5.html), just use 10 k-Ohm resistors as pull-up to 3.3V. Therefore you're connecting all the SD card lines to the Leonardo board, which is 5V level.
This will cause serious issues to the SD card or to the leonardo board. If your card reader falls in this second case, I suggest you to insert a resistor divider (1k + 1.5k) in series to each input lines of the SD card: DIN, CLK, CS.
In the following schematics I just show for the CLK line, of course you have to repeat this three times. A much better idea would be a level translator IC.

simulate this circuit – Schematic created using CircuitLab

If you have a similar SD card reader like below (or same but with micro SD card), than I had exactly the same problem.
It works as single device on SPI, but not together with another SPI device.
You can either use a SD recorder proto board, or use a microcontroller that has multiple SPIs.

An example of the SD recorder I used and works with another SPI device on one SPI port.
Cons: bigger, more expensive
Pro: has a RTC and proto space.

Yes, I have similar card reader as you showed. I hope there is a solution for this problem. http://www.ebay.com/itm/SPI-Reader-Micro-SD-Memory-Card-TF-Memory-Card-Shield-Module-for-Arduino-AD-/112173309871?hash=item1a1e0cdfaf:g:1-EAAOSwJ7RYT2jV

I used until recently the SD recorder shield, but I'm moving to STM32 which has multiple SPI ports, so I can cannot probably (no tried) a simple SD card reader as you have to one port, and other peripherals (like a RF radio) to another SPI.

@MichelKeijzers - I've never used an SPI device (always been an I2C child) but I thought the idea was you used the CS lead to control what gets the message.  From what you have said I assume there is more to it than that.

@CodeGorilla you are right, the CS (Chip Select, or SS: Slave Select) decides who gets the message. Normally one of the CS pins is low and the others are high. The SPI device with CS low pin can communicate with the master. All MISOs and MOSIs have to be coupled, and some devices (like the cheap SD card reader) does not support it ... I don't know the reason.

i suspect the reason is due to how the inputs/outputs are designed, the W5100 appears to be a 3v3 board with 5V compatible inputs, as does the link you posted to the SD reader, however depending on how these inputs/outputs are designed can mean they won't "play nice" with other boards on the same bus even though SPI is designed to do that.
depending on where the problem lies there are a few potential solutions, if (as i suspect) the problem is the output from the devices back to the arduino (ie you can write to them but not read from them) which you could confirm by connecting all lines in parallel, but only connecting one of the serial lines back to the arduino and check that it works, then swap the serial to the other device and check that. assuming that both devices work in this configuration you only need to fix the return signal. the simplest way of doing this would be to use two tri state buffers.
so the return signal is only connected to the arduino when that devices select line is active. and high impedance (disconnected) otherwise, programatically disconnecting one device from the bus.


text:
Power Measurement
I am trying to develop a system that reads the amount of power consumption from my load. Here is how my setup looks like;

The led represents a 5W and 12V light bulb(I was unable to get this in my simulator) and the battery i am using is 9 volts
Here is my code;
 sens = analogRead(A0);
 vol = sens * (2.0) * ( 5.0 / 1024.0);
 tot_vol = 5 - vol;
 current = vol / 10;
 power = current * tot_vol;
 Serial.print(power);
 Serial.print ("\n");
 delay(1000);
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
state = Serial.read(); // Reads the data from the serial port
}
if (state == '0') {
 digitalWrite(ledPin, LOW); // Turn LED OFF
 state = 0;
}
else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 state = 0;
 }
}

I am trying to calculate the voltage drop across my resistor and then get the current and then power from that. This data is sent to an android app via the bluetooth module. However, here is the output i am getting;

What am i doing wrong?

Question: why are you powering a 12V bulb with a 9V battery?

A number of things wrong:

You have no ground connection to the Arduino. It can't work out what the voltage you are measuring is relative to.  (Read this)
You should have the shunt resistor as the absolute last item in your chain of components so it is connected directly to ground (V+ -> LED -> LED's Resistor -> Relay -> Shunt Resistor -> GND
Your shunt resistor should be as low as you can get away with - low enough that it doesn't affect the circuit, yet high enough that you can measure a voltage drop. For that you need to first have a good idea about what level of current you will be measuring.

simulate this circuit – Schematic created using CircuitLab

Hi, i have updated the question with 2 images that represent my current situation(after following your instructions). I am getting roughly 0.48 watts per second for a 5w and 12v light bulb. Kindly advice if the power readings i am getting are accurate.

Your analog input is connected to the wrong side of the relay.

Where should the analog input be connected?

To the high side of the resistor.  I will draw a circuit.

Normally the shunt resistor (in you schema 220 ohm) is way lower than the load it should measure, 12volt/5Watt = 0.42 Amp and R = U/I, 9V/0,42A = 21ohm. So your 220ohm's shunt is inflicting on the measurement value.
So to change the current measurement circuit you have to use a low ohm resistor and since the voltage drop over a shunt/low ohm resistor is small you need a amplifier.
Here is a page about how to calculate a shunt and use it with Arduino:
http://www.vwlowen.co.uk/arduino/current/current.htm
If we use a simplified version, 8v over the lamp and 1volt over the shunt.
U = I x R
Rlamp = 21 ohm
Ilamp = 8 volt/21 ohm
Rshunt = U/I = 1 volt/0.42 Amp

Thank you. Even if i change the resistor to 10 ohms, the output does not really change

Yes, you need to be below the resistant of the light bulb (0,42 ohm). I will modify my answer with the formula.


text:
DHT11 returning incorrect values
I am trying to use DHT11 sensor with Arduino. But unfortunately it is returning following values:
Temperature = 1.00
Humidity = 2.00
My code is as follows:
#include <dht.h>
dht DHT;
#define DHT11_PIN 7

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

void loop()
{
    int chk = DHT.read11(DHT11_PIN);
    Serial.print("Temperature = ");
    Serial.println(DHT.temperature);
    Serial.print("Humidity = ");
    Serial.println(DHT.humidity);
    delay(1000);
}

Link to the library I am using is here
I have connected +ve to 3.3 V
I have connected -ve to Ground
I have connected out to digital pin # 7

Current temperature of the room otherwise is 34 degree celsius and 62% Humidity

This is not a DHT11, DHT11 is blue, DHT21 is black, and DHT 22 is white.
It must be a DHT22 hence the wrong values.
EDIT : on your pictures the white case says AM2302, it's definitely a DHT22 the code must be adapted accordingly.

I had the reverse problem: I used a DHT11 (blue one) instead of a dht22 (white one). The value I got were in the 500`C for the temperature and the 1500% for humidity. Replacing the DHT11 by the DHT22 solve it.


text:
Unable to send IR command
I am trying to switch the TV on using Arduino. Following is my set of code
#include <IRremote.h>

IRrecv receiver(2);
IRsend sender;
decode_results results;

long repeatitions;
long count;
unsigned int durations[100];
void (*reset)(void) = 0;

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

void loop() {
  if (Serial.available()) {
    repeatitions = Serial.parseInt();
    count = Serial.parseInt();
    for (int i =0; i < repeatitions; i++) {
      durations[i] = Serial.parseInt();
    }
    for (int i = 0; i < repeatitions; i++) {
      Serial.println("sending code");
      sender.sendRaw(durations, count, 40);
      delay(50);
    }
    reset();
  }
  if (receiver.decode(&results)) {
    Serial.println(results.value, HEX);
    Serial.print(results.rawlen - 1);
    for (int i =1; i <results.rawlen;i++) {
      unsigned int number = results.rawbuf[i] * USECPERTICK;
      Serial.print(",");
      Serial.print(number);
    }
    Serial.println("");
    receiver.resume();
  }
}

The code receiving part works fine. And it returned me following code:
A90
25,2400,600,1200,600,600,550,1200,600,600,600,1200,600,600,600,550,600,1200,600,600,600,600,550,650,600,600

But when I try to use the same code to switch the TV on after adding durations to the above returned code it doesn't work. I am entering following into the serial monitor
3,25,2400,600,1200,600,600,550,1200,600,600,600,1200,600,600,600,550,600,1200,600,600,600,600,550,650,600,600

I have attached a screenshot to show how I have installed the IR Transmitter LED.

I have two IR Transmitters. I have tried installing both in same manner 1 by 1. But unfortunately no success.
I am using IRRemote library by Shirriff https://github.com/z3t0/Arduino-IRremote

Where's your resistor?

This seems unlikely to work for many reasons.  Presumably you are following some guide but have gone somewhat astray, you need to include a link to that and the exact IR library you are using in the question.  In addition to the LED electrical issues (generally a transistor and series resistor are needed), pin 12 doesn't seem to be a usual output for IR sending on an ATmega328p - rather, it is usually pin 3 or 9.

I thought when using IR LED bulb the resistor wasn't required so I didn't include that in the circuit. Can you kindly share some circuit diagram that I should use in order to make the circuit work? Thanks

This would be in the instructions for whatever library you are using - I'd point out again that you have failed to identify which one you are using.

I have already mentioned the name of the library in the original question as you suggested. I am using IRRemote library by Shirriff https://github.com/z3t0/Arduino-IRremote

is the LED actually lighting up? use your smartphone camera to see IR light


text:
Motor on transistor causes arduino to reset
I have a motor hooked up to the emitter of a NTE24 transistor and ground, the collector is hooked up to 3.7V, and the base is connected through a 10ohm resistor to a PWM pin on an arduino mega, which is powered by 3.7V through Vin. I use analogwrite on the pin to control the motor speed.
When i turn it on, the arduino just resets. I think it’s because the base is drawing too much current from the arduino pwm pin, but if I replace the 10ohm resistor with 330ohms, it is far too slow. Any ideas? I have tried a TIP3C transistor as well to no avail.
Edit: I suppose my question now is I’m losing too much power in the transistor. Would a mosfet help with that? In addition, what’s a good small board that uses 3.3V that also has some sort of usb connection?
Edit 2: Read latest comment, tried MOSFET and fly back diode, now it just clicks and restarts :/

The NTE24 is an NPN transistor, so the emitter needs to go to ground and the collector to the load.  You could also be causing your lipo to sag too much.  I wasn't aware that there was any Arduion Mega specified for 3.3v operation, but even if there is the cell may sag under load to below a 3.3v regulator's input requirement, so it's often better to use a 2.8v or 3.0v regulator for such an application to provide more headroom.  And today people would use an NFET rather than a bipolar transistor.

@ChrisStratton the configuration he is using is the common collector one; it is perfectly valid in the analog domain, but I think that the OP should switch to the common emitter version like you suggest; the PWM wave will then power correctly the motor. As for the base resistor, 150-200 ohms is the minimum value the OP should put (otherwise the uC will fry its output). As for the arduino-mega at 3.7V, you are right; it is out of spec. At those voltages better use a 3.3V board (usually arduino micro can come in 3.3V variants, or other ones like the STM32 based ones)

@ChrisStratton I switched to common emitter, and I tried putting two 330ohms in parallel to drop resistance to around 165ohms, but the arduino starts resetting again, 330 is about as low as I can get. When I plug both ends of the motor straight into the power source it goes much faster than through the transistor. Should I try Mosfets? I know 3.7V isn’t good for the mega, so I’ve been trying to look for 3.3V arduino boards, but I can’t find one that have a usb B or A Port, which is really helpful. Any suggestions?

Did you remember the flyback diode?

@IgnacioVazquez-Abrams Where would I put that? Wouldn’t that only help with protecting the transistor? That doesn’t seem to be the problem, it seems like something with the transistor dissipating too much power at 330ohms, and drawing too much base current from the pwm pin with less ohms

You need to add more facts like, motor data, battery data. As the question is now it could be a  number of reasons. And regarding flyback diode, read this: https://en.wikipedia.org/wiki/Flyback_diode

Why you shouldn't do it, chances are that shorting an ATmega output pin to ground will not cause the process or reboot, so "drawing too much current from the PWM pin" is probably not the issue.  You do need the diode, unless you are using a MOSFET of the sort which implicitly contains one.

Try measuring the battery voltage with an oscilloscope... I think that you will see it going pretty low until the board resets when you start driving the motor....

@ChrisStratton I added a fly back diode, and I switched to 30N06L MOSFET, with 330 ohms between gate and pin with a 10k pull down resistor to ground, source to ground, and 3.3V to motor to drain. The moment it turns on the motor clicks and the arduino resets :(

As I've been saying all along, a lithium battery under load may well drop below the regulator's input voltage requirement.  It could also trigger the ATmega brownout detector.