body:
This is my send and receive code in STM32 (blue board).
But i can't send and receive data . why?
I did use Enrf24.h .
Enrf24 link: [https://github.com/spirilis/Enrf24][1]
send code is:

    #include <SPI.h>
    #include <Enrf24.h>
    #include <nRF24L01.h>
    #include <string.h>
    #define ce_nrf PB12
    #define csn_nrf PB13
    #define irq_nrf PA0
    Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
    const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
    void setup() {
      Serial.begin(9600);
      SPI.begin();
      SPI.setDataMode(SPI_MODE0);
      SPI.setBitOrder(MSBFIRST);
      radio.begin();  // Defaults 1Mbps, channel 0, max TX power
      radio.setTXaddress((void*)txaddr);
    }

    void loop() {
      Serial.print("Sending packet: ");
      radio.print("OONN");
      radio.flush();  // Force transmit (don't wait for any more data)
      delay(1000);
      Serial.print("Sending packet: ");
      radio.print("OOFF");
      radio.flush();
      delay(1000);
    }

receive code is:

    #include <SPI.h>
    #include <Enrf24.h>
    #include <nRF24L01.h>
    #define ce_nrf PB12
    #define csn_nrf PB13
    #define irq_nrf PA0
    Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
    const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
    const char *str_on = "ON";
    const char *str_off = "OFF";
    void dump_radio_status_to_serialport(uint8_t);
    void setup() {
      Serial.begin(9600);
      SPI.begin();
      SPI.setDataMode(SPI_MODE0);
      SPI.setBitOrder(MSBFIRST);
      radio.begin();  // Defaults 1Mbps, channel 0, max TX power
      radio.setRXaddress((void*)rxaddr);
      radio.enableRX();  // Start listening
    }

    void loop() {
      char inbuf[33];
      while (!radio.available(true));
      if (radio.read(inbuf)) {
        Serial.print("Received packet: ");
        Serial.println(inbuf);
      }
    }

this image can help :
[![enter image description here][2]][2]

  [1]: https://github.com/spirilis/Enrf24
  [2]: https://i.stack.imgur.com/Wb1Ki.png

title: STM32 and NRF send & receive

Answers: 3

body:
You did not say which library you are using, but based on the `#include`s, I am assuming http://maniacbug.github.io/RF24

This line in your receiver code:

      while (!radio.available(true));

does not make sense. You are passing `true` to the `radio.available()` function, but t[he function does not care about a parameter][1].

You probably mean something like:

    while (!radio.available());

When you pass in a variable, you are calling a variant of the function that expects a pipe number to be given, and `true` is defined as `1`. Your transmitter, however, is not sending on pipe number 1.

  [1]: http://maniacbug.github.io/RF24/classRF24.html#a127105eb7a3b351cfe777c1cec50627a

body:
First of all, remove

    while (!radio.available(true));

after that use

    PA_5 ----> SCK
    PA_6 ----> MISO
    PA_7 ----> MOSI

it will work correctly.

body:
It is better answer for some reseans
in Enrf library you can not send data with write untill txbuf_len==0

> size_t Enrf24::write(uint8_t c) {
> if (txbuf_len == 32) {
> flush();  // Blocking OTA TX   }
> txbuf[txbuf_len] = c;   txbuf_len++;
> return 1; }

dont use purge then

> txbuf_len = 0

this is for read dat

    #include <SPI.h>
    #include <Enrf24.h>
    #include <nRF24L01.h>
    #define ce_nrf PB12
    #define csn_nrf PB13
    #define irq_nrf PA0
    Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
    const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
    const char *str_on = "ON";
    const char *str_off = "OFF";
    void dump_radio_status_to_serialport(uint8_t);
    void setup() {
      Serial.begin(9600);
      SPI.begin();
      SPI.setDataMode(SPI_MODE0);
      SPI.setBitOrder(MSBFIRST);
      radio.begin();  // Defaults 1Mbps, channel 0, max TX power
      radio.setRXaddress((void*)rxaddr);
      radio.enableRX();  // Start listening
     // radio.autoAck(false);
    }

    void loop() {
      char inbuf[35];
      if (radio.read(inbuf))
      {
        Serial.print("Received packet: ");
        Serial.println(inbuf);
      }
    }

this is write for write data:

    #include <SPI.h>
    #include <Enrf24.h>
    #include <nRF24L01.h>
    #include <string.h>
    #define ce_nrf PB12
    #define csn_nrf PB13
    #define irq_nrf PA0
    Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
    const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
    void setup() {
      Serial.begin(9600);
      SPI.begin();
      SPI.setDataMode(SPI_MODE0);
      SPI.setBitOrder(MSBFIRST);
      radio.begin();  // Defaults 1Mbps, channel 0, max TX power
      radio.setTXaddress((void*)txaddr);
    }
    int i=0;
    void loop() {
      i++;
      Serial.print("Sending packet: ");
      Serial.println(i);
      radio.print("1234567890123456789012--------->");
      //radio.purge();
      delay(100);
    }


body:
## Libraries

- [NTPClient](https://github.com/arduino-libraries/NTPClient)

## Board

Olimex ESP32-POE board

## Behaviour

I have written a code that connects the board to a local NTP Server (which is an embedded board). I tried assigning the IP Address of the above NTP Server using `IPAddress` and then convert it to `c_str()` to pass into the `NTPClient` constructor as follows:
<!-- language-all: lang-cpp -->

     WiFiUDP ntpUDP; // udp socket object for NTP

     IPAddress NTPServer(192.168.3.11); // Local NTP Server IP Address

     NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000);

The reason for this is because the `NTPClient` class uses `const char*` for the IP Address of the NTP Server.

The values that are obtained once the code is flashed on the board are wrong because the timestamps are have the year `2106`.

On the contrary, when I use

     NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000);

and run the code on the board, this provides me perfect values of UTC time.

Why is there some discrepancy here?

# Code

    #include <Wire.h>
    #include <ETH.h>
    #include <WiFiUdp.h>
    #include <NTPClient.h>
    #include <RTClib.h>

    WiFiUDP ntpUDP;
    /* IP CONF for NODE */
    ///////// >>>> MODIFY Values Here <<<< ////////
    const IPAddress node_static_ip(192, 168, 3, 101);
    const IPAddress default_gateway(192, 168, 3, 250);
    const IPAddress subnet_mask(255, 255, 255, 0);
    const IPAddress dns_add(192, 168, 3, 250);
    const IPAddress NTPServer(192, 168, 3, 11);

    NTPClient timeClient(ntpUDP, "192.168.3.11", 0, 60000); // This works
    NTPClient timeClient(ntpUDP, NTPServer.toString().c_str(), 0, 60000); // This won't (provides timestamps of 2106)

    void setup() {
      // put your setup code here, to run once:
      Wire.begin(I2C_SDA, I2C_SCL);
      Serial.begin(115200);
      ETH.begin();
      ETH.config(node_static_ip, default_gateway, subnet_mask, dns_add);
      delay(1000);
      if (!rtc.begin()) {
        Serial.println("No RTC");
      }
      timeClient.begin();

    }
    void loop() {
      // put your main code here, to run repeatedly:
      timeClient.update();
      Serial.println(timeClient.getEpochTime());
      DateTime now_time(timeClient.getEpochTime());
      Serial.print(now_time.year(), DEC);
        Serial.print('/');
        Serial.print(now_time.month(), DEC);
        Serial.print('/');
        Serial.print(now_time.day(), DEC);
        Serial.print(now_time.hour(), DEC);
        Serial.print(':');
        Serial.print(now_time.minute(), DEC);
        Serial.print(':');
        Serial.print(now_time.second(), DEC);
    Serial.println();

      delay(2000);

    }

title: Using c_str() on String for IPAddress with NTPClient provides wrong values

Answers: 1

body:
The String object created as return from IPAddress.toString() as parameter to constructor of NtpClient is temporary. It contains the char array returned by c_str(). NTPClient doesn't copy the string, only stores a reference to it. And the referenced string (char array) doesn't exist at the time the NTPClient wants to use it.

    class TestClass {
    public:
      TestClass(const char* _ip) : ip(_ip) { }

      void test() {
        Serial.println("--");
        Serial.println(ip);
        Serial.println("--");
      }

    private:
      const char* ip;
    };

    //String s("abc");
    //TestClass Test(s.c_str()); <- this works

    TestClass Test(String("abc").c_str()); // <- this can't work

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


body:
[![enter image description here][1]][1][![enter image description here][2]][2][![enter image description here][3]][3]

Here is the link : https://www.circuito.io/app?components=10167,11021,12083,13678,13959,975601

   I'm just a beginner I don't have the idea on how GPS module wires should be connected

    #include "DHT.h"
    #include "NewPing.h"
    #include <SoftwareSerial.h>
    #define DEBUG true
     SoftwareSerial esp8266(11,10);
      //SoftwareSerial gps(8,9);
     #define DHTPIN 2       // DHT-11 Output Pin connection
     #define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
     #define TRIGGER_PIN 4
     #define ECHO_PIN 3
     #define MAX_DISTANCE 400

     NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

     float hum;
     float temp;

     DHT dht(DHTPIN, DHTTYPE);

     void setup() {
     Serial.begin (9600);
     Serial.println("START");
     esp8266.listen();
     esp8266.begin(9600);
     gps.begin(9600);
     dht.begin();

      pinMode(TRIGGER_PIN, OUTPUT);
      pinMode(ECHO_PIN, INPUT);

      sendData("AT+RST\r\n",2000,DEBUG);            // command to reset the
      module
         sendData("AT+CWMODE=2\r\n",1000,DEBUG);       // This will configure
         the mode
         as access point
       sendData("AT+CIFSR\r\n",1000,DEBUG);          // This command will get
       the ip
       address
      sendData("AT+CIPMUX=1\r\n",1000,DEBUG);       // This will configure the
      esp
    for multiple connections
    sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // This command will turn on
    the
    server on port 80
    }

    void loop()
    {

     delay(2000);  // Delay so DHT-11 sensor can stabalize

     hum = dht.readHumidity();  // Get Humidity value
     temp= dht.readTemperature();  // Get Temperature value

      digitalWrite(TRIGGER_PIN, LOW);
      delayMicroseconds(2);
      digitalWrite(TRIGGER_PIN, HIGH);
      delayMicroseconds(10);
      digitalWrite(TRIGGER_PIN, LOW);

    long duration,distance;
    duration= pulseIn(ECHO_PIN,HIGH);

    distance = duration/58.2;

    Serial.print("Humid: ");
    Serial.print(hum);
    Serial.print(" %, Temp: ");
    Serial.print(temp);
    Serial.print(" C, ");
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");
    delay(50);

    gps.listen();
    while (gps.available())
    Serial.write(gps.read());

    esp8266.listen();
    if(esp8266.available())         // This command will that check if the esp
        is sending a message
        {
        if(esp8266.find("+IPD,"))
        {
        delay(1000);

        int connectionId = esp8266.read()-48; /* We are subtracting 48 from the
        output because the read() function returns
                                            the ASCII decimal value and the
        first decimal number which is 0 starts at 48*/
         String webpage = "<meta http-equiv=\"refresh\" content=\"5;
         url=192.168.4.1/\">";
         webpage += "
Mabalacat City College Garbage Monitoring System
";
        webpage += "

";
        if (distance<=5)
        {
        webpage+= " Trash can is Red";
        }
        if (distance == 20)
        {
          webpage+= " Trash can is Orange";
          }
          if (distance == 35)
        {
          webpage+= " Trash can is Light Orange";
          }
          if (distance == 50)
        {
          webpage+= " Trash can is Yellow";
          }
          if (distance == 70)
        {
          webpage+= " Trash can is 2st Light Yellow";
          }
          if (distance == 85)
        {
          webpage+= " Trash can is 1st Light Yellow";
          }
          if (distance == 95)
        {
          webpage+= " Trash can is Green";
          }
          if (distance >= 100)
        {
          webpage+= " Trash can is Empty";
          }
          webpage+= "
";
          webpage+="Distance: ";
          webpage+=distance;
          webpage+=" cm";
          webpage+= "
";
          webpage+="Temperature: ";
          webpage+= temp;
          webpage+=" celsius";
          webpage+= "
";
          webpage+= "Humidity: ";
          webpage+= hum;
          webpage+= " %";

     webpage += "

";
     String cipSend = "AT+CIPSEND=";
     cipSend += connectionId;
     cipSend += ",";
     cipSend +=webpage.length();
     cipSend +="\r\n";
     sendData(cipSend,1000,DEBUG);
     sendData(webpage,1000,DEBUG);
     String closeCommand = "AT+CIPCLOSE=";
     closeCommand+=connectionId;
     closeCommand+="\r\n";
     sendData(closeCommand,3000,DEBUG);
    }
       }
      }

      String sendData(String command, const int timeout, boolean debug)
    {
    esp8266.listen();
    String response = "";
    esp8266.print(command);
    long int time = millis();
    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {
        char c = esp8266.read();
        response+=c;
      }
    }
    if(debug)
    {
      Serial.print(command);
      Serial.print("> ");
      Serial.print(response);
    }
    gps.listen();
    return response;
    }

  [1]: https://i.stack.imgur.com/Sa4CN.png
  [2]: https://i.stack.imgur.com/PF14m.png
  [3]: https://i.stack.imgur.com/WXYGy.png

