Two Arduino Control a LCD Display I´m building a system that has two arduinos (like the image on the botton) linked via ICSP. The "Programer"  programs the second one, called "Worker"( with a .hex file in the SD card of the Programer).

The Worker controls a LCD 16x4 and displays messages to the user.

What I´m tring to do is when the Programmer is programming the Worker it also displays a message like "Programming, wait" in the Worker LCD. But in code, just telling to the Worker displays a message is not going to happen because when it has been programmed it displays garbage in the LCD.

Q So is it possible the the Programmer takes control of the LCD before it begin to program the worker and displays its message?

The LCD works with normal 4-bit mode comunication and I would rather not converte it to I2C if it´s possible.

There are two solutions that come to my mind, one more HW based and another more SW based.

Solution 1

The HW way is to let the programmer control the LCD through 2:1 multiplexer(s). You will need to connect the LCD pins to the common pin of the multiplexer, the Programmer's ones to one of the two inputs and the Worker's to the other. Then the programmer can choose who controls the LCD through the additional pin. An example of the multiplexer you can choose is the 74LS157, but there are virtually infinite part numbers. The disadvantage of this approach is that you need to write the whole LCD control stack in the Programmer.

Solution 2

An alternative, more relying on the SW, is implementing a way to let the slave know that you want to program it. For instance, when a programming is needed the Programmer raises a pin; the Worker writes the string on the LCD, then stops working, raises another pin and waits to be cleared. The programmer then proceeds to flash the Worker, and the message will remain on the LCD. It may happen that garbage exits from the Worker's pins when being programmed. If so, change the enable pin or find a way to temporarily detach it from the Worker to avoid signals reaching the LCD. This schematic illustrates this concept:

simulate this circuit – Schematic created using CircuitLab

When the Programmer wants to program the unit, it sets the DL_Req pin to high. The Worker sees this, and performs accordingly. I think pins are not moved then, but if for instance some noise appears on the signals during programming (and the LCD displays this noise as weird chars), try changing the pin associated to the enable pins (LCD2 in the example above) or put something to prevent noise on that wire only, so that LCD content is not modified.

Personally I'd go with the second solution, but this depends on how much you can change the behavior of the worker and programmer


Using millis() and micros() inside an interrupt routine The documentation for attachInterrupt() says:

  ... millis() relies on interrupts to count, so it will never increment inside an ISR. Since delay() requires interrupts to work, it will not work if called inside an ISR. micros() works initially, but will start behaving erratically after 1-2 ms. ...

How does micros() differ from millis() (except of course for their precision)? Does the above warning mean that using micros() inside an interrupt routine is always a bad idea?

Context - I want to measure low pulse occupancy, so I need to trigger my routine when my input signal changes and record the current time.

The other answers are very good, but I want to elaborate on how micros() works. It always reads the current hardware timer (possibly TCNT0) which is constantly being updated by the hardware (in fact, every 4 µs because of the prescaler of 64). It then adds in the Timer 0 overflow count, which is updated by a timer overflow interrupt (multiplied by 256).

Thus, even inside an ISR, you can rely on micros() updating. However if you wait too long then you miss the overflow update, and then the result returned will go down (i.e you will get 253, 254, 255, 0, 1, 2, 3 etc.)

This is micros() - slightly simplified to remove defines for other processors:

unsigned long micros() {
    unsigned long m;
    uint8_t oldSREG = SREG, t;
    cli();
    m = timer0_overflow_count;
    t = TCNT0;
    if ((TIFR0 & _BV(TOV0)) && (t < 255))
        m++;
    SREG = oldSREG;
    return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
}

The code above allows for the overflow (it checks the TOV0 bit) so it can cope with the overflow while interrupts are off but only once - there is no provision for handling two overflows.

TLDR;

Don't do delays inside an ISR
If you must do them, you can time then with micros() but not millis(). Also delayMicroseconds() is a possibility.
Don't delay more than 500 µs or so, or you'll miss a timer overflow.
Even short delays may cause you to you miss incoming serial data (at 115200 baud you will get a new character every 87 µs).


How do I connect an accelerometer (GY-521) to a SparkFun Thing Dev (ESP8266)? All of the wiring diagrams I've found for wiring up a GY-521 accelerometer to an Arduino have looked something like this:

I've read in several places that it needs to be connected to A4 and A5. I want to connect one to a SparkFun ThingDev, which unfortunately only has a single analog input:

Is this possible?

I only need it for a very simple application (finding out if a machine is vibrating or not).

A4 and A5 on the Arduino double as the I2C pins SDA and SCL.  You are communicating with I2C, not analog.

The ESP8266 doesn't have I2C in hardware, but there is a software-based I2C implementation which can work on any pins.  The pinout you show has I2C labeled on pins 2 and 14. While you can use those you could use any two pins of your choosing.

Note that I2C on the ESP8266 has a slightly different begin function:

Wire.begin(2, 14);

That is where the pins you want to use are assigned - in this case, pin 2 for SDA and pin 14 for SCL.


Use Raspberry and Arduino IDE to programm ESP8266 I currently use Arduino IDE to generate binaries for ESP8266. Afterwards I copy the binaries with SFTP to my Raspberry Pi and flash the binaries using esptool.py.

These are lots of steps I need to do manually. Is it possible to automate this and use the Raspberry Pi as a programmer known to the Arduino IDE?

The goal is, that the "Upload" button in Arduino IDE does the full job.

Have you tried installing Python for Windows?

http://docs.python-guide.org/en/latest/starting/install/win/

In theory it should work and you should be able to run esptool.py on a Windows command line like you do on your Pi (provided that your usb to serial in recongnized by Windows).

