title: Datalogger with interruputs

text:
# Question
Title: Datalogger with interruputs
I'm trying to do a data logger. Writes into SD card has to stop when `millis()`=1000. Maybe I have a problem between `millis()` and my interrupt, because datalogger doesn't stop after `millis()`=1000. I'm working with Arduino Mega.

```
#include <SPI.h>
#include <SD.h>
volatile unsigned int cuenta = 0;
unsigned char contador = 0x00;
const int chipSelect = 53;
long currentMillis = 0;
long previousMillis = 0;
long interval = 1000;

void setup() {
  DDRA = B11111111;
  cli();//stop interrupts
  TCCR0A = 0;// set entire TCCR2A register to 0
  TCCR0B = 0;// same for TCCR2B
  TCNT0  = 0;//initialize counter value to 0
  // set compare match register for 10000khz increments
  OCR0A = 25;// = (16*10^6) / (1000*64) - 1 (must be <256)
  // turn on CTC mode
  TCCR0A |= (1 << WGM01);
  // Set CS01 and CS00 bits for 64 prescaler
  TCCR0B |= (1 << CS01) | (1 << CS00);
  // enable timer compare interrupt
  TIMSK0 |= (1 << OCIE0A);
  sei();//allow interrupts
  //periodo de cada pulso 255ms del tren total de pulsos aproximadamnte 255ms
  Serial.begin(9600);
  while (!Serial) {
    ;
  }
  Serial.print("Initializing SD card...");
  if (!SD.begin(chipSelect)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  Serial.println("card initialized.");
}

ISR(TIMER0_COMPA_vect) {
  cuenta++;
  if (cuenta > 9) {
    PORTA = ++contador;
    cuenta = 0;
  } else {
    PORTA = 0X00;
  }
}

void loop() {
  currentMillis = millis();
  if (currentMillis - previousMillis <= interval)
  {
    String dataString = "";
    for (int analogPin = 0; analogPin < 1; analogPin++) {
      int sensor = analogRead(analogPin);
      dataString = String(sensor);

      if (analogPin = 1) {
        dataString += ",";
      }
    }
    File dataFile = SD.open("datalog2.txt", FILE_WRITE);
    if (dataFile) {
      dataFile.println(dataString);
      dataFile.close();
      // print to the serial port too:
      Serial.println(dataString);
    }
    else {
      Serial.println("error opening datalog.txt");
    }
  }
}

```

# Answer
> 2 votes
The `millis()` function is based on a counter which is incremented by the Timer 0 overflow interrupt. Since you reconfigured that timer to never overflow, that counter is not incremented anymore.

If you want to configure an Arduino timer for your own purposes, you have to either:

* use *any* timer other than Timer 0, or
* loose the Arduino standard timekeeping functions: `millis()`, `micros()` and `delay()`.

I would favor the first option, especially on the Mega which has quite a few spare timers.

---
Tags: sd
---


title: NodeMCU capable of key injection?

text:
# Question
Title: NodeMCU capable of key injection?
Short version: Is the NodeMCU capable of key injection in the same way that an Arduino Teensy can be programmed with Duckuino script to function as a HID?

Long version: Recently, my 7+ year old iMac suddenly stopped working and now I am unable to boot into the Mac which is a right pain. Even more of a pain is that due to the fact that the iMac has a wireless keyboard as opposed to a USB meaning that I am unable to boot into Single User mode, recovery mode, safe boot etc. This is a pain as I am currently stuck with an iMac in an unsuccessful boot loop. I understand that the best option would be to buy a USB keyboard and use this separately; however, it turns out that one of my friends has a spare NodeMCU and said he's willing to lend it to me as he is pretty sure that the Duckuino script will work on it meaning that I could use the NodeMCU as a sort of impromptu keyboard to hold down the shift key on boot, effectively removing the need for me to buy and wait for a new USB keyboard.

I had found this video here on YouTube which explains the process of turning an Arduino into a "USB Rubber Ducky" but there is no mention of this working with a NodeMCU. Assuming that I have the ESP8266 addon for the Arduino IDE and was able to put the Duckuino script onto the NodeMCU, would the NodeMCU function as intended with the Duckuino script or is the NodeMCU hardware such that this would be impossible?

Thank you for any assistance,

Kind regards, John

P.s. This is what my NodeMCU looks like:

# Answer
> 2 votes
No, you can't use a NodeMCU for this.

To emulate a USB keyboard you have to have a device with a main MCU on it which is directly connected to USB. The ESP8266 on the NodeMCU is not a USB-capable MCU, and so it uses a USB to UART bridge chip to connect the ESP8266 to the USB of your computer.

You can't program that bridge chip, so you can't make it anything other than a serial port.

Common devices that are directly USB connected and can emulate a keyboard include:

* Arduino Micro
* Teensy 3.X
* Fubarino Mini / SD
* Arduino Leonardo
* chipKIT Lenny

And there are many more.

For 8-bit Arduino boards you need to look at the MCU it uses. If it's an ATMega32U4 as the main MCU then you can program it to be a keyboard.

---

Addendum: There are ways of making non-USB boards work as a keyboard. For ATMega328P based Arduinos and similar that use an ATMega16U2 chip as the USB to UART bridge, that bridge chip can be reprogrammed to appear as a keyboard. For other MCUs there may be software "bit-banged" USB implementations available (such as V-USB), though YMMV with those implementations, and they require building extra hardware to interface the chip to the USB port.

---
Tags: esp8266, arduino-ide, nodemcu, keyboard
---


title: Serial.begin(9600); in Arduino

text:
# Question
Title: Serial.begin(9600); in Arduino
I want to know what Serial.begin(9600); does and if it is necessary to write it in the code.

# Answer
> 2 votes
It enables the UART port and sets it to 9600 baud. Without it you can't use `Serial.print` etc.

---
Tags: arduino-uno
---


# Question
Title: Suddently, "avrdude: Device signature = 0x000000" with ArduinoISP. Is my chip dead?
I have some boards with the atmega32u4 that they were working perfectly before. I'm using an unnoficial UNO board to program them via ICSP. To power the uC I'm using two lithium batteries and a step-down converter to drop it to 5 V.

This started happening when I tried to upload code via ISCP when the target chip was not powered by mistake.

This is my error message:

```
Arduino: 1.8.5 (Windows 10), Placa:"Arduino Leonardo"

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

     Using Port                    : COM4
     Using Programmer              : stk500v1
     Overriding Baud Rate          : 19200
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     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  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 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 : STK500
     Description     : Atmel STK500 Version 1.x firmware
     Hardware Version: 2
     Firmware Version: 1.18
     Topcard         : Unknown
     Vtarget         : 0.0 V
     Varef           : 0.0 V
     Oscillator      : Off
     SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

```

What I've already tried:

* Different programmer (another Uno board);
* Uploading to a proper Leonardo board via ICSP, it worked;
* Uploading to another of my boards via ICSP, it worked;
* Running with the portable Arduino version;
* Check if the chip is being powered with 5 V;
* Changed wires and checked the connections;
* The chip does not get hot;

I've been around this two days straight, any help would be much appreciated.

# Answer
Mostly this error is due to connections/powering issues (as already mentioned in your output ).

* Check connections, especially power and ground also check the resistance between Vcc and GND of your target MCU. (If it's less than 100ohm that means something is off in your circuitry or your MCU is already fried.)
* Check if your MCU is actually getting enough power (voltage and current) also check if it's getting excess voltage.
* Make sure there is proper "common grounding" done between devices.
* If you are sure that the above points are checked and you still get the error try the override flag `-F` (avrdude through shell/command-line) and if you are still not able to upload try the manually changing the address (not recommended ) in your arduino's library so that it matches with the signature it's receiving.
* Finally try using a direct USB interface with atmega32u4 as atmega32u4 supports it and upload the bootloader again through an old software called **Flip** after that try again.

After all this if you are not able to upload then probably your MCU is dead and it might be due to an unnoticed wrong power connection or short circuit or unintentional fuse reconfiguration (highly unlikely).
> 3 votes

---
Tags: atmega32u4, icsp, arduinoisp
---


# Question
Title: Correct way of having loop end when required?
I'm brand new to Arduinos. I'm currently trying to modify a script from here which at the moment, simply turns an LED on or off depending on which HTTP GET request it receives. However, I want to modify this to have the LED modulate on/off when presented with the On HTTP GET request and then simply turn off all together when presented with the Off HTTP GET request. However, I have two conflicting methods that I have found about how to achieve this; the first is:

```
int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      do
      {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      } while (value = HIGH);
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

```

Wheareas the other is:

```
  int value = LOW;
    if (request.indexOf("/LED=ON") != -1)  {
      value = HIGH;
      void loop() {
      digitalWrite(ledPin, HIGH);
      delay(3000);
      digitalWrite(ledPin, LOW);
      delay(5000);
      value = HIGH;
      }
    }
    if (request.indexOf("/LED=OFF") != -1)  {
      digitalWrite(ledPin, LOW);
      value = LOW;
    }

```

As you can see, the first uses do...while and the second uses loop(). I have a feeling that the first of the two scripts would be more suitable as it should cut out as soon as `value` is set to `LOW` (i.e. when requested to turn off)

However, I would really appreciate it if someone could look through the two scripts and tell me which of the two is the correct way to achieve this sort of cut off when the HTTP GET Off is requested (if either for them even is the correct way to do this!).

Thank you in advance for your help,

Kind regards, Tom

# Answer
> 3 votes
As pointed out by Ignacio Vazquez-Abrams and jsotola, you need to use a state machine, like the one from the Blink Without Delay Arduino tutorial. Yours would be slightly more complicated because you need a way to turn it on and off, and because you use different on and off periods. Here is an example code that abstract the blinking logic into three functions:

* `update_led()` takes care of the blinking, and it has to be called quite often in order to achieve a smooth blinking
* `start_blinking()` and `stop_blinking()`, as their names suggest, are used to turn the blinking state machine on and off.

```
const uint32_t ON_TIME  = 3000;
const uint32_t OFF_TIME = 5000;

bool led_blinking;     // are we blinking the LED?
bool led_on;           // is the LED currently on?
uint32_t last_toggle;  // last time it toggled while blinking

void update_led() {
    if (!led_blinking) return;
    uint32_t now = millis();
    if (led_on && now - last_toggle >= ON_TIME) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now;
    }
    if (!led_on && now - last_toggle >= OFF_TIME) {
        digitalWrite(ledPin, HIGH);
        led_on = true;
        last_toggle = now;
    }
}

void start_blinking() {
    digitalWrite(ledPin, HIGH);
    led_blinking = true;
    led_on = true;
    last_toggle = millis();
}

void stop_blinking() {
    digitalWrite(ledPin, LOW);
    led_blinking = false;
    led_on = false;
}

```

You then have to call these functions from `loop()` as follows:

```
void loop() {
    // Keep the LED blinking if necessary.
    update_led();
    ...
    if (request.indexOf("/LED=ON") != -1)  {
        start_blinking();
    }
    if (request.indexOf("/LED=OFF") != -1)  {
        stop_blinking();
    }
    ...
}

```

---

**Edit**, in response to jsotola’s comments:

When answering the question, I was initially tempted to make a `BlinkingLed` class, with the functions as its public interface and the variables private. I resisted the temptation on the grounds that, given the apparent OP’s level of C++ knowledge, that could end up being well over his head. Instead, I used documentation as an informal way of separating the public from the private: you are only supposed to use what is documented, i.e. the functions. You don't “take a shortcut in your program and clear `led_blinking` directly”.

You could, of course, make the `led_blinking` variable part of the public interface. That could even be a nice simplification, as you don't need the start/stop function anymore. But then you loose control over the initial phase of the blinking pattern. That may not be an issue, but if you want the LED to turn on as soon as you set `led_blinking` to `true`, then you have to do something like

```
void update_led() {
    uint32_t now = millis();
    if (!led_blinking) {
        digitalWrite(ledPin, LOW);
        led_on = false;
        last_toggle = now - OFF_TIME;  // fix initial phase
        return;
    }
    ...
}

```

Note that the subtraction can overflow, but that's not as issue because it follows the rules of modular arithmetics.

I actually kind of like this option, with all the logic in a single function. This way the variables `led_on` and `last_toggle` can be made static local to the function, which provides true encapsulation without a class. However, from a pedagogic point of view, I think my initial proposal is easier to understand.

---
Tags: arduino-ide, nodemcu, http, loop
---


# Question
Title: Arduino and AVR Serial Communication over USB
I have a Arduino Uno Rev3 and I would like to use a AVR development toolchain to write a program that performs serial communication over USB.

Doing this using the Arduino IDE is fairly simple:

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

void loop() {
   int i;
   while(1) {
      Serial.write("hello\n");
      delay(5000);
   }
}

```

Then from Linux, I can simply read from `/dev/ttyACM0` and every 5 seconds I get "hello\n".

I found a blog post titled Simple Serial Communications With AVR libc that explains how to perform serial communication using an AVR development toolchain. The simplified version of the above Arduino sketch is below.

```
#ifndef F_CPU
#define F_CPU 8000000UL
#endif

#ifndef BAUD
#define BAUD 9600
#endif

#include <stdio.h>
#include <avr/io.h>
#include <util/delay.h>
#include <util/setbaud.h>

void uart_init() {
    // Upper and lower bytes of the calculated prescaler value for baud.
    UBRR0H = UBRRH_VALUE;
    UBRR0L = UBRRL_VALUE;

    // Configure data frame size to 8-bits.
    UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);

    // Configure to enable transmitter.
    UCSR0B = _BV(TXEN0);
}