title: Connecting wires and coding in GPS Module GY-NEO6MV2 with ESP8266-01

Answers: 1

body:
    GPS - Arduino
    ---------------
    GND -  GND
    TX  -  pin of SoftwareSerial RX
    RX  -  pin of SoftwareSerial TX
    Vcc -  3.3 V

Only one instance of SoftwareSerial can listen. Method listen() determines which one. So you must add `esp8266.listen();` before talking to esp8266 and `gps.listen();` before talking to GPS module.

 - in `setup()` add `esp8266.listen()` before first `sendData` call
 - in `loop()` add gps.listen() before `while (gps.available())`
 - in `loop()` add esp8266.listen() before `if (esp8266.available()) `


body:
I'm getting a redefinition error from my classes, but can't see what I did wrong.

**Error: Icon.cpp:3:6: error: redefinition of 'void Icon::setIcon(byte (*)[8])'**

Can any help me out on this? Thanks!

**MyFile.ino**

    #include "MyIcon.h"

    MyIcon myIcon;

**MyIcon.h**

    #ifndef MyIcon_h
    #define MyIcon_h

    #include "Arduino.h"
    #include "Icon.h"

    class MyIcon : public Icon {
      public:
        MyIcon();
    };

    #endif

**MyIcon.cpp**

    #include "MyIcon.h"

    MyIcon::MyIcon() {

      byte _icon[8][8] = {
        {1, 1, 1, 1, 1, 1, 1, 1},
        {1, 1, 2, 2, 2, 2, 1, 1},
        {1, 2, 1, 1, 1, 1, 2, 1},
        {2, 1, 2, 2, 2, 2, 1, 2},
        {1, 2, 1, 1, 1, 1, 2, 1},
        {1, 1, 1, 2, 2, 1, 1, 1},
        {1, 1, 2, 1, 1, 2, 1, 1},
        {0, 0, 0, 1, 1, 0, 0, 0},
      };
      MyIcon::setIcon(_icon);

**Icon.h**

    #ifndef Icon_h
    #define Icon_h

    #include "Arduino.h"

    typedef struct{
      byte r;
      byte g;
      byte b;
    } RGB;

    class Icon {
      public:
        Icon();
        inline virtual void setIcon(byte icon[8][8]){};
        inline virtual void setIconColors(RGB colors[3]){};
    };

    #endif

**Icon.cpp**

    #include "Icon.h"

    void Icon::setIcon(byte icon[8][8]) {
      __icon = icon;
    }

    void Icon::setIconColors(RGB colors[3]) {
      __colors = colors;
    }

**Edited on 09/11/18**

I attempted the following changes, before I realised thanks to KIIV, that I couldn't use array like that.

My idea was to be able to getIcon() and get back the byte array, which is later used to light up specific leds on a NeoMatrix panel.

I thought I would be able to build an icon "library" by extending a base class, setting the correct byte array in the class, and using it as needed (MyIcon, MyOtherIcon, etc...)

Have I completely missed the point?

**Icon.h**

    void setIcon(byte icon[8][8]);
    void setIconColors(RGB colors[3]);

**Icon.cpp**

    #include "Icon.h"

    Icon::Icon(){ }

    void Icon::setIcon(byte icon[8][8]){
      memcpy(__icon, icon, sizeof(icon));
    }

    void Icon::setIconColors(RGB colors[3]){
      memcpy(__colors, colors, sizeof(colors));
    }

title: Custom Classes - Redefinition of void error

Answers: 2

body:
You have bodies for `setIcon` and `setIconColors` in both the header file and the cpp file.  You can only have them in one or the other - choose.

Also, as an aside, the way that you are assigning icon data will go out of scope before you use it.  You create a local array variable which you then pass a pointer to to your constructor. That pointer is then saved. But then you go out of scope and the pointer is discarded, and the data will be overwritten.

body:
As Majenko writes, you are having two bodies.

The bodies in the header file are empty and probably you do not want this. It is normal to implement the functions in the cpp file (which you do), so in the header file remove the {} in

    inline virtual void setIcon(byte icon[8][8]){};
    inline virtual void setIconColors(RGB colors[3]){};

so it becomes

    inline virtual void setIcon(byte icon[8][8]);
    inline virtual void setIconColors(RGB colors[3]);


body:
I am having trouble configuring Arduino Due SPI to an [AD7490][1] ADC.

Here is how I have the pins connected:

 - +3.3V > 7490 pin 22 Vin
 - +3.3V > 7490 Vref
 - DUE CS (8) > 7490 pin 20 SS - slave select)
 - DUE SCK > 7490 pin 16 (SCK - clock)
 - DUE MOSI > 7490 pin 19 (MOSI - data out)
 - Ground > 7490 pin 24 (all ground lines are tied together)
 - DUE MISO > 7490 pin 15