If esptool.py fails to run under Python for Windows I would first suggest to open a ticket with the esptool maintainer and then try under a cygwin environement (https://www.cygwin.com).


Arduino port grayed out for Fake Board with CH340 I have downloaded and used Arduino IDE v1.8.4 from official site (needs no install) for windows10, and connected my random board with a ch340, but it's LED is only blinking and I can't select the port (ie. it's grayed).

I did test all USB ports and restarted my laptop but that didn't work!

I tried to install 1.6.9 IDE that I had before, but again the port option is unselectable!

This is my board:
http://uupload.ir/files/xgv_uno.jpg

Simplest possible thing would be that you do not have CH340g driver installed and you should try installing it first; These boards use CH340 for usb to serial and they need the driver to be installed; Please give it a try by getting the driver from the following link http://www.wch.cn/download/CH341SER_EXE.html or any other reliable source if there is any problem with the link;

If the board is not recognized even after that, it could be a bad USB port or a bad USB cable or even a board with the CH340 chip dead;


How do pins on an arduino mega 2560 work? I got a copy of Arduino from a local retailer here (it's a local copy and I'm pretty confused with how the pins actually work).

I know basic electronics so far, there should be two pins for every node one acting as the negative terminal and other as the positive terminal. If I were to connect an LED with my Arduino board which pins would I be utilizing?

Here let me tell you how pins are arranged on mine:

IOREF                                                                         GND

                                         13
RESET                                                                         12
3.3V     //this left group marked power                                        .
5V                                  //right group marked PWM                   2
GND            //right groupmarked communication                          TX0 -1
GND                                                                       RX0- 0

V1N                                                                       TX3-14
                                                                         RX2 -15
A0                                                                         ..
A1                                                                      SCL -21
..   //THIS left GROUP MARKED ANALOG IN
A7

A8
A9 //I believe it is part of the above group
..
A14
A15

     //the pins below marked DIGITAL
     52-50-`48-46...........................................................22`

there should be two pins for every node one acting as the negative terminal and other as the positive terminal.

No, there is one pin per node, and a common "Ground" pin which is the negative terminal. On your Mega2560 are 5 ground pins (effectively equivalent because they are connected). They are circled on the photo below, and marked GND on the board.

As Majenko says in his answer you must use a resistor in series with any LED you connect, or you will damage both the LED and the processor.

You may find a "breadboard" handy for making connections, most prototyping boards have a long connected strip for sharing the Ground wire between different places, like this:

The continuous blue lines indicate pins which are connected together (for Ground) and the continuous red lines are connected together for +5 V (usually).

  Btw can you tell me why there are two pins on the bottom horizontal row?

Just for convenience. You often want an extra ground pin, for example if you are trying to connect up two LEDs.

  Secondly, yes each pin can be set as input or output but is there any specific difference in the type of pins?

Some of the pins can optionally be used for extra hardware-supported features.

PWM: Pulse-width-modulated output
COMMUNICATION: Serial input/output (4 serial ports)
ANALOG IN: Analog-to-digital converter (ADC) input
DIGITAL: Digital (not analog) input/output
SDA/SCL: I2C communications
Pins 50-53: SPI communications (not marked on the board)

However all pins, as you noted, can - if you wish - be used for digital input or output.


Problem when using PROGMEM on array holding notes for speaker on Arduino The problem I've been having is a little weird. I'm trying to set up audio for my Arduino project and have been playing around with the example included in the IDE. The problem is whenever I try to make the array of notes go into PROGMEM, it makes the outputted note higher than the one I put in. I don't want it to do that.
In case it is relevant, the code I have is as follows:

    #define tuneSize 2
    // notes in the melody:
    const int melody[tuneSize] PROGMEM /*This is what's screwing it up*/= {
      NOTE_AS3, 0
    };

    // note durations: 4 = quarter note, 8 = eighth note, etc.:
    int noteDurations[tuneSize] = {
      6, 16
    };

    void setup() {
      // no need to repeat the melody.
      // iterate over the notes of the melody:
      for (int thisNote = 0; thisNote < tuneSize; thisNote++) {

        // to calculate the note duration, take one second
        // divided by the note type.
        //e.g. quarter note = 1000 / 4, eighth note = 1000/8, etc.
        int noteDuration = 1000 / noteDurations[thisNote];
        tone(8, melody[thisNote], noteDuration);

        // to distinguish the notes, set a minimum time between them.
        // the note's duration + 30% seems to work well:
        int pauseBetweenNotes = noteDuration * 1.30;
        delay(pauseBetweenNotes);
        // stop the tone playing:
        noTone(8);
    }
}

(Pitch.h can be found in the Arduino example tab under digital)

My circuit has an 8 ohm resistor on pin 8. That's it.

The only thing I can think is that since the PROGMEM is slower, the data doesn't get to the speakers as fast thus making the output weird. Does anyone know how to fix this issue? Also, just having it on SRAM is not ideal because I'm working with a display and the lib it uses uses a lot of SRAM.

You can not directly dereference something ("access an array") that is in flash memory. You have to use pgm_read_xxx functions from <avr/pgmspace.h> .

In your case you should probably write something like this:

tone(8, pgm_read_word(&melody[thisNote]), noteDuration);

Pgm_read_word reads two bytes. You could also call that inside your tone() function, the function would take the pointer in flash as an argument.

I would also recommend you using integer types from <stdint.h>, because they have defined sizes. Pure int is most likely 32-bit on your PC, but 16-bit on the AVR (I have learned this the hard way when my algorithm ran fine on the PC but gave totally junk output on the AVR).


Bluetooth OBD2 ELM327 connectivity issues I made a little project using an Arduino UNO, a 3.5" display, a HC-05 bluetooth module and an ELM327 (cheap ebay clone). I managed to establish communication, read the data, interpret and display it, but only one problem remains that keeps bothering me.

After some exchanges of data between Arduino and the OBD2 adapter, communication just drops.  I don't know if its from the HC-05 or ELM327. As far as I could debug it, the data from ELM327 comes incomplete. Usually the response from it, transformed into chars, is like "0103141 03 02 00 >" and I use the ">" char in the program as data exchange complete. When the problem occurs I receive fewer bytes from the OBD adapter and without the ">" char, something like "0103141 03 ".

I made a function that resets the HC-05 module and reconnects, but it takes a few seconds and I want my data to come as a continuous flow.

I tried a few methods of debugging, such as changing baud rate of the HC-05, and adding some delays, but I haven't come to a solution.

I believe that the problem might me one of these three:

The cheap ebay clone messing things up.
The HC-05 not sending the complete data.
A problem with my code.

Below I have attached the part of the code that does the sending of the command and reading the response. When the problem occurs, it gets stuck in the while loop because I have no terminating ">" char and I have to break it, call another function that re-establishes communication and so on.

So my question is: has anyone confronted this problem where ELM327 sends incomplete data that cannot be used?

 BTSerial.println("010F1");
 BTSerial.flush();
 delay(10);
  if (BTSerial.available()>0)
      busy = true;
  while(busy = true && inData != 62)
  {
      temp++;
      if (temp>500000){
          resetBT();
          BTSerial.println("ATWS");
          break;
      }
      if (BTSerial.available()>0){
          inData=0;
          inData = BTSerial.read();
          if(inData != 32) {
              buf[i] = inData;
              Serial.print(char(buf[i]));
              i++;
          }

      }

  }
Serial.println();
busy=false;
inData = 0;
i = 0;
memset(buf, 0, sizeof(buf));
temp = 0;

I managed to solve the issue. After some more testing, I ended up noticing that the problem was somehow the data exchange through the HC-05 bluetooth module. I changed it from being via SoftwareSerial library to the main serial com port and I had no issues since then. I don't know how that library may have caused the problem, but that was it.


Initialize a "Matrix" object in my own library? So, I'm trying to make a custom library to drive a 8x8 Bi-Color LED Matrix from 2 MAX7219's that incorporates two "Matrix" objects from the "Matrix" library and I cannot, for the life of me, figure out how to initialize them in my class. Can someone help me? By the way, I have been programming for 8 years, and consequently have a decent knowledge of the topic! Here is my current code:

header file

#include "Arduino.h"
#include "Matrix.h"
#include "Sprite.h"

class ZackBiColorMatrix{

    public:

        ZackBiColorMatrix(byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG);

        Matrix r;
        Matrix g;

        void setLED(byte col, byte row, byte val, char color);
        void writeSprite(byte x, byte y, Sprite sp, char color);

    private:

        byte redData;
        byte redLoad;
        byte redClock;

        byte greenData;
        byte greenLoad;
        byte greenClock;

};

and the .cpp file:

#include "Arduino.h"
#include "Sprite.h"
#include "Matrix.h"
#include "ZackBiColorMatrix.h"

ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG) {

    redData = dataR;
    redLoad = loadR;
    redClock = clockR;

    greenData = dataG;
    greenLoad = loadG;
    greenClock = clockG;

    r = Matrix (redData, redClock, redLoad);
    g = Matrix (greenData, greenClock, greenLoad);

}

void ZackBiColorMatrix::setLED (byte col, byte row, byte val, char color) {

    if (color == 'g') {

        g.write (col, row, val);

    }
    else if (color == 'r') {

        r.write (col, row, val);

    }

}
void ZackBiColorMatrix::writeSprite (byte x, byte y, Sprite sp, char color) {

    if (color == 'g') {

        g.write (x, y, sp);

    }
    else if (color == 'r') {

        r.write (x, y, sp);

    }

}

Also, I use the Eclipse Arduino IDE if that matters.

This is a C++ question actually.

In C++, you initialize class members in the class constructor definition by using a "member intialization list" as follows for your example:

ZackBiColorMatrix::ZackBiColorMatrix (byte dataR, byte loadR, byte clockR, byte dataG, byte loadG, byte clockG)
:   r(dataR, clockR, loadR),
    g(dataG, clockG, loadG) {
    ... Additional initialization here
}

This is a special C++ construct (note the colon : after the constructor declaration but before its implementation).

Also note that, in your example, I think you don't need to declare redData, redLoad, redClock, greenData, greenLoad, greenClock, sicne they are not being used once your 2 Matrix fields have been initialized.

Hence you could simplify your class further, I think.


How to properly reverse DC motor direction with 2 limit switchws Hello i am trying to reverse a dc motor direction upon hitting either limit switch. but noting is working can some one point me in right direction. all example i find use stepper motors and step count.

const int sw2 = 2;          //Up Limit switch
const int sw3 = 3;          //Down Limit switch
const int ic1_2 = 8;        //TA8409S IN2
const int ic1_1 = 9;        //TA8409S IN1
const int enable = 10;      //TA8409S Enable (motor)
int sw2State = 0;
int sw3State = 0;

void setup() {
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(ic1_1, OUTPUT);
  pinMode(ic1_2, OUTPUT);
  pinMode(enable, OUTPUT);
  digitalWrite(enable, 1);
  Serial.begin(9600);
}

void loop() {
  tilt_up();
}

void tilt_up()
{
Serial.print("up Started\n");
  digitalWrite(ic1_1, LOW);
  digitalWrite(ic1_2, HIGH);
  sw2State = digitalRead(sw2);
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
    Serial.print("sw2 pressde\n");
  }
}

void tilt_down()
{
  Serial.print("down Started\n");
  digitalWrite(ic1_1, HIGH);
  digitalWrite(ic1_2, LOW);
  sw3State = digitalRead(sw3);
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
    Serial.print("sw3 Pressed\n");
  }
 }

void loop() {
  tilt_up();
}

void tilt_up()
{
...
  if (digitalRead(sw2State == LOW)) {
    tilt_down();
...
  }
}

...

void tilt_down()
{
...
  if (digitalRead(sw3State == LOW)) {
    tilt_up();
...
  }
 }

You are recursing here. loop calls tilt_up which eventually calls tilt_down which calls tilt_up and so on until you - rather quickly - run out of RAM.

Rewrite so that you are not doing that.