void uart_putchar(char c) {
    // Wait until the register to write to is free.
    loop_until_bit_is_set(UCSR0A, UDRE0);

    // Write the byte to the register.
    UDR0 = c;
}

void uart_putstr(char *data) {
    // Loop until end of string writing char by char.
    while(*data){
      uart_putchar(*data++);
    }
}

int main() {
    uart_init();

    while(1) {
        uart_putstr("hello\n");
        _delay_ms(5000);
    }

    return 0;
}

```

The problem is, this doesn't actually work. I can build and flash the ATmega328p but reads to `/dev/ttyACM0` block forever. I suspect what is happening is that the serial communication is occurring on some pins and not over USB, but I am not sure.

Anyone have any idea on how I can emulate `Serial.write` using an AVR development toolchain and have the output be written over USB?

# Answer
> 1 votes
Turns out the problem was with my `Makefile`. `avr-gcc` was missing the `-mmcu=atmega328p` flag. Once I added that and changed `F_CPU` to `16000000UL` everything works.

---
Tags: arduino-uno, serial, usb, atmega328, avr
---


# Question
Title: How do I inherit a class that requires &foo() in its constructor?
# General

I have a library with a class constructor `class Math(&foo1,&foo2);`, which I would like to put into a library for `class Algebra()`, where `foo1` and `foo2` are defined in `Algebra.cpp`

My current constructor `Algebra::Algebra():Math(&Algebra::foo1,&Algebra::foo2)` is returning an error in the Arduino IDE to the effect of:

`error: no matching function for call to 'Math::Math(void (Algebra::*)(long unsigned int, byte), byte (Algebra::*)(long unsigned int))':Math(&Algebra::foo1, &Algebra::foo2)`

*Meta Note: I believe this is on topic because I'm dealing specifically with developing code for the Arduino Mega using libraries and hardware components designed for Arduino. If I am in error, and there is a better exchange for this question please let me know*

---

# Specifically,

I'm writing a library to combine Adafruit's I2C FRAM with the Extended database library (I have validated that the libraries work when called into a sketch independently, but I'd like to combine them to be more easily inheritable in \[*Big\_Machine\_api.h*\] that I will be making later) I'm testing my library with this sketch:

```
/*
 EDB_AT24C1024.pde
 Extended Database Library + Adafruit_FRAM_I2C EEPROM Test Sketch

 The Extended Database library project page is here:
 http://www.arduino.cc/playground/Code/ExtendedDatabaseLibrary

 The Adafruit_FRAM_I2C library project page is here:
 https://github.com/adafruit/Adafruit_FRAM_I2C

 */
#include "Arduino.h"
#include <Wire.h>
#include <Adafruit_FRAM_I2C_EDB.h>
#define TABLE_SIZE 131072

// Arbitrary record definition for this table.
// This should be modified to reflect your record needs.
struct LogEvent {
  int id;
  unsigned long Rotations;
}
logEvent;

// Create an EDB object with the appropriate write and read handlers
Adafruit_FRAM_I2C_EDB db;

// Run the demo
void setup() {
  Serial.begin(115200);
  Serial.println("DONE");
}

void loop() {
}

```

My ADAFRUIT\_FRAM\_I2C\_EDB.h file:

```
#ifndef ADAFRUIT_FRAM_I2C_EDB_h
#define ADAFRUIT_FRAM_I2C_EDB_h

#include <Arduino.h>
#include <Adafruit_FRAM_I2C.h>
#include <EDB.h>

#define MB85RC_DEFAULT_ADDRESS        (0x50) /* 1010 + A2 + A1 + A0 = 0x50 default */

class Adafruit_FRAM_I2C_EDB : public EDB {
 public:
  Adafruit_FRAM_I2C_EDB(uint8_t addr = MB85RC_DEFAULT_ADDRESS);
  void getDeviceID(uint16_t *manufacturerID, uint16_t *productID);

 private:
  Adafruit_FRAM_I2C _fram;
  uint8_t _FRAMaddr;
  void writer(unsigned long address, byte data);
  byte reader(unsigned long address);

};
#endif

```

My ADAFRUIT\_FRAM\_I2C\_EDB.cpp file:

```
#include "Arduino.h"
#include "Adafruit_FRAM_I2C.h"
#include "EDB.h"
#include "Adafruit_FRAM_I2C_EDB.h"
Adafruit_FRAM_I2C_EDB::Adafruit_FRAM_I2C_EDB(uint8_t addr)
:_FRAMaddr(addr),EDB(&Adafruit_FRAM_I2C_EDB::writer, &Adafruit_FRAM_I2C_EDB::reader) {
  _fram = Adafruit_FRAM_I2C();
  _fram.begin(_FRAMaddr);
}

void Adafruit_FRAM_I2C_EDB::getDeviceID(uint16_t *manufacturerID, uint16_t *productID) {
  _fram.getDeviceID(manufacturerID, productID);
}

void Adafruit_FRAM_I2C_EDB::writer(unsigned long address, byte data) {
  _fram.write8(address, data);
}

byte Adafruit_FRAM_I2C_EDB::reader(unsigned long address) {
  return _fram.read8(address);
}

```

Full Error List:

```
C:[...]\Arduino\libraries\Adafruit_FRAM_I2C_EDB\Adafruit_FRAM_I2C_EDB.cpp:16:84: note: candidates are:

In file included from C:[...]\Arduino\libraries\Adafruit_FRAM_I2C_EDB\Adafruit_FRAM_I2C_EDB.cpp:3:0:

C:[...]\Arduino\libraries\EDB-master/EDB.h:54:5: note: EDB::EDB(void (*)(long unsigned int, uint8_t), uint8_t (*)(long unsigned int))

     EDB(EDB_Write_Handler *, EDB_Read_Handler *);

     ^

C:[...]\Arduino\libraries\EDB-master/EDB.h:54:5: note:   no known conversion for argument 1 from 'void (Adafruit_FRAM_I2C_EDB::*)(long unsigned int, byte) {aka void (Adafruit_FRAM_I2C_EDB::*)(long unsigned int, unsigned char)}' to 'void (*)(long unsigned int, uint8_t) {aka void (*)(long unsigned int, unsigned char)}'