Below is my code, I feel like I am writing the correct bits into the register. The problem I think I'm having is getting the timing write. The code is a simple attempt to read a single channel.

    #include <SPI.h>

    // Set Constants
    const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the
    ADC:

    // Start setup function:
    void setup() {

    pinMode (adcChipSelectPin, OUTPUT);
    // set the ChipSelectPins high initially:
    digitalWrite(adcChipSelectPin, HIGH);
    // initialise SPI:
    SPI.begin();
    SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be
    sure.
    SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be
    sure.
    Serial.begin(9600);
    //Clock Speed: Master clock/divider
    //84Mhz/64 =  1.3 MHz
    SPI.setClockDivider(SPI_CLOCK_DIV64);

    } // End setup function.

    // Start loop function:
    void loop() {
    float voltage[2];
    for (int i = 0; i < 3; i++) {
    voltage[i] = readAdc(0, 0);
    }

    }// End of loop function.

    //Function to read the ADC, accepts the channel to be read.
    float readAdc(int channel, int slave) {

    float value;
    if (slave == 0) {
    noInterrupts(); // disable interupts to prepare to send address data to the
    ADC.
    digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to
    select the ADC.

    byte FirstByte = 0b10000011;
    byte SecondByte = 0b00110000;

    SPI.transfer(FirstByte);

    byte response1 = SPI.transfer(SecondByte);
    byte response2 = SPI.transfer(0x00);

    digitalWrite(adcChipSelectPin, HIGH); // take the Chip Select pin high to
    de-select the ADC.
    interrupts(); // Enable interupts.
    Serial.println(response1);
    Serial.println(response2);

    }

The serial.prints output 255 consistently. In my experience this means the SPI is configured incorrectly.

Any pointers are appreciated.

  [1]: https://www.analog.com/media/en/technical-documentation/data-sheets/AD7490.pdf

title: Trouble configuring Arduino Due SPI to ADC

Answers: 1

body:
For anyone else who comes across the same problem, this worked for me:

    // include the library code:
    #include <SPI.h>

    // Set Constants
    const int adcChipSelectPin = 8;      // set pin 8 as the chip select for the ADC:

    // Start setup function:
    void setup() {
     pinMode (adcChipSelectPin, OUTPUT);

     // set the ChipSelectPins high initially:
     digitalWrite(adcChipSelectPin, HIGH);

     // initialise SPI:
     SPI.begin();
     SPI.setBitOrder(MSBFIRST);         // Not strictly needed but just to be sure.
     SPI.setDataMode(SPI_MODE0);        // Not strictly needed but just to be sure.
     Serial.begin(9600);

     //Clock Speed: Master clock/divider
     //84Mhz/64 =  1.3 MHz
     SPI.setClockDivider(SPI_CLOCK_DIV64);

     //Send dummy values over when ADC is turned on
     //Hold Din High for 16 clock cycles twice
     digitalWrite(adcChipSelectPin, LOW);
     SPI.transfer(0xFF);
     SPI.transfer(0xFF);
     digitalWrite(adcChipSelectPin, HIGH);

     digitalWrite(adcChipSelectPin, LOW);
     SPI.transfer(0xFF);
     SPI.transfer(0xFF);
     digitalWrite(adcChipSelectPin, HIGH);
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     //Send dummy values, next read should have correct values

     digitalWrite(adcChipSelectPin, LOW);
     byte FirstByte = 0x83;
     byte SecondByte = 0x50;
     byte response1 = SPI.transfer(FirstByte);
     byte response2 = SPI.transfer(SecondByte);

     digitalWrite(adcChipSelectPin, HIGH);

     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     ///////////////////////////////////////////////////////////////////////////////////

     //50ns quiet time?
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
     asm volatile("nop");
    } // End setup function.

    // Start loop function:
    void loop() {
     float voltage[2];
     for (int i = 1; i < 17; i++) {
      voltage[i] = readAdc(0, 1);
      //50ns quiet time?
      asm volatile("nop");
      asm volatile("nop");
      asm volatile("nop");
      asm volatile("nop");
      asm volatile("nop");
     }
    } // End of loop function.

    //Function to read the ADC, accepts the channel to be read.
    float readAdc(int channel, int slave) {
     float value;
     if (slave == 0) {
      byte FirstByte = 0x83;
      byte SecondByte = 0x50;
      FirstByte |= channel << 2;

      noInterrupts(); // disable interupts to prepare to send address data to the ADC.

      digitalWrite(adcChipSelectPin, LOW); // take the Chip Select pin low to select the ADC.
      //Write = 1
      //SEQ = 0
      // ADD3-ADD0 = 0000
      //PM1 = PM0 = 1
      //Shadow = 0
      //WEAK/Tri = 1
      //Range = 0
      //Coding = 1
      //0b10000010 1010 0000
      //extra 4 zeros to fill

      //May need to wait 16 * (1/freq)
      //16 * (1/1.3MHz)
      byte response1 = SPI.transfer(FirstByte);
      byte response2 = SPI.transfer(SecondByte);
      digitalWrite(adcChipSelectPin, HIGH);

      interrupts(); // Enable interupts.

      //Serial.println(response1);
      Serial.println(response2);
      byte channel = (response1 >> 4);
      //byte value = (response1 << 4);
      //byte digitalValue = (response1 << 4) | response2;
      //Serial.println(digitalValue);
      //Serial.println(channel);

      byte digitalValue = 0x00;
      float value = (float(digitalValue) * 3.3) / 4096.000; // The digital value is
      converted to an analogue voltage using a VREF of 2.048V.
      //Serial.print(channel);
      //Serial.print("\t");
      //Serial.println(value);
     }
    }


body:
I have written some code to test buttons that I want to use

    const int buttonPin1 = 1;
    const int buttonPin2 = 2;
    const int buttonPin3 = 3;
    const int buttonPin4 = 4;
    const int buttonPin5 = 5;
    const int buttonPin6 = 6;

    int buttonState1 = 0;
    int buttonState2 = 0;
    int buttonState3 = 0;
    int buttonState4 = 0;
    int buttonState5 = 0;
    int buttonState6 = 0;

    void setup() {
      Serial.begin(9600);
      pinMode(buttonPin1, INPUT_PULLUP);
      pinMode(buttonPin2, INPUT_PULLUP);
      pinMode(buttonPin3, INPUT_PULLUP);
      pinMode(buttonPin4, INPUT_PULLUP);
      pinMode(buttonPin5, INPUT_PULLUP);
      pinMode(buttonPin6, INPUT_PULLUP);
    }

    void loop() {
      buttonState1 = digitalRead(buttonPin1);
      buttonState2 = digitalRead(buttonPin2);
      buttonState3 = digitalRead(buttonPin3);
      buttonState4 = digitalRead(buttonPin4);
      buttonState5 = digitalRead(buttonPin5);
      buttonState6 = digitalRead(buttonPin6);

      if (buttonState1 == HIGH) {
        Serial.println("button1 press");
      }
      if (buttonState2 == HIGH){
        Serial.println("button2 press");
      }
      else if (buttonState3 == HIGH){
        Serial.println("button3 press");
      }
      else if (buttonState4 == HIGH){
        Serial.println("button4 press");
      }
      else if (buttonState5 == HIGH){
        Serial.println("button5 press");
      }
      else if (buttonState6 == HIGH){
        Serial.println("button6 press");
      }
      else{

      }
    }

I have tried with the buttonPins being A0-A5 as well, and whenever I try to run the code, it always spams out that button 5 and button 2 are being pressed, despite me not pressing them, as well as when I remove the buttons entirely, and pull out all the wires from it, it still prints it out. Even when I re-run the code. How can I fix this?

title: Button state changes despite not being connected?

Answers: 2

body:
You are setting button pins with INPUT_PULLUP mode, which activates internal resistor connected to supply voltage. In this way, your input pins are in state HIGH if disconnected or if button is not pressed.

To fix this, you need to compare your button state with LOW. Also, make sure that one side of your buttons is connected to ground. Then, pressing the button will connect the button to ground and will bring your button pin to LOW.

body:
The answer is in the way you configured the buttons. Because you used `INPUT_PULLUP`, the Arduino will read the pin as `HIGH` when it is connected to ground.

To utilize this in your setup, the buttons must be connected to ground, not 5V. This way, when the button is pressed, the input pin gets connected to ground, causing it to read `HIGH`.

Another way to fix the problem is to leave the buttons connected to 5V and just set the button pins to normal input: `pinMode(buttonPin, INPUT);`

----------

In summary, there are two fixes: either connect your buttons between the input pins and ground, not 5V **OR** use `pinMode(buttonPin, INPUT);`.


body:
I have a Pro Micro board at which tried to upload a sketch with sparkfun's Pro Micro 3.3v processor selected.

After the upload completed successfully the board did not run again and is not even detected from the arduino ide anymore.

When I uploaded sketches with the leonardo 5.5v board selected everything went well and I had no problem. Now I can not burn the bootloader because of the arduino ide not detecting the board.

What can i do?

title: Arduino Pro Micro bricked?

Answers: 2

body:
Problem solved! By taping twice the reset and holding it the second time I managed to program my board and now the arduino ide detectes it and it works as expected.

Taping and releasing the button twice did not work but holding it the second time worked for me. I am a almost complete noob in electronics for now so to me is black magic that not releasing the button did the job instead of what everyone else is suggesting.

I hope this helps a newbie sometime in the future that is frustrated with his/er bricked board

body:
After bricking a few units I finally sat down and read the manual for my [SparkFun Qwiic Pro Micro - USB-C (ATmega32U4)][1]. I also figured out the cause.

The cause of my unit bricking was bad code. Compiled and profiled fine, but crashed the unit when uploaded.  As a result the port became unavailable and seemingly gone.  In my particular case one brick was via and unsupported command in my source. The second brick was abuse of memory. Sketches would upload, then the unit dies and the no connection message pops up.

The solution for this unit was use of the reset switch with some key timing, and a trusted script to recapture the device.  [This page][2] was all I needed to read, classif #RTFM syndrome.

The following is a layman version of events for those less fortunate having not endured decades of software brain melt.

## Recovery in a Nutshell

The USB port/comm when working will/can flip between the "normal" mode and the bootloader mode.  Bootloader is a mode where the devices is exposed and can receive code and special commands.

If something, like the code, is causing the device to crash, such as I had, then the desired USB/serial port is not available.

### The Reset Switch

The reset switch may also be some pins to be shorted.  The manual talks about high/low and resistance.  Generally I have found you just short the damn thing, milage may vary. I used the button.

Per the instructions you can double tab the button and then I seem to trail off and not really absorb the rest. Eventually I got the pattern.

### The Pattern

If you double click the reset button the device goes into boot loader for 8 seconds.

Find a short "hello world" sketch and have it ready.

Double tap the reset button and **immediately** upload the sketch.

> That may not work...

When uploading a sketch the beginning of the upload is the compile step.  This must complete before there is anything to ship to the device.

I had to click upload and then double tap and get the timing right.  Eventually I would use the shortcut (CMD/CRTL + U).  The sketch takes and the device is back to normal.

Hope this helps someone - I needed the dummy version.

  [1]: https://www.sparkfun.com/products/15795
  [2]: https://learn.sparkfun.com/tutorials/qwiic-pro-micro-usb-c-atmega32u4-hookup-guide#ts-serial


body:
I'd like to split serial communication into the two channels: 1) debug info, 2) application data.

There's only one Serial object to use.

However, maybe, there is an alternative way to print data separately, is there?

P.S. I use Nano and UNO.

title: Can I have two separated serial monitor for the same arduino board connected to PC?

Answers: 5

body:
Not without adding more hardware, no.

You could add a usb to UART adapter and use software serial. Better would be to switch to a board that has a proper usb connection and a usb stack that supports multiple CDC/ACM instances, like a chipKIT board (Lenny, for instance).

body: You can add another channel with the SoftwareSerial library and an FTDI cable. The cable costs about US$17 in the US and is available here from Amazon, Sparkfun, and probably others. Internationally, I don't know. The SoftwareSerial library does have some limitations, most notably that it has to interrupts off while it's actually operating to get its baud rate right. But it does work and may be the simplest solution for you.

body:
As Majenko mentioned in his answer, you can connect a USB to UART adaptor such as a [PL2303HX][1] to your Uno (cost is $0.70 CDN). Just connect the RX, TX, GND pins to your Arduino correctly and include the SoftwareSerial Library in your sketch.

Here is a simple test sketch which is almost identical to the "SoftwareSerialExample" that comes with the SoftwareSerial Library.

    #include <SoftwareSerial.h>

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

    void setup(){
      Serial.begin(9600);
      Serial.println("Print to Serial Monitor");
      mySerial.begin(9600);
      mySerial.println("Print to SoftwareSerial");
    }

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

  [1]: https://www.aliexpress.com/item/30pcs-USB-to-TTL-USB-TTL-STC-microcontroller-programmer-PL2303-in-nine-upgrades-plate-with-a/1726023406.html

body:
Depending on your software environment, the simplest thing may be to
send all the data multiplexed through the single serial port, then split
it into two channels at the other end. For that, you will need some sort
of multiplexing protocol. If all your data is text and line oriented,
this may be as simple as prefixing each line with "1" or "2" to select
the appropriate channel:

<!-- language: lang-c++ -->

    Serial.println("1This app data goes to stdout.");
    Serial.println("2This diagnostic message goes to sterr.");

If you want to send arbitrary byte streams, you would instead use two
control characters for selecting the channels and an "escape" character
for when you want the control characters to be transmitted literally.

For convenience, you could encapsulate this logic into two separate
objects and implement `stdout.println()` and `stderr.println()`.

Then on the computer side, you will have to write a program that reads
the serial port and splits the received bytes into two separate streams.
How you implement those streams is OS-dependent. On an Unixish system I
would probably use pipes, or pseudo-terminals if I needed bidirectional
communication.

body:
If you want to have two Serial Monitors, start the IDE twice. Use your desktop shortcut or start menu entry to start the second instance of the IDE. In the second instance you can select a different port. It will not work for Upload of course, but when you open the Serial Monitor, it will work at the selected port.

Other option is to use some terminal program to see the output of the com port.

The other answers cover the fact that you need an USB to TTL Serial adapter to connect to USB and in sketch SoftwareSerial as your second serial interface or use some board with two or more hardware serial ports like the Mega on the picture.

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

  [1]: https://i.stack.imgur.com/utbBE.gif


body:
I'm trying to add a watchdog on an Arduino Nano, for my code, and I'm following exactly code in [this manual][1], but after the amount of time for not resetting the watchdog- it resets but does not reboot.

At last paragraph- it says that :"

> However, I could not find something similar in Optiboot bootloader (If
> I'm wrong, correct me please!), used by Arduino UNO and other new
> boards. It seems that they sacrificed this check for size. So, it is
> possible that watchdog timer will be enabled after reset, so -  if you
> set it's value too low, your board may never come out of bootloader
> stage. So, to be always on the safe side, set watchdog to longer
> periods (2S and more).

So I've tried for 8s, but still same result.

What is wrong ?

> EDIT1:

    #include <avr/wdt.h>
    int k=1;
    void setup() {
      Serial.begin(9600);
      wdt_enable(WDTO_8S);
    }
    void loop() {
      //do stuff here
      k++;
      wdt_reset();
      Serial.println(1000 * k);
      delay(1000 * k);

    }

  [1]: https://tushev.org/articles/arduino/5/arduino-and-watchdog-timer

title: WatchDog on Arduino Nano - does not recover

Answers: 4

body:
This works on an Uno R3.

The sketch restarts every 4 seconds when wdt_reset() is commented out.

Please copy the code and try it.

      #include <avr/wdt.h>

      void setup() {
        pinMode(13,OUTPUT);
        digitalWrite(13,LOW);

        delay(50);
        digitalWrite(13,HIGH);    // flicker the LED to identify when setup() is running
        delay(50);
        digitalWrite(13,LOW);
        delay(50);
        digitalWrite(13,HIGH);
        delay(50);
        digitalWrite(13,LOW);
        delay(50);
        digitalWrite(13,HIGH);
        delay(50);
        digitalWrite(13,LOW);
        delay(50);

        wdt_enable(WDTO_4S);

      }
      void loop() {
        digitalWrite(13,HIGH);
        delay(500);
        digitalWrite(13,LOW);
        delay(500);
        //wdt_reset();
       }

body:
the "old" Nano bootloader doesn't clear the Watchdog flag and while the bootloader waits for the upload, the board resets.

flash the "new" bootloader to Nano

In IDE 1.8.6 you can select version of Nano in Tools menu. It is the 'new' bootloader if you select "Atmega328p" and 'old' if you select "Atmega328p (Old bootloader)". If you invoke "Burn bootloader" it will use the bootloader for the selected option.

body:
> After that leds on board start to flicker non stop, and data stop
> posting on serial monitor

Definitely have a read of the datasheet for the '328p, section 11.8. There are several modes of operation - it can interrupt; reset; or both. Even if it resets, it doesn't reload your initial RAM data, so, for instance, line 2 `int k=1;` looks like an executable statement but is an initializer and has no effect at reset, and `k` retains its current value. There are probably other, similar, anomalies that happen when the WDT fires.

You probably don't need to understand the WDT down to its last control-bit but definitely make sure you're using it in the mode you want to be in. It will probably be handy during your testing to have a tiny sketch that just disables the watchdog so you can quickly get your Arduino back for the next test.

body:
I got the WDT working in my Nano with the old bootloader using this code from an old post on [Arduino Forum][1].

The code is added after the wdt_reset();

      //reset watchdog
      wdt_reset();
      //set up WDT interrupt
      WDTCSR = (1 << WDCE) | (1 << WDE);
      //Start watchdog timer with 4s prescaller
      WDTCSR = (1 << WDIE) | (1 << WDE) | (1 << WDP3) | (1 << WDP0);

  [1]: https://forum.arduino.cc/t/arduino-nano-wdt-problem/492906


body:
I'm new to Arduino and I'm trying to use PWM to generate a tone through a buzzer. I've created a `for` loop, however, the `for` loop doesn't seem to break when the variable `ms` is < 1000000.

    int second = 1000000; //1 second in microseconds

    void setup() {
      pinMode(3, OUTPUT);
      Serial.begin(9600);
    }

    void loop() {
      //Play middle C for 1 second
      for(int ms=0; ms <= second; ms+=3830)
      {
        digitalWrite(3, HIGH);
        delayMicroseconds(1915);
        digitalWrite(3, LOW);
        delayMicroseconds(1915);
        Serial.println(ms);
      }
      Serial.write("Finished C");
    }

[![Screenshot of serial monitor][1]][1]

We can see on the serial output that the value of `ms` exceeds 1000000 but the `for` loop is still going. Can anyone see where I am going wrong?

  [1]: https://i.stack.imgur.com/6lg5C.png "Screenshot of serial monitor"

title: Won't break out of for loop

Answers: 2

body:
An `int` can't hold 1000000.  It is a *signed 16-bit variable*, which means it can only hold between -32768 and +32767.

To store larger numbers you need to use `long`, or `unsigned long` which are signed and unsigned *32-bit* variables.

body:
In addition to Majenko's answer (an `int` on this platform can't hold a number greater than 32767) you have a second problem. You are evidently trying to make a middle C tone (261.6 Hz) by toggling a pin with a period of 1/261.6 seconds. However your Serial.println **takes time**. In particular at 9600 baud each byte you send will take 1/960 of a second (because there are 8 data bits, one start bit and one stop bit per byte), and assuming the number you are printing is roughly 4 digits, plus carriage return plus linefeed, you are sending 6 bytes for each time around the loop.

6 bytes of 1/960 (1042 µs) would be 6252 µs which completely dwarves your delays of 1915 µs.

Whenever you try to do things with timing loops you need to take account that **everything** in the loop takes time, not just your `delayMicroseconds` statements.


body:
I have the Arduino Uno (non-original replica) board, general SPI lcd, and GUVA-S12SD analog UV sensor module.
The board (powered via USB) reads the data from the analog pin 0, converts it to voltage (multiplying the readout by (5.0/1023.0) ) and prints out to the LCD.

Being illuminated with an UV-flashlight, the sensor gives unstable readouts varying for around 0.03-0.04 V each readout cycle. I am a complete noob in electronics, so I want to ask how can I check where the problem is? Is this my error in wiring, faulty module, just normal behaviour of an analog sensor or something else?

Mine sensor module isn't from Adafriut and looks a bit different, the one in the diagram is just to show the general wiring.

Thanks! [![wiring diagram][1]][1]

(Sensor module description: https://www.electroschematics.com/11509/guva-s12sd-uv-sensor-module-circuit/ )

The code of the sketch is:

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    int sensorValue;
    float sensorVoltage;
    LiquidCrystal_I2C lcd(0x27,16,2);  // display setup
    void setup() {
      lcd.init();
      lcd.backlight();
      lcd.setCursor(0, 0);
      lcd.print("");
    }

    void loop() {
      sensorValue = analogRead(A0);
      sensorVoltage = sensorValue * (5.0 / 1023.0);
      lcd.setCursor(0, 0);
      lcd.print(sensorVoltage/0.1); // rather low voltage is expected
      delay(1000);
    }

Update: I tried to measure the output with a multimeter (as Vasekdvor suggested in answers) and it showed very similar results: continuous 0.04-0.07 V oscillations. Their magnitude seems to grow along with the intensivity of the illumination.

With sensor being dark, multimeter shows 0.006 V (changing to 0.007 V occasionally) between A0 pin and the ground.

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

title: Unstable analog sensor readout

Answers: 1

body:
> the sensor gives unstable readouts varying for around 0.03-0.04 V each
> readout cycle

  If your sensor outputs 0 to 5V and you're only getting 0.03 to 0.04 variance then I would say that it's working pretty well.  You can get a more stable output by averaging several readings before printing them.

  Additionally, for even more stable readings consider powering your Audrino from a battery.  USB power can induce a considerable amount of noise if it's coming from a PC or Laptop USB port.  Also, there is a low noise mode where you can put the Arduino to sleep during your ADC reading (and it wakes up afterwards) which helps a lot with ADC noise reduction.


body: My Arduino Uno (r3) board seems to be broken. It can still be powered over USB, and can store/run code properly, but the DC power in system appears to be crippled. I'm not entirely sure what happened, but I was most likely being careless with the power in and the vin pin. I'm not sure what component(s) are broken, but when I plug in 12v into the barrel connector, the uno doesn't power on. I can read about 0.6 volts from the 5 volt pin, and at some other locations on the board. Besides the 0.6, the only other voltage I read is the 12 volt, although it is slightly lower than the power supply, which outputs about 12.2 volts. How can I go about fixing this? Or is it even worth it?

title: Broken Arduino Uno, works over USB but cannot take DC in

Answers: 1

body:
As you have noticed, measuring voltages is the first step. Here's some voltages for you and what they mean if they aren't there. These are all assuming precisely 12V in through the barrel jack. They are in order of "priority" - start at the top and work down, the first one that fails is your culpret (i.e., the barrel jack feeds VIN through the diode, VIN feeds 5V through the 5V regulator, and 5V feeds 3.3V through the 3.3V regulator).

* Roughly 11.4V on VIN - if it's not there the input protection diode has blown
* 5V on the 5V pin - if it's not there the 5V regulator has blown
* 3.3V on the 3.3V pin - if it's not there the 3.3V regulator has blown

Fixing it may be as simple as replacing the faulty component identified above - although they are all surface mount and some are more tricky to replace than others.  That said, if it is (as it sounds) the 5V regulator that has gone, that is one of the larger components (SOT-223) so should be eaiser to replace. Also it's dirt cheap - I get them for a few cents each in bulk.


body:
I have written some software which, when loaded onto an Arduino Micro, blocks communications for some reason. Lets stipulate that there is something wrong with it.

Using the Ardiono IDE on Windows 10, and (ex internet) pressing the board's reset button twice within 5 seconds of power-up, then (device manager) a comms port comes into existence for 2 seconds, presumably under control of the micro-controller's bootstrap program.

In the IDE, you can only select an existing comms port. As above, a comms port comes into existence for 2 seconds.

The download button causes compilation and downloading to the comms port - typically taking 8 seconds.

Thus, one can only replace the duff program by selecting the briefly available comms port, compiling and downloading to it, which takes longer that the port availability window.

And so replacing the duff code with anything is impossible. Have I missed something here? Does anyone have some "emergency" code that waits for a port to appear and immediately loads something innocuous?

BTW the Tags restriction is preventing me from using meaningful tags.

title: Arduino Comms disrupted, prevents program loading (catch 22)

Answers: 1

body:
I would suggest:

1. Turn on verbose compilation in the IDE.
2. Set up as you have been with the right port selected and go to upload - it will fail as normal
3. Find the `avrdude` command in the verbose output and copy the full command and its parameters
4. Open a command prompt or terminal window and paste in the command you copied (but don't run it yet).
5. Press reset twice to trigger the serial port creation
6. Run the command you pasted. It should immediately start uploading and "fix" your problem.


body:
The following source code is from the official ESP8266 website(Explanation provided): https://arduino-esp8266.readthedocs.io/en/latest/esp8266wifi/client-examples.html
This .ino code returns the html code of the server name mentioned in "const char* server" declaration, on to the Serial Monitor.

And Yes, this code perfectly returned the html codes of wwww.google.com, www.arduino.cc etc. But when I try it with my 'led blinking.html' I am unable to find any luck. I guess it is because the website should be hosted on a live server.

**Other Details:**
1. uC Board: Wemos D1 mini (An ESP8266 Variant)
2. I am using Xampp to run Apache server and MySQL
3. Wemos board is set up as a WiFiClient

    #include <ESP8266WiFi.h>

    const char* ssid = "xxxxx";
    const char* password = "xxxxxxxx";

**I have put the html,php code of the website in the directory :** C:/xampp/htdocs/LED BLINKING/led blinking.html

**IP Address of my Windows PC:** 192.168.100.9

    const char* server = "192.168.100.9/LED BLINKING/led blinking.html";

I tried with just "192.168.100.9"; too.
I also unblocked the windows firewall for my ApacheHTTP Server. Now I can view the webpage on my mobile with the URL: 192.168.100.9/LED BLINKING/led blinking.html.

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

      Serial.printf("Connecting to %s ", ssid);
      WiFi.begin(ssid, password);
      while (WiFi.status() != WL_CONNECTED)
      {
        delay(500);
        Serial.print(".");
      }
      Serial.println(" connected");
    }

    void loop()
    {
      WiFiClient client;

      Serial.printf("\n[Connecting ...");
      if (client.connect(server, 80))
      {
        Serial.println("connected]");

        Serial.println("[Sending a request]");
        client.print(String("GET /") + " HTTP/1.1\r\n" +
                     "server: " + server + "\r\n" +
                     "Connection: close\r\n" +
                     "\r\n"
                    );

       Serial.println("[Response:]");
        while (client.connected())
        {
          if (client.available())
          {
            String line = client.readStringUntil('\n');
            Serial.println(line);
          }
        }
        client.stop();
        Serial.println("\n[Disconnected]");
      }
      else
      {
        Serial.println("connection failed!]");
        client.stop();
      }
      delay(5000);
    }

The output on Serial Monitor is:
Connecting to ssid connected
[Connecting connection failed!]

title: How to access a website running on my localhost(host/server) to Serial Monitor using ESP8266(Client)?

Answers: 1

body:
Variable `server` is a hostname or IP address for TCP connection.
The `/LED BLINKING/led blinking.html` goes after HTTP GET. Now there is `/` and it worked for main page of servers.

You need

    client.print(String("GET /LED BLINKING/led blinking.htm") + " HTTP/1.1\r\n" +
                 "server: " + server + "\r\n" +
                 "Connection: close\r\n" +
                 "\r\n"
                );
and you must escape the space


body:
I'm doing a project on Arduino Uno and it requires me to connect 3 different sensors together: Waveshare 2.9 E-paper, MFRC522 RFID Reader and a ESP8266 wifi module. problem is, The e-paper and RFID uses the same multiple digital pins. How can I connect all of them together in a beardboard?

Edit:
The E-Paper uses:

    e-paper 3V3 -> Arduino 3V3
    e-paper GND -> Arduino GND
    e-paper DIN -> Arduino D11
    e-paper CLK -> Arduino D13
    e-paper CS -> Arduino D10
    e-paper DC -> Arduino D9
    e-paper RST -> Arduino D8
    e-paper BUSY -> Arduino D7

The rfid uses:

    SDA --> Digital 10
    SCK --> Digital 13
    MOSI --> Digital 11
    MISO --> Digital 12
    IRQ --> unconnected
    GND --> GND
    RST --> Digital 9
    3.3V -->3.3V

The wifi uses:

    GND --> GND
    VIN --> 3.3v
    Enable --> 3.3V
    TX --> RX
    RX --> TX

I'm very new to electronics so i'm sorry if something does not make sense

I'm using library, code and instructions from this 3 websites:

E-paper ( Waveshare 2.9 E-paper): https://www.instructables.com/id/Getting-Started-With-E-Paper-Display-Modules/

RFID (MFRC522 RFID Reader): https://randomnerdtutorials.com/security-access-using-mfrc522-rfid-reader-with-arduino/

Wi-Fi (ESP8266 wifi module): https://www.hackster.io/jeffpar0721/add-wifi-to-arduino-uno-663b9e

Thanks!

title: How can I connect multiple different sensors that uses the same pins?

Answers: 1

body:
You are lucky, the two devices creating the conflict both use the same pins because they both use the same interface, [SPI to be precise][1], which allows to have multiple devices connected using different `Chip Select` pins, abbreviated as `CS`.

Of the two libraries, one allows to define the `CS` pin (RFID module), the other has it hardcoded (ePaper). So, when declaring your RFID library, you should use the constructor that allows to define the chip select pin:

    void PCD_Init(byte chipSelectPin, byte resetPowerDownPin);

This means in your code you should use:

    PCD_Init(6,8) rfid;

The above also implies one of your RFID connections must be changed: what was previously `SDA --> Digital 10` is now going to be `SDA --> Digital 6`. Please note I picked pin 6 randomly among the pins that seem unused by your code, but any other unused pin will be a good choice, including analog pins.

BTW, the web page about the RFID module uses a pin naming which causes a lot of confusion because it mixes up `SDA` with `MISO` and `MOSI`: those names are used in two different types of interface, the former is called [I2C or TWI][2], the latter [SPI][1]. On Arduino the two interfaces share a couple of pins, but they are very different in many different ways.

In your case both modules use `SPI`, which is good for you.

  [1]: https://www.arduino.cc/en/Reference/SPI
  [2]: https://www.arduino.cc/en/Reference/Wire


body:
My web server running on ESP8266, stop working after while.
I cannot connect to it - browser shows `connection time out` error.
No error, no crash... nothing.

Have you any idea how to fix it?

My code:

    #include <ESP8266WiFi.h>
    #include <WiFiClient.h>
    #include <ESP8266WebServer.h>
    #include <NTPClient.h>
    #include <WiFiUdp.h>
    #include <ESP8266mDNS.h>
    #include <FS.h>

    #include "console.h"
    #include "tictactoe.h"
    #include "main.h"

    #define L_GREEN 2
    #define L_YELLOW 0
    #define L_ORANGE 4
    #define L_RED 5

    const char* ssid = "***";
    const char* password = "***";

    int requests = 0;
    String IPs = "[";

    IPAddress staticIP86_10(192,168,0,115);
    IPAddress gateway86_10(192,168,0,1);
    IPAddress subnet86_10(255,255,255,0);

    ESP8266WebServer server(80); //Server on port 80

    String getContentType(String filename);
    bool handleFileRead(String path);

    WiFiUDP ntpUDP;
    NTPClient timeClient(ntpUDP, "1.sk.pool.ntp.org", 60*60, 60*1000);

    //===============================================================
    // Game Data
    //===============================================================

    /*String ticPlayer1 = "";
    String ticPlayer2 = "";
    String ticClick = "-1";
    int ticReset = 0;*/

    //===============================================================
    // LEDs
    //===============================================================
    void LEDblink(int pin) {
      requests++;
      digitalWrite(pin, HIGH);
      delay(10);
      digitalWrite(pin, LOW);
    }
    //===============================================================
    // This routine is executed when you open its IP in browser
    //===============================================================
    void handleNotFound(){
      if(server.uri().indexOf(".php")>-1) {
        Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+" (Blocked)\n");
        return;
      }
      Serial.print("404 "+server.uri()+": "+server.client().remoteIP().toString()+"\n");
      String s = HTML_Pro_notFound;
      server.send(404, "text/html", s);

      LEDblink(L_YELLOW);
    }
    void sendFile(String path, String type) {
      Serial.print(server.client().remoteIP().toString()+": "+server.uri()+"\n");
      if (SPIFFS.exists(path)) {                            // If the file exists
        File file = SPIFFS.open(path, "r");                 // Open it
        size_t sent = server.streamFile(file, type);        // And send it to the client
        file.close();                                       // Then close the file again
      }
    }
    //===============================================================
    void reboot() {
     server.send(200, "text/plain", "true");
     LEDblink(L_RED);
     digitalWrite(15, LOW);
     digitalWrite(0, HIGH);
     digitalWrite(2, HIGH);
     ESP.restart();
    }
    void admin() {
     if(!server.hasArg("user") || !server.hasArg("pass") || server.arg("user") == NULL || server.arg("pass") == NULL || server.arg("request")=="login") {
        String expire = "";
        if(server.arg("remember")=="on"){expire="30";}else{expire="0";}
        server.send(200, "text/html", "<!DOCTYPE html><meta charset='UTF-8'><title>ProTools.tk | Please Wait</title><link rel='stylesheet' type='text/css' href='/main.css'><form class='center' action='/admin' method='post' style='display:none;'><input class='a' type='text' name='user'><input class='a' type='password' name='pass'><input class='a' type='text' name='request' value='panel'><button class='a' type='submit'></button></form>

");
        //server.sendHeader("Location","/login");
        //server.send(303);
     }
     if((server.arg("user")=="***")&&(server.arg("pass")=="***")) {
       if(server.arg("request")=="data") {
         String c = "{\"uptime\":"+String(millis(),DEC)+",\"req\":"+String(requests)+",\"ips\":"+IPs+"]}";
         server.send(200, "text/json", c);
       }
       else if(server.arg("request")=="panel") {
         server.send(200, "text/plain", "Admin panel here");
       }
       else {
        server.send(400, "text/plain", "400 Bad Request");
       }
     }
     else{
       server.sendHeader("Location","/login");
       server.send(303);
     }
     LEDblink(L_RED);
    }
    void console() {
     Serial.print("Console :"+server.client().remoteIP().toString()+"\n");
     String s = HTML_console;
     server.send(200, "text/html", s);
     LEDblink(L_ORANGE);
    }

    //===============================================================
    /*void minesPage() {
     String s = HTML_mines;
     server.send(200, "text/html", s);
     LEDblink(L_YELLOW);
    }
    void minesScript() {
     String s = JS_mines;
     server.send(200, "text/javascript", s);
     LEDblink(L_YELLOW);
    }
    void minesStyle() {
     String s = CSS_mines;
     server.send(200, "text/css", s);
     LEDblink(L_YELLOW);
    }*/

    //===============================================================

    /*void ticPage() {
     String s = HTML_tictactoe;
     server.send(200, "text/html", s);
     LEDblink(L_YELLOW);
    }
    void ticScript() {
     String s = JS_tictactoe;
     server.send(200, "text/javascript", s);
     LEDblink(L_YELLOW);
    }
    void ticStyle() {
     String s = CSS_tictactoe;
     server.send(200, "text/css", s);
     LEDblink(L_YELLOW);
    }

    void ticData() {
     Serial.print("TicTacToe: "+server.client().remoteIP().toString()+"\n");
     String user = server.arg("user");
     String clicked = server.arg("click");
     String request = server.arg("request");
     String leave = server.arg("leave");
     if(user != "") {
      if(user == "get") {
       server.send(200, "text/plain", "{\"Player1\":\""+ticPlayer1+"\", \"Player2\":\""+ticPlayer2+"\"}");
      }
      else if(ticPlayer1 == "") {
       ticPlayer1 = user;
       server.send(200, "text/plain", "player1");
      }
      else if(ticPlayer2 == "") {
       ticPlayer2 = user;
       server.send(200, "text/plain", "player2");
      }
      else {
       server.send(200, "text/plain", "Full");
      }
      if(ticPlayer1 != "" && ticPlayer2 != "") {
       ticClick = "0";
      }
      digitalWrite(L_ORANGE,HIGH);
      delay(500);
      digitalWrite(L_ORANGE,LOW);
     }
     else if(leave != "") {
      if(leave == ticPlayer1) {
       ticPlayer1 = "";
      }
      else if(leave == ticPlayer2) {
       ticPlayer2 = "";
      }
      ticClick = "-1";
      server.send(200, "text/plain", leave+" left");
     }
     else if(clicked != "") {
      ticClick = clicked;
      server.send(200, "text/plain", "OK: "+ticClick);
     }
     else if(request != "") {
      if(request == "checkClicked") {
       server.send(200, "text/plain", ticClick);
      }
      if(request == "reset") {
       ticReset++;
       if(ticReset == 2) {
        ticPlayer1 = "";
        ticPlayer2 = "";
        ticClick = "-1";
        ticReset = 0;
        server.send(200, "text/plain", "Reseted");
       }
       else {
        server.send(200, "text/plain", "Verification required");
       }
      }
     }
     LEDblink(L_YELLOW);
    }*/
    //==============================================================
    //                  SETUP
    //==============================================================
    void setup(void){
      Serial.begin(9600);

      //Onboard LED port Direction output
      pinMode(L_GREEN,OUTPUT);
      pinMode(L_YELLOW,OUTPUT);
      pinMode(L_ORANGE,OUTPUT);
      pinMode(L_RED,OUTPUT);

      digitalWrite(L_RED, HIGH);

      WiFi.hostname("ESP8266");

      WiFi.begin(ssid, password);     //Connect to your WiFi router

      MDNS.begin("ESP8266");
      MDNS.addService("http", "tcp", 80);

      digitalWrite(L_RED, LOW);
      // Wait for connection
      digitalWrite(L_ORANGE, HIGH);
      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      digitalWrite(L_ORANGE, LOW);
      digitalWrite(L_YELLOW, HIGH);

      WiFi.config(staticIP86_10, gateway86_10, subnet86_10);

      //If connection successful show IP address in serial monitor
      Serial.println("");
      Serial.print("Connected to ");
      Serial.println(ssid);
      Serial.print("IP address: ");
      Serial.println(WiFi.localIP());  //IP address assigned to your ESP

      SPIFFS.begin();

      server.on("/", []() {                                          // root
        sendFile("/page.html", "text/html");
        LEDblink(L_YELLOW);
      });
      server.on("/main.css", []() {                                  // main.css
        sendFile("/main.css", "text/css");
        LEDblink(L_ORANGE);
      });
      server.on("/page.css", []() {                                  // page.css
        sendFile("/page.css", "text/css");
        LEDblink(L_ORANGE);
      });
      server.on("/page.js", []() {                                   // page.js
        sendFile("/page.js", "text/javascript");
        String ip = server.client().remoteIP().toString();
        if(IPs=="["){
          IPs+="{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
        }else{
          IPs+=",{\"time\":"+String(timeClient.getEpochTime(),DEC)+",\"ip\":\""+ip+"\"}";
        }
        LEDblink(L_YELLOW);
      });
      server.on("/login/style.css", []() {                           // login/style.css
        sendFile("/login/style.css", "text/css");
        LEDblink(L_ORANGE);
      });
      server.on("/cookies.js", []() {                                // cookies.js
        sendFile("/cookies.js", "text/javascript");
        LEDblink(L_ORANGE);
      });

      server.on("/translator", []() {                                // translator
        sendFile("/translator/page.html", "text/html");
        LEDblink(L_ORANGE);
      });
      server.on("/translator/style.css", []() {                      // translator/style.css
        sendFile("/translator/style.css", "text/css");
        LEDblink(L_ORANGE);
      });
      server.on("/translator/script.js", []() {                      // translator/script.js
        sendFile("/translator/script.js", "text/javascript");
        LEDblink(L_ORANGE);
      });

      server.on("/login", []() {                                     // login
        sendFile("/login/page.html", "text/html");
        LEDblink(L_ORANGE);
      });
      server.on("/admin", admin);
      server.on("/reboot", reboot);
      server.on("/console", console);

      /*server.on("/minesweeper", minesPage);
      server.on("/minesweeper/script.js", minesScript);
      server.on("/minesweeper/style.css", minesStyle);

      server.on("/tictactoe", ticPage);
      server.on("/tictactoe/script.js", ticScript);
      server.on("/tictactoe/style.css", ticStyle);
      server.on("/tictactoe/data", ticData);*/

      server.onNotFound(handleNotFound);

      server.begin();                  //Start server
      timeClient.begin();
      Serial.println("HTTP server started");
      digitalWrite(L_YELLOW, LOW);
      digitalWrite(L_GREEN, HIGH);
    }
    //==============================================================
    //                     LOOP
    //==============================================================
    void loop(void){
      timeClient.update();
      server.handleClient();          //Handle client requests
    }

title: ESP8266 WebServer not responding (connection time out)

Answers: 1

body: Use the latest version of Arduino esp8266 core package (2.4.2 or higher).


body:
I'm trying to get GPS coordinates using TinyGPS. But it keeps printing ********* for the data fields. Any idea on how to get this working?. Here is what the serial monitor looks like. [![enter image description here][1]][1]

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

Here is my code

    #include <SoftwareSerial.h>

    #include <TinyGPS.h>

    /* This sample code demonstrates the normal use of a TinyGPS object.
       It requires the use of SoftwareSerial, and assumes that you have a
       4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
    */

    TinyGPS gps;
    SoftwareSerial ss(1, 0);

    static void smartdelay(unsigned long ms);
    static void print_float(float val, float invalid, int len, int prec);
    static void print_int(unsigned long val, unsigned long invalid, int len);
    static void print_date(TinyGPS &gps);
    static void print_str(const char *str, int len);

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

      Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
      Serial.println("by Mikal Hart");
      Serial.println();
      Serial.println("Sats HDOP Latitude  Longitude  Fix  Date       Time     Date Alt    Course Speed Card  Distance Course Card  Chars Sentences Checksum");
      Serial.println("          (deg)     (deg)      Age                      Age  (m)    --- from GPS ----  ---- to London  ----  RX    RX        Fail");
      Serial.println("-------------------------------------------------------------------------------------------------------------------------------------");

      ss.begin(4800);
    }

    void loop()
    {
      float flat, flon;
      unsigned long age, date, time, chars = 0;
      unsigned short sentences = 0, failed = 0;
      static const double LONDON_LAT = 51.508131, LONDON_LON = -0.128002;

      print_int(gps.satellites(), TinyGPS::GPS_INVALID_SATELLITES, 5);
      print_int(gps.hdop(), TinyGPS::GPS_INVALID_HDOP, 5);
      gps.f_get_position(&flat, &flon, &age);
      print_float(flat, TinyGPS::GPS_INVALID_F_ANGLE, 10, 6);
      print_float(flon, TinyGPS::GPS_INVALID_F_ANGLE, 11, 6);
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      print_date(gps);
      print_float(gps.f_altitude(), TinyGPS::GPS_INVALID_F_ALTITUDE, 7, 2);
      print_float(gps.f_course(), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
      print_float(gps.f_speed_kmph(), TinyGPS::GPS_INVALID_F_SPEED, 6, 2);
      print_str(gps.f_course() == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(gps.f_course()), 6);
      print_int(flat == TinyGPS::GPS_INVALID_F_ANGLE ? 0xFFFFFFFF : (unsigned long)TinyGPS::distance_between(flat, flon, LONDON_LAT, LONDON_LON) / 1000, 0xFFFFFFFF, 9);
      print_float(flat == TinyGPS::GPS_INVALID_F_ANGLE ? TinyGPS::GPS_INVALID_F_ANGLE : TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON), TinyGPS::GPS_INVALID_F_ANGLE, 7, 2);
      print_str(flat == TinyGPS::GPS_INVALID_F_ANGLE ? "*** " : TinyGPS::cardinal(TinyGPS::course_to(flat, flon, LONDON_LAT, LONDON_LON)), 6);

      gps.stats(&chars, &sentences, &failed);
      print_int(chars, 0xFFFFFFFF, 6);
      print_int(sentences, 0xFFFFFFFF, 10);
      print_int(failed, 0xFFFFFFFF, 9);
      Serial.println();

      smartdelay(1000);
    }

    static void smartdelay(unsigned long ms)
    {
      unsigned long start = millis();
      do
      {
        while (ss.available())
          gps.encode(ss.read());
      } while (millis() - start < ms);
    }

    static void print_float(float val, float invalid, int len, int prec)
    {
      if (val == invalid)
      {
        while (len-- > 1)
          Serial.print('*');
        Serial.print(' ');
      }
      else
      {
        Serial.print(val, prec);
        int vi = abs((int)val);
        int flen = prec + (val < 0.0 ? 2 : 1); // . and -
        flen += vi >= 1000 ? 4 : vi >= 100 ? 3 : vi >= 10 ? 2 : 1;
        for (int i=flen; i<len; ++i)
          Serial.print(' ');
      }
      smartdelay(0);
    }

    static void print_int(unsigned long val, unsigned long invalid, int len)
    {
      char sz[32];
      if (val == invalid)
        strcpy(sz, "*******");
      else
        sprintf(sz, "%ld", val);
      sz[len] = 0;
      for (int i=strlen(sz); i<len; ++i)
        sz[i] = ' ';
      if (len > 0)
        sz[len-1] = ' ';
      Serial.print(sz);
      smartdelay(0);
    }

    static void print_date(TinyGPS &gps)
    {
      int year;
      byte month, day, hour, minute, second, hundredths;
      unsigned long age;
      gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
      if (age == TinyGPS::GPS_INVALID_AGE)
        Serial.print("********** ******** ");
      else
      {
        char sz[32];
        sprintf(sz, "d/d/d d:d:d ",
            month, day, year, hour, minute, second);
        Serial.print(sz);
      }
      print_int(age, TinyGPS::GPS_INVALID_AGE, 5);
      smartdelay(0);
    }

    static void print_str(const char *str, int len)
    {
      int slen = strlen(str);
      for (int i=0; i<len; ++i)
        Serial.print(i<slen ? str[i] : ' ');
      smartdelay(0);
    }

title: TinyGPS doesn't give longitude latitude and other data

Answers: 2

body:
    #include <SoftwareSerial.h>
    #include <TinyGPS++.h>
    #include <SPI.h>

    float lattitude,longitude; // create variable for latitude and longitude object
    SoftwareSerial gpsSerial(8,9);//rx,tx
    TinyGPSPlus gps;// create gps object

    void setup(){
        Serial.begin(9600); // connect serial
        gpsSerial.begin(9600); // connect gps sensor
        delay(1000);
    }

    void loop(){

      while(1)
      {
       while (gpsSerial.available() > 0)
       { gps.encode(gpsSerial.read()); }

          if (gps.location.isUpdated())
          {
           lattitude=gps.location.lat();
           longitude=gps.location.lng();
           break;
          }

     }
       Serial.print("LATTITUDE="); Serial.println(lattitude,6);
       Serial.print("LONGITUDE="); Serial.println(longitude,6);
       delay(1000);
    }

I managed to get it working using the following library `TinyGPS++.h`

body:
From the description:
It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
But you are using Pin0 and Pin 1, as shown in your code:
SoftwareSerial ss(1, 0);
given that pin0 and pin one are hard Tx and Rx may create problems.

to check if the GPS is receiving anything use the BareMinimum sketch:
void setup() {
  // put your setup code here, to run once:
}
void loop() {
  // put your main code here, to run repeatedly:
}

//Remember that Tx connects to Tx and Rx to Rx

that will show the NMEA string in the serial monitor.
(you can see a video about it, search for:"GPS Module with Arduino- Ublox NEO-6M"

Note:
in TinyGPS the Rx connects to Tx and Tx connects to Rx...

In case you use Softwareserial.h with Arduino Mega  you may have issues as not all pins can Rx (receive)... please check:
https://www.arduino.cc/en/Reference/SoftwareSerial

for NEO-6M the seed should be 9600baud, not 4800 as shown in the sketch, please check page 11 on:

https://www.u-blox.com/sites/default/files/products/documents/NEO-6_DataSheet_(GPS.G6-HW-09005).pdf

Also change Serial.begin(115200); to 9600  so they are in sync.


body:
I have Feetech FS5323M servo, with Sweep example code from Arduino site, it works fine, it rotates from 0 to 180 degree and back as expected.

The problem comes when I try to set servo position. I've added a simple `servo.write(90);` in setup, to reset servo position, but it didn't work (`writeMicroseconds(1500);` also failed).

After digging a little bit, I've discovered that I can rotate the servo only by a couple of degrees from its current physical position.

If the servo is at 140 degrees, I can move it back and forth only up to 7 degrees, value bigger than this will result in servo staying at its current position. So if I want to move it to 180 degrees I have to make a loop and go to this position in steps of 1-7 degrees (with delay = 15 * degree).

I attached external 2A power to the circuit and connected the grounds. It didn't solve the problem. The circuit is very simple, just servo connected to pin 3, without anything else. I also tried to add a 300uF capacitor between power and ground.

**Edit 1:**
I've tested pin 9 and 10 and the same happens. Sadly I have no way to test it on any other board because I have only one, same goes for the servo. I uploaded sweep example with the step size of 10, the servo didn't move or even twitched. I tried it both with a delay of 15 as well as 150.

**Edit 2:**
I've tested the program with only one `servo.write(90);` statement, but the issue hasn't been resolved. I tried it in setup and later in loop, in both programs there was only one `write` statement.

title: Servo can be moved only in steps of couple degree

Answers: 2

body:
> The problem comes when I try to set servo position. I've added a
> simple servo.write(90); in setup, to reset servo position, but it
> didn't work

Understand that the method "setup()" in the Arduino paradigm is only run once after power up or reset.  Any code in "setup()" which positions the servo will immediately get over written by the code that positions the servo in the "loop()" method.  Likely this happens so quickly that the servo will not even react to the line "servo.write(90);".

body:
Your servo should be powered separately from the Arduino as it draws 150mA just running and its stall current is well over an amp, according to the [specs on this page][1]. If you're powering it from the Arduino, it is quite likely that it drags the Arduino's supply voltage down enough to shut down the processor, but you may be getting away with it for very short moves.

  [1]: https://feixiang668.en.made-in-china.com/product/gvkElyHjHmAD/China-2018-Feetech-New-20kg-High-Torque-Aluminum-Middle-Case-Metal-Gears-Digital-Servo-Traxxas.html


body: I need to bootload my Uno board but I do not have another Arduino at my disposal so how do I bootload without another Arduino board

title: How to burn bootloader into arduino uno without using another arduino

Answers: 2

body:
There are 3 main options how to write bootloader or program to AVR over ISP.

 1. [dedicated AVR programmer][1] or [Arduino ISP programmer][2]
 2. other Arduino with Arduino as ISP sketch or similar
 3. [parallel port of a computer][3]

  [1]: http://www.ladyada.net/learn/avr/programmers.html
  [2]: https://store.arduino.cc/arduino-isp
  [3]: https://www.instructables.com/id/Simplest-AVR-Parallel-port-programmer/

body:
The USBTinyISP programmer attaches to your computer's USB port and uses the 6-pin ICSP port on your Arduino to program it.  It can program both bootloaders and sketches.  It can be purchased for less than $10 from Amazon or Ebay.

[USBTinyISP programmer][1]

  [1]: http://www.amazon.com/SODIAL-microcontroller-USBtinyISP-downloader-ATTINY2313A-PU/dp/B075LJPF4L


body:
i would like to ask you for help with design of an circuit.

I have and atmega328p, with detection for voltage on its Vin (Vcc).
I have made and voltage divider and its output i connected to Analog Pin. And i would like to, if an voltage decrease under an certain level (4.5V), to shutdown itself (atmega328p).

As i said the voltage detection is no problem (there is an voltage divider), programing it is as well no problem, but i though that i program it like this:

> Detect voltage on analog pin A0, if the voltage is less than certain
> level (4.5V), write to memory and send to digital pin 3 an "LOW" (0)
> logical state.

This will turn the mosfet off and the atmega will loose its ground (GND) and its shuts down, but i have there an pull-up resistor which when the atmega shutsdown takes its lead an set Gate at MOSFET to high (transistor will turn on) and atmega turns on, then it shuts down and this will do the infinite cycling until there's no power to turn on atmega.

I want to use an Supercapacitor (2.2F 5.5V) to power it when the main input is lost and to give an atmega a time to write to memory and steadily turns off.

I am adding an schematics to better look at the problem.

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

*I know that there is no crystal and capacitors and the other things to make it reliable and fully functional, but this is not a subject of this question.Its an first sketch, which is not completed.*

I know some ICs that can detect Voltage and turn its output to some logical state (1 or 0), like an MAX809 (803 or 810) and so on and of course this is my backup plan, but i want to ask you, if you have any great idea to make this without any special ICs and more easily? I also thought about some OPamp or thyristor maybe, i don't know......

Can you help me with an idea or better with an schematics how to do it ? Thanks.

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

title: Arduino write to memory and self shut down (over MOSFET) - An idea help

Answers: 2

body:
It would be easier to simply to power down the CPU using software once you're ready to shut down:

    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    cli();
    sleep_enable();
    sleep_bod_disable();
    sei();
    sleep_cpu();

body:
You should be using a P-channel MOSFET (which is set to be normally OFF with a pull-up resistor) and the Arduino is responsible for keeping it on:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

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

<!-- End schematic -->

In this schematic M1 is normally off.  You press and hold SW1 and the Arduino gets power. The first thing it then does is turn on the GPIO. That turns M2 on, which in turn pulls the gate of M1 LOW turning it on. You can now release M1 and the Arduino will stay on.  When you want to turn off, just switch off the GPIO, turning off M2, which then allows R1 to pull the gate of M1 up again turning off the power.

This arrangement means:

* You can control an incoming voltage higher than 5V (thanks to M2 doing the actual switching of the power MOSFET)
* You get a soft-power switch to turn the power on
* Current draw of the control circuit is basically the incoming voltage divided by the resistance of R1 (you can safely increase this if you want to reduce current draw - 1MΩ is fine).
* You can have all the rest of the circuitry on the Arduino side of M1 so it has power removed when switched off (to prevent over-discharge of your batteries)
* You are switching VCC, not GND (switching GND can cause all sorts of problems).


body:
I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.

My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?

The simulator feeds a `float val` that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the `AccelStepper` library.
<!-- language-all: lang-cpp -->

    void ProgOut(byte id, float val) {
    switch (1) {
    case 1:

    if (val)
            { stepper1.moveTo(val * 11.3222222);         }

            stepper1.run();

    break; }}

I have tried something like this:

    void ProgOut(byte id, float val) {
    switch (1) {
    case 1:
    if ( stepper1.distanceToGo () >= 4064){
              stepper1.moveTo(4076);
              stepper1.setCurrentPosition(0);
    }
        else if (val)
            {

                    stepper1.moveTo(val * 11.3222222);
            }

            stepper1.run();

    break; }}

title: How do I make a stepper motor compass cross 360° to 0°?

Answers: 2

body:
Two options (for starters):

1. Use the `move()` class rather than the `moveTo()` class. This will allow you to do relative moves rather than absolute.
2. Use `setCurrentPosition()` (which sets the current position to zero) followed by `moveTo()` with a destination which is `newPos - prevPos`.

For either to work you will need to keep track of the current position of the needle.

To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.

    // delta is the angular adjustment required.
    delta = (currHeading + 180 - prevHeading) % 360 - 180;
    setCurrentPosition();        // Zero the motor.
    moveTo(delta);               // Move absolute from the new zero.
    prevHeading = currHeading;   // Keep track.

- The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
- Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.

body:
Also working on making a compass for flight simulator.
Hopefully the following code will help answer the question.
This is a working code that I have tested using serial monitor...
Note: For Flight Sim use, I did find that to get enough speed and smooth movement for the X27-168 gauge motor you need to use a stepper driver with microstepping rather than driving the X27-168 directly from the Nano I/O pins. You will have to adjust Max speed & acceleration and also edit the firmware for micro-stepping with using a stepper driver. Note: When using a stepper driver chip, you need to use the correct type for 6 step coil energising that the X27-168 stepper uses eg. AX1201728SG. Polulu (A4988) type stepper drivers use 8 steps coil energisation which will not move the gauge motor correctly - while it will move the gauge motor it creates a lot of noise and is not ideal.

I did have to add the following to get both left and right movements through North.
I used Movement rather than delta -
        if(Movement( < -180){Movement = Movement + 360;}

A single movement of 180 degrees defaults to CCW direction. however with Flight simulator data extraction, you shouldn't get a single movement of that amount.

-----------------------------------------------------
****

    /*Analog Compass Gauge.**
    This uses an Arduino Nano processor that has four of its I/O's directly connected to an X27-168 geared stepper motor(Gauge indicator motor).
    While it works, there should really be four sets of protection diodes across each of the I/O pins - diode to +5V & diode to 0V to eliminate spikes over 5v and below 0v on each I/O pin.
    The X27-168 geared stepper motor has had the internal stop cut off on the main output shaft gear to allow full 360 degree movement.
    A 55mm dia plastic round plate has been fitted to the X27-168 geared stepper motor 1mm diameter drive shaft and a printed label attached to the plate to show compass direction.
    The plastic plate has a small Neodymium magnet (1mm dia x 2mm long) which can pass near a Hall Effect sensor (A3144)to provide a homing reference signal.
    +5v,0v and I/O signal pin is connected directly to the Hall Effect sensor. The Nano internal I/O resistor is used to provide a pullup voltage for the Hall effect sensor signal.  The firmware uses the AccelStepper library.
    PC Serial Monitor is used to enter new compass headings.
    The X27-168 geared stepper motor is referred to as "stepper1" in the firmware.
    */
        #include "AccelStepper.h"
            AccelStepper Stepper1(AccelStepper::FULL4WIRE, 3, 4, 5, 6);   // Define stepper I/O pins (Using I/O pins connected directly to X27-168 Geared Stepper Motor)
           //AccelStepper Stepper1(AccelStepper::DRIVER, 2, 5); // Defines I/O pins when using a stepper driver e.g. AX1201728SG Quad driver chip -  Dir pin - Stepper pin
           #define Home_Sensor      2   // Pin 2 - Connected to Home Sensor - Hall Effect A3144- (0v when sensed)
           int Offset = -67;   // ****** Adjust this setting to ensure North facing when at Home Position(0)  ******
           int MaxSpeed = 80;   // ****** Adjust this setting for Max Speed of Stepper as to not miss steps    ******
           int Acceleration = 25   // ****** Adjust this setting for Acceleration of Stepper as to not miss steps ******
           int    Move_finished =   1;   // Used to check if move is completed
           long   Initial_Homing = -1;   // Used to Home Stepper at startup
           String InputString =    "";   // String to hold incoming data from serial monitor
           bool   StringComplete = false;   // Whether the string is complete
           int    LastHeading = 0;   // Register for Last heading
           int    NewHeading  = 0;   // Register for New heading
           int    Movement;   // Register for difference between Last and New heading
           void setup() {
           Serial.begin(9600);   // Start the Serial monitor at 9600 Baud
           pinMode(Home_Sensor, INPUT_PULLUP);   // Using internal pullup for Hall Effect sensor
           delay(5);   // Wait for stepper Driver wake up (if used)
           Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Max Speed of Stepper (Slower to get better accuracy)
           Stepper1.setAcceleration(Acceleration );   // Intial Homing Acceleration of Stepper
           Serial.println("........ Homing Stepper ........");

           while (digitalRead(Home_Sensor)) {   // Make the Stepper1 move CW until the sensor is activated
           Stepper1.moveTo(Initial_Homing);   // Set the position to move to
           Initial_Homing--;   // Decrease by 1 for next move if needed
           Stepper1.run();   // Start moving stepper1
           delay(5);
           }
           Stepper1.setCurrentPosition(0);   // Set the current position as zero for now
           Initial_Homing=1;
           while (!digitalRead(Home_Sensor)) {   // Make the Stepper1 move CCW until the sensor is deactivated
           Stepper1.moveTo(Initial_Homing);
           Stepper1.run();
           Initial_Homing++;
           }
           //**** Should now be Homed to Magnet position which may not be North as per label. Below allows tuning to correct position of label ****
           Stepper1.setCurrentPosition(0);
           Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Correction Max Speed of Stepper1
           Stepper1.setAcceleration(Acceleration );   // Intial Homing Correction Acceleration of Stepper1

           Stepper1.moveTo(Offset);   // To correct to have North as Home position
           while(Stepper1.distanceToGo() != 0){Stepper1.run();}   // Step to adjusted home position
           Stepper1.setCurrentPosition(0);   // Set Home position that will be used for all further movements..
           Serial.println("........ Homing Completed ........");
           Serial.println(" *** Enter Compass Heading 0 - 259 Degrees ***");
           // ---------   End of intial Homing Setup  ------------
           }
           void loop() {
           while (Serial.available() > 0) {   // Read serial input:
           int InChar = Serial.read();
           if (isDigit(InChar)) {InputString += (char)InChar;}   // Convert the incoming byte to a char and add it to the string
           if (InChar == '\n') {   // If you get a newline,
           NewHeading = (InputString.toInt());   // Convert input heading string to int value heading
           NewHeading = (NewHeading/2)*2;   // Eliminates 1 degree movements. Reduces movement errors with small movements
           Serial.print(NewHeading);

           if(NewHeading > 359 ||NewHeading < 0) {   // Displays error message if input is out of range
           NewHeading = LastHeading;   // No change due to incorrect data entered
           Serial.println("Input Error. Enter value between 0 - 259 Degrees ");
           }
           else { Serial.print("Heading "); Serial.print(NewHeading); Serial.println("...  Enter New Heading");

           }
           InputString = "";   // Clear the string for new input:
           Movement = ((NewHeading + 180 - LastHeading) % 360) - 180;   // Allows movement from North East to North West
           if(Movement < -180){Movement = Movement + 360;}   // Allows movement from North West to North East
           Stepper1.setCurrentPosition(0);   // Zero the motor.
           Stepper1.setMaxSpeed(MaxSpeed);   // Set Max Speed of Stepper1
           Stepper1.setAcceleration(Acceleration );   // Set Acceleration of Stepper1

           Stepper1.move(Movement*2);   // Set new move to position of Stepper1
           LastHeading = NewHeading;   // New heading now becomes last heading
           }
           }
           while(Stepper1.distanceToGo() != 0){Stepper1.run();   // Keep updating AccelStepper for current movement
           int XInChar = Serial.read();XInChar = Serial.read();}   // Keep clearing serial buffer- Only allow new heading input once movement finished.
           }


body:
I am trying to emulate the behavior of a circuit using an Attiny85

This is the result I got so far:

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

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

In the picture above, D2 is VCC, D4, D5 and D6 are outputs of the circuit I am trying to emulate. D7 is the output of Attiny85

The code I am using is:

 #define F_CPU 8000000L
 #include <avr/io.h>
 #include <avr/interrupt.h>
 #include <util/delay.h>

 int main() {

   DDRB = 0b00001000;

   PORTB = 0b00001000;
   _delay_ms(5);

   PORTB = 0b00000000;
   _delay_ms(5);
   PORTB = 0b00001000;
   _delay_ms(5);

   PORTB = 0b00000000;
   _delay_ms(5);

   _delay_ms(5);

   while(1)
   {
      PORTB = 0b00001000;
     _delay_ms(1);
      PORTB = 0b00000000;
     _delay_ms(1);
   }
  return 0;
 }

According to this, it takes roughly 64ms from powerup until it actually run the main program.

Is there any reason for such a delay? How can I reduce it somehow (ideally to 20ms or less)?

title: How long does it takes for arduino to reach main()?

Answers: 1

body:
The ATtiny85 has a built-in delay counter that keeps the MCU in reset
mode for some time after the power is applied. This seems to be intended
as a wait for the clock and power to be stabilized. The length of this
delay depends on your selected clock source, and is somewhat
configurable with the fuses.

According to your code, your MCU is clocked at 8 MHz. I assume you
are then using the internal RC oscillator as a clock source. If this is
the case, you have three choices for the startup delay:

- 20 CPU cycles
- 20 CPU cycles + 4 ms
- 20 CPU cycles + 64 ms

The latter is recommended if your power rises slowly, and is the default
configuration in which these MCUs are shipped. If you power level rises
fast, you may want to select a shorter delay by programming the SUT
fuses. See the datasheet for details (section System Clock and Clock
Options → Clock Sources → Calibrated Internal Oscillator).


body:
I need to connect NodeMCU and NRF24L01. where I'm receiving data from another NRF24L01 Transmission. I managed to connect to a WiFi network but the data receiving is not taking place as expected. Here is my code

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

    RF24 myRadio(7, 8);
    const char* ssid = "******";
    const char* password = "********";
    struct package
    {
        int id = 0;
        float longitude = 0.0;
        float latitude = 0.0;
        char text[100] = "empty";
    };

    byte addresses[][6] = {"0"};

    typedef struct package Package;
    Package data;

    void setup()
    {
        Serial.begin(115200);
        delay(1000);
        WiFi.begin(ssid, password);

        Serial.println();
        Serial.print("Connecting");
        while (WiFi.status() != WL_CONNECTED)
        {
         delay(500);
         Serial.print(".");
        }
        Serial.println("success!");
        Serial.print("IP Address is: ");
        Serial.println(WiFi.localIP());
        myRadio.begin();
        myRadio.setChannel(115);
        myRadio.setPALevel(RF24_PA_MAX);
        myRadio.setDataRate(RF24_250KBPS);
        myRadio.openReadingPipe(1, addresses[0]);
        myRadio.startListening();
    }

    void loop()
    {

        if (myRadio.available())
        {
            while (myRadio.available())
            {
                myRadio.read(&data, sizeof(data));
            }
            Serial.print("\nPackage:");
            Serial.print(data.id);
            Serial.print("\n");
            Serial.println(data.longitude);
            Serial.println(data.latitude);
            Serial.println(data.text);
        }
    }

Any idea on why this is not receiving data as expected?. This somehow managed to connect to my WIFI successfully. Here are my pin connection
[![enter image description here][1]][1]

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

title: How to connect NodeMCU to NRF24L01

Answers: 1

body:
The Dx pin labels on NodeMcu and Wemos/Lolin boards do not correspond to esp8266 internal io pin numbers. The pins_arduino.h file in core defines Dx constants which map internal io numbers to Dx labels.

Use `RF24 myRadio(D7, D8);`


body:
I just got an Idea of trying to code rain simulation with arduino and Adafruit OLED display. When I finished it was quite messy code so I thought That maybe doing it Object Oriented would help. This code is just a sketch that MAYBE works. The thing is that I need to create an array of objects(drops) and then display them. I have tried to display just one drop and it does not seem to do anything, even Serial wont print the **pos_y**. I have never wrote an Arduino code with objects so I just made a quick research and tried. here is the code:

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define OLED_RESET 4
    Adafruit_SSD1306 display(OLED_RESET);

    class Drop{
      private:
      int pos_x = random(0, 128);
      int pos_y = random(-5, -20);
      int len = random(3, 7);
      int speed = random(6, 13);
    public:
     void fall()
    {
     display.drawFastVLine(pos_x, pos_y, len, 1);
     pos_y = pos_y + speed;
     delay(5);
     Serial.println(pos_y);
     display.display();
     display.clearDisplay();
    }

    };

    Drop* drop = new Drop[50];

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(9600);
    display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
    display.clearDisplay();
    display.display();
    }

    void loop() {
      drop[1].fall();
    }

 I will appreciate any suggestion or solution, spent almost entire day doing this "simple thing"..

title: Arduino Object Array initialization

Answers: 1

body:
The code works without the display commands. A problem could be that you start with negative `pos_y` and use it as parameter for `drawFastVLine`.

Function random returns first parameter if it is a larger value then the second parameter. `random(-5, -20)` always returns -5.

To have more random random values, you should call [randomSeed][1] in setup().

And you can use global array `Drop drop[50];`.

  [1]: https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/


body:
I have uploaded a simple code to control a 8 channel relay by turning individual relays on and off
When I upload the code it works properly, the code works properly and the relays turn on and off in the desired pattern. However when i disconnect the USB cable from my computer and reconnect it, the code isnt working anymore, there is no visible action happening. Is the code erased from memory after power is cut?

    int pins[] = {D0, D1, D2, D4, D5, D6, D7, D8};
    int i;

    void setup()
    {
      Serial.begin(115200);
      for(i=0;i<8;i++)
      {
        pinMode(pins[i],OUTPUT);
        digitalWrite(pins[i],HIGH);
      }
    }
    void loop()
    {
      for(i=0;i<8;i++)
      {
        digitalWrite(pins[i],LOW);//Turns this relay on
        Serial.println(pins[i]);
    //Turn the previous relay off
        if(i==0)
        {
          digitalWrite(pins[7],HIGH);
        }
        else
        {
          digitalWrite(pins[i-1],HIGH);
        }
        delay(700);
      }
    }

My circuit:
NodeMCU | Relay
D0 IN1
D1 IN2
D2 IN3
D4 IN4
D5 IN5
D6 IN6
D7 IN7
D8 IN8
Vin VCC
GND GND

title: NodeMCU ESP8266 12E loses code after power is reconnected

Answers: 2

body:
D3 (GPIO0) and D4 (GPIO2) both need to be high on startup for the user program to be executed. The relay board connected to those pins are preventing a sufficient high on those pins.

If you need to use those pins then try using a stronger pull-up resistor on those pins. Try 330-470 ohms.

Either that or you will need to add additional circuitry between the port pins and the relay driver. Also please be aware that this will place a high on the relay driver input and will try to turn on the relays. Your powerup conditions may not be what you expect.

body: Your code will block the loop for more than 5 seconds. For the NodeMcu I found that if the main loop is delayed for long time strange things will happen. So you may also try refactoring to get rid of the for loop and using a simple counter to toggle the relays in each iteration of the main loop. so that your main loop will only be blocked for less than a second.


body:
I'd like to connect a [12V access control device](https://www.aliexpress.com/item/Security-RFID-Proximity-Entry-Door-Lock-Access-Control-System-Quality-5YOA/32283856982.html) to the Arduino, but I lack the understanding.

How can the signals from and to the device be done when they have different voltages?

I am afraid that the 12V would brick the Arduino.

title: Communicating with a 12V device?

Answers: 1

body:
You could use an [opto-coupler][1]:

> An opto-isolator (also called an optocoupler, photocoupler, or optical
> isolator) is an electronic component that transfers electrical signals
> between two isolated circuits by using light. Opto-isolators
> prevent high voltages from affecting the system receiving the
> signal. Commercially available opto-isolators withstand
> input-to-output voltages up to 10 kV and voltage transients with
> speeds up to 25 kV/μs.
>
> A common type of opto-isolator consists of an LED and a
> phototransistor in the same opaque package. Other types of
> source-sensor combinations include LED-photodiode, LED-LASCR, and
> lamp-photoresistor pairs. Usually opto-isolators transfer digital
> (on-off) signals, but some techniques allow them to be used with
> analog signals.

Here is an example schematic and packaging:

[![Optocouple][2]][2]

If you have a heavy load (although this does not seem to be your case) then they can also be used in conjunction with relays - here is an eight channel opto-coupler relay module board:

> [![12V 8 Channel Level Trigger Optocoupler Relay Module For Arduino][3]][3]
>
> [![12V 8 Channel Level Trigger Optocoupler Relay Module For Arduino showing optocouples][4]][4]

  [1]: https://en.wikipedia.org/wiki/Opto-isolator
  [2]: https://i.stack.imgur.com/OJIy6.png "Optocouple"
  [3]: https://i.stack.imgur.com/FBcjs.jpg "12V 8 Channel Level Trigger Optocoupler Relay Module For Arduino"
  [4]: https://i.stack.imgur.com/dauUX.png "12V 8 Channel Level Trigger Optocoupler Relay Module For Arduino showing optocouples"