Also see what @MikaelPatel told you in your other question. You have the brackets in the wrong place.

  if (digitalRead(sw2State == LOW)) {

should be:

  if (digitalRead(sw2State) == LOW) {


where is the digitalPinToInterrupt macro defined I am new to arduino, and it's confusing to me how you can just write code in the IDE and use functions or macros such as #define ISR() in the avr-libc library without having to include the header file in the arduino sketch. I was trying to find where digitalPinToInterrupt() is defined, but had no luck. Any idea?

Generally, if you want to find identifiers in your Arduino board support, you can run the ctags program on the libc and Arduino core files.  ctags is used as part of the build process in its effort to generate C++ declarations for you.  So it is generally available to you as an Arduino user.  You should find ctags or ctags.exe in:

/path/to/arduino15/builtin/tools/ctags/version-number/

This can be run against your board support in:

/path/to/arduino15/packages/vendor/hardware/architecture/version-number/

And your standard libraries found under directories in the form of:

/path/to/arduino15/packages/vendor/tools/compiler-tool/version-number/

If you're wondering what /path/to/arduino15/ would be on your system, it's documented here in terms of where the preferences file is stored.  The relevant paths containing and version numbers and architecture names should show in the verify/compile output when verbose mode is turned on in preferences.
Specific example
On my linux system with reasonably current versions of UNO-related things, my command-line would look like:
~/.arduino15/packages/builtin/tools/ctags/5.8-arduino11/ctags \
    -f /tmp/output-file \
    -R \
     ~/.arduino15/packages/arduino/hardware/avr/1.8.3/ \
    ~/.arduino15/packages/arduino/tools/avr-gcc/4.8.1-arduino5/avr/include/

The resulting tag file can then greped or just opened and the following entries can be found, showing the filenames and line numbers to investigate:
DigitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/circuitplay32u4/pins_arduino.h   138;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/ethernet/pins_arduino.h  79;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/gemma/pins_arduino.h 64;"    d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/leonardo/pins_arduino.h  160;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/mega/pins_arduino.h  110;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_control/pins_arduino.h 120;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/robot_motor/pins_arduino.h   115;"   d
digitalPinToInterrupt   /home/user/.arduino15/packages/arduino/hardware/avr/1.8.3/variants/standard/pins_arduino.h  79;"    d

In the case of an UNO the standard variant is the significant declaration.

There are different implementations of ctags.  The one used by the Arduino support files is Exuberant CTAGS and you may want to read its documentation, to learn how to control the program to display differently to only search for specific identifiers, etc.  It is also typically used with editors that have some special support for the resulting tags file, to jump to definitions, like an IDE would.


Im having another problem with my code the error is "redefinition of 'AF_DCMotor motor'? Heres the code

#include <AFMotor.h>

AF_DCMotor motor(1, MOTOR12_8KHZ);
AF_DCMotor motor(2, MOTOR12_8KHZ);
AF_DCMotor motor(3, MOTOR34_1KHZ);

void setup()  {
  Serial.begin(9600);
  Serial.printIn("Motor Test!");
  motor1.setSpeed(15); //set speed of motor
  motor2.setSpeed(15); //set speed of motor
  motor3.setSpeed(15); //set speed of motor

}
void loop() {
  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(5000);

  Serial.print("tack"); //first song starts
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor1.run(RELEASE);
  delay(9000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song ends
  motor1.run(RELEASE);
  delay(20000);

  Serial.print("tick");
  motor1.run(FORWARD);
  delay(2000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(5000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(BACKWARD);
  delay(2000);

   Serial.print("tock");
  motor2.run(FORWARD);
  delay(1000);

  Serial.print("tick");
  motor2.run(RELEASE);
  delay(1000);

  Serial.print("tick");
  motor2.run(FORWARD);
  delay(2000);

  Serial.print("tack");
  motor1.run(BACKWARD);
  delay(2000);

  Serial.print("tock"); //first song stops
  motor2.run(RELEASE);
  delay(14000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(11000);

  Serial.print("tick"); //first song stops
  motor3.run(FORWARD);
  delay(22000);

  Serial.print("tock"); //first song stops
  motor3.run(RELEASE);
  delay(19000);
}

Here is the error:

   ^~~~~~

   motor

snowmanDC_Motor:13:3: error: 'motor3' was not declared in this scope

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:13:3: note: suggested alternative: 'motor'

   motor3.setSpeed(15); //set speed of motor

   ^~~~~~

   motor

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino: In function 'void loop()':

snowmanDC_Motor:18:3: error: 'motor1' was not declared in this scope

   motor1.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:18:3: note: suggested alternative: 'motor'

   motor1.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:47:3: error: 'motor2' was not declared in this scope

   motor2.run(FORWARD);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:47:3: note: suggested alternative: 'motor'

   motor2.run(FORWARD);

   ^~~~~~

   motor

snowmanDC_Motor:115:3: error: 'motor3' was not declared in this scope

   motor3.run(RELEASE);

   ^~~~~~

C:\Users\serluca\Documents\Arduino\snowmanDC_Motor\snowmanDC_Motor.ino:115:3: note: suggested alternative: 'motor'

   motor3.run(RELEASE);

   ^~~~~~

   motor

exit status 1
redefinition of 'AF_DCMotor motor'

Adafruit has a V1 and a V2 motor shield. They have different libraries too. AFMotor.h is for the V1 shield. From the error, I can tell you installed V2 lib. For that you need to include:

#include <Adafruit_MotorShield.h>


Why is there a limitation in using Serial.println on ESP8266? I'm trying to upload this code on ESP8266, and when I do, it just resets continuously.  This also happens when you have memory bugs, but obviously, this code has no memory bugs!  Here is the code:

#include "Arduino.h"

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

void loop()
{

}

void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
    }
}

Also, in the serial monitor, I get this (per reset):

Soft WDT reset

ctx: cont
sp: 3ffef130 end: 3ffef390 offset: 01b0

>>>stack>>>
3ffef2e0:  feefeffe feefeffe feefeffe 00002580
3ffef2f0:  0000001c 00000001 3ffe85b1 402023d4
3ffef300:  feefeffe 00000005 3ffe842d 3ffee364
3ffef310:  3fffdad0 00000006 3ffee340 40201fd1
3ffef320:  3ffe85b0 00000000 3ffee340 40201fd1
3ffef330:  3ffe8428 00000000 3ffee340 40201fec
3ffef340:  00000001 feefeffe 3ffee340 40202010
3ffef350:  feefeffe 00000000 00002580 40201c00
3ffef360:  3fffdad0 00000000 3ffee35c 40201c2e
3ffef370:  feefeffe feefeffe feefeffe 402021c8
3ffef380:  feefeffe feefeffe 3ffee370 40100718
<<<stack<<<
Õ®(ŽL‰Ì==   I5

So, why is this happening?

It's happening because you're not giving the ESP8266 a chance to do its housekeeping activities and the watchdog (which is enabled by default) is timing out - as evidenced by the very first line of your output:

  Soft WDT reset

You need to allow the MCU to do other things at the same time as you are printing to serial:

void foo(){
    for(unsigned int i = 1; i <= 10000; i++){
        Serial.println("FOOBAR");
        yield();
    }
}


Is there any version of arduino that can do something like serial interruption? I am using an Arduino to control servo MX18A by serial, and trying to use computer to communicate with the Arduino by another serial to send commands to Arduino and change the servo control mode. Once the computer send a message to Aruduino, I hope it could response in time because may be there is something emergency like the servo being out of control ,under which circumstance I have to change the control strategy in time.

However, it seems like Arduinos like UNO, MEGA does not have serial interruption, so once the message from computer comes, it could not response in time.

I know that judging serial.available() in every loop is one solution, but in my different servo control strategy there are many time delays, for loops and while loops, which means that I have to put serial.available() in every time delay or for loops, making the code hard to write and maintain.

It is not a case of "An Arduino" that can do serial interupts. All Arduino boards have serial interrupts, but they are already used to receive the data and store it in a buffer for you to consume when you have the time.

The Arduino API does not define any serial interrupt handling routines. That kind of thing is designed to be handled internally by the API code, not by the user. That's the whole point of the Arduino API - to abstract away such technicalities from the user.

If you want to use the serial interrupt yourself you will have to write your own serial handling code.

Or write your code in such a way that serial interrupts aren't needed.


arduino pro mini analog pins read different values i need to read a voltage with an arduino pro mini using the analog pins.

I created this simple test code:

int sensorValue;
float voltage;

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

void loop() {
  sensorValue = analogRead(A0);
  voltage= sensorValue * (5.0 / 1023.0);
  Serial.println(voltage);
}

my setup looks like this:

everything works so far. I get about 4,5v as a result. Now i want to port everything to an arduino pro mini. After i did that i only got 2,5v as a result. I also tried it with different pins and with an other arduino pro mini.

So what did i do wrong? Do i need an other pull-up resistor?

I made a circuit bellow for you. Note that the top resistor is 100 ohm and the bottom one is only 10 ohm. What I did is called a voltage divider. This way you can read voltages up to 50V. Simply connect the positive of your power source that you want to measure to the red wire and the ground of that same source to the black wire.

I also included a code that you could use:

Please notify me if any mistakes were spotted.

#define sensor A0 //defining sensor pin

float resistor1 = 100; //you can change it if you want, just make sure you also do it on the circuit
float resistor2 = 10;

float Vmax = (5*resistor1 + 5* resistor2)/resistor2;

void setup() {
  pinMode(sensor, INPUT); //declaring sensor as an output
  Serial.begin(9600);

  Serial.print("Do not input more then (V) : "); // print max input voltage
  Serial.print(Vmax);

  Serial.println(); //skip line
}

void loop() {
  float V = analogRead(sensor); //measuring analog values

  V = analogRead(sensor) * Vmax / 1024

  Serial.println(V); //printing voltage
}


Smooth servo control library Is anyone aware of an Arduino library for smoothly controlling a servo?

I have an especially fast servo, which is trivial to control using Arduino's built-in Servo library. However, the library doesn't support proportional control. You specify a position, and the servo immediately goes to that position as fast as it can. With my servo, that creates incredibly fast jerky motion.

I've found some algorithms for interpolating a smooth servo motion by generating small incremental changes to the signal over time. I've been able to translate this to some Arduino code, and although the motion is much slower, it's still very jittery.

I've search for pure Arduino implementations, but I've not found anything. Does anyone know of an implementation? I find it hard to believe no one else has faced this type of servo control problem with an Arduino before.

Infortunately, I did not find any library but I found that the method shown below could work quite well for small projects. By adding a small delay, it helps the servo run a little smoother. It is not really ideal but it should work if your goal is to minimize the roughness of the servo.

Also by adding a 100uF capacitor between 5V and GND, the capacitor will help calm the sudden rush you might get when the servo first starts to turn. That rush is caused by the servo asking for more current when the servo is not moving.

#include <Servo.h>   //servo library
Servo myservo;       //servo object
int previousAngle = 0;

const int potPin = A3; //sensor pin

void setup() {
  myservo.attach(9);  //data pin of the servo
  pinMode(potPin, INPUT); //sensor pin as an input
}

void loop() {
  int val = analogRead(potPin);
  int angle = map(val, 0, 1023, 0, 180);

  if(angle>previousAngle)
  {
    for(int i=previousAngle; i<=angle; i++)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  if(angle<previousAngle)
  {
    for(int i=previousAngle; i>=angle; i--)
    {
      myservo.write(i); //turn servo by 1 degrees
      delay(10);        //delay for smoothness
    }
  }

  previousAngle = angle;
}


Printing the messages having problem in SIM 900A to Arduino I have added my Arduino code for reading messages from GSM SIM900A using Arduino. But the output is showing something different. Please help me.

#define SERIAL_BUFFER_SIZE 256

char msg;
void setup() {
  Serial.begin(9600);   // Setting the baud rate of GSM Module
  delay(60000);
  Serial.println("AT");
  delay(1000);
  Serial.println("AT+CREG=1");
  delay(1000);
  Serial.println("AT+CMGF=1"); // set SMS mode to text
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  Serial.println("AT+CMGR=\"ALL\"");
  delay(1000);
  while ( Serial.available() > 0) Serial.read();  // removing serial buffer values
  Serial.println("AT+CMGR=1");
  delay(2000);
}

void loop() {
  while (Serial.available() > 0) {
    msg = serial.read()
    Serial.print(msg);
  }
}

This is the output:

+CMGR: "REC READ","+91xxxxxxxxxx","","16/07

Hello Guys i found the issue. Serial.read() function reads only 62bytes. After i have update the serial buffer size in library file C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\HardwareSerial.H ... It shows the messages which is stored in serial buffer.


What is the correct way to interpret the built-in Analog-to-Digital Converter output? When using the built-in analog to digital converter of the Arduino Uno Rev 3's Atmega328P with a reference voltage of 5V, what is the appropriate function to interpret the output? There is conflicting information on the Arduino website and in the datasheet for the Atmega328P (Arduino Uno Rev 3's chipset).

A lot of code examples on the internet indicate that the appropriate conversion factor is 5V/1023 (including the Arduino website: float voltage= sensorValue * (5.0 / 1023.0);).

Per the Atmega328P's datasheet, it indicates the conversion factor is 5V/1024:

If Vin and Vref are 5V, then the ADC reading would need to be 1024 in order to have a true reading of 5V, which is not possible since 1023 is the max output of the ADC. The closest reading to 5V we can get from this equation is ~4.9951 (5V*1023/1024).

With the Arduino example's conversion factor of 5V/1023, we get 5V for an ADC output of 1023.

Additionally, since the information from both sources is in conflict, it got me thinking a little more: The ADC is inherently sampling, and I am not sure if the ADC rounds up/down to the nearest value, so perhaps the closest approximation of Vin is an equation like the following that splits the difference:

Vin = (ADC+(ADC+1))/2 * 1024/Vref

Using the above equation, an ADC reading of 0 with Vref=5V would give Vin = (0 + (0+1))/2 *1024/5V = ~0.00244. This equation never gives a reading of 5V or 0V, but rather a value that splits the difference between samples.

Perhaps I am splitting hairs since the absolute accuracy of the ADC is "±2 LSB absolute accuracy", but I would still like to know which is the best equation to convert an output from the ADC into a voltage measurement.

the Atmega328P's datasheet, it indicates the conversion factor is
  5V/1024 [...]

Indeed. And the datasheet is the only authoritative source. All the
other sources are second-guessing.

  If Vin and Vref are 5V, then the ADC reading would need to be 1024 in
  order to have a true reading of 5V

You can't get a true reading of 5 V. As per the datasheet (emphasis
mine): “0x000 represents analog ground, and 0x3FF represents the
selected reference voltage minus one LSB”.

Any input voltage larger that the maximum representable voltage will
read as 0x3ff (i.e. 1023), just like any negative voltage (within
the forward voltage of the protection diode) will read as zero. Thus,
reading either 0 or 1023 should be interpreted as a saturation
of the ADC, meaning the actual voltage is unknown.

  The ADC is inherently sampling, and I am not sure if the ADC rounds
  up/down to the nearest value

In principle it should round to the nearest value. The transition in the
reading from 0 to 1 should ideally happen at
Vref/2048. C.f., again, the datasheet, subsection “ADC
Accuracy Definitions”: “Offset: The deviation of the first transition
(0x000 to 0x001) compared to the ideal transition (at 0.5 LSB).”

A little bit further in the page it is stated that the ideal position of
the last transition (1022 to 1023) is “at 1.5 LSB below maximum”.

  Perhaps I am splitting hairs since the absolute accuracy of the ADC is
  "±2 LSB absolute accuracy"

Indeed. If you really care you should probably calibrate your ADC. See
Response of the Arduino ADC.

Edit: in a comment you mention that the factor 1024 could
conceivably be “a persistent typo that it appears in multiple AVR
chipset datasheets”. It may be an error, but certainly not a typo, as
the datasheet contains multiple independent statements that confirm the
factor 1024.


Seeking to measure back EMF of an electric motor via Arduino Is it possible to measure the back EMF of a motor, using just the Arduino and no sensors?

Or what type of sensor do I need? One that measures current?

There is no need to measure the windings of the motor... please see the great write up for full details using an Arduino to sense the back EMF on a PWM driven motor to control the speed. This can be applied to a 3 phase motor as well, see Back EMF.

This person uses the analog input and a voltage divider to sense when the EMF happened, basically he gets the motor running, then periodically grounds one side of the motor through the H-Bridge he is using to drive it, and the other side of the  motor goes to a voltage divider into the Arduino... and it is also an open circuit at this time so the voltage generated is from the collapsing of the coil field so if it is 12V it becomes a safe 4V at the Arduino Analog input.

Now your question says "measure the back EMF", what I provided senses the back EMF... to measure it you just need to sample the Analog pin a bunch of times, and that will give you a reference of the max amplitude.


Unable to interface AD7705 (SPI) with Arduino Code as shown below. I am unable to get the 16-bit data. Can someone help me identify my mistake?

byte spiTransfer(volatile byte data) {
  SPDR = data;
  while (!(SPSR & _BV(SPIF)));
  return SPDR;
}
#define DOUT      (50)
#define DIN       (51)
#define SCLK      (52)
#define CS_AD7705 (53)
#define DRDY (4)

void setup() {
  Serial.begin(9600);
  pinMode(DOUT, OUTPUT);
  pinM ode(DIN, INPUT);
  pinMode(SCLK,OUTPUT);
  pinMode(CS_AD7705,OUTPUT);
  pinMode(DRDY,INPUT);
  SPCR = _BV(SPE) | _BV(MSTR) | _BV(CPOL) | _BV(CPHA) | _BV(SPI2X) | _BV(SPR1) | _BV(SPR0);
  delay(10);
  digitalWrite(CS_AD7705, LOW);
  spiTransfer(00010000); //setup register
  spiTransfer(01100110);
  spiTransfer(00100000); //clock register
  spiTransfer(00001000);
  digitalWrite(CS_AD7705, HIGH);
}

void loop() {
  unsigned int data=0;
  digitalWrite(CS_AD7705,LOW); // enable device
  while(!digitalRead(DRDY));
  data = spiTransfer(00111000);  // select ch1 and setup read 16-bit data register
  data = spiTransfer(0)<<8;
  // Get the most significant 8 bits
  Serial.println("data : "+data);
  data |= spiTransfer(0); // Get the least significant 8 bits
  digitalWrite(CS_AD7705, HIGH); // release device
  delay(1000);
  Serial.println(data, HEX);
}

I think the main problem is the values you are passing to spiTransfer().  By the way they are written I think you think you are passing binary values, you aren't you are passing decimal values.  So

data = spiTransfer(00111000);  // select ch1 and setup read 16bit data

should be

data = spiTransfer(B00111000);  // select ch1 and setup read 16bit data

The number needs prefixing with a B

Also passing a volatile parameter to this function looks wrong to me, especially when you only pass in constants.


Where this function is defined? This is the code for timer example in esp8266..(got from a website)

My doubt is where the function   timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE)  is defined ??
I am look in Ticker.cpp, but not found.

#include < ESP8266WiFi.h>
#include < Ticker.h >

Ticker blinker;

#define LED 2  //On board LED

//=======================================================================
void ICACHE_RAM_ATTR onTimerISR(){
    digitalWrite(LED,!(digitalRead(LED)));  //Toggle LED Pin
    timer1_write(600000);//12us
}

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

    pinMode(LED,OUTPUT);

    //Initialize Ticker every 0.5s
    timer1_attachInterrupt(onTimerISR);
    timer1_enable(TIM_DIV16, TIM_EDGE, TIM_SINGLE);
    timer1_write(600000); //120000 us
}

void loop()
{
}

Those functions have nothing to do with the Ticker library. Those functions are defined in the ESP8266 core.

The example you cite has this at the top of it:

  Hardware Timer0 is used by WiFi Functions. We can use only Timer1. Use of timer instead of Ticker gives advantage of precision timing and You can get timer interrupt in micro seconds.

Note the use of "instead of Ticker" there. That says that the code below has nothing to do with Ticker.


No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code I followed this tutorial for a demo code for the SR04 ultrasonic distance sensor (without the LCD display). I've installed the Arduino IDE and wrote the code in it and saved it in some location. Compilation of the code is successful. However when I try to upload the code, I get the message:

Invalid library found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469: no headers files (.h) found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469

There are no header files in the directory and I'm wondering if I need to download additional header files or if I should configure something else.

If the folder is not needed then delete it.

The Arduino IDE uses the folders in the library folder to search for library header files (ie. .h files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.


Can ESP8266 replace Arduino? I’m a hobbyist and have used Arduino so far for simple projects. Now I want to build a project involving addressable LEDs, I want to write several programs on the Arduino for the LEDs and on my phone I select which ones to run.

I found ESP8266 as a good and cheap solution to talk to my Arduino. Searching on the web to learn getting it to work I found that It has its own mcu on it and I can write and upload my code in Arduino IDE! 20kB of RAM, 80MHz CPU and 4MB of flash for 3 USD (However I’m not sure of these numbers but even one fourth of it is great)!! If I just need a few GPIOs why should use an Arduino UNO? Is this module reliable?

Well, the answer of the question "Can it replace Arduino" - yes, in many cases it can.
Whether it would be "the Arduino killer" - I doubt it.
There are multiple arduinos and ESPs in my home and 1 ESP in my office running 24/7 as a part of my self-made (and constantly under development) smart home solution, together with 1-2 PCs. On top of that I have several experiments / unfinished projects involving the ESP.
So, from my not-so-limited experience, here are the pros and cons of ESP compared to Arduino:

++++ Internet connectivity built in!
++ Faster clock and more memory.
+ Runs on 3V3 (most, but not all Arduinos are 5V) so it can interface 3v3 devices (like most of the display modules) directly, without level shifters.
+ The "basic" ESP-12E costs about as much as an Arduino nano or pro micro.

- The "basic" ESP-12E is 2.0mm pitch, not 2.54mm, making it a pain in the ass to work with.
- There are breakouts that make it easier for prototyping, but they increase the cost and take too much space on a breadboard / protoboard.
- The most common breakout - NodeMCU - is more expensive and has pins remapped, major annoyance, unless you program it in Lua, which is only ok for very simple projects. IMO, it should be used for prototyping only.
- They run on 3v3, making it hard to interface 5V modules, fully turn on most MOSFETs, etc.
- They are extremely picky on their power supply.
- They draw significantly more power than the Arduino when not transmitting and much more when transmitting.
- They are almost always worse for battery operated projects - you need 3v3 regulator (which has quiescent current), you need to sleep a lot (and you need GPIO16 broken out for that) and at the end of the day an arduino + a low-power radio will do the same job while lasting significantly longer on battery.
- They have less GPIO pins and some of them must have set voltages at startup (GPIO0 - high, GPIO2 - high or floating, GPIO15 - low), also they "wiggle" some of their IO pins on startup, often making them unusable for many devices.
- They only have one ADC, and to my knowledge it is slower than the already slow Arduino ADCs, plus you can only use it with 0-1.1V (internal reference).
- Many of the Arduino libraries work out of the box or are already ported, but many don't. You either have to port them yourself or wait for someone to do it. In general, the Arduino community is much bigger and more mature, so most "noob-friendly" tutorials, libraries, etc. are provided for the Arduino.

Having that said, the ESP8266 is still great and extremely useful. Even Lua is useful for quick small projects. In most cases where internet connectivity is required, they seem to be the best solution. In many other cases, whether you will use ESP or Arduino actually doesn't matter. And sometimes the Arduino (or the little ATTiny85) is the better choice.
As always, "the right tool for the job" is the way to go.
Or combination of tools.


Can I have more than 1 pin "activated" at the same time? I have a group project in school. My group mates want an alternate blinking, rapid blinking and fading LEDs in our project. The thing is they want it to go simultaneously. Is there anyway I can do that?

If you change each led in order they will change fast enough that you cannot tell. The lag between changes will be on the order of microseconds.

If you want to dive into direct port manipulation you can change multiple leds at the same time. Though not all at the same time instead they are grouped.


power nodemcu with battery and LDO, what if battery is empty? I've read a lot but im still confused..
i want to battery power my nodemcu while it will be mostly deep sleeping and waking up every 1-2 minutes.
i've seen the best way to power it with the least wasting power is though a lithium battery.
so i've bought a 18650 rechargable battery and a MCP1700 LDO which will give me constant 3.3V, that ill connect straight to 3.3V pin and bypass nodemcu's regulators as i understand from here
My question is: if all the previous are correct, what will happen when 18650 batter power fall down the 3.5V (3.3V + 0.2V (from MCP1700 dropout))
Will it stop automatically giving power at all? Will it provide less than 3.3V but it will harm nodemcu?

As with any electronics, once you get outside of normal operating parameters, behaviour becomes undefined. It's up to you to avoid that.

The smartest thing to do is to employ a battery protection circuit or some means to shut down the system (or prevent it from waking up from deep sleep) before the voltage drops too low. This will also prevent your battery from damage by overdischarging it.

The ESP's minimum operating voltage according to its datasheet is 3.0V. Below that, behaviour is undefined but you can expect unreliable operation, crashes or even permanent damage. If you're writing to Flash memory when below the minimum voltage, the Flash might become corrupted (including the program the ESP is running).


Use Print library to set string variable I need a function that has the basic functionality of the Print library, accepting different kinds of argument types and parsing them. However, I would like to then store the result in a string/char array. Does anybody know how I might utilize the Print library to do so?

You can get all the functionality of Print by creating your own class
that inherits from it. For this, you only need to implement the
size_t write(uint8_t) method that prints a single character. Here is a
simple class that inherits from both Print and String, i.e. you get
a String you can print() and println() into:

// A String you can print() and println() into.
class PrintString : public Print, public String
{
public:
    PrintString() : String() {}

    size_t write(uint8_t c) {
        *this += (char) c;
        return 1;
    }
};

And here is how you could use it:

PrintString answer;
answer.print("The answer is ");
answer.println(42);


Using a toggle switch to run part of a sketch First, I am a beginner for this.  I just ordered my first book on coding Arduino and I'm working through some simple applications using a DS3231 (that has a temperature reading), LCD, MicroSD card module, etc.  My board is a Uno R3.  Currently, I need a sketch to run part of a program which contains a loop to collect data and have this run when a toggle switch is turned on.  So, toggle goes on and part of program runs, toggle goes off and this part exits.
The reason I need a toggle with constant on/off is the problem with G forces and vibration.  I momentary push button input will not be reliable.  Ultimately, all the components will be in a amateur high-power rocket to run a roll control program.
If you can help, I greatly appreciate your assistance.

There are different ways to accomplish the same thing.

The condition is a flag, or a read port.

if(digitalRead(inPin))
     {
     // Your first code here.
     }
else
     {
     // second code
     }

Switch contacts will bounce when opening or closing. You may want to consider that. Usually it is stable within 10 milliseconds. Depending on what you are doing it may or may not be relevant.


Compiling for Wemos D1 mini with Visual Studio Code I'm giving Visual Studio Code (VSC) a try and am getting unexpected results. I have a program (sketch) that compiles fine in the Arduino IDE. I create a workspace in VSC, initialize the project, and after some more mucking about I get a compile there appears to succeed:
[Done] Finished verify sketch - RanchMonitor2.ino

But the console pane shows four "problems":

How can the compilation have succeeded if there are problems?
The same sort of thing is happening with one of the samples - HelloServer.ino
In this case the problems are an incomplete type and memcpy_P not defined.
I wouldn't think it should make a difference, but I'm working without a board physically attached to the USB port.
UPDATE:
I think "Problems" are issues identified by Intellisense. They appear even before a compilation is attempted. All I have to do is open the workspace and wait a few seconds, then the "problems" appear. Hence my conjecture they are Intellisense warnings, not compilation errors.
Adding "ESP8266" to the Defines section of c_cpp_properties.json got rid of the error "WiFiManager" is undefined.

Intellisense reports "Problems" - these are distinct from compile time errors. Just because Intellisense can't resolve a literal or something doesn't mean it won't be resolved in the compiler; thus it's possible to have the IDE report a problem but still be able to have a successful compile. In the case described above, two changes to the c_cpp_properties.json file provided Intellisense with the information it needed. A header file was added to the forcedInclude section to provide pin definitions. A literal "ESP8266" was added to the defines section to indicate the processor type. This define is used in lots of header files so it must be know to Intellisense when reading the headers. Here are the relevant sections of that .json file:
        "forcedInclude": [
            "C:\\Users\\David\\AppData\\Local\\Arduino15\\packages\\esp8266\\hardware\\esp8266\\2.7.1\\variants\\d1_mini\\pins_arduino.h"
        ],
        "defines": [
            "USBCON",
            "ESP8266"
        ],


Arduino Mega, PWM analogWite doesn't work with Timer interrupt Can anybody explain me, why the PWM doesn't work in such a simple example?

Generally, Timer interrupt is being called once per 100 ms and then in the interrupt function the bool flag (state ) is being set. Then in the main loop the flag is checked and when it is 1 (true) several instructions are being executed. Next, PWM is generated and measured via ADC and also displayed on the LCD.

The problem is that the PWM is generated as 0 or sligthly over the 0, even when the value put to the  analogWrite is 255 (max of 8 bit). Variable counter is incremented without problems and this value is being put to the analogWrite and despite it the PWM doesn't work.

I don't know, totally, what can be wrong.

Can anybody help me?

 #include<LiquidCrystal.h>
 #include<TimerOne.h>

  LiquidCrystal lcd(52, 50, 48, 46, 44, 42, 40);

  int out = 12;
  int in = A7;
  volatile bool state;

  int counter = 0;
  volatile int y;

  void setup()
  {
    lcd.begin(16, 2);
    lcd.clear();
    pinMode(out, OUTPUT);
    pinMode(in, INPUT);

    analogReference(DEFAULT);
    Timer1.initialize(100000);
    Timer1.attachInterrupt(functionInterrupt);

     state = 0;
      y = 0;
   }

   void loop()
   {
     y = analogRead(in);
     y = y / 4;
     y = y - 128;

    if (state == 1)
    {
      state = 0;

      counter++;
      if (counter > 255)
      //counter = 0;
      counter = 200;

      //state = 0;
     }

      analogWrite(out,counter);

      lcd.home();
      lcd.setCursor(0, 1);
      lcd.print(counter);
      lcd.setCursor(12,1);
      lcd.print(y);
     }

    void functionInterrupt()
    {
      state = 1;

     }

When you use a timer to generate an Interrupt Service Routine (as you do with the TimerOne library) you change the configuration of that timer (in your case timer1). The timer is used by the TimerOne library to provide an interrupt, but also by the microcontroller itself to produce a PWM signal on some pins depending on the timer: in your case (Arduino Mega, timer 1) on the 11 and 12. If you use one of these pins as "analog" output while controlling an ISR with the same timer you won't get the expected output, because the timer isn't any more configured as needed by the PWM generation mechanism but as needed by you (you changed the configuration of the timer in the Timer1.initialize(100000); function call).

So, either you use another PWM pin as output either you use a timer library which uses another timer (or you implement it by yourself).


Sending data to a webserver with GPRS/GPS Shield (U-blox Sara G-350) I am working on a project for tracking cars. I am using an Arduino UNO to receive the position from GPS/GPRS shield. I am OK on obtaining the coordinates position.
Now I need to send the position to a webserver and then show it on a webpage using the Google Maps API. Which accepts it in a POST or GET method.
Here is the shield model:
U-blox Sara G-350
and this is its manual here

Here is my approach:

#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial gprsSerial(7 ,8);

void setup() {
  // put your setup code here, to run once:
  gprsSerial.begin(19200);
  Serial.begin(19200);
  delay(2000);

 gprsSerial.println("AT+CGDCONT=3,\"IP\",\"weborange\"");
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UHTTP=2,1,\"www.navtec.16mb.com\"");
                   //AT+UHTTP=<profile_id>,<op_code>,<HTTP_server_name>
 toSerial();
 delay(2000);

 gprsSerial.println("AT+UHTTP=0,5,80");
 toSerial();
 delay(2000);

}

void loop() {

 //gprsSerial.println("AT+UHTTP=2,1,\"submit\"");
                    //AT+UHTTP=<profile_id>,<op_code>,<param_val>[,<param_val1>]
 //toSerial();
 //delay(2000);

 gprsSerial.println("AT+UHTTPC=2,1,\"/add.php\",\"filename\"");  //Problem here!!!!!!!!
                   //AT+UHTTPC=<profile_id>,<http_command>,<path>,<filename>[,<param1>[,<param2>[,<param3>]]]
 toSerial();
 delay(2000);
}

void toSerial()
{
  while(gprsSerial.available()!=0)
  {
    Serial.write(gprsSerial.read());
  }

}

This is what I get:

  +CGDCONT=3,"IP","weborange"

  OK
  +UHTTP=0

  OK
  +UHTTP=2,1,"www.navtec.16mb.com"

  OK
  +UHTTP=0,5,80

  OK
  +UHTTPC=2,1,/add.php,filename

  ERROR
  +UHTTPC=2,1,/add.php,filename

  ERROR
  +UHTTPC=2,1,/add.php,filename

  ERROR
  +UHTTPC=2,1,/add.php,filename

  ERROR ...

Thanks for your time, I am waiting for your support, any ideas could help. Sorry for my bad English

I worked on a project similar to yours. I think you forgot to establish a connection first.
Just add those lines of code at the top of setup() method:

 gprsSerial.println("AT+UPSDA=2,0"); //Reset connection
 toSerial();
 delay(2000);
  gprsSerial.println("AT+UPSD=2,1,\"weborange\""); //Establish a new one
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSDA=2,3");
 toSerial();
 delay(2000);
 gprsSerial.println("AT+UPSND=2,0");
 toSerial();
 delay(2000);

I hope it works for you. Else, you can use AT+UHTTPER=2 after all to check for error source.


cannot connect ESP8266 web server after some time I am new to ESP8266 and found an example about turning a LED ON/OFF using web interface. It works well but after some time (few minutes) i cannot open the web page (in my case it is http://192.168.100.23 and i made it static IP). It keeps 'waiting for 192.168.100.23'. I can ping the IP. Can someone please help to find what the problem is? Thank you very much!

Below is the code:

#include <ESP8266WiFi.h>
#define LED D2
const char* ssid = "myAP";
const char* password = "32133213";
unsigned char status_led=0;
WiFiServer server(80);

void setup() {
  Serial.begin(115200);
  pinMode(LED, OUTPUT);
  /*WiFi.persistent( false );
  WiFi.setAutoConnect(true);
  WiFi.mode(WIFI_STA);*/
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("new client");
  while(!client.available())
  {
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  if (req.indexOf("/ledoff") != -1)
  {
    status_led=0;
    digitalWrite(LED,LOW);
    Serial.println("LED OFF");
  }
  else if(req.indexOf("/ledon") != -1)
  {
    status_led=1;
    digitalWrite(LED,HIGH);
    Serial.println("LED ON");
  }
  String web = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  web += "\r\n";
  web += "\r\n";
  web += "
LED Status
\r\n";
  web += "
\r\n";
  if(status_led==1)
      web += "LED On\r\n";
  else
      web += "LED Off\r\n";
  web += "
\r\n";
  web += "
\r\n";
  web += "\r\n";
  web += "<button>LED On</button >\r\n";
  web += "\r\n";
  web += "
\r\n";

  web += "\r\n";
  web += "<button>LED Off</button >\r\n";
  web += "\r\n";

  web += "\r\n";
  web += "\r\n";

  client.print(web);
}

The esp8266 enters modem sleep in STA mode without WiFi traffic. You can turn off the sleep mode with WiFi.setSleepMode. The possible parameters are WIFI_NONE_SLEEP, WIFI_LIGHT_SLEEP or WIFI_MODEM_SLEEP.

After some longer time the servers on esp8266 with arduino core usually get inaccessible even it the esp8266 connects as client to other servers or still sends UDP messages. It is a known issue with some possible workaround documented.


Arduino LCD Simple Problem Hi my lcd doesnt display that i was expected. Can anyone help me???

RS-->22
RW-->GROUND
E-->23
D4-->24
D5-->25
D6-->26
D7-->27

    #include <LiquidCrystal.h>

LiquidCrystal lcd(22, 23, 24, 25, 26, 27);
void setup() {

lcd.begin(16,2);

lcd.setCursor(0,1);
lcd.print("Hello!");
delay(1000);
}
void loop() {
lcd.setCursor(0,1);
lcd.print(millis()/1000);
}

I Had a similar problem with a different display, It looks like you are printing the value without clearing the display so all the numbers print on top of each other creating those squares. try adding lcd.clear() in the loop to clear the display before it prints another value.


Can I program a 3.3v chip on a 5v board? I bought a Gertboard a while ago, and one of the features it has on-board is an ATMega328 (DIP). However, since the Gertboard is designed for use with the Raspberry Pi, it only operates at 3.3v, so the clock speed is limited to ~12MHz.

Programming it via the Raspberry Pi is quite cumbersome though. Instead, I'd like to transfer the chip to an Arduino Uno board so I can upload sketches from my desktop PC. I would then transfer it back to the Gertboard for normal operation.

The problem is that my Uno operates at the more typical 5v / 16MHz.

Is it safe to attempt this? Do I need to make any configuration changes in the IDE to tell it to account for a different clock speed?

The clock speed selected will affect both delay*() and millis()/micros() as well as the functions in <util/delay.h>, therefore you must use the target system's correct clock speed if you are using any of these functions. This can be easily done by editing boards.txt and copying an existing entry for the Uno and changing the value of the f_cpu parameter to match the target system (in this case, 12000000).

The difference in voltage does not matter, since the chip can run at either voltage and no connection is being made between the 5V system and the 3.3V system.


Arduino fade to color change I am making a fun LED Christmas tree project using this code:

// Source location \\adam\U_DRIVE\_BACKED_UP\_Documents\Electronics\XmasTree
#include <FastLED.h>
#define NUM_LEDS 102
#define DATA_PIN 6
CRGB leds[NUM_LEDS];
void setup() {
  Serial.begin(9600);
  Serial.println("Boot");
  // put your setup code here, to run once:
  FastLED.addLeds<NEOPIXEL, DATA_PIN>(leds, NUM_LEDS);

  //  SetRandomLight;
  SetAllOff();
  delay(10); //Delay before getting going.
  BootUp();
  randomSeed(analogRead(0) + analogRead(1) + analogRead(2) + analogRead(3) + analogRead(4) + analogRead(5) + analogRead(6));
}

void loop() {
  // put your main code here, to run repeatedly:
  SingleDrift();
  FastLED.show();
  //delay(random(50));
}

void FadeAll(int x)
{
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].subtractFromRGB(x);
  }
}

void SetRandomLight() {
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].r = random(128);
    leds[i].g = random(128);
    leds[i].b = random(128);
    Serial.println(i);
  }
}