C:[...]\Arduino\libraries\EDB-master/EDB.h:50:7: note: constexpr EDB::EDB(const EDB&)

 class EDB {

       ^

C:[...]Arduino\libraries\EDB-master/EDB.h:50:7: note:   candidate expects 1 argument, 2 provided

C:[...]Arduino\libraries\EDB-master/EDB.h:50:7: note: constexpr EDB::EDB(EDB&&)

C:[...]\Arduino\libraries\EDB-master/EDB.h:50:7: note:   candidate expects 1 argument, 2 provided

exit status 1
Error compiling for board Arduino/Genuino Mega or Mega 2560.

```

# Answer
> 3 votes
You just pass the variables to the parent constructor in the initialization list of the child. No need for qualifications or anything like that.

Here's an example that compiles:

```
class Math {
    private:
        int _foo1;
        int _foo2;

    public:
        Math(int &foo1, int &foo2) : _foo1(foo1), _foo2(foo2) {}
};

class Algebra : public Math {
    private:
        int myFoo1 = 12;
        int myFoo2 = 34;

    public:
        Algebra() : Math(myFoo1, myFoo2) {}
};

```

Math's constructor takes two integers passed by reference. The Algebra constructor's initialization list calls the parent Math constructor with two of its own member integers that are then automatically passed by reference, since that is what the constructor calls for.

However, that isn't what your actual problem is. You're asking about one thing, then showing an error that is for a completely different problem.

You have a constructor (actually any function will do the same) that expects a pair of pointers to two functions:

* `void (*)(long unsigned int, uint8_t)`
* `uint8_t (*)(long unsigned int)`

That is, you need two functions, such as:

```
void reader(unsigned long a, uint8_t b) {
}

```

and

```
uint8_t writer(unsigned long a) {
    return 3;
}

```

But instead you are attempting to pass member functions of a class. The problem here is that although they *look* the same, because they are class members they *aren't* the same.

Any class member function has an additional implied parameter, which is a pointer to the containing class instance and is called `this`. So your functions actually look more like:

```
void reader(Adafruit_FRAM_I2C_EDB *this, unsigned long a, uint8_t b) {
}

```

and

```
uint8_t writer(Adafruit_FRAM_I2C_EDB*this, unsigned long a) {
    return 3;
}

```

(Note: that's only an approximation - it's actually a lot more involved than that, but it serves to illustrate the problem). As you can see that doesn't match what is expected, and so you can't pass those functions to the parent constructor - they're simply wrong.

This is a commonly occuring problem - often seen when trying to use a class member function with `attachInterrupt()`. You just can't do it. Or not like that anyway.

The only way of passing a member function directly is for that member function to be `static`. That then acts like a normal function, and there is no `this` parameter. However, it can only act on other `static` variables and functions. So using it takes a little more care - plus of course `static` functions and variables are shared between all instances of a class.

---
Tags: eeprom
---


# Question
Title: Resistors on LCD - does a small difference matter?
I recently have tried to connect an LCD to my Arduino Uno. The tutorial tells me I need a 220 Ohm resistor, but the only ones I have are 330 Ohm. Does it matter?

Here's the Fritzing diagram by the way:

# Answer
> 4 votes
No, it doesn't matter. That resistor is just for the backlight LEDs. The larger the resistor the dimmer the backlight will be. As @VE7JRO suggests, you can always put two 330Ω resistors in parallel, which will halve the resistance to 165Ω, which will give a brighter backlight.

# Answer
> 0 votes
Nope. The lcd has backlight led which needs to powered separately. More resistance, dimmer it will be. Higher voltage decreases life span of your lcd backlit.

---
Tags: arduino-uno, lcd, resistor
---


title: FIle not being found on sd card

text:
# Question
Title: FIle not being found on sd card
I have some quite long code to copy a file from an SD to the same card, but under a different name. I have one version where the file names are built-in to the sketch, but to make it more portable, i have implemented a serial file selection system. There are 3 phases; choosing the input file, choosing the output file, and the copying. I have included checks to see if the files exist, confirmation for the names and so on. However, in the middle of my code, just before the copying phase, the input file disappears, and the arduino does not find it. It finds it in the first phase, finds the output file, but can't find the input file in the copying phase. SD.exists() and SD.open() both confirm this, but if i remove the sd card and put it into a computer, the file is there.

My code:

```
#include <SoftReset.h>
#include <SPI.h>
#include <SdFat.h>
#define csPin 4
#define roundTo 64

SdFat SD;
File sourceFile;
File outputFile;

int bufSize;
uint32_t lastPos = 0, timeLast, timeNow;
#define BAUD 115200
//make timeBetweenChars the time it takes (in milliseconds) between each char being transferred over serial, and make it at least one
unsigned long timeBetweenChars = max(1000 / (BAUD / 8), 1);

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(BAUD);
  while (!Serial) {
  }
  Serial.print(F("Initializing SD card..."));
  /******************************************************************************/
  // see if the card is present and can be initialized:
  if (!SD.begin(csPin, SPI_FULL_SPEED)) {
    Serial.println(F("Card failed, or not present"));
    soft_restart();
  }
  Serial.println("Card initialized.");

  Serial.println(F("Files on card:"));
  SD.ls();
  //******************************************************************************
  //START OF INPUT FILE NAME
  //******************************************************************************
enterInputFileName:
  Serial.println(F("Enter input file name:"));
  while (!Serial.available()); // wait till serial available
  char inbuf[64];
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  byte pos = 0;
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    inbuf[pos] = Serial.read();
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for input file name
  char inputFileName[pos];
  //copy data from inbuf to inputFileName
  strcpy(inputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmInputFileName:
  Serial.print(F("Select file '"));
  Serial.print(inputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  char confirm = Serial.read();
  bool tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmInputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterInputFileName; break;
    case 'n': goto enterInputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmInputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(inputFileName);
  Serial.println("' as input file");
  if (SD.exists(inputFileName)) {
    Serial.println(F("File exists"));
  }
  else {
    Serial.println(F("Error, file does not exist. Please choose another file"));
    goto enterInputFileName;
  }
  //******************************************************************************
  //END OF INPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF OUTPUT FILE NAME
  //******************************************************************************
enterOutputFileName:
  //clear input buffer
  for (byte w = 0; w < (sizeof(inbuf) / sizeof(inbuf[0])); w++) {
    inbuf[w] = '\0';
  }
  Serial.println(F("Enter output file name:"));
  //wait for some chars to arrive
  while (!Serial.available());
  /******************************************************************************/
  //create variable to store how many valid (not newline or carriage return) chars have been read
  pos = 0;
  //found here Serial.print(SD.exists(inputFileName));
  //read into array as long as not getting newline char
  while (Serial.available() && Serial.peek() != '\n' && Serial.peek() != '\r') {
    //file found on first loop, but not after that
    // found here Serial.println(SD.exists(inputFileName));
    inbuf[pos] = Serial.read();
    //not found here Serial.println(SD.exists(inputFileName));
    pos++;
    //wait so there is time for the next char to arrive in the buffer
    delay(timeBetweenChars);
  }
  //input file not found here
  while (Serial.available() && (Serial.peek() == '\n' || Serial.peek() == '\r')) {
    //remove next char from buffer
    Serial.read();
    //wait in case there is another char to be cleared
    delay(timeBetweenChars);
  }
  //end array at pos
  inbuf[pos] = '\0';
  /******************************************************************************/
  //create new array with correct size for output file name
  char outputFileName[pos];
  //copy data from inbuf to outputFileName
  strcpy(outputFileName, inbuf);
  /******************************************************************************/
  //confirm if you entered the right file name
confirmOutputFileName:
  Serial.print(F("Select file '"));
  Serial.print(outputFileName);
  Serial.println(F("'? Y/N"));

  while (!Serial.available()); // wait till serial available
  confirm = Serial.read();
  tooManyChars = 0;
  // wait for the next chars
  delay(timeBetweenChars);
  while (Serial.available()) {
    //read next char
    char extra = Serial.read();
    //if it isn't a newline or carriage return
    if (extra != '\n' && extra != '\r') {
      //too many characters entered
      tooManyChars = 1;
    }
    //wait for next char
    delay(timeBetweenChars);
  }
  /******************************************************************************/
  if (tooManyChars) {
    Serial.println(F("Enter 1 char"));
    goto confirmOutputFileName;
  }

  //if only 1 char entered
  switch (confirm) {
    case 'Y': break;
    case 'y': break;
    case 'N': goto enterOutputFileName; break;
    case 'n': goto enterOutputFileName; break;
    //invalid char entered
    default: Serial.println(F("Enter Y/N")); goto confirmOutputFileName; break;
  }
  /******************************************************************************/
  Serial.print(F("Using file '"));
  Serial.print(outputFileName);
  Serial.println("' as output file");

  if (SD.exists(outputFileName)) {
    Serial.println(F("File already exists. Overwrite? Y/N"));
confirmOverwrite:
    while (!Serial.available()); // wait till serial available
    confirm = Serial.read();
    tooManyChars = 0;
    // wait for the next chars
    delay(timeBetweenChars);
    while (Serial.available()) {
      //read next char
      char extra = Serial.read();
      //if it isn't a newline or carriage return
      if (extra != '\n' && extra != '\r') {
        //too many characters entered
        tooManyChars = 1;
      }
      //wait for next char
      delay(timeBetweenChars);
    }
    /******************************************************************************/
    if (tooManyChars) {
      Serial.println(F("Enter 1 char"));
      goto confirmOverwrite;
    }

    //if only 1 char entered
    bool overwrite = 0;
    switch (confirm) {
      case 'Y': overwrite = 1; break;
      case 'y': overwrite = 1; break;
      case 'N': goto enterOutputFileName; break;
      case 'n': goto enterOutputFileName; break;
      //invalid char entered
      default: Serial.println(F("Enter Y/N")); goto confirmOverwrite; break;
    }
    if (overwrite) {
      Serial.println(F("Removing output file"));
      SD.remove(outputFileName);
    }
  }
  Serial.println(F("Creating output file"));
  outputFile = SD.open(outputFileName, FILE_WRITE);
  outputFile.close();
  //******************************************************************************
  //END OF OUTPUT FILE NAME
  //******************************************************************************

  //******************************************************************************
  //START OF COPYING
  //******************************************************************************
  //read source and write to output
  sourceFile = SD.open(inputFileName);
  timeLast = micros();
  //debug line
  Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
  if (sourceFile) {
    pinMode(LED_BUILTIN, OUTPUT);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.println(F("Copying"));
    while (sourceFile.available()) {
      //make buffer size 50% of free ram, or amount of bytes left if smaller
      int ram = round((freeRam() * 0.5) / roundTo) * roundTo;
      bufSize = min(ram, sourceFile.available());
      //round to nearest value of roundTo
      bufSize = round(bufSize / roundTo) * roundTo;
      byte data[bufSize];
      sourceFile.readBytes(data, bufSize);
      lastPos = sourceFile.position();
      sourceFile.close();
      outputFile = SD.open(outputFileName, O_APPEND | O_WRITE);
      outputFile.write(data, bufSize);
      outputFile.close();
      sourceFile = SD.open(inputFileName);
      sourceFile.seek(lastPos);
      //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
      printStats();
    }
    sourceFile.close();
    outputFile.close();
    Serial.println(F("Finished"));
    unsigned int sec = millis() / 1000;
    unsigned int mins = sec / 60;
    sec -= mins * 60;
    Serial.print(F("Time taken: "));
    Serial.print(mins);
    Serial.print(':');
    Serial.print(sec);
    Serial.print(F("Speed: "));
    Serial.print((sourceFile.size() / 1000) / (millis() / 1000));
    Serial.print(F(" KB/s"));
  }
  // if the file isn't open, pop up an error:
  else {
    Serial.println("error opening files");
    Serial.print(F("Exists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.println(SD.exists(outputFileName));
    SD.initErrorHalt();
  }
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(200);
  digitalWrite(LED_BUILTIN, LOW);
  delay(200);
}

int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

void printStats() {
  timeNow = micros();
  uint32_t timeTaken = timeNow - timeLast;
  float sent = sourceFile.position() / 1000.0;
  float fileSize = sourceFile.size() / 1000.0;
  float left = fileSize - sent;
  float speed;
  speed = 1000000UL / timeTaken * bufSize;
  speed /= 1000;
  unsigned int sec = millis() / 1000;
  unsigned int mins = sec / 60;
  sec -= mins * 60;
  int estSec = (left / speed);
  int estMin = estSec / 60;
  estSec -= estMin * 60;
  Serial.print(F("\tSent (KB): ")); Serial.print(sent);
  Serial.print(F("\tLeft (KB): ")); Serial.print(left);
  Serial.print(F("\tSize (KB): ")); Serial.print(fileSize);
  Serial.print(F("\tTime: "));      Serial.print(mins); Serial.print(':'); Serial.print(sec);
  Serial.print(F("\tSpeed (KB/sec): "));     Serial.print(speed);
  Serial.print(F("\tFree: "));      Serial.print(freeRam() - bufSize);
  Serial.print(F("\tBuf: "));       Serial.print(bufSize);
  Serial.print(F("\tEST: "));       Serial.print(estMin); Serial.print(':'); Serial.print(estSec);
  //Serial.print(F("\tExists(I,O): ")); Serial.print(SD.exists(inputFileName)); Serial.print(SD.exists(outputFileName));
  Serial.print('\n');
  timeLast = micros();
}

```

My serial output(I chose Nova.mp3 as input file and output.mp3 as output file):

```
Initializing SD card...Card initialized.
Files on card:
output.mp3
Nova.mp3
Eclipse.wav
Enter input file name:
Select file 'Nova.mp3'? Y/N
Using file 'Nova.mp3' as input file
File exists
Enter output file name:
Select file 'output.mp3'? Y/N
Using file 'output.mp3' as output file
File already exists. Overwrite? Y/N
Removing output file
Creating output file
Exists(I,O): 01
error opening files
Exists(I,O): 01
No error found.

```

I know i am not running out of memory, and have no compiler errors, but i have no clue what is going wrong. Is it possible I have put in some unnecessary code? Also, if it was possible to have multiple files open at a time, would i spped up my read/write speed?

# Answer
The problem is that you have the char arrays for zero terminated c-string one char shorter then needed. I see you assign the terminating zero to inbuf\[pos\] and then you allocate pos chars for the filename and copy pos count of characters. That leaves out the terminating zero and the c-string of the filename is not terminated by 0 and continues in memory with random content.
> 2 votes

---
Tags: arduino-mega, sd-card
---


title: PIR motion wake ESP8266 from deepsleep

text:
# Question
Title: PIR motion wake ESP8266 from deepsleep
I'm trying, what I thought would be simple, to wake a sleeping ESP8266 via motion detected by a PIR.

There are a lot of schematics around and they all seem to go about it more or less the same way, and the simplest form seems to be this:

Where RST is the RST pin of the ESP8266 and Trigger is the PIR's trigger line.

The problem I'm finding is that this is not working.

The PIR is working fine, and throws out almost 3v for 2 seconds when triggered and 0 when no motion is detected.

My ESP is being woken up when the PIR trigger is OVER, not when it STARTS. So if the PIR senses motion for a long time, the ESP will only wake up when the motion STOPS.

The PIR is one of these.

The ESP is currently a NodeMCU on breadboard, but the final product will be a Wemos D1 Mini.

What am I doing wrong here?

# Answer
> 1 votes
What you need is an edge detector. As long as the PIR output is hight, the ESP stays in reset mode.

You can use a capacitor to do the trick, as shown in the following schematic.
You'll probably want to get rid of the pull-down resistor R1 since you're using an open-collector output.

If the voltage at the collector is the blue curve, then the resulting voltage at the output of the circuit will be similar to the yellow curve. (Note that this simulation used an ideal square wave as input, produced by a push-pull output from a CMOS chip, for example. An open-collector output will have slightly different characteristics, the high peak won't be as high.)

At the instant when the collector voltage drops to (almost) zero, the voltage across C1 will be 0V, so the output is close to 0V as well. Then the capacitor immediately starts to charge through R2, so the voltage on the reset pin rises exponentially.

To prevent a high voltage peak when the PIR turns off, a diode is used to discharge the capacitor more quickly. If the resistor at the collector is large enough, this might not be an issue at all.

The same principle is used in the Arduino UNO, for example, to reset the ATmega when DTR goes low.

---
Tags: esp8266, sleep
---


# Question
Title: Writing to serial LCD seems to interfere with servos
I have an OBD-based Arduino project (OBD adapter link below) which uses two servos and a serial LCD from Sparkfun (link below). My problem: writing to the LCD seems to interfere with the servos. Details:

1) When all LCD-related code is excluded, the servos work smoothly. 2) When LCD-related code is included, but the servos are not hooked up, the LCD displays everything OK. 3) When the LCD-related code is included, even if the LCD itself is NOT hooked up, the problem occurs. There's a brief noise from the servos every time I write to the LCD (the servos don't move much, they just make a brief noise).

Any idea what's causing this? Below are the relevant parts of the code (OBD, servo, LCD):

```
#include <Arduino.h>
#include <Wire.h>
#include <OBD.h>
#include "MPU6050.h"
#include <SoftwareSerial.h>
#include <Servo.h>

int servoPin1=13;
int servoPin2=12;

Servo servo1;
Servo servo2;

COBDI2C obd;
SoftwareSerial lcd(2,3);

void clearDisplay() {
  lcd.write(0xFE);
  lcd.write(0x01);
}

void setLCDCursor(byte cursor_position) {
  lcd.write(0xFE);
  lcd.write(0x80);
  lcd.write(cursor_position);
}

void Show() {
  setLCDCursor(0);
  lcd.print("Test");
}

void setup() {
  lcd.begin(9600);
  clearDisplay();
  setLCDCursor(0);
  lcd.print("OBD");

  pinMode(servoPin1,OUTPUT);
  pinMode(servoPin2,OUTPUT);
  servo1.attach(servoPin1);
  servo2.attach(servoPin2);
  servo1.write(0);
  delay(200);
  servo2.write(100);
  delay(200);

  obd.begin();
  conn=obd.init(PROTO_AUTO);
  lcd.print("Connected");

  Wire.begin();
}

void loop() {
  conn=obd.readPID(PID_RPM,rpm);
  if (condition) {
     servo2.write(50);
    delay(500);
    servo1.write(100);
    delay(500);
  }
  Show();
  delay(1000);
}

```

OBD adapter Serial LCD

# Answer
> 2 votes
You are using SoftwareSerial which turns interrupts off when sending/receiving in order to precisely time gaps between bits. The Servo library may use hardware timers, but to work on pins 12 and 13 would require interrupts to "copy" the pulses to those pins. Thus the copies will be distorted when writing to, or reading from, SoftwareSerial.

I suggest using hardware serial (pins 0 and 1) for talking to the LCDs, which does not turn interrupts off. Alternatively, implement the servo positioning using the hardware timers yourself, which (once set up) won't change the pulse widths if interrupts are turned off.

# Answer
> 0 votes
The servo control PWM signal is generated in HW. So should be stable if left alone with adequate power despite what the code is doing. Servos are analog devices. So any perturbation in the shape or length of the wave form may affect the servo.

Consider, once the servo has reached the desired position, turning off the PWM signal which, for most servos, simply leaves them motionless where they are.

---
Tags: lcd, servo
---


title: Arduino IDE and subfolders

text:
# Question
Title: Arduino IDE and subfolders
I have a sketch with multiple source files and folders arranged like so. I've divided up the project like this to keep things clean.

```
|
\---project
    |   project.ino
    |   types.h
    |
    +---sub1
    |       gadget1.c
    |       gadget1.h
    |       gadget2.c
    |       gadget2.h
    |
    \---blarg
            foobar.c
            foobar.h

```

The sketch file includes the headers via quoted include directives (rather than the lib alternative with angled brackets). This seems to work for compilation.

However, when the IDE tries to link, all references to implementations (c source files) in the subfolders generate "undefined reference" errors. Almost as if the IDE is completely ignoring the C source files.

In trying to resolve this I've discovered that apparently the handling of subfolders by the IDE seems to be all over the place. Some versions only acknowledge headers in subfolders, others work if you put everything in a "src" folder (I've also seen mention of a "utility" folder), some people suggest modifying environment variables, etc. I've even tried manually adding source files via the "sketch/add file" option which makes the files visible in the IDE but does not solve the linking problems. All these methods seem to depend on IDE version, and I couldn't distill what was the correct way vs a hack or work-around.

So my question is what is the correct/current way of organizing the above project so that it can be compiled/linked using the IDE? I am using IDE version 1.8.5 which I believe is either the latest version, or close too it.

# Answer
From Arduino IDE 1.6.10 onward the Arduino IDE compiles all source files in the `src` subfolder of the sketch and recursively through all folders under the `src` folder.

Support for compilation of sketch subfolders was added one or two IDE versions before 1.6.10 and was originally not limited to the `src` folder but a lot of problems were reported by people who had stored separate programs in subfolders of their sketch that caused compilation errors so this feature was restricted to the `src` subfolder only.

So if you structure a sketch like this:

```
foo
|_foo.ino
|_src
   |_bar.cpp
   |_bar.h

```

And use this `#include` directive in your sketch:

```
#include "src/bar.h"

```

it will work fine.

> Almost as if the IDE is completely ignoring the C source files.

Arduino sketches are converted to C++ before being compiled. They are not C. If you want to use C in C++ code you need to wrap it in `extern "C" {}`

```
extern "C" {
#include "src/sub1/gadget1.h"
}

```

> what is the correct/current way of organizing the above project

```
project
|_project.ino
|_types.h
|_src
   |_sub1
   |  |_gadget1.c
   |  |_gadget1.h
   |  |_gadget2.c
   |  |_gadget2.h
   |_blarg
      |_foobar.c
      |_foobar.h

```
> 10 votes

---
Tags: arduino-ide
---


# Question
Title: Detect a camera flash? Light sensor, photoresistor?
I'm looking to build an Arduino-based "camera flash logger" to detect when a camera flash goes off, and maintain a log of those events. My thinking is to use a photoresistor to measure light level, and watch for sudden changes using a loop. Something like:

```
const int ldrPin = A0;

// no idea what this number would end up being
// just putting something here to start with
const int threshold = 10;
int currentLevel, lastLevel = 0;

void setup() {
    Serial.begin(9600);
    pinMode(ldrPin, INPUT);
}

void loop() {
    lastLevel = currentLevel;
    currentLevel = analogRead( ldrPin );

    // look for a sudden change
    if( abs( lastLevel - currentLevel ) > threshold ) {

        // serial out here to simplify the example.
        // I'll be logging outputs (with timestamps) to an SD card.
        Serial.println( currentLevel );
    }
}

```

A couple of things I'm not sure of though:

1. will the response time of a photoresistor be fast enough to respond to the very short (sometimes less than 1ms) burst from a camera flash?
2. is a loop measuring level changes the best way to go about this, or would something like a state change interrupt be better? The ambient light level will vary depending on time of day, so it's an edge detection problem, as opposed to just reading a light level.

Apologies if this comes across as a "you haven't done your homework yet" question. I haven't started the project yet, so all I'm hoping for is a little direction on which way to proceed.

# Answer
A photo-resistor would not be recommended to detect a camera flash accurately. For example, the Jameco Part #202403 (Part PDF) has a response time of 50 to 75 milliseconds. Photo-resistors are more suitable for general light levels, for instance, like how bright it is in a room.
On the other hand, photo-transistors are suitable for very fast reaction times. The Jameco Part #2129385 (Part PDF) has a response time of 15 microseconds, which is more than 1000 times faster. A photo-resistor will be able to respond to the light change, but it will be nowhere as sensitive.
As with any product, however, search for the product PDF before buying it.
> 1 votes

---
Tags: photoresistor
---


# Question
Title: Water pressure an salinity sensor connected to arduino
I am trying to design a project that Arduino would have connected water and salinity sensor, would be packed in a special box be droped into ocean up to 500 meters. What sensors should I use and how should they be conencted. I assume that I would need professional equipment, not chineese stuff from ebay. Hardware needs to be able to work under 50\*C and up to 50bar

Update:

Budget is about up to 400 pounds for sensors. Resolution of pressure 0 to 100 bar Resolution of salinity doesnt matter so much. Few percents of mistake, just to measure it somehow

# Answer
I suggest that you look for a sensor from Honeywell. The problem is that the pressure is very high for a board mounted sensor and the atmospheric pressure is varying. The board mounted sensors measure a maximum of 10 bar. It is not clear what accuracy you require. Is there a connection to the surface? If so you should measure differential pressure between the seabed and the surface. Can you be content with a maximum depth of 100 m?

I don't think salinity varies much offshore so it might not be worth measuring.
> 1 votes

---
Tags: sensors
---


# Question
Title: Can't display the two float values correctly from pyserial on Arduino's LCD
I transported two float values with pyserial to COM3 and Arduino accepted the values.

But it displayed the first value correctly on LCD, the second value can't be read and showed "nan" on LCD.

Python code:

```
import serial
import struct
ser =serial.Serial("COM3", 115200, timeout=2)

##======Get  Ready================
print("Connecting to Arduino.....")
for i in range (1,10):
    rv=ser.readline()
    print("Loading...")
    #Debug print (rv) # Read the newest output from the Arduino
    print (rv.decode("utf-8"))
    ser.flushInput()
    sleep(1) # Delay for one tenth of a secon
    Str=rv.decode("utf-8")
    #Debug print(Str[0:5])
    if Str[0:5]=="Ready":
          print("Get Arduino Ready !")
          break
##------------------------------------------------------
d = 77.25
a = 111.32
ser.write(struct.pack('>2f',d,a))

```

Arduino code:

```
#include <LiquidCrystal.h>
float x;
byte *xdata = (byte *) & x;
float y;
byte *ydata = (byte *) & y;
int num = 0;
char coor[2];

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup() {
  Serial.begin(115200); // set the baud rate
  Serial.println("Ready"); // print "Ready" once
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
}

void loop(){
  while(Serial.available() > 0){
    for(int i = 0; i < 2; i++){
      coor[i] = Serial.read();
      }
    if(coor[0] == 'B' ){
      xdata[3] = coor[0];
      ydata[3] = coor[1];
      num = 1;
    } else if(num == 1){
      xdata[2] = coor[0];
      ydata[2] = coor[1];
      num++;
    } else if(num == 2){
      xdata[1] = coor[0];
      ydata[1] = coor[1];
      num++;
    } else if(num == 3){
      xdata[0] = coor[0];
      ydata[0] = coor[1];
      num = 0;
    // use the values
    Serial.write(xdata,4);
    Serial.write(ydata,4);
    lcd.print(x);
    lcd.setCursor(8,0);
    lcd.print(y);
      }
    }

```

The LCD monitor will show 77.25 and nan. It can't show 111.32 correctly.

# Answer
I don't understand why you read the bytes this way. Your original version was reading only the bytes of the first float into xdata and -1 into ydata. (`read` returns -1 if no data is available, it doesn't wait.) Now when two bytes are read with `readBytes`, first two bytes of the first float are written one into xdata\[0\] and second into ydata\[0\].

read first float with `readBytes(xdata, 4)` and the the second with `readBytes(ydata, 4)`
> 0 votes

---
Tags: serial, python, float
---


# Question
Title: In the latest version of Arduino Desktop IDE, are there all features of Arduino Web Editor?
I would like to know if there are always the latest features in Arduino Desktop IDE if I update it every day.

I mean if there is a new feature in Arduino Web Editor, can I get it on Arduino Desktop IDE?

# Answer
You will always get the same API features in both, because the API is separate to both of them - it's a plugin that's developed separately.

Would you get the same GUI facilities? No idea. Maybe - maybe not. It depends how useful they would be. You may get features added to the GUI that don't appear on the web. Or you may get the other way around. If they are essential to the operation of the system, though, you will get them added to both.
> 1 votes

---
Tags: arduino-ide
---


# Question
Title: What is the difference between Arduino board and Genuino Board?
I've got an Arduino UNO REV3 SMD EDITION.

In the Arduino Editor, I've selected `Arduino/Genuino Uno`.

In a tutorial, I saw `Hardware required : Arduino or Genuino Board`

What is the difference between Arduino board and Genuino Board?

# Answer
The name Genuino grew out of the split between Massimo and Gianluca (aided in part by Microsoft of course, and a trademark wrangle that went wrong). Each side wanted to appear to be more "genuine" than the other. That lead to the "Genuino" name (a *genuine* Arduino), and a version number war with the IDE.

Both sides started making their own variants of boards, with some only available from the USA (Arduino) and others only outside the USA (Genuino).

Since they have patched up their differences now the two boards are one and the same. A Genuino Uno and an Arduino Uno are the exact same board. They always have been, there has just been arguments over the name.
> 7 votes

---
Tags: arduino-uno, genuino
---


# Question
Title: How to properly link an Arduino and its sensors
To finalize a prototype, I would like to have a proper structure containing the arduino (uno here), its shields and its sensors. I would like the sensors to be soldered to the arduino+shields block, but the sensors were sold on a small separate PCB (example).

**What is the recommended method to have a strong, clean link between the two ?**

# Answer
> 2 votes
You could solder those modules to a prototype shield. If you replace the header with a right-angle one (or even just bend the pins on the existing one) you could even mount it vertically to save space.

* Prototype shield:

* Right-angled headers:

---
Tags: arduino-uno, sensors, communication
---


# Question
Title: Do I need to power off the Arduino board before doing something?
Is it safe to build a circuit while the Arduino board is powered?

Should I power the board only when I have to upload the program?

# Answer
> 2 votes
It is not safe, as you may accidentally connect some points, which should not be connected and destroy Arduino and/or any other part of circuit. typically legs of resistors/LEDs tends to touch other legs near them, when you are putting it in - and if it is powered, magical smoke can happened easily.

Even if you do not this kind of mistake, not everything can be put in random order without risc of damage.

So everytime you change something with circuit, disconnect power source/USB first. And if you have big capacitors anywhere, you better make sure, they are discharged too.

You switch on the board, when the building is done and you want to program it, or use the already present program.

# Answer
> 1 votes
It can be dangerous, not only to the Arduino, but to whatever you are connecting, if you do so with the power applied.

Current can end up flowing where it shouldn't, and components can become damaged.

However if it's something as simple as an LED then it really doesn't matter.

---
Tags: power
---


# Question
Title: Problem stacking ADS1292r ECG shield and Wifi shield on Arduino Uno
I want to use ADS1292r ECG shield with Arduino Uno (Seeeduino V4.2) and store the data in an SD card through an Wifi shield. But the ADS1292r shield uses Digital pin 4 for "RESET" purposes, while the same pin is the "SD card select" pin for the WiFi shield. So if I stack all 3 of them, the SD card can't be initialized. Is there any way to solve this problem?

# Answer
As a generic answer to these sorts of problems (same pin needed by different libraries), I have had success with slightly bending the pin of the top shield to the side to that it doesn't make direct contact with the board underneath (ie doesn't plug into the header socket).

Assuming the shields are all stackable, you can run a jumper wire from the top of the pin to any other pin which is permitted by the configuration. If not, you may have to solder a wire.

In your example, put the WiFi shield on top with its D4 pin bent to the side (with ECG shield between Uno and WiFi shield) , and run a jumper between the **tops** of D3 and D4 (ie on the WiFi Shield). Thus the SD Card select would now be set to D3 instead of D4, and no other connection is made to D4 on the WiFi shield.

I can't verify that you won't have trouble with other pins (eg it looks like both shields use D7).
> 1 votes

---
Tags: arduino-uno, wifi
---


# Question
Title: Reconstruct uint32_t from char array to RTC.set
I am currently experimenting with a Digistump ATTiny85. Since it has no Serial, I use the basic `DigiUSB` library for communication. The RTC library used is this one: https://github.com/JChristensen/DS3232RTC/. The DigiUSB library is from Digispark.

I attached a DS3232 via TWI to the Digistump, because I want to use this construct as a USB-Realtime-Clock.

Initially setting the time in the `setup` method works as follows

```
  RTC.set(1532341020);

```

But I am unable to transfer the time via the pseudo serial connection and set it remotely. What I've tried so far:

* Using `union` with `char` and `uint32_t`. Althougt the char representation is correct (tried DigiUSB.println()), the `uint32_t` representation of this union is not what I need.
* Tried to adapt to some shifting examples, but seriously got lost here. All examples where about 4 byte streams.
* `atoi` and some other functions with no success.

Here is my current sketch

```
#include <DS3232RTC.h>
#include <DigiUSB.h>

//union ArrayToInteger {
//  char array[10];
//  uint32_t integer;
//};

unsigned char foo[10];
uint32_t num;

void setup() {
  RTC.begin();
  //RTC.set(1532341020);
  DigiUSB.begin();
}

void loop() {
  if (DigiUSB.available() >= 10) {
    for (int i=0; i<=10; i++) {
    foo[i] = DigiUSB.read();
  }
  RTC.set((uint32_t)foo);
  DigiUSB.delay(100);
  DigiUSB.refresh();
  //DigiUSB.println(_foo.array);
  DigiUSB.println(RTC.get());
} else {
  DigiUSB.refresh();
  DigiUSB.println(RTC.get());
  DigiUSB.refresh();
  DigiUSB.delay(1000);
  }
}

```

In the end I need the a `char _foo 0123456789` represented as/converted to `uint32_t num 0123456789`

Kinda stuck here. Can anyone point me in the right direction ore provide an example?

# Answer
> 1 votes
Answering this question based on the help from above. It works with this code. Thank you all for the help. The clock does not reply the newly set time instantly, but after a few seconds.

```
#include <DS3232RTC.h>
#include <DigiUSB.h>
char foo[10];

void setup() {
  RTC.begin();
  DigiUSB.begin();
}

 void loop() {
   if (DigiUSB.available() >= 10) {
     for (int i=0; i<=10; i++) {
       foo[i] = DigiUSB.read();
   }
   RTC.set(atol(foo));
   DigiUSB.delay(100);
   DigiUSB.refresh();
   DigiUSB.println(RTC.get());
} else {
   DigiUSB.refresh();
   DigiUSB.println(RTC.get());
   DigiUSB.refresh();
   DigiUSB.delay(1000);
   }
}

```

# Answer
> 2 votes
There are several possible issues here:

* can you send the number, as a string, from the PC to the ATtiny?
* can you convert the string to an actual number?
* can you give this number to the RTC?

The phrasing of your question sounds like your issue is with the conversion. However that is easily handled with `atol()`. Here is a test program I tried on my Uno:

```
void setup() {
    char time_string[] = "1532341020";
    uint32_t time_number = atol(time_string);

    Serial.begin(9600);
    Serial.print("string: \"");
    Serial.print(time_string);
    Serial.print("\", number = ");
    Serial.println(time_number);
}

```

The output is:

```
string: "1532341020", number = 1532341020

```

---
Tags: programming, usb, attiny, convert
---


# Question
Title: Rc car controller using the RC-switch library
simulate this circuit – Schematic created using CircuitLab

(Newbie in arduino) Hi so i have a project which involves creating an rc car which uses the 433Mhz rf module and an arduino nano with a servo motor and an ultrasonic parking sensor.

I'm having problems with the code both on the transmitter and receiver, Here is the code for the transmitter.

```
 #include <RCSwitch.h>
RCSwitch mySwitch = RCSwitch();
// Assigning controller buttons to Digital Pins
 const int forward = 8;
 const int reverse = 9;
 const int rightTurn = 10;
 const int leftTurn = 11;

 int Fwd = 0
 int Bwd = 0
 int Lt  = 0
 int Rt  = 0

void setup () {
  pinMode (forward, INPUT);
  pinMode (reverse, INPUT);
  pinMode (rightTurn, INPUT);
  pinMode (leftTurn, INPUT);
  mySwitch.enableTransmit(7);
  Serial.begin (9600);         // Debugging only
  Serial.println ("Transmitting");
}

void loop () {
  Fwd = digitalRead(forward);
  Bwd = digitalRead(reverse);
  Rt  = digitalRead(rightTurn);
  Lt  = digitalRead(leftTurn);

  if (Fwd == HIGH) {
    mySwitch.send('1');
    Serial.println ("Forward");
    delay(100);
  }

  if (Bwd == HIGH) {
    mySwitch.send('2');
    Serial.println ("Reverse");
    delay(100);
  }

  if (Rt == HIGH) {
    mySwitch.send('3');
    Serial.println ("Left Turn");
    delay(100);
  }

  if (Lt == HIGH) {
    mySwitch.send('4');
    Serial.println ("Right Turn");
    delay(100);
  }
}

```

And here's the code for the receiver

```
#include <RCSwitch.h>
#include <Servo.h>

const int IN1 = 3;
const int IN2 = 4;
const int trigPin = 5;
const int echoPin = 6;
int distance = 0;

RCSwitch mySwitch = RCSwitch();
Servo myservo;

void setup () {
  mySwitch.enableReceive(2);
  myservo.attach(7);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin (9600);    // Debugging only
  Serial.println ("Receiver Ready");
}

void loop () {
 if (mySwitch.available()) {

    int value = mySwitch.getReceivedValue();

      if(value == '1') {
        forward ();
        Serial.println (" = forward");
      }

      if(value == '2'){
        backward ();
        Serial.println (" = backward");
      }

      if(value == '3') {
        left ();
        Serial.println (" = left");
      }

      if(value == '4') {
        right ();
        Serial.println (" = right");
      }
      Serial.print(" ");
    }

}

void forward () {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}
long duration;
int value = mySwitch.getReceivedValue();
void backward () {
  if ((distance > 10)&& (value == '2'))
  {
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, LOW);
  }
  else if ((distance < 10)&& (value == '2'))
  {
  digitalWrite (IN1, HIGH);
  digitalWrite (IN2, LOW);
  }
  delayMicroseconds(10);
  // Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);
  // Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);
  // Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);
  // Calculating the distance
  distance= duration*0.034/2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance); //distance is the returned integer,
}

void right () {
  myservo.write(0);
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

void left () {
  myservo.write(90);
  digitalWrite (IN1, LOW);
  digitalWrite (IN2, HIGH);
}

```

The problem is when i run the code the buttons start getting pressed even if I'm not pressing them and even when i disconnect them from the arduino. and also the receiver cant receive any data. Please help

# Answer
As you wrote in your comment, you didn't use pullup or pulldown resistors for connecting the buttons. In this case the pin is floating, whenever the corresponding button is not pressed. It will pick up random noise from the environment and change it's state randomly.

A pullup or pulldown resistor defines a specific value for the pin, if the button is not pressed (LOW or HIGH). The value of such is a resistor is not critical, as long, as it isn't a too big load. Pick some value in the kiloohms (for example 10kOhm).

But you don't need external resistors for this. The Atmega328, which is the heart of the Arduino Nano, already has buildin pullup resistors for each digital output pin. You can activate them by using

```
pinMode(pin_number, INPUT_PULLUP);

```

In this case you will have to change the if-statements to check for `LOW` instead of `HIGH` and connect the button to ground instead of 5V, because with a pullup resistor in idle state the pin will be pulled up to 5V and the button can then pull it down to ground.
> 0 votes

---
Tags: arduino-nano, servo, button, code-review, rf
---


# Question
Title: For Arduino, is there a meaningful difference between carriage returns?
Serial.write(0x0d); // hex

Serial.write(13); // ASCII

Serial.write('\r'); // char

Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)

# Answer
> 0 votes
As mentioned before they are all the same. The thing you have to rememeber is that the compiler takes the human readable code you write and turns it into the instructions the processor can understand. If you want to explore ways the compiler does thing you can compile the program into the hex file and then compare. Or for even less detail, but much easier, look at the size of the file created when you compile in the IDE using just the one line in question inside the setup function

```
write(0x0d)  ----> 1334 bytes
write(13)    ----> 1334 bytes
write('\r')  ----> 1334 bytes

```

For this simple example we can assume that all three of these are producing the exact same hex file. There are many more complicated example of different ways to do the same task that may produce more or less efficient code, but in this case the compiler is going to produce the same instruction set to the processor.

As pointed out in the comments, I am not saying that because they are the same size they must be the same hex code. As any single byte being written would produce the same size code, but not the same result. But when comparing two methods that we know are the same functionality ( 0x0d and '\r') and they produce the same size binary, then we can assume the compiler reduced them to the same code.

# Answer
> 0 votes
> Is one more efficient?

after compilation it is same for all notations. the function and the value are the same for all 3 notations.

# Answer
> 0 votes
There is no difference between all the lines of code in your question. All representations stand for one value, containing one byte. There is only one implementation of `Serial::write()`, which has a `uint8_t` as parameter. So all the different representations result in a `uint8_t` anyway.

---
Tags: serial, softwareserial, digital
---


# Question
Title: Voltmeter using Arduino mega 2560 giving unexpected result after some time
I have been trying to construct a smart energy meter that can observe readings of 220v household. For now i am working on voltmeter. I have been following the circuit I attached. Transformer step down 220V to 6V. Zener diode is of 5V. The output from the circuit( 5v max) is fed to arduino Mega 2560 A0 pin. * I am powering arduino using a USB cable * Arduino takes this voltage as input from pin A0 in form of analog values between 0 to 1023. 0 being 0 volt and 1023 being 5v.So any random analog value corresponds to X=(5/1023)\*Y where Y is obtained analog value. X is then multiplied by a value obtained by hit and try method (165 in my case) to reach the exact reading of voltage in line observed via multimeter. Now the problem is that, everything works fine when i calibrate it, but after some time when i switch circuit on the value is inaccurate by margin, and i have to calibrate it again and again every time I turn circuit on after some time.If i switch circuit on soon after switching it off, it gives almost accurate value. *I guess this issue is due to the capacitor, but i don't know anything about it or how to solve it* I have constructed the same circuit more than 5 times, soldering it 3 times and 2 times on bread board and i am sure there is no problem with my implementation, verified it many times. this is my code:

```
float V; // Voltage samples
float V0;

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

void loop() {
  for(int i=0; i<=20000; i++){
    V = V + analogRead(A0);
  }
  V = V / 20000;
  V = round(V);

  float V0 = V * (5.0 / 1023.0);
  I0 = I0 * 165; // has to be callibrated again and again each time circuit is switched on after a while

  Serial.print("Voltage = ");
  Serial.print(V0);
  Serial.println(" -------------- ");
  delay(1500);
}

```

this is the link i am following http://engineerexperiences.com/3-phase-smart-energy-meter-using-arduino.html

Any help would be appreciated, Thanks!

# Answer
With that circuit you can expect a roughly 10% variance in the output voltage depending on the exact moment at which you sample the voltage.

The basic circuit you have, and the waveforms generated, are like this:

That green waveform is the one you are reading. As you can see, exactly where you sample defines what the result will be.

Since you're trying to average over an undefined period (20,000 samples of how long per sample exactly?) you're not going to get a particularly well defined output.

You should change your sampling strategy to perform multiple samples over a well defined period to find the *maximum* value. That is the value you should then use in your calculations.

Ideally, you want to repeatedly sample for *at least* one entire waveform cycle. At 50Hz that's a period of 20ms (17ms for 60Hz).

For example:

```
uint16_t maxval = 0;
uint32_t ts = millis();
while (millis() - ts < 20) {
    uint16_t val = analogRead(0);
    if (val > maxval) {
       maxval = val;
    }
}

// Use "maxval" in your calculations.

```

With this strategy, because you're looking for the *peak* value, you don't care about the impact that the capacitor has on the circuit (except that it will remain artificially high for a period if the voltage drops), so you could actually simplify the circuit and remove that capacitor completely.
> 1 votes

# Answer
I just wanted to add some points to what Majenko already said.

You are making a measurement device, so you need a precise reference. So why are you using the 5V reference?

Your 5V in your circuit is assumed to be stable. But is it? Maybe some time you are using the PC to power it, then you attach a lot of loads to the USB ports, then you use a wall USB power supply. Every time the 5V can change (see here for instance). A variation in the supply of +/-5% will be translated in a +/- 12V for a 240V input (I don't know if this is above or below your expected accuracy).

The solution is to use the internal reference, which is an internal peripheral used explicitely for measuring analog sources.

In your case (Arduino MEGA 2560) you have a 1.1V or a 2.56V internal references. Your transformer is a 240-\>6V transformer, which means the value you should read after it is around 8.5V (6Vrms has a peak of 6\*1.415 = 8.5V). After the voltage divider, this becomes 1.53 V. Consequently you can use the 2.56V reference in this case. To do so write, in your setup function, `analogReference(INTERNAL2V56);`. Then your readings will be relative to 2.56V rather than 5.0V (so `float V0 = V * 2.56 / 1023.0;`).

(Note: the way to implement this was taken from the arduino reference manual; I never implemented it, so it may require tweaking)
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: RGB LED strip controlled through PySerial only somewhat functional
I am trying to set up an LED-strip of 30 RGB LEDs (model WS2801). The strip is connected to an Arduino Uno and an external power supply and the goal is to send colors to the arduino using PySerial which are then shown on the LED strip.

I have been trying to wrap my head around the communications, which I am having a hard time with, especially due to the loose typing of python.

I wrote some code that generates smooth color transitions and got the strip to actually show a fairly smooth color transition, unfortunately the colors are the wrong ones.

Now I am guessing something overflows somewhere, especially since colors such as 0xFF0000 (red) show as a yellow tone, which indicates that on top of red some green gets added as well.

The Python code using pySerial:

```
@classmethod
def set_lights(self: RGBHardware, colors: List[int]) -> None:
    for i in range(len(colors)):
        rgb = color_to_rgb(colors[i])
        self.arduino.write(chr(76).encode()) # 'L'
        self.arduino.write(chr(i).encode())
        self.arduino.write(chr(rgb[0]).encode())
        self.arduino.write(chr(rgb[1]).encode())
        self.arduino.write(chr(rgb[2]).encode())
    self.arduino.write(chr(90).encode()) # 'Z'

@classmethod
def turn_on(self) -> None:
    self.arduino = serial.Serial('/dev/ttyACM0', 115200)
    if self.arduino.isOpen:
        self.arduino.close()
    self.arduino.open()
    pass

```

The code running on the Arduino Uno:

```
void setup() {
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif

  Serial.begin(115200);
  strip.begin();
  // Update LED contents, to start they are all 'off'
  strip.show();
}

void loop() {
   while (Serial.available()) {
        uint8_t serial = Serial.read();
        if (serial == 'Z') {
            strip.show();
        } else if (serial == 'L') {
            int i = getNextInput();
            int r = getNextInput();
            int g = getNextInput();
            int b = getNextInput();
            strip.setPixelColor(i, Color(r,g,b));
        }
   }
}

uint8_t getNextInput() {
  while(!Serial.available()); // wait for a character
  return Serial.read();
}

```

I am having the strong feeling I am just missing a miniscule detail and it is quite frustrating.

Any help would be greatly appreciated!

EDIT: So I recorded some data and pasted the results below. I found that always not the whole LED-strip was updated and none of it with the correct color. Once even the character "Z" seemed to go missing (that causes the strip to fully refresh) so no color was showing at all.

What I also forgot to mention earlier was that I am using Celery in Python to do the light switching as a background task.

To record the results I used

`print("i, R,G,B: " + str(i) + ", " + str(rgb[0]) + "," + str(rgb[1]) + "," + str(rgb[2]))` to print the data in python and

`Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));` to do the same on the Arduino.

Sending color red from Python:

```
[2018-07-23 16:13:57,121: WARNING/ForkPoolWorker-7] i, R,G,B: 0, 255,0,0
[2018-07-23 16:13:57,122: WARNING/ForkPoolWorker-7] i, R,G,B: 1, 255,0,0
[2018-07-23 16:13:57,123: WARNING/ForkPoolWorker-7] i, R,G,B: 2, 255,0,0
[2018-07-23 16:13:57,125: WARNING/ForkPoolWorker-7] i, R,G,B: 3, 255,0,0
[2018-07-23 16:13:57,126: WARNING/ForkPoolWorker-7] i, R,G,B: 4, 255,0,0
[2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 5, 255,0,0
[2018-07-23 16:13:57,127: WARNING/ForkPoolWorker-7] i, R,G,B: 6, 255,0,0
[2018-07-23 16:13:57,128: WARNING/ForkPoolWorker-7] i, R,G,B: 7, 255,0,0
[2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 8, 255,0,0
[2018-07-23 16:13:57,129: WARNING/ForkPoolWorker-7] i, R,G,B: 9, 255,0,0
[2018-07-23 16:13:57,131: WARNING/ForkPoolWorker-7] i, R,G,B: 10, 255,0,0
[2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 11, 255,0,0
[2018-07-23 16:13:57,132: WARNING/ForkPoolWorker-7] i, R,G,B: 12, 255,0,0
[2018-07-23 16:13:57,133: WARNING/ForkPoolWorker-7] i, R,G,B: 13, 255,0,0
[2018-07-23 16:13:57,134: WARNING/ForkPoolWorker-7] i, R,G,B: 14, 255,0,0
[2018-07-23 16:13:57,136: WARNING/ForkPoolWorker-7] i, R,G,B: 15, 255,0,0
[2018-07-23 16:13:57,137: WARNING/ForkPoolWorker-7] i, R,G,B: 16, 255,0,0
[2018-07-23 16:13:57,139: WARNING/ForkPoolWorker-7] i, R,G,B: 17, 255,0,0
[2018-07-23 16:13:57,140: WARNING/ForkPoolWorker-7] i, R,G,B: 18, 255,0,0
[2018-07-23 16:13:57,141: WARNING/ForkPoolWorker-7] i, R,G,B: 19, 255,0,0
[2018-07-23 16:13:57,142: WARNING/ForkPoolWorker-7] i, R,G,B: 20, 255,0,0
[2018-07-23 16:13:57,144: WARNING/ForkPoolWorker-7] i, R,G,B: 21, 255,0,0
[2018-07-23 16:13:57,145: WARNING/ForkPoolWorker-7] i, R,G,B: 22, 255,0,0
[2018-07-23 16:13:57,146: WARNING/ForkPoolWorker-7] i, R,G,B: 23, 255,0,0
[2018-07-23 16:13:57,147: WARNING/ForkPoolWorker-7] i, R,G,B: 24, 255,0,0
[2018-07-23 16:13:57,148: WARNING/ForkPoolWorker-7] i, R,G,B: 25, 255,0,0
[2018-07-23 16:13:57,149: WARNING/ForkPoolWorker-7] i, R,G,B: 26, 255,0,0
[2018-07-23 16:13:57,150: WARNING/ForkPoolWorker-7] i, R,G,B: 27, 255,0,0
[2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 28, 255,0,0
[2018-07-23 16:13:57,151: WARNING/ForkPoolWorker-7] i, R,G,B: 29, 255,0,0

```

Received color red on the arduino:

```
i, R,G,B: 0, 195,191,0
i, R,G,B: 1, 195,191,0
i, R,G,B: 2, 195,191,0
i, R,G,B: 3, 195,191,0
i, R,G,B: 4, 195,191,0
i, R,G,B: 5, 195,191,0
i, R,G,B: 6, 195,191,0
i, R,G,B: 7, 195,191,0
i, R,G,B: 8, 195,191,0
i, R,G,B: 9, 195,191,0
i, R,G,B: 10, 195,191,0
i, R,G,B: 11, 195,191,0
i, R,G,B: 12, 195,191,0
i, R,G,B: 13, 195,191,0
i, R,G,B: 14, 195,191,0
i, R,G,B: 15, 195,191,0
i, R,G,B: 16, 195,191,0
i, R,G,B: 17, 195,191,0
i, R,G,B: 18, 195,191,0
i, R,G,B: 19, 195,191,0
i, R,G,B: 20, 195,191,0
i, R,G,B: 21, 195,191,0
i, R,G,B: 22, 195,191,0
i, R,G,B: 23, 195,191,0
i, R,G,B: 24, 195,191,0
i, R,G,B: 25, 195,191,0
i, R,G,B: 26, 76,27,195

```

Sending color green from Python:

```
[2018-07-23 16:22:34,374: WARNING/ForkPoolWorker-8] i, R,G,B: 0, 0,255,0
[2018-07-23 16:22:34,376: WARNING/ForkPoolWorker-8] i, R,G,B: 1, 0,255,0
[2018-07-23 16:22:34,377: WARNING/ForkPoolWorker-8] i, R,G,B: 2, 0,255,0
[2018-07-23 16:22:34,378: WARNING/ForkPoolWorker-8] i, R,G,B: 3, 0,255,0
[2018-07-23 16:22:34,380: WARNING/ForkPoolWorker-8] i, R,G,B: 4, 0,255,0
[2018-07-23 16:22:34,381: WARNING/ForkPoolWorker-8] i, R,G,B: 5, 0,255,0
[2018-07-23 16:22:34,382: WARNING/ForkPoolWorker-8] i, R,G,B: 6, 0,255,0
[2018-07-23 16:22:34,383: WARNING/ForkPoolWorker-8] i, R,G,B: 7, 0,255,0
[2018-07-23 16:22:34,384: WARNING/ForkPoolWorker-8] i, R,G,B: 8, 0,255,0
[2018-07-23 16:22:34,385: WARNING/ForkPoolWorker-8] i, R,G,B: 9, 0,255,0
[2018-07-23 16:22:34,386: WARNING/ForkPoolWorker-8] i, R,G,B: 10, 0,255,0
[2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 11, 0,255,0
[2018-07-23 16:22:34,387: WARNING/ForkPoolWorker-8] i, R,G,B: 12, 0,255,0
[2018-07-23 16:22:34,388: WARNING/ForkPoolWorker-8] i, R,G,B: 13, 0,255,0
[2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 14, 0,255,0
[2018-07-23 16:22:34,389: WARNING/ForkPoolWorker-8] i, R,G,B: 15, 0,255,0
[2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 16, 0,255,0
[2018-07-23 16:22:34,390: WARNING/ForkPoolWorker-8] i, R,G,B: 17, 0,255,0
[2018-07-23 16:22:34,391: WARNING/ForkPoolWorker-8] i, R,G,B: 18, 0,255,0
[2018-07-23 16:22:34,392: WARNING/ForkPoolWorker-8] i, R,G,B: 19, 0,255,0
[2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 20, 0,255,0
[2018-07-23 16:22:34,393: WARNING/ForkPoolWorker-8] i, R,G,B: 21, 0,255,0
[2018-07-23 16:22:34,394: WARNING/ForkPoolWorker-8] i, R,G,B: 22, 0,255,0
[2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 23, 0,255,0
[2018-07-23 16:22:34,395: WARNING/ForkPoolWorker-8] i, R,G,B: 24, 0,255,0
[2018-07-23 16:22:34,396: WARNING/ForkPoolWorker-8] i, R,G,B: 25, 0,255,0
[2018-07-23 16:22:34,397: WARNING/ForkPoolWorker-8] i, R,G,B: 26, 0,255,0
[2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 27, 0,255,0
[2018-07-23 16:22:34,398: WARNING/ForkPoolWorker-8] i, R,G,B: 28, 0,255,0
[2018-07-23 16:22:34,399: WARNING/ForkPoolWorker-8] i, R,G,B: 29, 0,255,0

```

Received color green on the Arduino:

```
i, R,G,B: 0, 0,195,191
i, R,G,B: 1, 0,195,191
i, R,G,B: 2, 0,195,191
i, R,G,B: 3, 0,195,191
i, R,G,B: 4, 0,195,191
i, R,G,B: 5, 0,195,191
i, R,G,B: 6, 0,195,191
i, R,G,B: 7, 0,195,191
i, R,G,B: 8, 0,195,191
i, R,G,B: 9, 0,195,191
i, R,G,B: 10, 0,195,191
i, R,G,B: 11, 0,195,191
i, R,G,B: 12, 0,195,191
i, R,G,B: 13, 0,195,191
i, R,G,B: 14, 0,195,191
i, R,G,B: 15, 0,195,191
i, R,G,B: 16, 0,195,191
i, R,G,B: 17, 0,195,191
i, R,G,B: 18, 0,195,191
i, R,G,B: 19, 0,195,191
i, R,G,B: 20, 0,195,191
i, R,G,B: 21, 0,195,191
i, R,G,B: 22, 0,195,191
i, R,G,B: 23, 0,195,191
i, R,G,B: 24, 0,195,191
i, R,G,B: 25, 0,195,191
i, R,G,B: 26, 76,28,0

```

Sending color blue from Python:

```
[2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 0, 0,0,255
[2018-07-23 16:26:52,416: WARNING/ForkPoolWorker-2] i, R,G,B: 1, 0,0,255
[2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 2, 0,0,255
[2018-07-23 16:26:52,417: WARNING/ForkPoolWorker-2] i, R,G,B: 3, 0,0,255
[2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 4, 0,0,255
[2018-07-23 16:26:52,418: WARNING/ForkPoolWorker-2] i, R,G,B: 5, 0,0,255
[2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 6, 0,0,255
[2018-07-23 16:26:52,419: WARNING/ForkPoolWorker-2] i, R,G,B: 7, 0,0,255
[2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 8, 0,0,255
[2018-07-23 16:26:52,420: WARNING/ForkPoolWorker-2] i, R,G,B: 9, 0,0,255
[2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 10, 0,0,255
[2018-07-23 16:26:52,421: WARNING/ForkPoolWorker-2] i, R,G,B: 11, 0,0,255
[2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 12, 0,0,255
[2018-07-23 16:26:52,422: WARNING/ForkPoolWorker-2] i, R,G,B: 13, 0,0,255
[2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 14, 0,0,255
[2018-07-23 16:26:52,423: WARNING/ForkPoolWorker-2] i, R,G,B: 15, 0,0,255
[2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 16, 0,0,255
[2018-07-23 16:26:52,424: WARNING/ForkPoolWorker-2] i, R,G,B: 17, 0,0,255
[2018-07-23 16:26:52,425: WARNING/ForkPoolWorker-2] i, R,G,B: 18, 0,0,255
[2018-07-23 16:26:52,426: WARNING/ForkPoolWorker-2] i, R,G,B: 19, 0,0,255
[2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 20, 0,0,255
[2018-07-23 16:26:52,427: WARNING/ForkPoolWorker-2] i, R,G,B: 21, 0,0,255
[2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 22, 0,0,255
[2018-07-23 16:26:52,428: WARNING/ForkPoolWorker-2] i, R,G,B: 23, 0,0,255
[2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 24, 0,0,255
[2018-07-23 16:26:52,429: WARNING/ForkPoolWorker-2] i, R,G,B: 25, 0,0,255
[2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 26, 0,0,255
[2018-07-23 16:26:52,430: WARNING/ForkPoolWorker-2] i, R,G,B: 27, 0,0,255
[2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 28, 0,0,255
[2018-07-23 16:26:52,431: WARNING/ForkPoolWorker-2] i, R,G,B: 29, 0,0,255

```

Received color blue on the Arduino:

```
i, R,G,B: 0, 0,0,195
i, R,G,B: 1, 0,0,195
i, R,G,B: 2, 0,0,195
i, R,G,B: 3, 0,0,195
i, R,G,B: 4, 0,0,195
i, R,G,B: 5, 0,0,195
i, R,G,B: 6, 0,0,195
i, R,G,B: 7, 0,0,195
i, R,G,B: 8, 0,0,195
i, R,G,B: 9, 0,0,195
i, R,G,B: 10, 0,0,195
i, R,G,B: 11, 0,0,195
i, R,G,B: 12, 0,0,195
i, R,G,B: 13, 0,0,195
i, R,G,B: 14, 0,0,195
i, R,G,B: 15, 0,0,195
i, R,G,B: 16, 0,0,195
i, R,G,B: 17, 0,0,195
i, R,G,B: 18, 0,0,195
i, R,G,B: 20, 0,0,195
i, R,G,B: 23, 191,76,26

```

Sending color orange from Python:

```
[2018-07-23 16:29:20,725: WARNING/ForkPoolWorker-9] i, R,G,B: 0, 255,128,0
[2018-07-23 16:29:20,726: WARNING/ForkPoolWorker-9] i, R,G,B: 1, 255,128,0
[2018-07-23 16:29:20,727: WARNING/ForkPoolWorker-9] i, R,G,B: 2, 255,128,0
[2018-07-23 16:29:20,728: WARNING/ForkPoolWorker-9] i, R,G,B: 3, 255,128,0
[2018-07-23 16:29:20,729: WARNING/ForkPoolWorker-9] i, R,G,B: 4, 255,128,0
[2018-07-23 16:29:20,731: WARNING/ForkPoolWorker-9] i, R,G,B: 5, 255,128,0
[2018-07-23 16:29:20,732: WARNING/ForkPoolWorker-9] i, R,G,B: 6, 255,128,0
[2018-07-23 16:29:20,733: WARNING/ForkPoolWorker-9] i, R,G,B: 7, 255,128,0
[2018-07-23 16:29:20,734: WARNING/ForkPoolWorker-9] i, R,G,B: 8, 255,128,0
[2018-07-23 16:29:20,735: WARNING/ForkPoolWorker-9] i, R,G,B: 9, 255,128,0
[2018-07-23 16:29:20,736: WARNING/ForkPoolWorker-9] i, R,G,B: 10, 255,128,0
[2018-07-23 16:29:20,737: WARNING/ForkPoolWorker-9] i, R,G,B: 11, 255,128,0
[2018-07-23 16:29:20,738: WARNING/ForkPoolWorker-9] i, R,G,B: 12, 255,128,0
[2018-07-23 16:29:20,739: WARNING/ForkPoolWorker-9] i, R,G,B: 13, 255,128,0
[2018-07-23 16:29:20,740: WARNING/ForkPoolWorker-9] i, R,G,B: 14, 255,128,0
[2018-07-23 16:29:20,741: WARNING/ForkPoolWorker-9] i, R,G,B: 15, 255,128,0
[2018-07-23 16:29:20,742: WARNING/ForkPoolWorker-9] i, R,G,B: 16, 255,128,0
[2018-07-23 16:29:20,743: WARNING/ForkPoolWorker-9] i, R,G,B: 17, 255,128,0
[2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 18, 255,128,0
[2018-07-23 16:29:20,744: WARNING/ForkPoolWorker-9] i, R,G,B: 19, 255,128,0
[2018-07-23 16:29:20,745: WARNING/ForkPoolWorker-9] i, R,G,B: 20, 255,128,0
[2018-07-23 16:29:20,746: WARNING/ForkPoolWorker-9] i, R,G,B: 21, 255,128,0
[2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 22, 255,128,0
[2018-07-23 16:29:20,747: WARNING/ForkPoolWorker-9] i, R,G,B: 23, 255,128,0
[2018-07-23 16:29:20,749: WARNING/ForkPoolWorker-9] i, R,G,B: 24, 255,128,0
[2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 25, 255,128,0
[2018-07-23 16:29:20,750: WARNING/ForkPoolWorker-9] i, R,G,B: 26, 255,128,0
[2018-07-23 16:29:20,751: WARNING/ForkPoolWorker-9] i, R,G,B: 27, 255,128,0
[2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 28, 255,128,0
[2018-07-23 16:29:20,752: WARNING/ForkPoolWorker-9] i, R,G,B: 29, 255,128,0

```

Received color orange on the Arduino:

```
i, R,G,B: 0, 195,191,194
i, R,G,B: 1, 195,191,194
i, R,G,B: 2, 195,191,194
i, R,G,B: 3, 195,191,194
i, R,G,B: 4, 195,191,194
i, R,G,B: 5, 195,191,194
i, R,G,B: 6, 195,191,194
i, R,G,B: 7, 195,191,194
i, R,G,B: 8, 195,191,194
i, R,G,B: 9, 195,191,194
i, R,G,B: 10, 195,191,194
i, R,G,B: 11, 195,191,194
i, R,G,B: 12, 195,191,194
i, R,G,B: 13, 195,191,194
i, R,G,B: 14, 195,191,194
i, R,G,B: 15, 195,191,194
i, R,G,B: 16, 195,191,194
i, R,G,B: 17, 195,191,194
i, R,G,B: 18, 195,191,194
i, R,G,B: 19, 195,191,194
i, R,G,B: 76, 23,195,191
i, R,G,B: 194, 128,0,76

```

Received color orange on the Arduino (again):

```
i, R,G,B: 0, 195,191,194
i, R,G,B: 1, 195,191,194
i, R,G,B: 2, 195,191,194
i, R,G,B: 3, 195,191,194
i, R,G,B: 4, 195,191,194
i, R,G,B: 5, 195,191,194
i, R,G,B: 6, 195,191,194
i, R,G,B: 7, 195,191,194
i, R,G,B: 8, 195,191,194
i, R,G,B: 9, 195,191,194
i, R,G,B: 10, 195,191,194
i, R,G,B: 11, 195,191,194
i, R,G,B: 12, 195,191,194
i, R,G,B: 13, 195,191,194
i, R,G,B: 14, 195,191,194
i, R,G,B: 15, 195,191,194
i, R,G,B: 16, 195,191,194
i, R,G,B: 17, 195,191,194
i, R,G,B: 18, 195,191,194
i, R,G,B: 128, 0,76,24
i, R,G,B: 27, 195,191,194

```

Another Edit: What is also interesting is that the main color (e.g. when I send red most of the LEDs are yellow) stays the same every time I tried. But the amount of LEDs that gets passed differs with each try. The same goes for the last one or two LEDs the Arduino receives. Their colors and indexes are all over the place.

# Answer
This

```
...
  self.arduino.write(chr(76).encode()) # 'L'
  self.arduino.write(chr(i).encode())
  self.arduino.write(chr(rgb[0]).encode())
  self.arduino.write(chr(rgb[1]).encode())
  self.arduino.write(chr(rgb[2]).encode())
self.arduino.write(chr(90).encode()) # 'Z'
...

```

should be spelled:

```
  self.arduino.write(b'L')
  self.arduino.write(i.to_bytes(1,'big'))
  self.arduino.write(bytes(rgb))
self.arduino.write(b'Z')

```

It is much more readable this way; you could refactor even further:

```
  sout = b'L' + i.to_bytes(1,'big') + bytes(rgb)
  self.arduino.write(sout)
self.arduino.write(b'Z')

```

Your also wasting effort here:

```
Serial.println("i, R,G,B: " + String(i) + ", " + String(r) + "," + String(g) + "," + String(b));

```

This should be said more like this:

```
Serial.print(i);
Serial.print(", ");
Serial.print(r);
Serial.print(", ");
Serial.print(g);
Serial.print(", ");
Serial.println(b);

```

This eliminates three temporary String objects you were creating with String().

The rest of the code looks like it should work so you should try trouble shooting, you could:

* Lower the baud rate till it works
* Try 9600 baud and increase it until it stops working
* Try the a serial sample program, make sure the serial portion is working correctly first
* Write your own minimal test program, make sure the serial is working correctly at first.
> 1 votes

---
Tags: arduino-uno, rgb-led, python, led-strip
---


# Question
Title: How does Arduino memorize the last bytes from Bluetooth HC-05?
I have made a home automation project.

Description: Light on, off through HC-05 Bluetooth module and my Android app. The problem is when the power is gone, the system stops, that's OK. After that, when the power comes back, the system remains off, as because of no storage of the value.

Please any one help me, that how to store Bluetooth data on EEPROM on Arduino. My simple code looks like...

```
#include <EEPROM.h>
#define ledPin 7
int state = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);
  Serial.begin(9600); // Default communication rate of the Bluetooth module
}

void loop() {

  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
    Serial.println("LED: OFF"); // Send back, to the phone, the String "LED: ON"
    state = 0;
  }
  else if (state == '1') {
    digitalWrite(ledPin, HIGH);
    Serial.println("LED: ON");;
    state = 0;
  }
}

```

# Answer
Sir you didn't used EEPROM functions, you just initialized them. For example

if you use these function then your issue will be solved out..
> 0 votes

---
Tags: arduino-nano, eeprom
---


# Question
Title: Can't burn Bootloader on Atmega328P Using Arduino Uno
I'm trying to create an Arduino Uno following the circuit described in the diagram below which I'd based from here.

I'd tried this circuit on an Atmega328 PDIP version (with the correct connections since the PDIP has different pinouts from this TQFP) and I was successful in creating and using my own Arduino.

However, when I've used the TQFP version and had this circuit layout and printed on a pcb, I can't burn the bootloader using an Arduino UNO.

I've double checked the pinouts from the Atmega328P datasheet and they are correct. Using a tester, I've also verified that the connections are there.

By the way, I've used the following connections.

```
Arduino Digital Pin 13 to SCLK
Arduino Digital Pin 12 to MISO
Arduino Digital Pin 11 to MOSI
Arduino Digital Pin 10 to RESET
Arduino 5V to VCC
Arduino GND to GND

```

I've also burned the ArduinoISP program on th Arduino UNO, selected Arduino as ISP and chosen Arduino UNO as board.

When I press 'Burn Bootloader', I'm getting this error message.

```
avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

```

I've looked at different forums and they are only saying to check the connections which I'd already checked that there is.

# Answer
> 1 votes
I have had this problem in the past and it has always been one of two solutions

1. The wires **were** misconfigured, and I only saw it after the Nth time
2. Wrong chip, I was trying to program a 328 when it expected a 328p

And the secret third option:

3. Some chip/wire/etc. was busted/burned/bad.

Unfortunately These were the only outcomes to ever come for me when I encountered that particular error.

# Answer
> 1 votes
here is a Link... https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

If bootloader is burned with arduino uno in atmega328 then code will be uploaded for once and run correctly but next time you tried to burn code in atmega328 then code will not burn in atmega328. I also tried this way but it just work one time for me then I bought usbasp(price 1.5$) to burn bootloader permanently. after burning bootloader with usbasp then its works perfect for me. Just connect crystall with filtering capacitor thats enough to burn bootloader. above config is just in case you want to use it as MCU.

# Answer
> 0 votes
The design is missing 0.1uF caps on VCC, AVCC, and Aref.

Aref should not connect to 5V directly. It is connected internally thru a mux and only needs the 0.1uF to Gnd. If Aref is direct connected and then the sketch selects the internal 1.1V reference, it can/will damage the chip.

Change the 220 ohm resistor on D13/SCK to 1K. 220 ohm puts quite a load on the SCK line for a Programmer. 1K will result in a plenty bright LED.

Do you have a 0.1uF between DTR of a Serial programmer and the Reset pin? A Programmer needs direct control of the Reset line, a Serial programmer (such as an FTDI Basic module) needs to go thru a cap so a Reset pulse is created.

---
Tags: atmega328, bootloader
---