void SetAllOff()
{
  Serial.println("Blanking all.");
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i] = 0x000000;
    leds[i].r = 0;
    leds[i].g = 0;
    leds[i].b = 0;

    //Serial.println(i);
  }
  FastLED.show();
}

void SingleDrift() {
  int mini = 5;
  int maxi = 255;
  FastLED.setBrightness(maxi);
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    int rnd = random(10);
    if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
    if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
    if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
    if (rnd == 4) leds[i].fadeToBlackBy(2);
    if (rnd == 5) leds[i].g++;
    //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
    //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
    if (leds[i].g < 2) leds[i].g = 2;
  }

  int i = random(NUM_LEDS);
  Serial.println(i);
  if (leds[i].r + leds[i].g + leds[i].b > 10) return; //If the LED is still bright, do not change it.
  if (random(100) > 80)
  {
    //Choose a colour
    int r = random(20);
    switch (r)
    {
      case 99:
        for (i = 0; i < NUM_LEDS; i++)
        {
          int x = leds[i].r;
          leds[i].r = leds[i].b;
          leds[i].b = x;
        }

      case 1:
      case 2:
      case 3:
        leds[i] = CRGB::Red;
        break;
      case 4:
      case 5:
      case 6:
        leds[i] = CRGB::Green;
        break;
      case 7:
        leds[i] = CRGB::Blue;
        break;
      case 8:
        leds[i].r = random(128, 255);
        leds[i].g = random(128, 255);
        leds[i].b = random(128, 255);
      case 9:
        leds[i] = CRGB::Yellow;
        break;
      case 10:
        leds[i] = CRGB::Crimson;
        break;
      case 12:
        leds[i] = CRGB::Aqua;
        break;
      case 13:
        leds[i] = CRGB::BlueViolet;
        break;
      case 14:
        leds[i] = CRGB::MidnightBlue;
        break;
      case 15:
        leds[i].setRGB( 255, 255, 255);
        break;
    }
  }
}

void BootUp()
{
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].b = map(i, 0, NUM_LEDS, 0, 255);
    leds[i].r = map(i, NUM_LEDS, 0, 0, 255);
  }
  for (int pc = 0; pc < 100; pc++)
  {
    FastLED.setBrightness(pc);
    FastLED.show();
    delay(3);
  }
  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i] = -leds[i];
    FastLED.show();
    delay(10);
  }

  for (int i = 0; i < NUM_LEDS; i++)
  {
    leds[i].setRGB( 0, 10, 0);

    FastLED.show();
    delay(10);
  }
}

The LED cycle currently fades to green every time, so I would like to add different color fades. However, I could not figure out how to change the color/timing after poking around. Could someone please point me in the right direction for what I changes to the code I need to make?

I think line 84 that keeps the leds green instead of going black. I think line 81 is there to create some kind of shimmer effect on some of the green leds and to skew the color to a bit more green. So I removed those. To prevent the leds from going to black instead of green, I added an if statement that stops any further fading out, if the total "brightness" is 16 or lower. I have no idea how this will look. You might have to tweak this 16-value a bit.
That's the best I could do without a full rewrite of the code.
void SingleDrift() {
  int mini = 5;
  int maxi = 255;
  FastLED.setBrightness(maxi);
  for (int i = 0; i < NUM_LEDS; i++)
  {
    if (leds[i].r > 64) leds[i].r = leds[i].r - 8;
    if (leds[i].g > 64) leds[i].g = leds[i].g - 8;
    if (leds[i].b > 64) leds[i].b = leds[i].b - 8;

    if ( (leds[i].r + leds[i].g + leds[i].b) > 16) // prevent fading to black
    {
      int rnd = random(10);
      if (rnd == 1 && leds[i].r >= 2) leds[i].r = leds[i].r - 1;
      if (rnd == 2 && leds[i].g >= 2) leds[i].g = leds[i].g - 1;
      if (rnd == 3 && leds[i].b >= 2) leds[i].b = leds[i].b - 1;
      if (rnd == 4) leds[i].fadeToBlackBy(2);
      //if (rnd == 5) leds[i].g++;
      //if (rnd == 6 && leds[i].g < 240) leds[i].g = leds[i].g + 1;
      //if (rnd == 7 && leds[i].b < 240) leds[i].b = leds[i].b + 1;
      //if (leds[i].g < 2) leds[i].g = 2; // I think this line kept the leds green
    }
  }
  ...


How does an LED in an LED-strip like WS2811 know when it should be on or off I was experimenting with an Arduino board and an LEDstrip WS2811
it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?

The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.

So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

EDIT:

  but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.

Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.


Cannot set MOSI pin low even after ending SPI I'm building a battery operated device and must shutoff MOSI pin during sleep because it leaks current through the SD card if I don't (about 400 µA).

Problem is, it won't stay off.  I've looked at SPI documentation and as far as I know I just need to call spi.end() then set pinmode to output and finally digitalWrite LOW.  I observe with an oscilloscope that it does go low upon my asking it to but only for about 1 µs (actually it goes low twice within a 5 µs time period).

I've also tried manually setting the pin low using the PORT registers and the behavior is the same... see relevant code:

spi.end();

//pinMode(pin_MOSI, OUTPUT);
//digitalWrite(pin_MOSI, LOW);

//Both above (commented out) and below result in the same behavior -- pin does not stay LOW

DDRB |= B00100000;            //set pin 5 as output
PORTB &= B11011111;           //set output low for pin 5

delay(5000);

...As you can see there is a delay to ensure that it isn't being set high by some other code.

Is there some sort of SPI interrupt that automatically sets the pin high again?

Hardware details:

MCU: ATMEGA1284P;
Programmer: Atmel-ICE

UPDATE (13-Mar-2019):

I didn't realize that SPI is implemented by Atmel in hardware directly (see datasheet page 105):

  MOSI/PCINT13 – Port B, Bit 5
  – MOSI: SPI Master Data output, Slave Data input for SPI channel. When the SPI0 is enabled
  as a slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI
  is enabled as a master, the data direction of this pin is controlled by DDB5. When the pin is
  forced to be an input, the pull-up can still be controlled by the PORTB5 bit.

I am currently chasing down this latest information and will hopefully come to a resolution soon.  I will post any progress.

Indeed, SPI is hardware implemented.  I was able to get the MOSI pin to operate as intended by clearing the SPI enable bit from the SPCR register as follows:

SPCR &= 0B10111111;  //disable SPI

To re-enable after sleep, I'm assuming I'll just do SPCR |= 0B01000000; ...pretty sure that will work but I'll update here if I have to modify my solution.

.

Perhaps also pertinant information:

I was using an object of SPIClass in SPI.h which is from the Arduino core libraries -- for some reason it wasn't disabling SPI in hardware when calling the spi.end() method, maybe because there was some other SPI object initialized by some other library.  Here is the source from SPI.cpp for the end method:

void SPIClass::end() {
  uint8_t sreg = SREG;
  noInterrupts(); // Protect from a scheduler and prevent transactionBegin
  // Decrease the reference counter
  if (initialized)
    initialized--;
  // If there are no more references disable SPI
  if (!initialized) {
    SPCR &= ~_BV(SPE);
    interruptMode = 0;
    #ifdef SPI_TRANSACTION_MISMATCH_LED
    inTransactionFlag = 0;
    #endif
  }
  SREG = sreg;
}

The line SPCR &= ~_BV(SPE); should have done the job for me but I'm guessing it never got there because initialized was probably still non-zero.


Is there a way to "list" (in BASIC, or "cat" in LINUX) the current sketch loaded in my xxxDUINO? I was surprised when I couldn't find an old post where someone asked this question. Seems like a natural beginner, uh excuse me, "newbie" question, but then I'm a throw-back to the days when a home computer came with 3,583 bytes (three-thousand, five-hundred eighty-three). So again, as seen in the title, can I "list" my sketch? I'm pretty sure the answer is NO since if it were a good question someone would have asked it already. It just strikes me as odd that my old VIC-20 could do something this phenomenal techno-marvel can't. Not much of an accomplishment for the dinosaurs, but HEY! We're on the scoreboard now! [nothing's worse than that miserable goose-egg :(   ]

No. the code burned in an Arduino is compiled not interpreted like Basic.

Basically your C language sketch is compiled into AVR assembly language. The resulting hexadecimal is what is burned to the Arduino.

Yes you could disassemble the hex like we used to do in the good old days, but as before it is highly unpredictable and most of the time not very useful.

Just a quick example. The following simple Arduino sketch that just sets a pin in output and then sets it HIGH:

void setup() {
  pinMode(13, OUTPUT);
  digitalWrite(13, HIGH);
}

void loop() {
}

The resulting hex file is 3.5Kb.This include various sections of data and code. One would have to analyse the section, convert the hex (op-code) to assembly language and find which part correspond to the C code.

It is possible, and there are probably tools that do a fairly good job. Would the C language generated by the decompilation once recompile perform exactly like the original compiled cole. I doubt it.


Cannot get HC-12 to function with Arduino Pro Micro clone [first time usage]

I'm checking this config out with a simple sketch derived from one @ https://www.allaboutcircuits.com/projects/understanding-and-implementing-the-hc-12-wireless-transceiver-module/.

The sketch acknowledges a command from the Serial Monitor and responds accordingly along with an "OK".  I have used this sketch countless times before with numerous HC-12 and UNO, and this particular HC-12 functions properly when connected to such.

For the Pro Micro, the command is echoed back instead, which, in my experience, indicates that the HC-12 is not receiving/responding.

The Pro Micro test config is very basic: Pro Micro, HC-12, USB connection, 5 direct jumper connections for vcc, gnd, pins 4-6. Vcc output reads 4.2 volts.

I specify:

const byte HC12RxdPin = 4; // "RXD" Pin on HC12
const byte HC12TxdPin = 5; // "TXD" Pin on HC12
const byte HC12SetPin = 6; // "SET" Pin on HC12

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin)

I have also tested with an IN4007 in the power connect for the HC-12, but results are the same.

I've swapped HC-12s, and checked out the requisite pins by using another sketch that toggles an led on each.
The Arduino IDE is 1.8.2, and I am specifying a Leonardo board.  This is the suggestion I found whilst researching.

I have seen a few projects using the HC-12 with the Pro Micro and other small boards, but noticed no special considerations for such.

Have you any suggestions or solutions [even better]?

Solution to problem is as follows:
 For the Arduino Pro Micro [as for the Leonardo], Serial1 must be used instead of a SoftwareSerial specification, e.g.,

SoftwareSerial HC12(HC12TxdPin, HC12RxdPin).

Code is to be modified by changing HC12.available() to Serial1.available().  The same holds true for the reads and writes.
Pins are to be wired such that the HC-12 RXD pin connects to the Pro Micro TXD pin, and the HC-12 TXD pin connects to the Pro Micro RXD pin.
My thanks to @mico for providing the reference that explains it all.


Nan values in Egg Incubator I've recently built my Arduino Incubator, which consists of a DHT22 sensor, an LCD Keypad Shield, some fans, resistors, e.t.c.

I uploaded the sketch, and everything seemed fine. However, when I try to select the temperature and humidity I want, it won't let me change anything, and it says "Temperature: NanC, Humidity: Nan%".

What am I doing wrong? I didn't write the code myself. I copied it from a guy who made his incubator and wrote his code himself. He has the incubator project on github.

As you can see in the pictures he posted, everything appears to be working fine. What would be the problem? I don't have a lot of Arduino knowledge, although I am OK with reading and tinkering with code.

The display below, shows NaN when I try to select my own temperature/humidity. When I see the current temperature/humidity, it works fine. The sensor works with no problems at all, though I didn't connect a pullup resistor. I am going to try adding one. However, to me it seems like the problem isn't that. I get NaN errors when trying to select my own value. The buzzer beeps, the servo turns and the fan works fine. As said above, DHT sensor works and sends the values.

Useful Links:

The code (Github)

The schematic (Github)

The whole incubator project (Github)

Update - 7/1/2019
Thanks to Jot, everything works fine now! He corrected my code, and he adviced me to reset the values in the EEPROM. I would have given up the project, unless he had helped me. I have now fully finished the build, even though I plan to add some features in the future.

I want to add:

A backup power source (lead acid battery)
Bigger ventilation holes
Design improvements
The ability to control everything using the serial monitor, so I can connect to the Arduino via Internet (Using an MFP Storage Server which I have)
A larger box for more eggs
A system which turns the eggs automatically
A pump which pumps water to the sponge automatically as well

However, nothing could be done without Jot's help. Again, thanks a lot to Jot for his help, and the efforts he put in order to help me. I really appreciate that, since I have not any kind of Arduino knowledge (I'm 14 years old), and I found his advices and comments very very useful.

I have now put 5 eggs inside the incubator, and it is right now working. I am counting backwards from today, and in about 21 days I am going to have chickens!

Here are some pictures of the machine for those who are interested (or just curious!):

The incubator working, with the screen turned on:

The "egg hatching" room:
(Inside, there is a wet sponge, all the devices and of course, 5 eggs!)

Hi Lefteris the builder,
StackExchange is about questions and answers.
Arduino is about learning and fast prototyping.

For guidance with your project, the forum at http://forum.arduino.cc/ is more appropriate.

I suppose that a number of us have read the code that you use. We really do read code.
That code is not bad, but there are a few weak spots in that code:

Not enough comments to explain what is going on.
Many conditions with flags. That is okay,
but the flags are sometimes a boolean and
sometimes a byte, and there is no explanation what the flag is
used for.
Many checks for isnan(). Does that indicate that
a floating point "nan" problem might pop up
at any time in the sketch?
Most of the code is in the loop(). I don't mind that, but
others prefer to put large blocks of code in functions.

It seems that your hardware is working okay.

It is hard to confirm that the code for the Holt-Winters algoritme is working.

All this together is too confusing for us at the moment.

I have changed my answer, the hardware seems to be working.

Below is the changed sketch to test it without extra hardware.
I use the serial monitor. The sadw keys (followed by enter) are the cursor keys and the space bar (followed by enter) is select.

#include <avr/wdt.h>
// #include <Servo.h>
// #include <LiquidCrystal.h>
// #include <DHT.h>
#include <EEPROM.h>

// stty -F /dev/ttyACM0 115200 cs8 cread clocal -hupcl time 30 && tee incubator.log </dev/ttyACM0

#define WDT_TIMEOUT WDTO_8S // if defined, enable hardware watchdog
#define DHTPIN 3 // data pin of the DHT T/H sensor
#define T_OFFSET 0.9 // temperature sensor offset
#define FAN_PIN 2 // fan tacho signal pin
#define FAN_THRES 500 // fan alarm threshold
#define BEEPER A2 // pin where beeper is attached
#define BRIGHTNESS 10 // display brightness pin
#define HEATER A1 // heater MOSFET pin
#define DELAY 2000 // loop delay in ms
#define TS_ADDR 0 // temperature set point EEPROM address
#define HS_ADDR 4 // humidity set point EEPROM address
#define HC_ADDR 8 // humiditiy control mode EEPROM address
#define TI_RESET 1 // integral reset threshold, set integral to 0 when T error greater than this
#define HI_RESET 5 // integral reset threshold, set integral to 0 when H error greater than this
#define ALARM_T 2 // temperature alarm threshold, alert if T error greater than this
#define ALARM_H 8 // humidity alarm threshold, alert if H error greater than this
#define H_AUTO_THRES 3 // disable vent control in auto mode if H error < this
#define H_AUTO_COUNT 200 // disable for n cycles
#define HWAT 0.25 // holt winters parameters for temperature smoothing
#define HWBT 0.2
#define HWAH 0.7 // holt winters parameters for humidity smoothing
#define HWBH 0.5
#define A 0.005 // long average parameter
#define VENTCLOSED 80 // consider vent closed if under this angle
#define VENTOPENMS  480000L // open vent if closed longer
#define VENTRESETMS 600000L // reset vent after this time (>VENTOPENMS!)

// Servo vent;
// DHT dht(DHTPIN, DHT22);
// LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

#define RIGHT 16
#define UP 8
#define DOWN 4
#define LEFT 2
#define SELECT 1
#define NO_KEY 0

// added define to show messages on serial monitor.
#define lcd Serial

byte getKey() {
//  int key = analogRead(0);
//  if (key < 50) {
//    return RIGHT;
//  } else if (key < 150) {
//    return UP;
//  } else if (key < 300) {
//    return DOWN;
//  } else if (key < 500) {
//    return LEFT;
//  } else if (key < 800) {
//    return SELECT;
//  } else {
//    return NO_KEY;
//  }
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    switch (inChar)
    {
      case 'w': return UP;
      case 'a': return LEFT;
      case 's': return DOWN;
      case 'd': return RIGHT;
      case ' ': return SELECT;
    }
  } else {
    return NO_KEY;
  }
}

void eeread(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    *b++ = EEPROM.read(address + i);
  }
}

void eewrite(int address, int length, void* p) {
  byte* b = (byte*)p;
  for (int i = 0; i < length; i++) {
    EEPROM.write(address + i, *b++);
  }
}

void write_byte(int address, byte &value) {
  eewrite(address, sizeof(value), &value);
}

byte read_byte(int address) {
  byte value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_int(int address, int &value) {
  eewrite(address, sizeof(value), &value);
}

int read_int(int address) {
  int value;
  eeread(address, sizeof(value), &value);
  return value;
}

void write_float(int address, float &value) {
  eewrite(address, sizeof(value), &value);
}

float read_float(int address) {
  float value;
  eeread(address, sizeof(value), &value);
  return value;
}

void heater(boolean on) {
//  digitalWrite(HEATER, !on ? LOW : HIGH);
}

boolean heater() {
//  return digitalRead(HEATER) == HIGH;
  return true;
}

volatile int fancount;

void count() {
  ++fancount;
}

void beep(unsigned long f, unsigned long l) {
//  pinMode(BEEPER, OUTPUT);
  byte v = 0;
  f = 500000 / f;
  l = (1000 * l) / f;
  for (int i = 0; i < l; ++i) {
//    digitalWrite(BEEPER, v = !v);
//    delayMicroseconds(f);
  }
//  pinMode(BEEPER, INPUT);
}

float Ts, Hs; // set points
byte Hcontrol; // H control mode
byte Ts_changed, Hs_changed; // setpoint changed flags
float ET, dETdt, IETdt; // prop/diff/integ terms for T
float EH, dEHdt, IEHdt; // prop/diff/integ terms for H
float T, Tavg = NAN, Tvar, Tstd;
float H, Havg = NAN, Hvar, Hstd;
float Hpower, Hduty; // heater current power, average duty cycle
unsigned long t0, Hon, talarm, tventclosed;
byte displayMode;
byte key, bri = 255, alarm;
boolean ventclosed;
int fanrpm;

void setup() {
#if defined(WDT_TIMEOUT)
//  wdt_enable(WDT_TIMEOUT);
#endif
  Serial.begin(9600);
  Serial.println("Egg Incubator");
  Serial.println("Use wsad and space is select");

//  pinMode(HEATER, OUTPUT);
//  heater(0);
//  pinMode(BRIGHTNESS, OUTPUT);
//  analogWrite(BRIGHTNESS, bri = 255);
//  lcd.begin(16, 2);
//  lcd.noCursor();
  lcd.print("Incubator 0.7");
//  lcd.setCursor(0, 1);
  Serial.println();
  lcd.print(__DATE__);
//  dht.begin();
//  vent.setMinimumPulse(800);
//  vent.setMaximumPulse(2600);
//  vent.attach(11);
  //  write_float(TS_ADDR, Ts=37.8);  write_float(HS_ADDR, Hs=55);
  Ts = read_float(TS_ADDR);
  Hs = read_float(HS_ADDR);
  Hcontrol = read_byte(HC_ADDR);
//  pinMode(FAN_PIN, INPUT_PULLUP);
//  attachInterrupt(0, count, FALLING);
//  sei();
//  beep(800, 100);
//  beep(1000, 100);
//  beep(1200, 100);
//  beep(1600, 100);
}

void loop() {
  unsigned long t1 = millis();
  int dt = t1 - t0;

  if (!key) {
    key = getKey();
  }

  if (key) {
//    analogWrite(BRIGHTNESS, bri = 255);
  }

  if (t1 - Hon > Hpower * DELAY) {
//    heater(0);
  }

  if (Hcontrol && Hcontrol < H_AUTO_COUNT) {
//    vent.refresh();
  }

  if (alarm && !(alarm & 8)) {
//    beep(1000, 50);
//    beep(1414, 50);
  }

  if (dt > DELAY || key) {

    if (!key) {
      //    beep(2000, 50);
//      T = dht.readTemperature() + T_OFFSET;
      T = 30.0 + T_OFFSET;             // set to fixed value !
//      H = dht.readHumidity();
      H = 60.0;                        // set to fixed value !

      if ((isnan(T) || T < 10 || T > 60) || (Hcontrol && (isnan(H) || H < 5 || H > 95))) {
//        heater(0);
//        lcd.clear();
        lcd.print("SENSOR ERROR!");
//        lcd.setCursor(0, 1);
        Serial.println();
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        beep(2000, 1000);
        return;
      }

      float dts = dt * 1e-3;

      if (dt > DELAY) {
        fanrpm = fancount * 60 / dts;
        fancount = 0;
      }

      if (fanrpm < FAN_THRES) {
        alarm |= 4;
      } else {
        alarm &= ~4;
      }

      // temperature Holt-Winters smoothing
      float E0 = ET;
      ET = HWAT * (T - Ts) + (1 - HWAT) * (ET + dETdt * dts); // smoothed T error (deviation from set point)
      dETdt = HWBT * (ET - E0) / dts + (1 - HWBT) * dETdt; // smoothed derivative
      IETdt += ET * dts; // integral of error
      if (abs(ET) > TI_RESET) // reset integral on big deviation
        IETdt = 0;
      float pidT = 1.1765 * (ET + 0.010526 * IETdt + 23.75 * dETdt); // PID value, adjust coefficients to tune
      Hpower = fanrpm > FAN_THRES ? max(0, min(1, -pidT)) : 0;
      heater(Hpower > 0.1);
      Hon = millis();

      if (abs(ET) > ALARM_T) {
        alarm |= 1;
//        vent.write(ET < 0 ? 0 : 180);
        if (Hcontrol > 1) {
          Hcontrol = 2;
        }
      } else {
        alarm &= ~1;
      }

      // humidity Holt-Winters smoothing
      E0 = EH;
      EH = HWAH * (H - Hs) + (1 - HWAH) * (EH + dEHdt * dts); // smoothed H error (deviation from set point)
      dEHdt = HWBH * (EH - E0) / dts + (1 - HWBH) * dEHdt; // smoothed derivative
      IEHdt += EH * dts; // integral of error
      if (abs(EH) > HI_RESET) // reset integral on big deviation
        IEHdt = 0;
      float pidH = 0.1176 * (EH + 0.09091 * IEHdt + 2.75 * dEHdt); // PID value, adjust coefficients to tune
//      vent.write(pidH * 180);

      if (Hcontrol && abs(EH) > ALARM_H) {
        alarm |= 2;
      } else {
        alarm &= ~2;
      }

      boolean ventclosed0 = ventclosed;
//      ventclosed = vent.read() < VENTCLOSED;
      ventclosed = VENTCLOSED;

      if (ventclosed && ventclosed != ventclosed0) {
        tventclosed = millis();
      }

      boolean openvent = ventclosed && millis() - tventclosed > VENTOPENMS;
      if (openvent) {
//        vent.write(180);
        if (millis() - tventclosed > VENTRESETMS) {
          tventclosed = millis();
        }
      }

      if (Hcontrol > 1) {
        if (abs(EH) > H_AUTO_THRES || openvent) {
          Hcontrol = 2;
        } else {
          if (Hcontrol < H_AUTO_COUNT) {
            ++Hcontrol;
          } else {
            IEHdt = 0;
          }
        }
      }

      // long term averages
      Tavg = A * T + (1 - A) * (isnan(Tavg) ? T : Tavg);
      Tvar = A * pow(T - Tavg, 2) + (1 - A) * (isnan(Tvar) ? 0 : Tvar);
      Tstd = sqrt(Tvar);

      Havg = A * H + (1 - A) * (isnan(Havg) ? H : Havg);
      Hvar = A * pow(H - Havg, 2) + (1 - A) * (isnan(Hvar) ? 0 : Hvar);
      Hstd = sqrt(Hvar);

      Hduty = A * Hpower + (1 - A) * Hduty;

      if (Ts_changed) {
        if (Ts_changed-- == 1)
          write_float(TS_ADDR, Ts);
      }

      if (Hs_changed) {
        if (Hs_changed-- == 1)
          write_float(HS_ADDR, Hs);
      }
    }

    if (key & SELECT) {
      displayMode = ++displayMode % 8;
    }

//    lcd.clear();
    Serial.println();
    lcd.print("T=");
    lcd.print(Ts + ET);
    lcd.print("C H=");
    lcd.print(Hs + EH, 1);
    lcd.print("%");

//    lcd.setCursor(0, 1);
    Serial.println();

    float uptime;
    char unit;
    switch (displayMode) {
      case 0: // raw values
        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
        break;
      case 1: // temperature setpoint
        if (key & (UP | DOWN | LEFT | RIGHT)) {
          Ts = max(20, min(50, Ts + (key & (UP | RIGHT) ? +1 : -1) * (key & (UP | DOWN) ? 0.1 : 1)));
          Ts_changed = 10;
        }
        lcd.print("Ts=");
        lcd.print(Ts);
        lcd.print("C");
        break;
      case 2: // humidity setpoint
        if (key & (UP | DOWN)) {
          Hs = max(10, min(90, Hs + (key & UP ? +1 : -1)));
          Hs_changed = 10;
        }
        if (key & RIGHT) {
          if (Hcontrol < 2) {
            Hcontrol = ++Hcontrol;
          } else {
            Hcontrol = 0;
          }
          IEHdt = 0;
          write_byte(HC_ADDR, Hcontrol);
        }
        lcd.print("Hs=");
        lcd.print(Hs);
        lcd.print("% ");
        lcd.print(Hcontrol == 1 ? "on" : (Hcontrol > 1 ? "auto" : "off"));
        break;
      case 3: // average temperatur
        lcd.print("Ta=");
        lcd.print(Tavg);
        lcd.print("C (");
        lcd.print(Tstd);
        lcd.print(")");
        break;
      case 4: // average humidity
        lcd.print("Ha=");
        lcd.print(Havg);
        lcd.print("% (");
        lcd.print(Hstd);
        lcd.print(")");
        break;
      case 5: // heater duty cycle
        lcd.print("Hd=");
        lcd.print(Hduty);
        lcd.print(" Hp=");
        lcd.print(Hpower);
        break;
      case 6: // air vent
        lcd.print("V=");
//        lcd.print(vent.read() / 180.0);
        lcd.print(" F=");
        lcd.print(fanrpm);
        break;
      case 7: // average humidity
        uptime = t1 * 1e-3;
        unit = 's';
        if (uptime > 60) {
          uptime /= 60;
          unit = 'm';
          if (uptime > 60) {
            uptime /= 60;
            unit = 'h';
            if (uptime > 24) {
              uptime /= 24;
              unit = 'd';
            }
          }
        }
        lcd.print("Up=");
        lcd.print(uptime, 1);
        lcd.print(unit);
        break;
      default:;
    }

    Serial.println();

    if (alarm & 7) {
      if (!talarm) {
        talarm = millis();
      }
      // sound on persistent alarm and fan failure
      if (millis() - talarm > 300000L || alarm & 4) {
        alarm &= ~8;
      }
//      analogWrite(BRIGHTNESS, bri = 255);
//      lcd.setCursor(0, 0);
      if (alarm & 1)
        lcd.print("T ");
      if (alarm & 2)
        lcd.print("H ");
      if (alarm & 4)
        lcd.print("F ");
      lcd.print("ALARM!          ");
      if (!(alarm & 8) && key) {
        alarm |= 8; // alarm acknowledged
        talarm = millis();
      }
      if (!(alarm & 8)) {
//        lcd.setCursor(0, 1);
        Serial.println();

        lcd.print("T=");
        lcd.print(T);
        lcd.print("C H=");
        lcd.print(H, 1);
        lcd.print("%");
      }
    } else {
      alarm = 0;
      talarm = 0;
    }

    if (key) {
      delay((key & SELECT) ? 500 : 200);
    }

    if (bri) {
//      analogWrite(BRIGHTNESS, --bri);
    }
    key = 0;
    t0 = t1;
  }

#if defined(WDT_TIMEOUT)
  wdt_reset();
#endif
}

@Lefteristhebuilder, you have selected that sketch, but the sketch might not handle problems very well.

Anyone can write code for Arduino and put it online.
At least at Github it is possible that others can write an issue (as you did). The project at Github has 9 stars and the creator showed the project at the Arduino "Project Hub". That is all good, but I'm not very happy with the code itself.


Length of uint8_t* const array I've an array of type uint8_t* const with 6 items, defined like this

uint8_t* const neighbourSet[] = {PEER1, PEER2, PEER3, PEER4, PEER5, PEER6};

Whereas each element in this array is static uint8_t defined like this

static uint8_t PEER1[] {0x86, 0xF3, 0xEB, 0x7A, 0xE8, 0x3B};
static uint8_t PEER2[] {0x86, 0xF3, 0xEB, 0x7A, 0xA1, 0x09};
static uint8_t PEER3[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0xED};
static uint8_t PEER4[] {0x84, 0x0D, 0x8E, 0x03, 0x99, 0xD5};
static uint8_t PEER5[] {0x80, 0x7D, 0x3A, 0xC5, 0x2B, 0x79};
static uint8_t PEER6[] {0x84, 0x0D, 0x8E, 0x03, 0x95, 0x1D};

When I do

  Serial.print("size:");
  Serial.println(sizeof(neighbourSet));

I get size:24. I am expecting the size to be 6. could someone explain ?
I don't want to hardcode the total number of PEER in a separate integer variable. I want my for loop to run through each element till the total size of array.

    for (int i = 0; i < sizeof(neighbourSet); i++) {
         //do something for each PEER.
         delay(50);
    }

sizeof() gives the number of bytes. You are looking for membersof(). It is often defined as:

#define membersof(x) (sizeof(x) / sizeof(x[0]))

And in the example above:

for (int i = 0; i < membersof(neighbourSet); i++) {
     //do something for each PEER.
     delay(50);
}

For more practical C/C++ macro and type extensions please see the Cosa Types.h file.


nrf24l01+ does not work with a battery, or very unreliably For a project in progress, I have an Arduino UNO sending a message when a condition occurs, and a Raspberry Pi that listens to it. Both are fitted with NRF24L01+ modules with antennas.

It works perfectly when the Arduino is powered from a wall socket, for instance using a 9V / 1A power supply. But when I try it with a 9V battery (which is supposed to supply 600 mAh), the Raspberry Pi receives only 1/10 of the messages.

Could you tell me:

Why this happens
How I can solve this problem (software / wiring / capacitor / ...)
What would be the best way to power an Arduino whose only job is to detect that a switch closes, and emit a message over the air

Here is the code of the emitter (Arduino). And there is the code of the receiver (Raspberry Pi).

Thank you.

According to the datasheet of another 9V battery, I should not expect more than 30 - 50 mA of constant current. This is probably the reason why.

Long story made short: One can not power a NRFL01+ reliably with a 9V battery.
I'd be better off using 2xAA batteries.