text:
Arduino atmega328p
This program should prompt the user for an encryption key to be input through the serial
monitor. The encryption key contains 16 characters. However, the message that will be
encrypted can be up to 128 characters. As such, when storing the encryption key in the
EEPROM, you should repeat it so that it fills locations 0-127.
in the code, I'm trying to repeat the 16 character key 8 times
volatile bool prese_button = false;
String Password;
int counter = 8;
boolean right_pass;
void setup() {
  DDRD &= 0b11111011;
  PORTD |=0b00000100;
  EICRA |= 0b00000010;
  EIMSK |= 0b00000001;
  Serial.begin(9600);
}

void loop() {
  Serial.println("Please enter a 127 character password:");
  while (Serial.available() == 0) {}  //wait for serial terminal to be ready
  Password = Serial.readString();
  Serial.print("your password is: ");  //just to verify it was read correctly
  Serial.println(Password);
  for ( int j = 0 ;j < 128; j++) //   28 char
  {
    for (int i = 0; i<16 ; i++) {     //16 char
      EEPROM_write ( (j), Password[i] );
    }
  }
}

And what exactly is the problem?

I don't think your code does what you've described. But what exactly are you asking?

   for ( int j = 0 ;j < 128; j++) //   28 char
  {
    for (int i = 0; i<16 ; i++) {     //16 char
      EEPROM_write ( (j), Password[i] );
    }
  }

In these two for loops you are writing 128 times 16 characters.  That seems more than you described in your post.  If you have 16 things and need to repeat to fill 128 slots then you need 128 / 16 = 8 repeats of the 16 character sequence.  It's just basic math.  So that outer loop should count to 8, not 128.
for ( int j = 0 ;j < 8; j++) //  8 repeats of the 16 char
      {
        for (int i = 0; i<16 ; i++) {     //16 char
          EEPROM_write ((i + (16*j)), Password[i] );
        }
      }

Yes, and you'd have to calculate the address.  I'll add an example to the answer.


text:
Send/receive data from/to Raspberry Pi to/from Arduino with HM-10 (Bluetooth LE module)
My goal is to send a string from an Arduino via an HM-10 bluetooth module to a Rasperry Pi. I do this today by connecting the HM-10 on the Arduino to another HM-10 module (master/slave) and then from that module to the Raspberry Pi via USB Serial adapter which gives me a /dev/ttyUSB0 that I can read. I would like to just have the Arduino's HM-10 connect up directly to the Bluetooth of the Raspberry Pi without any extra modules at all.
I found the app "Arduino Bluetooth Controller" (Android) that can connect to the module and serial communication is working.
I also have the HC-05 module and there I can solve it by using rfcomm bind 2 , but that doesn't work on the HM-10.
I'm open to any solution that can do this. Either bind the serial communication using rfcomm (or alternative) like on the HC-05, or try to build an app that is doing the same thing the Android app does, only on the Raspberry Pi.

HM-10 is a BLE device. You'll need to understand BLE programming, which is quite different than classic Bluetooth.
There is no standard BLE service for serial communication.
The best way on a Pi to use BLE is with the

noble and bleno modules for node.js.
Or start by playing with gatttool.

If you are fit in Phyton:
The HM-10 style device will send notifications that the Pi's BLE device can read. Basically you need to
attach a 'delegate' call-back function to the Peripheral object,
and then wait for notifications.
The call-back can then process the received data.
You'll have to install the bluepy lib on the PI. This sample code writes to an Arduino HC-10 device
import bluepy.btle as btle

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
s = p.getServiceByUUID("0000ffe0-0000-1000-8000-00805f9b34fb")
c = s.getCharacteristics()[0]

c.write(bytes("Hello world\n", "utf-8"))
p.disconnect()

Here is some code for reading from an Arduino HC-10 device
import bluepy.btle as btle

class ReadDelegate(btle.DefaultDelegate):
    def handleNotification(self, cHandle, data):
        print(data.decode("utf-8"))

p = btle.Peripheral("AA:BB:CC:DD:EE:FF")
p.withDelegate(ReadDelegate())

while True:
    while p.waitForNotifications(1):
        pass

p.disconnect()

I ended up using bluepy like in your example and with some chunking of the incoming data (seems to be a 20 byte limit) it all works great! Thank you!

source: Stack Exchange

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

sort: votes


text:
How can I control Servo motor properly by using TimerOne and ServoTimer2 Library?
In this project I want smooth rotation of the Servo(Pin (D10) periodically where period time select by a potentiometer(actually I will use pressure sensor in this pin now it is unavailable to me so I am using g potentiometer).The Time period controlled by by a potentiometer position(two) change at Pin A0.Two Led(blue & red) (D7,D9)(in this pin I will use two valve controller servo) blink with same period and other yellow Led blink same period but oppositely.All working except Servo which rotation is not smooth .It's rotation sometime maintain proper period and sometime unnecessarily stop.Before I tried TimerOne and Servo Library but they are creating some conflict and not uploaded to Board.I am using Arduino Uno Board.What change should I do either in Circuit or in Code.I am new in this field.Any kind help would be grateful for me thank you.And my code is
#include <TimerOne.h>
#include "ServoTimer2.h"
const int potPin = A0;
const int bluePin =7;
const int redPin =8;
const int whitePin = 9;
const int yellowPin = 11;
const int myServoPin = 10;
ServoTimer2 myServo;
int angle;
int speed;
int potVal;
int breathPress;
int lowPress=12;
int upPress=24;
int lowCount=0;
int upCount =0 ;
int time1;
int time2;
int timeDiff;
int temp;
int potPin1 = A2;
int breathRatio;
int ratioVal;
void setup() {
  pinMode(potPin,INPUT);
  pinMode(bluePin,OUTPUT);
  pinMode(redPin,OUTPUT);
  pinMode(potPin1,INPUT);
  pinMode(whitePin,OUTPUT);
  pinMode(yellowPin,OUTPUT);
  myServo.attach(10);

  Timer1.initialize(100000);
  Timer1.attachInterrupt(Blink);
  Serial.begin(9600);
 }

void loop() {
  breathRatio=analogRead(potPin1);
  ratioVal = map(breathRatio,0,1023,1,6);

  digitalWrite(bluePin,HIGH);
  digitalWrite(yellowPin,HIGH);
  digitalWrite(whitePin,LOW);
  myServo.write(90);

  delay(timeDiff);
  digitalWrite(bluePin,LOW);
  digitalWrite(yellowPin,LOW);
  digitalWrite(whitePin,HIGH);
  myServo.write(60);
  delay(timeDiff);

}

void Blink(){
  potVal = analogRead(potPin);
  breathPress = map(potVal,0,1023,0,30);
  Serial.print("Pressure=");
  Serial.println(breathPress);
  Serial.println(time1);
  Serial.println(time2);
  Serial.print("Time Difference :");
  Serial.println(timeDiff);
  if(breathPress<10){
  digitalWrite(redPin,LOW);
  }
  if(breathPress>27){
    digitalWrite(redPin,LOW);
  }
  else {
    digitalWrite(redPin,HIGH);
  }
  if ((breathPress - 10 )<= 0){
    lowCount = 1;
    upCount =0;
    time1 = millis();
  }
  if((breathPress - 27)>=0){
    lowCount = 0;
    upCount = 1;
    time2 = millis();
  }
  if(time1-time2 >= 0){
    timeDiff = time1-time2;
  }
  else{
    timeDiff = time2-time1;
  }

And output showing
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15
13096
14994
Time Difference :1898
Pressure=15

your post looks like a book exploded ... you will wait a long time before someone spends their time reading that wall of words ... sentences have a space after a period ... related thoughts are grouped into paragraphs

If you used a "Blink Without Delay" style if statement and millis to handle the timing for both this and the leds then you could use the normal Servo library and your life would be much much much easier.

You copied your question text 2 times into the question. I removed the duplicated text for you

What you are claiming does not makes sense to me. In your code you are not moving the sensor smoothly. You are setting it to 60 and 90 degrees successively. You don't control the movement between these values. That's, what the servo does. It moves directly, where you tell it to move. You cannot control how the servo moves between two values, that you set. To move slower (you could call that smooth) between the values, you would need to set the inbetween values for the servo. So instead of going directly from 60 to 90, you would go in steps, from 60 to 61, to 62, ... to 89, to 90 degrees.
Also you are not controlling the servo with the Timer1 library, at least not directly. You measure a time difference with the library. This time difference is then the time, that the servo will stay in the current position, until it is moved again.

Note, that this
if((breathPress - 27)>=0)

is an over-complicated way of writing
if(breathPress >= 27)

by using for loop?actually I tried that but there is no motion of Servo.

Yes, for example with a for loop. We don't see your former code. Also your current question is rather ill stated. I understood about half of it. Please improve your question, so that it is more clear, what your problem is. If you already knew, that you need to use a for loop, why not asking about why your for loop code does not work?

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


text:
What is the difference between delay() and delaymicroseconds()
Does delaymicroseconds() provide something more than the time accuracy

There is a more important difference between the two functions other than the unit of time the accept as parameters
the function delay() calculates time using the time interript of the arduino. However Delaymicroseconds() does not use the time interrupt
As you may know once an interrupt is called it stops all other interrupts
So the real difference is you can not use delay() in a program in which you are using an interrupt and instead, use delaymicroseconds() but be aware that it has a range where it is accurate and it is between 3 and 16383 micro seconds

That's not entirely true.  You can use delay in a program with an interrupt, you just can't use it in the ISR.

"delay() calculates time using the time interript" - that's not really of importance. As you can see in the source code ( https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/wiring.c), delay() uses the micros() function which itself requires timer interrupts to increment a counter. The respective interrupt gets fired even if you don't use delays. As long as you don't need interrupts from the involved timer, there are no complications using interrupts and delay(). You are right about delayMicroseconds(): it counts a defined number of CPU cycles (determined by F_CPU).


text:
Arduino vs Wemos Fan control
I have a working fan control with the correct wiring that works with arduino.
I would like to change the arduino with a Wemos D1 mini board.
When I hook everything up. The fans are not activated.
The fan is driven by a 12v charger. And the irf540n cicruit powers that. They just share a common ground and the pwm pin D5
Is there something I need to know about the difference in both of them?
Below is the code, I've changed D5 in the code to 14.
Still nothing seems to work.
    #define fan D5

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("start");
  pinMode(fan, OUTPUT);

  digitalWrite(fan, LOW);
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(1000);
  digitalWrite(fan, HIGH);

  delay(1000);
  digitalWrite(fan, LOW);
}

Yes. The Wemos is 3.3V. Have you taken that into account with your circuit design?

What kind of Arduino did you use before? Arduino is a broad family of different boards with different chips

@Majenko I thought that didn't matter because the fan is driven by a 12v charger. And the irf540n cicruit powers that. They just share a common ground and the pwm pin D5

IRF540 is not a good choice. You want something that has a lower threshold voltage really.

Indeed just switched everything up with an Arduino and it works... @Majenko would a level bit shifter work for this? (pure out of interest)

The IRF540 is not suitable to be controlled by a 3.3V device because it has a gate-source-threshold voltage of 2-4V (that's the voltage at which the mosfet starts to conduct, but you need to be above that voltage). While this worked at 5V logic level on the arduino, the 3.3V are not enough to make the mosfet switch entirely.
A suitable mosfet has a threshold voltage below 1V. Also for a fan, you eon't need a big mosfet rated for 30A, a tiny one will do it.


text:
NRF24I01 with antenna Communication Delay
I am doing my senior design project which is due in a week, I am currently using the NRF24I01 with antennas for both the transmitter and the receiver. I am building a robot that is suppose to climb a wall, the transmitter and receiver are to allow me to controller where it goes using a joystick. I will attach both codes. My current issue is when I push on the joystick one motor will run full speed while the other starts slow then catches up to full speed. After I let go of the joystick, the motors will still spin full speed for a minute trying to catch up for the delay in the beginning.
This is really frustrating because I am not well-versed with Arduino and I cannot figure out how to fix it, please help.
Also I am using the radio.head library.
Reciever code:
#include <RHReliableDatagram.h>
#include <RH_NRF24.h>

#include <SPI.h>

#define CLIENT_ADDRESS 1
#define SERVER_ADDRESS 2

// Motor A connections analog 0 is digital 14 on arduino
int enA = 9;
int in1 = 2;
int in2 = 4;

// Motor B connections
int enB = 5;
int in3 = 7;
int in4 = 6;

// Create an instance of the radio driver
RH_NRF24 RadioDriver;

// Sets the radio driver to NRF24 and the server address to 2
RHReliableDatagram RadioManager(RadioDriver, SERVER_ADDRESS);

// Define a message to return if values recieved
uint8_t ReturnMessage[] = "JoyStick Data Received";

// Define the Message Buffer
uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

void setup()
{
    // Set all the motor control pins to outputs
    pinMode(enA, OUTPUT);
    pinMode(enB, OUTPUT);
    pinMode(in1, OUTPUT);
    pinMode(in2, OUTPUT);
    pinMode(in3, OUTPUT);
    pinMode(in4, OUTPUT);

    // Initilize RadioManager with defaults - 2.402 Ghz (channel 2), 2Mbps, 0dbm
    if (!RadioManager.init())
        Serial.println("init failed");
}

void loop()
{
    if (RadioManager.available())
    {
        // Wait for a message addressed to us from the client
        uint8_t len = sizeof(buf);
        uint8_t from;

        if (RadioManager.recvfromAck(buf, &len, &from))
        {
//          Serial Print the values of joystick
//          Serial.print("got request from : 0x");
//          Serial.print(from, HEX);
//          Serial.print(": MotorA = ");
//          Serial.print(buf[0]);
//          Serial.print("MotorB = ");
//          Serial.print(but[1]);
//          Serial.print(" Dir = ");
//          Serial.println(buf[2]);

            // Set Motor Direction
            if (buf[2] == 1)
            {
                // Motors are backwards
                digitalWrite(in1, LOW);
                digitalWrite(in2, HIGH);
                digitalWrite(in3, LOW);
                digitalWrite(in4, HIGH);
            }
            else
            {
                // Motors are forwards
                digitalWrite(in1, HIGH);
                digitalWrite(in2, LOW);
                digitalWrite(in3, HIGH);
                digitalWrite(in4, LOW);
            }

            // Drive Motors
            analogWrite(enA, buf[1]);
            analogWrite(enB, buf[0]);

            // Send a reply back to the orginitor client, check for error
            if (!RadioManager.sendtoWait(ReturnMessage, sizeof(ReturnMessage), from))
                Serial.println("sendtoWait failed");
        }
    }
}

Transceiver code:
#include <RHReliableDatagram.h>
#include <RH_NRF24.h>

#include <SPI.h>
#define joyVert  A0
#define joyHorz  A1

int joyposVert = 512;
int joyposHorz = 512;

#define CLIENT_ADDRESS 1
#define SERVER_ADDRESS 2

RH_NRF24 RadioDriver;

RHReliableDatagram RadioManager (RadioDriver, CLIENT_ADDRESS);

uint8_t motorcontrol[3];

uint8_t buf[RH_NRF24_MAX_MESSAGE_LEN];

void setup()
{
    // put your setup code here, to run once:
    Serial.begin(9600);
    if (RadioManager.init())
        Serial.println("init failed");
    motorcontrol[2] = 0;
}

void loop()
{
    // put your main code here, to run repeatedly:
    Serial.println("Reading motorcontrol values");
    joyposVert = analogRead(joyVert);
    joyposHorz = analogRead(joyHorz);

    //FORWARD & BACKWARD
    if (joyposVert < 460)
    {
        motorcontrol[2] = 1;
        motorcontrol[0] = map(joyposVert, 460, 0, 0, 255);
        motorcontrol[1] = map(joyposVert, 460, 0, 0, 255);

    }
    else if (joyposVert > 564)
    {
        motorcontrol[2] = 0;
        motorcontrol[0] = map(joyposVert, 564, 1023, 0, 255);
        motorcontrol[1] = map(joyposVert, 564, 1023, 0, 255);
    }
    else
    {
        motorcontrol[0] = 0;
        motorcontrol[1] = 0;
        motorcontrol[2] = 0;
    }

    // STEERING
    if (joyposHorz < 460)
    {
        // Move Left
        joyposHorz = map(joyposHorz, 460, 0, 0, 255);

        motorcontrol[0] = motorcontrol[0] - joyposHorz;
        motorcontrol[1] = motorcontrol[1] + joyposHorz;

        // Dont exceed range of 0-255 for motor speeds
        if (motorcontrol[0] <   0) motorcontrol[0] = 0;
        if (motorcontrol[1] > 255) motorcontrol[1] = 255;

    }
    else if (joyposHorz > 564)
    {
        // Move Right
        joyposHorz = map(joyposHorz, 564, 1023, 0, 255);

        motorcontrol[0] = motorcontrol[0] + joyposHorz;
        motorcontrol[1] = motorcontrol[1] - joyposHorz;

        // Dont exceed range of 0-255 for motor speeds
        if (motorcontrol[0] > 255) motorcontrol[0] = 255;
        if (motorcontrol[1] <   0) motorcontrol[1] = 0;

    }
    // Adjust to prevent "buzzing" at very low speed
    if (motorcontrol[0] < 8)motorcontrol[0] = 0;
    if (motorcontrol[1] < 8)motorcontrol[1] = 0;

    // Display the Motor Control Values in the serial monitor.
//  Serial.print("Motor A: ");
//  Serial.print(motorcontrol[0]);
//  Serial.print(" - Motor B: ");
//  Serial.print(motorcontrol[1]);
//  Serial.print(" - Direction: ");
//  Serial.println(motorcontrol[2]);

    // Send a message containing Motor Control data to manager_server
    if (RadioManager.sendtoWait(motorcontrol, sizeof(motorcontrol), SERVER_ADDRESS))
    {
        // Now wait for a reply from the server
        uint8_t len = sizeof(buf);
        uint8_t from;

        if (RadioManager.recvfromAckTimeout(buf, &len, 2000, &from))
        {
            Serial.print("got reply from :0x");
            Serial.print(from, HEX);
            Serial.print(": ");
            Serial.println((char*)buf);
        }
        else
        {
            Serial.println("No reply, is nrf24_reliable_datagram_server running?");
        }
    }
    else
        Serial.println("senttoWait failed");

//  delay(10);  //Wait a bit before next transmission
}

First thing to do is to open your code in the Arduino IDE and press Control-T to format the code and line up the blocks.  I don't know how you can try to see the logic in this with code wandering all over the page.  When real coders write with the nice neat blocks, we don't do that just to make it pretty.  It makes it easier to read as well.  The IDE does it for you so there's really no excuse.  Oftentimes that exercise alone will make the problem stand out like a sore thumb.

Please find out, when exactly the message gets send by the transceiver and when the full message is received by the receiver (finding out, which part of the code causes the delay). You can light an LED right before sending the message, turning it off afterwards. and on the receiver you can turn on an led, when the message got fully received. That way you can determine, if the timing problem really lies in the radio code, or if it is something else.

@Delta_G It is lined up in my code but when I put it in here I just manually spaced it so I know it is not great to look at. But in my actual code it is.

@chrisl When I look at the serial monitor most of the time the messages are sent and received immediately.  For some reason sometimes it will report to me that the message failed to send.

@jsotola The motors work fine when they are connected to a direct power source. The transmitter and receiver have some delay which affects the motors, which is why it will spend for a while without me using the joystick. Using deductive reasoning and some help from a professor I understand my issues are with the communication between the two NRF24I01 I just do not understand what it is.

@jsotola Yes but the main issue is the delay when I move the controller. It does not matter if I move the motor side to side or forward or backwards the same issue will occur... or another common issue if i hold the controller in one spot (forward, backwards left, or right) the motors may not start I keep holding the stick for many a minute or 30 seconds then the motors will start. After I let go of the joystick the motors will still spin for a little longer than the time I help the joy stick in that position.

@jsotola I kind of understand what you are saying. If it help I am using a motor driver to control the motors. For the issue you are saying is there a resource you know of that can help. Right now I am using the transmitter code that connects the joystick to move the individual motors so I have a full 360 scope of movement.  This project has deemed to be very difficult and my knowledge of code is not that strong so I am having to teach myself so my understand of the components responsibilities are lacking.

solve the problem in steps .... the transmission delays do not really matter right now .... transmit only the joystick position of only one axis .... on the receiver, move both the motors at the same time and in the same direction .... choose the forward or backward depending on the joystick value received  ..... your code is pretty close to that already

I am only using one joystick to control both the motors would this make a difference to your suggestion?

a joystick usually has X and Y .... send only one .... that way you have only simple data to deal with

I ditched the RH_NRF lib due to x problems when used in applications like yours, I now use an optimized high speed nRF24L01 library Give it a try https://github.com/nRF24/RF24

I would suggest changing your code so that you only send any data when the position of the joystick actually changes, rather than blasting data constantly flooding the link.

@Majenko this does not work (sending only when changes) if you use it as RC equipment. In my boat /flying models this acts as fail safe/heartbeat -no signal from the remote stop engines or initiate failure procedure. (Just as an info for the special case usage in remote controled models)

Periodic sending is fine. Flooding a digital link could cause problems. A regular heartbeat packet one every 100ms or something shouldn't flood the link and give you your failsafe.


text:
Why calling digitaWrite(pinNum,HIGH) before setup() not working?
I am writing a library to operate a linear actuator, let's call the library ActuatorV2. It is composed of two files, a .h and and .cpp files. To create an object, I instantiate the object as follows
Actuator act(pulsePin,directionPin,enablePin);

Within the constructor of the object, four tasks are performed:
1) pin assignment,
2) setting pin modes,
3) setting pulse frequency
4) enabling the actuator.
When performing the fourth task (enabling), I simply set the enablePin to HIGH as follows digitalWrite(enablePin,HIGH); There is absolutely nothing special here, but for some odd reason, when setup() is called in the sketch, the enablePin is set back to LOW. I know this because I have an LED light connected to the enablePin, and I visually monitor it during the operation.
Any idea why this happens?
I am aware that in the documentation of setup() here, it is clearly stated that pinMode() should be placed in setup(). But I have used the approach shown in the MWE before a few months ago, and it was working just fine.

Hardware used
MacBook Pro
Arduino Due
MWE
Sketch
#include <ActuatorV2.h>

// defining actuator pins and properties
const int pulstPin      = 4;
const int directionPin  = 5;
const int enablePin     = 6;
const int pulseFrequency= 500;

// initializing the actuator
Actuator act(pulstPin, directionPin, enablePin, pulseFrequency);

void setup() {
    // do nothing
}

void loop() {
    // do nothing
}

Library (Actuator.h, Actuator.cpp)
Actuator.h
#ifndef Actuator_h
#define Actuator_h

#include<Arduino.h>

class Actuator{
    private:
    // private variables
    // pins
    int _pulsePin;
    int _directionPin;
    int _enablePin;
    // pulse frequency parameters
    int _pulseFrequency;
    int _pulseDelay = 5;   // 2.5 microseconds manufacturer recommendation
    int _interpulseDelay;

    // private methods
    void assignPins(int pulsePin, int directionPin, int enablePin);
    void setPinModes();

    public:
    // constructors
    Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency);
    // public methods
    void setPulseFrequencyParameters(int freq);
    void enable();
};

#endif

Actuator.cpp
# include<ActuatorV2.h>
# include<Arduino.h>

Actuator::Actuator(int pulsePin, int directionPin, int enablePin, int pulseFrequency){
    // 1) pin assignment
    assignPins(pulsePin,directionPin,enablePin);

    // 2) setting pin modes
    setPinModes();

    // 3) setting pulse frequency
    setPulseFrequencyParameters(pulseFrequency);

    // 4) enable actuator
    enable();
}

void Actuator::assignPins(int pulsePin, int directionPin, int enablePin){
    _pulsePin = pulsePin;
    _directionPin = directionPin;
    _enablePin = enablePin;
}

void Actuator::setPinModes(){
    pinMode(_pulsePin,OUTPUT);
    pinMode(_directionPin,OUTPUT);
    pinMode(_enablePin,OUTPUT);
}

void Actuator::setPulseFrequencyParameters(int pulseFrequency){
  int _pulseFrequency = pulseFrequency;
  int minPeriod = 10; // 10 micro-seconds which is 4 X 2.5 (manufacurer recommended pulse width for reliable operation)
  /*
  ---------------------------------------------------------------------
  Pulse shape

  3.3 V
        |  |``````````|                     |``````````|
        |  |          |                     |          |
        |__|          |_____________________|          |__________ time
  0   V
           \__________/\____________________/
                pd              ipd
           \________________________________/
                     one pulse

  pd: pulse delay. Minimum 3 micro seconds
  ipd: inter-pulse delay. Minimum 3 micro seconds
  ---------------------------------------------------------------------
  */

  float period = 1.0/((float) pulseFrequency);

  if (period < minPeriod){
    _pulseDelay = 5;
    _interpulseDelay = 5;
  } else  {
    _pulseDelay = 5;
    _interpulseDelay = period - _pulseDelay;
  }
}

void Actuator::enable(){
  digitalWrite(_enablePin,HIGH);
  delay(500); // delay to observe the result if effective.
}

This is why many library classes have a begin() method: in order to defer to setup() the initializations that should not be done in the constructor.

@EdgarBonet, does that mean setup() dose reset things? I didn't know how to read the source code, but I still would like to know why this worked before, and it isn't working now.

Your constructor runs before main. Main initializes the hardware, including setting the pin modes to a default sane setting.

@Majenko, your reply is very helpful. I actually went to your other answer, and I found all what I needed there. Thanks again.

@Majenko it's probably true for the DUE - initialization is way more complex on ARM devices. For AVR based Arduinos all I can see is starting timers and ADC - it's not messing with pins at all. However there is also weak call for initVariant, so it might be different for each variant too.

The point is you can't trust it. So don't do it...

We can't trust it for sure. Thinking back, I might have been using an Arduino Uno when a code similar to my MWE worked. Thanks again.


text:
Sending Variable to IFTTT via ESP32 using Asynchronous Web Server
I have been trying to send three variables to IFTTT from my ESP32 using Asynchronous Web Server. However, I couldn't set the "URL" that was supposed to be the response that will trigger my IFTTT. Here's is my code:
server.on("/ifttt", HTTP_GET, [](AsyncWebServerRequest *request){

String jsonObject = "{\"value1\":\"" + Global_T + "\"" + ",\"value2\":\"" + Global_H  + "\"" + ",\"value3\":\"" + Global_K +  "\"}";

AsyncWebServerResponse *response = request->beginResponse(200, "application/json", jsonObject);

response ->addHeader("Host", server_ifttt);
request ->send(response);
});

It shall get triggered every fixed interval that I have set, and enter here to send it to IFTTT, but this is how it looks like. I not sure where should I add in the "URL" so that the response could be directed to IFTTT.

shouldn't you be using a web client to send data to IFTTT?

Sorry, I was kinda new in this. Which means it is impossible for me to send data to IFTTT if I am using Asynchronous Web Server?

no, that is not what it means ... you can have web server code, but you also need web client code to connect to the IFTTT server

As already said in the comments you need client code - Here are ready to use blocks for your scenario - NEVER use String class if you want to have a stable running IoT device, so define global char arrays (compiled to flash) and keep heap fragmentation at a minimum, The code is commented to get you started, change to your needs:
/* Your constants */
#define READ_THIS_PIN 4
const char MakerIFTTT_Key[] = "r8X-blahblahYourKeyGoesHere";
const char MakerIFTTT_Event[] = "stack_exchange_example";

/* Define global char arrays to get rid of string class */
    char numBuf[20];       // We "just know" this is big enough for (un)signed longs
    char postRequest[256];    // Hand-calculated to be big enough (size to your needs)
/* Helper functions for constructing the POST data
    append a string or int to a buffer, return the resulting end of string */

char *appendStr(char *tempChr, char *s) {
    while ((*tempChr++ = *s++))
        ;
    return tempChr-1;
}

char *appendUl(char *tempChr, unsigned long u) {
    return appendStr(tempChr, ultoa(u, numBuf, 10));
}
/*
 This is called once per iteration to read the pin
 and send a POST to trigger the IFTTT/Maker event
*/

void updateEvent() {
    WiFiClient client;

    /* Connect to the Maker event server */
    client.connect("maker.ifttt.com", 80);

    /* Construct the POST request */

    postRequest[0] = {'\0'}; /* Reset char array */
    char *p = postRequest;
    p = appendStr(p, "POST /trigger/");
    p = appendStr(p, "MakerIFTTT_Event");
    p = appendStr(p, "/with/key/");
    p = appendStr(p, "MakerIFTTT_Key");
    p = appendStr(p, " HTTP/1.1\r\n");
    p = appendStr(p, "Host: maker.ifttt.com\r\n");
    p = appendStr(p, "Content-Type: application/json\r\n");
    p = appendStr(p, "Content-Length: ");

    /* We need to remember where the content length will go, which is: */
    char *contentLengthHere = p;

    /* It's always two digits, so reserve space for them (the NN) */
    p = appendStr(p, "NN\r\n");

    /* End of headers */
    p = appendStr(p, "\r\n");

    /* Construct the JSON; remember where we started so we will know len */
    char *jsonStart = p;

    // This example reports a pin, uptime, and "hello stack" change to your need */
    p = appendStr(p, "{\"value1\":\"");
    p = appendUl(p, 12);    //analogRead(READ_THIS_PIN));
    p = appendStr(p, "\",\"value2\":\"");
    p = appendUl(p, millis());
    p = appendStr(p, "\",\"value3\":\"");
    p = appendStr(p, "hello, stack!");
    p = appendStr(p, "\"}");

    /* Go back and fill in the JSON length
       we just know this is at most 2 digits (and need to fill in both) */
    uint8_t i = strlen(jsonStart);
    contentLengthHere[0] = '0' + (i/10);
    contentLengthHere[1] = '0' + (i%10);

    // finally we are ready to send the POST to the server!
    client.print(postRequest);
    client.stop();
}


text:
ESP32 on Arduino IDE: Identify the board type in code (preprocessor macro)
I have read the answers on this post, but they do not seem to be providing a solution for ESP32 boards.
Is there a way to get the .name that is used from the boards.txt without modifying the platform.txt?
for example for uno there is uno.name=Arduino Uno
for esp32 esp32wrover.name=ESP32 Wrover Module
For ESP32 I can only find .name having the specific board name
This is a sample of the first 2 boards defined in boards.txt for esp332
menu.UploadSpeed=Upload Speed
menu.CPUFreq=CPU Frequency
menu.FlashFreq=Flash Frequency
menu.FlashMode=Flash Mode
menu.FlashSize=Flash Size
menu.PartitionScheme=Partition Scheme
menu.DebugLevel=Core Debug Level
menu.PSRAM=PSRAM
menu.Revision=Board Revision

##############################################################
### DO NOT PUT BOARDS ABOVE THE OFFICIAL ESPRESSIF BOARDS! ###
##############################################################

esp32.name=ESP32 Dev Module

esp32.upload.tool=esptool_py
esp32.upload.maximum_size=1310720
esp32.upload.maximum_data_size=327680
esp32.upload.wait_for_upload_port=true

esp32.serial.disableDTR=true
esp32.serial.disableRTS=true

esp32.build.mcu=esp32
esp32.build.core=esp32
esp32.build.variant=esp32
esp32.build.board=ESP32_DEV

esp32.build.f_cpu=240000000L
esp32.build.flash_size=4MB
esp32.build.flash_freq=40m
esp32.build.flash_mode=dio
esp32.build.boot=dio
esp32.build.partitions=default
esp32.build.defines=

esp32.menu.PSRAM.disabled=Disabled
esp32.menu.PSRAM.disabled.build.defines=
esp32.menu.PSRAM.enabled=Enabled
esp32.menu.PSRAM.enabled.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32.menu.PartitionScheme.default.build.partitions=default
esp32.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32.menu.PartitionScheme.default_8MB.upload.maximum_size=3342336
esp32.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32.menu.PartitionScheme.minimal.build.partitions=minimal
esp32.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32.menu.PartitionScheme.fatflash.build.partitions=ffat
esp32.menu.PartitionScheme.fatflash.upload.maximum_size=2097152
esp32.menu.PartitionScheme.app3M_fat9M_16MB=16M Flash (3MB APP/9MB FATFS)
esp32.menu.PartitionScheme.app3M_fat9M_16MB.build.partitions=app3M_fat9M_16MB
esp32.menu.PartitionScheme.app3M_fat9M_16MB.upload.maximum_size=3145728

esp32.menu.CPUFreq.240=240MHz (WiFi/BT)
esp32.menu.CPUFreq.240.build.f_cpu=240000000L
esp32.menu.CPUFreq.160=160MHz (WiFi/BT)
esp32.menu.CPUFreq.160.build.f_cpu=160000000L
esp32.menu.CPUFreq.80=80MHz (WiFi/BT)
esp32.menu.CPUFreq.80.build.f_cpu=80000000L
esp32.menu.CPUFreq.40=40MHz (40MHz XTAL)
esp32.menu.CPUFreq.40.build.f_cpu=40000000L
esp32.menu.CPUFreq.26=26MHz (26MHz XTAL)
esp32.menu.CPUFreq.26.build.f_cpu=26000000L
esp32.menu.CPUFreq.20=20MHz (40MHz XTAL)
esp32.menu.CPUFreq.20.build.f_cpu=20000000L
esp32.menu.CPUFreq.13=13MHz (26MHz XTAL)
esp32.menu.CPUFreq.13.build.f_cpu=13000000L
esp32.menu.CPUFreq.10=10MHz (40MHz XTAL)
esp32.menu.CPUFreq.10.build.f_cpu=10000000L

esp32.menu.FlashMode.qio=QIO
esp32.menu.FlashMode.qio.build.flash_mode=dio
esp32.menu.FlashMode.qio.build.boot=qio
esp32.menu.FlashMode.dio=DIO
esp32.menu.FlashMode.dio.build.flash_mode=dio
esp32.menu.FlashMode.dio.build.boot=dio
esp32.menu.FlashMode.qout=QOUT
esp32.menu.FlashMode.qout.build.flash_mode=dout
esp32.menu.FlashMode.qout.build.boot=qout
esp32.menu.FlashMode.dout=DOUT
esp32.menu.FlashMode.dout.build.flash_mode=dout
esp32.menu.FlashMode.dout.build.boot=dout

esp32.menu.FlashFreq.80=80MHz
esp32.menu.FlashFreq.80.build.flash_freq=80m
esp32.menu.FlashFreq.40=40MHz
esp32.menu.FlashFreq.40.build.flash_freq=40m

esp32.menu.FlashSize.4M=4MB (32Mb)
esp32.menu.FlashSize.4M.build.flash_size=4MB
esp32.menu.FlashSize.8M=8MB (64Mb)
esp32.menu.FlashSize.8M.build.flash_size=8MB
esp32.menu.FlashSize.8M.build.partitions=default_8MB
esp32.menu.FlashSize.2M=2MB (16Mb)
esp32.menu.FlashSize.2M.build.flash_size=2MB
esp32.menu.FlashSize.2M.build.partitions=minimal
esp32.menu.FlashSize.16M=16MB (128Mb)
esp32.menu.FlashSize.16M.build.flash_size=16MB

esp32.menu.UploadSpeed.921600=921600
esp32.menu.UploadSpeed.921600.upload.speed=921600
esp32.menu.UploadSpeed.115200=115200
esp32.menu.UploadSpeed.115200.upload.speed=115200
esp32.menu.UploadSpeed.256000.windows=256000
esp32.menu.UploadSpeed.256000.upload.speed=256000
esp32.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32.menu.UploadSpeed.230400=230400
esp32.menu.UploadSpeed.230400.upload.speed=230400
esp32.menu.UploadSpeed.460800.linux=460800
esp32.menu.UploadSpeed.460800.macosx=460800
esp32.menu.UploadSpeed.460800.upload.speed=460800
esp32.menu.UploadSpeed.512000.windows=512000
esp32.menu.UploadSpeed.512000.upload.speed=512000

esp32.menu.DebugLevel.none=None
esp32.menu.DebugLevel.none.build.code_debug=0
esp32.menu.DebugLevel.error=Error
esp32.menu.DebugLevel.error.build.code_debug=1
esp32.menu.DebugLevel.warn=Warn
esp32.menu.DebugLevel.warn.build.code_debug=2
esp32.menu.DebugLevel.info=Info
esp32.menu.DebugLevel.info.build.code_debug=3
esp32.menu.DebugLevel.debug=Debug
esp32.menu.DebugLevel.debug.build.code_debug=4
esp32.menu.DebugLevel.verbose=Verbose
esp32.menu.DebugLevel.verbose.build.code_debug=5

##############################################################

esp32wrover.name=ESP32 Wrover Module

esp32wrover.upload.tool=esptool_py
esp32wrover.upload.maximum_size=1310720
esp32wrover.upload.maximum_data_size=327680
esp32wrover.upload.wait_for_upload_port=true

esp32wrover.serial.disableDTR=true
esp32wrover.serial.disableRTS=true

esp32wrover.build.mcu=esp32
esp32wrover.build.core=esp32
esp32wrover.build.variant=esp32
esp32wrover.build.board=ESP32_DEV

esp32wrover.build.f_cpu=240000000L
esp32wrover.build.flash_size=4MB
esp32wrover.build.flash_freq=40m
esp32wrover.build.flash_mode=dio
esp32wrover.build.boot=dio
esp32wrover.build.partitions=default
esp32wrover.build.defines=-DBOARD_HAS_PSRAM -mfix-esp32-psram-cache-issue

esp32wrover.menu.PartitionScheme.default=Default 4MB with spiffs (1.2MB APP/1.5MB SPIFFS)
esp32wrover.menu.PartitionScheme.default.build.partitions=default
esp32wrover.menu.PartitionScheme.defaultffat=Default 4MB with ffat (1.2MB APP/1.5MB FATFS)
esp32wrover.menu.PartitionScheme.defaultffat.build.partitions=default_ffat
esp32wrover.menu.PartitionScheme.default_8MB=8M Flash (3MB APP/1.5MB FAT)
esp32wrover.menu.PartitionScheme.default_8MB.build.partitions=default_8MB
esp32wrover.menu.PartitionScheme.minimal=Minimal (1.3MB APP/700KB SPIFFS)
esp32wrover.menu.PartitionScheme.minimal.build.partitions=minimal
esp32wrover.menu.PartitionScheme.no_ota=No OTA (2MB APP/2MB SPIFFS)
esp32wrover.menu.PartitionScheme.no_ota.build.partitions=no_ota
esp32wrover.menu.PartitionScheme.no_ota.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3g=No OTA (1MB APP/3MB SPIFFS)
esp32wrover.menu.PartitionScheme.noota_3g.build.partitions=noota_3g
esp32wrover.menu.PartitionScheme.noota_3g.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.noota_ffat=No OTA (2MB APP/2MB FATFS)
esp32wrover.menu.PartitionScheme.noota_ffat.build.partitions=noota_ffat
esp32wrover.menu.PartitionScheme.noota_ffat.upload.maximum_size=2097152
esp32wrover.menu.PartitionScheme.noota_3gffat=No OTA (1MB APP/3MB FATFS)
esp32wrover.menu.PartitionScheme.noota_3gffat.build.partitions=noota_3gffat
esp32wrover.menu.PartitionScheme.noota_3gffat.upload.maximum_size=1048576
esp32wrover.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
esp32wrover.menu.PartitionScheme.huge_app.build.partitions=huge_app
esp32wrover.menu.PartitionScheme.huge_app.upload.maximum_size=3145728
esp32wrover.menu.PartitionScheme.min_spiffs=Minimal SPIFFS (1.9MB APP with OTA/190KB SPIFFS)
esp32wrover.menu.PartitionScheme.min_spiffs.build.partitions=min_spiffs
esp32wrover.menu.PartitionScheme.min_spiffs.upload.maximum_size=1966080
esp32wrover.menu.PartitionScheme.fatflash=16M Flash (2MB APP/12.5MB FAT)
esp32wrover.menu.PartitionScheme.fatflash.build.partitions=ffat

esp32wrover.menu.FlashMode.qio=QIO
esp32wrover.menu.FlashMode.qio.build.flash_mode=dio
esp32wrover.menu.FlashMode.qio.build.boot=qio
esp32wrover.menu.FlashMode.dio=DIO
esp32wrover.menu.FlashMode.dio.build.flash_mode=dio
esp32wrover.menu.FlashMode.dio.build.boot=dio
esp32wrover.menu.FlashMode.qout=QOUT
esp32wrover.menu.FlashMode.qout.build.flash_mode=dout
esp32wrover.menu.FlashMode.qout.build.boot=qout
esp32wrover.menu.FlashMode.dout=DOUT
esp32wrover.menu.FlashMode.dout.build.flash_mode=dout
esp32wrover.menu.FlashMode.dout.build.boot=dout

esp32wrover.menu.FlashFreq.80=80MHz
esp32wrover.menu.FlashFreq.80.build.flash_freq=80m
esp32wrover.menu.FlashFreq.40=40MHz
esp32wrover.menu.FlashFreq.40.build.flash_freq=40m

esp32wrover.menu.UploadSpeed.921600=921600
esp32wrover.menu.UploadSpeed.921600.upload.speed=921600
esp32wrover.menu.UploadSpeed.115200=115200
esp32wrover.menu.UploadSpeed.115200.upload.speed=115200
esp32wrover.menu.UploadSpeed.256000.windows=256000
esp32wrover.menu.UploadSpeed.256000.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400.windows.upload.speed=256000
esp32wrover.menu.UploadSpeed.230400=230400
esp32wrover.menu.UploadSpeed.230400.upload.speed=230400
esp32wrover.menu.UploadSpeed.460800.linux=460800
esp32wrover.menu.UploadSpeed.460800.macosx=460800
esp32wrover.menu.UploadSpeed.460800.upload.speed=460800
esp32wrover.menu.UploadSpeed.512000.windows=512000
esp32wrover.menu.UploadSpeed.512000.upload.speed=512000

esp32wrover.menu.DebugLevel.none=None
esp32wrover.menu.DebugLevel.none.build.code_debug=0
esp32wrover.menu.DebugLevel.error=Error
esp32wrover.menu.DebugLevel.error.build.code_debug=1
esp32wrover.menu.DebugLevel.warn=Warn
esp32wrover.menu.DebugLevel.warn.build.code_debug=2
esp32wrover.menu.DebugLevel.info=Info
esp32wrover.menu.DebugLevel.info.build.code_debug=3
esp32wrover.menu.DebugLevel.debug=Debug
esp32wrover.menu.DebugLevel.debug.build.code_debug=4
esp32wrover.menu.DebugLevel.verbose=Verbose
esp32wrover.menu.DebugLevel.verbose.build.code_debug=5

As I guess you mean the preprocessor defines to distinguish between different boards and include/exclude based on this different code parts.In ArduinoIDE except from
 #ifdef ESP32
 const uint8_t pinA = 12;
 #endif

no luck as of core 1.04, because there are no preproc macros defined (like in other architectures).If you are using PlatformIO you can get the board type from the define ARDUINO_BOARD.
On ArduinoIDE you only can write your own macros (but this only solves the problem for your dev environment)
So as of core 1.04 you can only do it manually by un/commenting defines:
/** Choose the correct model to use and compile the right pin settings*/
#define AI_THINKER_KIT
//#define WROVER_DEV_KIT
//#define ESP_EYE_32
//#define M5STACK_PSRAM
//#define M5STACK_NO_PSRAM

As an example the build.board property for SAM Boards is:
adafruit_itsybitsy_m0.build.board=ITSYBITSY_M0

Then in the Adafruit SAMD Boards platform.txt file you can see where the macro is defined:
## Compile c files
recipe.c.o.pattern="{compiler.path}{compiler.c.cmd}" {compiler.c.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.c.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile c++ files
recipe.cpp.o.pattern="{compiler.path}{compiler.cpp.cmd}" {compiler.cpp.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.cpp.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

## Compile S files
recipe.S.o.pattern="{compiler.path}{compiler.S.cmd}" {compiler.S.flags} -DF_CPU={build.f_cpu} -DARDUINO={runtime.ide.version} -DARDUINO_{build.board} -DARDUINO_ARCH_{build.arch} {compiler.S.extra_flags} {build.extra_flags} {build.cache_flags} {compiler.arm.cmsis.c.flags} {includes} "{source_file}" -o "{object_file}"

If you want to dig intoit deeper: Arduino 3rd party hardware documantatuion

Yes that is exactly what I want it for.
I will have to do it manually. Thank you for your response

Please mark the answer as accepted


text:
Ethernet Shield Not Working With TFT Screen
I'm trying to stack up Arduino UNO, Ethernet Shield and Waveshare 2.8" TFT Shield. Since I'm new to this I'm mostly doing basic stuff.
I successfully manage to get ethernet shield and TFT shield to work individually. Then since TFT shield will not be able to use the ICSP interface I connected the jumpers as it says on wiki.

Hardware configuration

When using the Arduino board with ICSP interface, the jumpers SB1,    SB2 and SB3 on the LCD module should be kept open.
When using the Arduino board without ICSP interface, the jumpers SB1,    SB2 and SB3 on the module should be connected with a 0R
  resistor,    respectively.

After this I put everything together and try to get them working with the below code but for some reason I don't know, Ethernet shield stopped working. I get the error Ethernet shield was not found.  Sorry, can't run without hardware. :(. Even though the error, my TFT screen lights up and runs demo. Probably I'm missing something simple. I'll appreciate any help or guidance.
#include <stdint.h>
#include <LCD.h>
#include <SPI.h>
#include <Ethernet.h>

IPAddress server(192, 168, 0, 107);
IPAddress ip(192, 168, 0, 177);
IPAddress myDns(192, 168, 0, 1);
IPAddress gateway(192, 168, 0, 1);
EthernetClient client;
byte mac[] = {0x90, 0xA2, 0xDA, 0x00, 0x23, 0x36};

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

  /*--------- TFT Init -------------*/
  SPI.setDataMode(SPI_MODE3);
  SPI.setBitOrder(MSBFIRST);
  SPI.setClockDivider(SPI_CLOCK_DIV4);
  SPI.begin();
  Tft.lcd_init();
  /*--------- TFT Init End -------------*/

  /*--------- Ethernet Setup -------------*/
  Serial.println("Initialize Ethernet with DHCP:");
  if (Ethernet.begin(mac) == 0) {
    Serial.println("Failed to configure Ethernet using DHCP");
    if (Ethernet.hardwareStatus() == EthernetNoHardware) {
      Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
    } else if (Ethernet.linkStatus() == LinkOFF) {
      Serial.println("Ethernet cable is not connected.");
    }
    // no point in carrying on, so do nothing forevermore:
    // while (true) {
    //   delay(1);
    // }
  }
  // print your local IP address:
  Serial.print("My IP address: ");
  Serial.println(Ethernet.localIP());
  /*--------- Ethernet Setup End -------------*/

  /*--------- Ethernet Connection Demo Setup -------------*/
  if (client.connect(server, 3000)) {
    Serial.print("connected to ");
    Serial.println(client.remoteIP());
    // Make a HTTP request:
    client.println("GET / HTTP/1.1");
    client.println("Host: localhost");
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  beginMicros = micros();
  /*--------- Ethernet Connection Demo Setup End -------------*/
}

void loop()
{
  /*--------- TFT Demo -------------*/
  Tft.lcd_clear_screen(WHITE);
  for (int x = 1; x <= 240; x++) {
    for (int y = 1; y <= 320; y++) {
      Tft.lcd_draw_rect(x, y, 1, 1, RED);
      delay(1);
    }
  }
  /*--------- TFT Demo End -------------*/

  /*--------- Ethernet Check-Up ---------*/
  switch (Ethernet.maintain()) {
    case 1:
      //renewed fail
      Serial.println("Error: renewed fail");
      break;

    case 2:
      //renewed success
      Serial.println("Renewed success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    case 3:
      //rebind fail
      Serial.println("Error: rebind fail");
      break;

    case 4:
      //rebind success
      Serial.println("Rebind success");
      //print your local IP address:
      Serial.print("My IP address: ");
      Serial.println(Ethernet.localIP());
      break;

    default:
      //nothing happened
      break;
  }
  /*--------- Ethernet Check-Up End ---------*/

  /*--------- Ethernet Demo ---------*/
  int len = client.available();
  if (len > 0) {
    byte buffer[80];
    if (len > 80) len = 80;
    client.read(buffer, len);
    if (printWebData) {
      Serial.write(buffer, len); // show in the serial monitor (slows some boards)
    }
    byteCount = byteCount + len;
  }

  // if the server's disconnected, stop the client:
  if (!client.connected()) {
    endMicros = micros();
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    Serial.print("Received ");
    Serial.print(byteCount);
    Serial.print(" bytes in ");
    float seconds = (float)(endMicros - beginMicros) / 1000000.0;
    Serial.print(seconds, 4);
    float rate = (float)byteCount / seconds / 1000.0;
    Serial.print(", rate = ");
    Serial.print(rate);
    Serial.print(" kbytes/second");
    Serial.println();

    // do nothing forevermore:
    // while (true) {
    //   delay(1);
    // }
  }
  /*--------- Ethernet Demo End ---------*/
}

From examining the schematics of the Ethernet shield as well as the TFT shield, it looks like the Chip Select (CS) pin of the Ethernet shield uses the same pin (Arduino pin D4) as the Interrupt pin of the Touch Panel on your TFT shield (TP_IRQ) in the schematic.
I don’t think you can solve this without modifying any hardware. Either the TFT shield or the Ethernet shield should be modified to use a different pin, and these modifications should be reflected in the underlying library.
My guess is the Ethernet shield would be easiest to modify as its PCB can be reached from two sides. You could also cut the D4 pin from the TFT shield and connect its PCB trace to an unused digital pin via a short wire.

The error message is from the ethernet library. As I do not have the sufficient hardware to test this indicates a pin conflict. So the ethernet shield v1 uses/needs one or more pins the LCD shield is using.How to find out dig into the circuit documenation and look at the used pins.Be aware that a lot of tuts/infos on the net are about ethernet shield v2 which is hardware differnt from v1.

Circuit schematics for Waveshare and Ethernet shield v1
Check also for shorts between USB (Arduino) / Ethernet plug and the above shields, I isolate them normaly with a piece of isolation tape (to be safe than sorry).

EDIT
Ethernet shield: Arduino communicates with both the W5100 and SD card using the SPI bus (through the ICSP header).
This is on digital pins 10, 11, 12, and 13 on the Uno.
Pin 10 is used to select the W5100 and pin 4 for the SD card.
These pins cannot be used for general I/O

The wave share uses CS=D10, RS=D7, RST=D9 and the SD CS can be defined on eg SD_CS 5 with this library as the waveshare lib is not usable other than basic playing around.
This lib is Adafruit_GFX compatible so a wide variety of programs and other libs work.
So your chance is

to remap the SD CS by software if the other pins pose no conflict (you have to test it) or
get an other Ethernet connector (not a shield because its more flexible) or
remap manually with dupont wires the LCD shield (because it's the top most) and change the according pins in the libs header file.

Do not cut traces or solder around its not worth the effort and you might break things

Thank you for your answer. First of all I did isolate the USB like you said when I first fit the shield. Secondly, since I can run the code above separately with no error I assume my code is good for my versions. Let's say there is a pin conflict. Do you have any idea/suggestion on how to fix that? Do you think I can set another pin for them just with code? Ethernet library has Ethernet.init(sspin) function. Does this mean I have to do some soldering? Thanks again.

See my edit and test the other TFT lib first without ethernet shield


text:
Arduino Turn Signals
Could I use an Arduino to power run the following lights? Here I have a project in mind, and although I am new to electronics, I am a computer programmer (C, C++, C#, Java) by profession so the coding side doesn't worry me, what I am confused about is what power supply I need etc.

If you mean you want to power it directly from a GPIO pin from an Arduino: no, for two reasons:

It doesn't show the current needed, but it's likely more than 20 or 40 mA which is maximum for a GPIO pin. So you need to use a transistor, which can be used to turn on something with higher current, with the current of a GPIO pin. Search for 'Transistor as a switch' for more info.
Also, it's 12 V and the Arduino delivers 5 V.

What you need is a separate 12V adapter, with a current capability MORE than what that light needs. I cannot find the current (mA) in the link, so you might need to measure it (e.g. with a digital multimeter). If you don't have a digital multimeter, buy one, you need one anyway if you will do electronics. You can even buy a 3 euro one from China if you want (for now).

If you look at the specs of those lights, they draw 1 watt at 12 volts. That is both too much current and too much voltage for an Arduino. (You're only supposed to draw about 20 mA from a single pin, and somewhere between 500 mA and 1 amp from the 5V regulator. (It is heat limited, and typically not very well heat-sinked. Er, heat-sunk?)
An Arduino only puts out 3.3v and 5V.
If you're looking to drive these from a car/motorcycle, you should be able to power them directly from the 12V battery of the vehicle. Failing that, get a 12V power supply that can put out as much current as you need for ALL of the lights you need, plus 10%-20% extra, for "slop".
What you should do is to buy a MOSFET power transistor designed for switching logic level signals for each turn signal you need to control. These would work well:
https://www.adafruit.com/product/355
You'd then use logic lines from the Arduino to control the gates of the transistors, and each transistor would switch the power for one of your turn signal lights.


text:
How does code typed in Arduino IDE runs on a nodemcu?
I actually have a series of questions regarding Nodemcu and esp8266.

How does code typed in Arduino IDE run on Nodemcu?
What firmware is present on the nodemcu?
How do I upload the above firmware on esp8266-01 module?
I want my esp8266-01 module to work with a Lilypad Arduino. So this is the way I want it to work: Lilypad Ardiuno has acquires some data using a sensor. It wants to post this data to a server on internet. So to do the job it uses a ESP8266-01. Will the configuration work?

NodeMCU name has a development board and a firmware. both can be used independently. maybe you have the NodeMcu firmware on the NodeMcu board. NodeMcu firmware with the Lua language will not work with Arduino IDE.

how does code typed in Arduino IDE runs on Nodemcu

The IDE runs the compiler which turns the C into assembly and then machine code.  That is then uploaded to the ESP8266.

what firmware is present on the nodemcu.

The code that you just wrote and uploaded.

i want my esp8266-01 module to work with a Lilypad Arduino .So this is the way I want it to work Lilypad Ardiuno has acquires some data using a sensor it wants the post this data to a server on internet.So to do the job it uses a ESP8266-01.So will the configuration work?

Sure, if you program it to do that.  Two choices:

Use the AT firmware on the ESP-01 (installed by default)
Write custom firmware (as above) for the ESP-01 to do what you want.

Thankyou so much @Majenko , it would be very kind of you if you point me to some references for question no. three.thankyou once again .it was very helpful

Google: Arduino ESP8266 AT and you'll find your answers.


text:
Several ESP8266 in wifi network should share information
I am currently working on a project for my home where several ESP8266 (each with a relay) control lights. I have developed an android for this where I find the ESP8266s via mdns but the problem is that sometimes one or two won't be found ever (depends on the position where I am trying it). So my idea was to make them talk to each other so everyone knows like an list of ip addresses from the others. This would give me the possibility to find every ESP as soon as i have found one.

I guess you are asking if it is feasible: if this is the case, I would say yes, without too many troubles. Each ESP can launch MDNS discovery, so they can discover each other.

Waht you may be looking for is a mesh network, you can use the standerd lib ESP8266WiFiMesh. Mesh reduces the loading of smart devices on the router by
 forming a mesh between the smart devices.There are unluckely no examples ready to use but you can look at the provided example and modify it to your needs,
You find the lib in your core dir
C:\Users\Your_Username\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.6.3\libraries\ESP8266WiFiMesh

but be aware there are a lot of open issues and PRs (which means lot of trouble in a stable production)
EDIT
There is also the Arduino library painlessMesh. Its well documented and has lot of examples and can be combined with MQTT.For MQTT there is one condition where you might consider this option, if you have deep sleeping nodes on battery (than mesh might be contra productive)

And here's the source code online as well: https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFiMesh


text:
How to code an arduino to execute a particular code using a slide switch
I’m pretty new to arduino. I need help concerning a project I’m making. I’m using a SPDT slide switch to switch between what code(method) should be executed.i.e when I shift the switch to the left, XXX method should be executed and when I move the switch to the right, YYYY method should be executed. The center pin of the switch is connected to arduino +5v while the     left and right leg of the switch are connected like how a tactile switch is interfaces with the arduino. Please can anyone help me with the code, or at least how to program the arduino? Thank you

Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.
You effectively have:

simulate this circuit – Schematic created using CircuitLab
However you are over complicating things.  A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time.  If one is pressed the other must be released.
You can completely ignore half the switch and treat the other half as a button: if the "button" is pressed then the switch is in one position. If the "button" is released then it's in the other position.
Unless it's a "center off" switch, in which case it has 3 positions, not 2, and the middle one has nothing connected.
If it is a simple 2-position SPDT switch then just disconnect the D12 wire and remove the right-and resistor in your drawing. Then read D13 to determine the position: HIGH is one position and LOW is the other.
If it's a 3-position "center off" switch then move the D12 wire 4 holes to the left so that it connects to the switch-resistor junction, not ground. Then you will need to read both D12 and D13 - which ever one is HIGH is the one that is activated, and the switch is in that position.
Then it's a simple "if / else" (2 position) or "if / elseif / else" (3 position center-off) structure to decide which code to run.

“Your switch wiring for D12 is wrong. You connect your inputs directly to ground and that can never change, regardless of the position of the switch.”  I don’t understand how it is wrong, each side of the switch is basically like a push button, and that’s the exact same wiring as a push button.  I do agree with “However you are over complicating things. A SPDT switch is nothing more than two buttons, only one of which can be pressed at one time. If one is pressed the other must be released”. It’s a 2 position switch.

The method I first used did work but once I move the switch to one position, it won’t go back to its former position(as in not physically). I think maybe there’s a problem with the code.


text:
problem using one function to blink different leds
I wrote a function to blink an led using millis and want to blink multiple leds with the same function but with different delay intervals. When I call this function thrice to blink 3 different leds, all the leds blink with the shortest delay. As far my understanding is, functions can be reused if you want to perform same task but why doesn't it work in this case? It works incase I rename the function before calling it again.
Is it wrong to call single function more than once to perform same task but on different pins? How would you call a function without renaming it?
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {
blinkLed(redLed, 1000);
blinkLed(yellowLed, 4000);
blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {
  static unsigned long oldTime = 0;
  unsigned long newTime = millis();
  static boolean ledState = LOW;

  if (newTime - oldTime >= timePeriod) {
    oldTime = newTime;
    ledState = !ledState;
  }
  digitalWrite(led, ledState);
}

Edit: I have modified the function to not have shared variables but it just blinks redLed. why doesn't it work now? Here is the code:
const int redLed = 10;
const int yellowLed = 11;
const int greenLed = 12;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(greenLed, OUTPUT);
}

void loop() {

  blinkLed(redLed, 1000);
  blinkLed(yellowLed, 4000);
  blinkLed(greenLed, 8000);
}

void blinkLed(int led, unsigned long timePeriod) {

  switch (led) {
    case 10:
      static unsigned long oldTime1 = 0;
      unsigned long newTime1 = millis();
      static boolean redState = LOW;

      if (newTime1 - oldTime1 >= timePeriod) {
        oldTime1 = newTime1;
        redState = !redState;
      }
      digitalWrite(led, redState);
          break;

    case 11:
      static unsigned long oldTime2 = 0;
      unsigned long newTime2 = millis();
      static boolean yellowState = LOW;

      if (newTime2 - oldTime2 >= timePeriod) {
        oldTime2 = newTime2;
        yellowState = !yellowState;
      }
      digitalWrite(led, yellowState);
          break;

    case 12:
      static unsigned long oldTime3 = 0;
      unsigned long newTime3 = millis();
      static boolean greenState = LOW;

      if (newTime3 - oldTime3 >= timePeriod) {
        oldTime3 = newTime3;
        greenState = !greenState;
      }
      digitalWrite(led, greenState);
      break;
  }
}

You want to let the LEDs blink concurrently.
Your static variables oldTime, and ledState are shared between the three LEDs.
So there is ony ONE ledState in your program but you need that state for each one.
Same applies for oldTime.
Resolve the this issue and your LEDs will blink as expected.
btw. you don't need the ledState as you can read its current state.

the led pin is defined as OUTPUT,  so wouldn't I be reading what I am writing to the pin? Also how does the pin defined as output work as input at the same time?

@Zaffresky if you are readin an output pin, you are reading, what you have written to it. But thats exactly, what you need, since you simply want to toggle the pin

To resolve the shared variables issue I modified my function but there  are other problems now. Scratching my head now about how to fix it. May be the easiest way without creating classes (need to learn it first) is just copy function with different names and calling them.

@Zaffresky that is bruteforcing your idea into code. that is far from good coding habbits. Classes are easy if done primitively. Take a look at Majenko's Blinker Code. You really Need only to track three states (one for each LED) and those states consist of at most two variables. You can use a struct with those two variables if you feel that way. Just pass it as a pointer or reference to your blinkLed function.

Yes, functions can be re-used if you want to perform the same task in different places or at different times. But your problem is that you only have one set of "time" variables.
You would be better off learning to create this as a class which can not only contain the "blink" function but also the variables that define the state for a specific instance of the blinking.
For example here is a small library I wrote ages ago as a demonstration.

I thought with each function call, a new copy of variables will be created and managed independently then previous function call and previous values of variables therein. I don't know anything about classes so will look it up

No, one function = one set of variables. You could pass references to other local variables, but that gets messy. Simpler to use a class.

Just putting other peoples' suggestions together:
void blinkLed(int led, unsigned long timePeriod) {
  static unsigned long oldTime[42];
  unsigned long newTime = millis();
  boolean ledState = digitalRead(led);

  if (newTime - oldTime[led] >= timePeriod) {
    oldTime[led] = newTime;
    ledState = !ledState;
  }
  digitalWrite(led, ledState);
}

Nah, sort of. it will work but still not a nice solution. The all known magic number 42 is really not what you want to do. You'd rather create a struct or class that encapsulates: pin, timePeriod, oldTime and ledState. The function will then take only the state object as its only argument.

Other people excluding Kwasmich*

@Abel why did you chose 42 for OldTime? And are you defining oldTime as an array?

Making a the singular value oldTime into an array is the easiest way to scale the code.  Ideally 42 would be replaced by the max numbered possible digital out pin per the arduino header or simply the max of the used port +1 aka 13.  Array because sacrificing mem for simplicity over implementing class or map.


text:
restart counter of elapsed millis willingly with read
When I trigger high it will count for as long as I ask it while I am high then shut off. I am able to start counting again whenever I want by triggering low and going back to high and it starts from the beginning as long as the time in low is not within the time I asked it to be high. The problem is I go low mid count then quickly back to high the count picks up where millis left off without starting from the beginning. Is there a way to make this better.
unsigned long induceTime = 0;
unsigned long elapseTime;
long setTime = 10000;
int openClose;
int openClosePin = 2;
int writeToPin = 3;
void setup() {
Serial.begin(9600);
}

void loop() {
  int openClose = digitalRead(openClosePin);
  elapseTime = millis();
  if (openClose == HIGH && elapseTime < induceTime + setTime){
    digitalWrite(writeToPin, HIGH);
    Serial.println(' ');
    Serial.println(elapseTime);
    Serial.println(' ');
    Serial.println(induceTime);
    Serial.println(' ');
}
  if (openClose == LOW && elapseTime > induceTime + setTime){
    induceTime = elapseTime;
    Serial.println(elapseTime);
    Serial.println(induceTime);
}

delay(500);
}

Thanks for the help, this code is closer to what I was looking for. This is for a water level pump, when the trigger is high it turns on, when the water rises the trigger goes low and stays on during the timer as a failsafe and then turns off with when the elapsed time is greater than the set time and also not in my code it turns off with a additional trigger. Here is my working code.

unsigned long induceTime = 0;
unsigned long elapseTime;
long setTime = 10000;
int openClose;
int openClosePin = 2;
int writeToPin = 3;
void setup() {
Serial.begin(9600);
}

void loop() {
  int openClose = digitalRead(openClosePin);
  elapseTime = millis();
  if (openClose == HIGH){                //reset count
    induceTime = millis();
    digitalWrite(writeToPin, HIGH);
    Serial.println(induceTime);
}
  if (openClose == LOW){
    elapseTime = millis() - induceTime;  //induceTime is set when leave high
    if (elapseTime < setTime){
      digitalWrite(writeToPin, HIGH);
      Serial.println(elapseTime);
      Serial.println("within setTime high");
}
    if (elapseTime > setTime){
      digitalWrite(writeToPin, LOW);
      Serial.println(elapseTime);
      Serial.println("within setTime for low");
}
    Serial.println(' ');
    Serial.println(elapseTime);
    Serial.println(' ');
    Serial.println(induceTime);
    Serial.println(' ');
}
delay(1000);                              //so that I can see serial monitor
}

It's OK to accept your own answer as the solution to the problem.

First make your code rollover safe and second add an other condition:
So as I understood LOW/HIGH changes should start a timer from zero irrelevant if a running timer is over or not - so timer is still running HIGH/LOW -> and LOW/HIGH should restart
// repalce / paste before setup
unsigned long startTime = 0;
bool timerIsOn = false;
//unsigned long elapseTime;

 // replace your loopwith this
void loop() {
  int openClose = digitalRead(openClosePin);
//  elapseTime = millis();
  if (openClose == HIGH && timerIsOn = false){
       timerIsOn = true;
       startTime = millis();
       digitalWrite(writeToPin, HIGH);
       Serial.print(' ');
       Serial.print(millis());
       Serial.print(' ');
       Serial.print(startTime);
        Serial.println(' ');
   }
   // This condition is for time is up
  if (timerIsOn = true && millis() - startTime > setTime){
     digitalWrite(writeToPin, LOW);
     timerIsOn = false;
     Serial.print(setTime);
     Serial.print(' ');
     Serial.println(millis()-startTime);
  }
   // This condition is for going low before time is up
  if (openClose == LOW && timerIsOn = true){
    digitalWrite(writeToPin, LOW);
    timerIsOn = false;
    Serial.print('timerIsOn = ');
    Serial.println(timerIsOn);
    Serial.print(' ');
    Serial.println(millis()-startTime);
  }
 // If you go LOW after time is up it does nothing waits for the next HIGH
}

For starters, millis should be used relatively to avoid rollover.  Simple fix is to subtract the induceTime over to the same side of the comparison.
Example:
    elapseTime - induceTime > setTime
This also brings up the issue that your 'counter' is always elapseTime aka millis instead of (elapseTime - induceTime) so it never truly stops counting.
You are also never calling
    digitalWrite(writeToPin, LOW);
So it goes high and stays high.  I suspect you meant to set it to low in an else statement somewhere.
Now for the issue regarding quickly changing signals:
Beyond that you could use an interrupt and timer so that your sample rate (determined by the delay(500)) doesn't come into play.  This will give the best possible timing at the cost of restricting which pins you can use for openClosePin and you should also check that you sufficiently debounce the signal (in hardware).
Alternatively you can reduce the 500 to an acceptable #. But you would then want to have another counter to prevent spamming your serial output.
Below example only implements ISR and reduction of 500.  Does not implement timer (which would be required for precise use of setTime to shut the writeToPin off to LOW).
volatile unsigned long induceTime = 0;
volatile unsigned long elapsedTime;
unsigned long setTime = 10000;
//volatile int openClose; //may want to toggle this in isr...
int openClosePin = 2;
int writeToPin = 3;

void pinChangedISR(){
  if(digitalRead(openClosePin)){ //rising
    digitalWrite(writeToPin, HIGH);
    induceTime = millis();
  }
  else{//falling
    digitalWrite(writeToPin, LOW);
    elapsedTime = millis() - induceTime;
  }
}

void setup() {
  pinMode(writeToPin, OUTPUT);
  pinMode(openClosePin, INPUT); //may want INPUT_PULLUP depending on hardware
  attachInterrupt(digitalPinToInterrupt(openClosePin), pinChangedISR, CHANGE);
  Serial.begin(9600);
}

void loop() {
  static int frameCount = 0;
  unsigned long delayTime = 100;
  openClose = digitalRead(openClosePin);
  if (openClose == HIGH){
    elapsedTime = millis() - induceTime;
    if(elapsedTime >= setTime) digitalWrite(writeToPin, LOW);
    else if(setTime - elapsedTime < 100) delayTime = setTime - elapsedTime;
  }
  if(framecount >= 5){ //time to print...
    framecount = 0;
    if(digitalRead(writeToPin) == HIGH){
      Serial.println(' ');
      Serial.println(elapsedTime);
      Serial.println(' ');
      Serial.println(induceTime);
      Serial.println(' ');
    }
    else{ //this part's a bit different
      Serial.println(elapsedTime); //reporting duration of last pulse when pulse inactive
      Serial.println(millis()); //reporting current time for inducetime comparison
    }
  } else ++framecount;
  delay(delayTime);
}


text:
Arduino GPIO automatically turns high
I've been trying to turn on 21W bulb with Protected MOSFETS.
But somehow the bulbs are getting high automatically from arduino.
I've tried all the hardware related things like pull down with different resistors, but no luck.
Is it possible due to separate ground of controller and Switch?
Because Switch and bulbs are powered through SMPS of 12V 10A while Arduino through Laptop USB cable.
Used this protected mosfet, circuit as given on page no 50 of datasheet.
Following is the code I used.
#include <TimerOne.h>

int LED = 13;
int IN0 = 12;
int IN1 = 11;
int OUT1 = 10;
int OUT2 = 9;
int OUT3 = 5;
int OUT4 = 7;
int OUT5 = 6;
int count = 0;

void setup() {
 pinMode(IN0, INPUT);
 pinMode(IN1, INPUT);
 pinMode(OUT1, OUTPUT);
 pinMode(OUT2, OUTPUT);
 pinMode(OUT3, OUTPUT);
 pinMode(OUT4, OUTPUT);
 pinMode(LED, OUTPUT);
 digitalWrite(OUT3, LOW);
 Timer1.initialize(1000000);
 Serial.begin(9600);

}

//void flash_R()
//{
//  digitalWrite(LED, !digitalRead(LED));
//  digitalWrite(OUT3, !digitalRead(OUT3));
//  //digitalWrite(OUT4, !digitalRead(OUT4));
//
//  if(digitalRead(LED)){
//    Serial.println("ON");
//  }
////  Serial.print("Count Value: ");
////  Serial.println(count++);
//}

void flash_L()
{
  //digitalWrite(OUT3, LOW);
  digitalWrite(LED, !digitalRead(LED));
  digitalWrite(OUT3, !digitalRead(OUT3));
  //digitalWrite(OUT4, !digitalRead(OUT4));

  if(digitalRead(OUT3)){
    Serial.println("hello");
    //Serial.print("Count Value: ");
    //Serial.println(count++);
  }
}

void loop() {
    Timer1.attachInterrupt(flash_L);
  }

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

I'm very interested in your schematics. To answer your question: Unless there is some kind of (optical) isolation, both parts of the circuit need the same ground to act as a reference. This may very well be the cause of your problem and you should correct it as soon as possible. Separate grounds could cause large currents to flow between different parts of your circuit and be really dangerous to your Arduino as well as your laptop.

@StarCat for schematic, circuit is same as given in datasheet application cicuit and datasheet link I've shared. For input, simple zener based active high circuit used for 12v to 5v and given to controller. For arduino power supply what if I used same power source as of SMPS which is used to power up bulb and switch. So that Ground of switch and arduino will be same.

You don't have to use the same power supply as long as the grounds are connected. However, you could use the 12V 10A supply for powering the Arduino as long as it's connected to the external power connector (via a barrel plug). What resistor value did you use in the input circuit in combination with the Zener?

First resistor of 4K7(series), then a 4V7 zener, Pull Down resistor of 4K7, 0.1UF cap (all 3 other terminal to ground) then again a series resistor of 47K other end connected to controller pin. I wish to upload whole image of ckt but somehow its not getting uploaded due to some error.

@StarCat Thank you soo much. Your help really solved my problem. Just one more question, After programming arduino, completely disconnected it from laptop. So, to perform any operations like UART arduino needs to be connected to laptop. So, how advisable it is to connect arduino to both laptop and to SMPS via barrel plug?

It's no problem to have the Arduino Uno connected to both the (external) power supply and USB. The external supply will override the USB power.


text:
i2c scanner stuck on scanning for my 0.96in OLED screen with my Arduino Nano

My pins are connected as follows; vcc-3v3, gnd-gnd, sda-A4, scl-A5.

Measure the voltage at SCL after the scan has been stuck. If it's LOW, the problem is probably the slave. Do you have external pullups?

no I don't have any pullup resistors on hand but do you think that could be the problem

I2C requires pullups, but sometimes, slaves already have them onboard. Can you measure the resistance between Vcc-SDA and Vcc-SCL? If it's larger than 10kOhm this can be the problem.

Is it a 3.3 V only OLED? I suppose its vcc(OLED)-3v3(Nano).
Most OLEDs use 3.3V -5V where sometimes the 3.3V from the Arduino is not sufficient.If its a 3.3V only OLED could you give the make of the OLED (does it have jumpers to change I2C address). Normaly the I2C scanner should return at least with nothing found.


text:
How to get the free/used space on a SD card and transmit it
I'm using this block of code to read and sum up the bytes of all the text files I have on an SD card:
long get_sd_memory_taken() {
  File dir = SD.open("/");
  long sd_memory_taken;
  int c = 0;
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      return sd_memory_taken;
      break;
    }
    if(strcmp(entry.name(), "SYSTEM~1") == 0) {
      continue;
    }
    if(c > 15) {
      tft.println(entry.name());
      tft.println(entry.size());
    }
    sd_memory_taken += entry.size();
    entry.close();
    c++;
  }
}

The SD card is 8GB so the number won't be larger than 8,589,934,592. The function get_sd_memory_taken() returns the number so it can be send to a phone using Bluetooth. I just checked that long can hold max 2,147,483,647, so if the SD card is filled more than that, I suppose errors are gonna appear. How can I prevent this? I was thinking of maybe using a double and put the comma maybe 5 digits to the left and send that or maybe divide the number into 10 smaller longs and send them to the phone separately. I think the former method is better but I'm not sure if it'll work. What's the best way to go about this problem where I'm trying to use as less memory as possible?

What Arduino (and SD lib) are you using?

unsigned long long aka uint64_t can hold up to 9,223,372,036,854,775,807.

@Codebreaker007 Blue Pill, SD.h

@Majenko I'll try that, hopefully that's the most memory-efficient way to do it

8 bytes is all that uses. Same a double.

for a lot of arduino boards, a double is 32 bits (synonymous to float).  just be aware if you run into this here when working a different board.

As SD.h includes
  #include "utility/SdFat.h"
  #include "utility/SdFatUtil.h"

or if you use the SDfat library than this function is more efficient than going all over the place:
#include <SdFat.h>

SdFat SD;

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = SD.vol()->freeClusterCount();
  lFreeKB *= SD.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.print(lFreeKB);
  Serial.println(" KB");
}


text:
Boolean function call with character pointer input - dont understand how to get updated pointer value
Thank you for everyone's help in trying to find a solution. This library I'm working with was prewritten and is one of the most buggy hardware libraries I've had the misfortune to use. I have now solved to problem by reusing the response parsing code from the library and rewriting my own sequence to return the number using a completely different approach. Many Thanks again!
I am currently attempting to understand how this function works and am struggling. I want to be able to access the 'number' variable in my main function but currently when I do that I get nothing (as in "") when I try to printout the variable with:
Serial.println(incomingNumber);

I am currently preassigning the number as:
char incomingNumber[14];

at the top of my project file.
With a class initial setup of:
DFRobot_SIM808 sim808(&Serial);

I'm then later calling the function like this:
if(sim808.isCallActive(incomingNumber)){Serial.println(incomingNumber);}

This seems like I'm currently making a fundamental error in understanding data types but I'm a bit lost so any help would be really appreciated.
I havent included my entire project here because its currently quite long and spread across both the main and some library files but if anyone needs more info please ask and I'll upload the extras.
The function from the library I'm working with is included below:
bool DFRobot_SIM808::isCallActive(char *number)
{
char gprsBuffer[46];  //46 is enough to see +CPAS: and CLCC:
char *p, *s;
int i = 0;

sim808_send_cmd("AT+CPAS\r\n");
/*Result code:
    0: ready
    2: unknown
    3: ringing
    4: call in progress

  AT+CPAS   --> 7 + 2 = 9 chars
            --> 2 char
  +CPAS: 3  --> 8 + 2 = 10 chars
            --> 2 char
  OK        --> 2 + 2 = 4 chars

  AT+CPAS

  +CPAS: 0

  OK
*/

sim808_clean_buffer(gprsBuffer,29);
sim808_read_buffer(gprsBuffer,27);
//HACERR cuando haga lo de esperar a OK no me har閾哸 falta esto
//We are going to flush serial data until OK is recieved
sim808_wait_for_resp("OK\r\n", CMD);
//Serial.print("Buffer isCallActive 1: ");Serial.println(gprsBuffer);
if(NULL != ( s = strstr(gprsBuffer,"+CPAS:"))) {
  s = s + 7;
  if (*s != '0') {
     //There is something "running" (but number 2 that is unknow)
     if (*s != '2') {
       //3 or 4, let's go to check for the number
       sim808_send_cmd("AT+CLCC\r\n");
       /*
       AT+CLCC --> 9

       +CLCC: 1,1,4,0,0,"656783741",161,""

       OK

       Without ringing:
       AT+CLCC
       OK
       */

       sim808_clean_buffer(gprsBuffer,46);
       sim808_read_buffer(gprsBuffer,45);
        //Serial.print("Buffer isCallActive 2: ");Serial.println(gprsBuffer);
       if(NULL != ( s = strstr(gprsBuffer,"+CLCC:"))) {
         //There is at least one CALL ACTIVE, get number
         s = strstr((char *)(s),"\"");
         s = s + 1;  //We are in the first phone number character
         p = strstr((char *)(s),"\""); //p is last character """
         if (NULL != s) {
            i = 0;
            while (s < p) {
                number[i++] = *(s++);
            }
            number[i] = '\0';
         }
         //I need to read more buffer
         //We are going to flush serial data until OK is recieved
         return sim808_wait_for_resp("OK\r\n", CMD);
       }
     }
  }
}
return false;
}

On the face of it, what you are doing is perfectly correct. Either the library isn't detecting the phone number correctly or the module you are using doesn't report the phone number.

so the gsm module is on Serial or the Serial Monitor? 14 is the size of the array, not the value. the char array content is uninitialized.

From what I understand is it generally better to initialize the array size at the maximum, even if the end product is much shorter?

you write "I am currently preassigning the number as char incomingNumber[14];"

Yeah, DFRobot libraries SUCK. For example, I had to rewrite their DFPlayerMini MP3 player library cause it was so terrible

You can't use Serial.println(array);. In fact, I'm not even sure how the compiler even let you do this...
A better approach would be to use Serial.write(array, sizeof(array));
Also, in order to ensure the function is even executing that portion of the code in the first place, you should but some debugging prints in the code. Like this:
     if (NULL != s) {
        i = 0;
        while (s < p) {
            number[i++] = *(s++);
            Serial.write(number[i++]); //-------- debug
            Serial.print(' '); //-------- debug
        }
        number[i] = '\0';
        Serial.println(); //-------- debug
     }

Also, proper use of whitespace is your friend ;)

You can't use Serial.println(array); -- Yes you can. It's just a C string that's NULL terminated. There's absolutely nothing wrong with that.


text:
nodemcu doesnt response in at command mode
I want to sent AT command into node mcu esp8266 module with arduino IDE  through serial monitor.
I connect the node mcu to arduino uno board in following sequence:
RX to pin 2 of arduino
TX to pin 3 of arduino
Vin of node mcu to 3.3V of arduino
GND to GND
EN of node mcu to 3.3V of arduino
I send at commands in serial monitor but dont get any response.
I also checked different baud rates.
what is the problem? what thing I'm doing wrong?
    #include <SoftwareSerial.h>
SoftwareSerial esp8266(2,3); //2 -->rx  ,3 -->tx

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

void loop() {
  if (esp8266.available()>0)
  {
      char c = esp8266.read();
      Serial.write(c);
  }
  if (Serial.available()>0)
  {
    delay(1000);
    String cmd = "";
    while (Serial.available())
    {
      cmd += (char)Serial.read();
    }
    esp8266.println(cmd);
  }
}

It is an actual NodeMCU as in a NodeMCU Version 1.0 or 0.9, etc? Not some random ESP8266 module that you're calling a NodeMCU?

@Majenko as I'm reading the board information it's model nomber is: esp-12E. I will send the image.

wire rx to tx, not rx to rx and tx to tx. do you have the AT firmware uploaded to NodeMcu? does it respond to AT commnds over USB on NodeMcu? change the baud rate to 9600 baud in firmware and sketch because SoftwareSerial doesn't work reliably at 115200 baud. why do you want to use NodeMcu this way.?

As Majenko already noted in his answer(s), the NodeMCU that you're using most probably does not come with the AT firmware installed and will not respond to AT commands out of the box. It's actually much more powerful than what you are trying to use it for.

Some points to note:

VIN should connect to 5V (it goes through the on-board 5V -> 3.3V regulator). If you connect VIN to 3.3V you will be starving the device of power.
The NodeMCU doesn't come with AT firmware installed. You will have to install it first before it will respond.
If you have a NodeMCU why are you bothering with an Arduino? The NodeMCU can do everything (and more) that the Arduino can do (except it lacks IO).

did OP do something right?


text:
Why when I pull an EEPROM index the value returned is garbage?
I have an array of colors for my tft screen:
const uint16_t colorTheme [] PROGMEM = {BLACK, WHITE, NAVY, CYAN, RED, GREEN, VERDEAQ, PINK, ORANGE, PURPLE, GRAY, YELLOW};

When I try to use colorTheme [EEPROM.read (2500)] I am returned with a value of any garbage, or a value of 0, and I checked it in read_eeprom and the value of EEPROM.read (2500) is equal to 4, and 4 in mine vector is cyan color, not black or 0 number, why does this go so wrong?

Your array is in PROGMEM, but you are accessing it as if it were in RAM.
You must use pgm_read_word() to access the data in your array.
pgm_read_word(&(colorTheme[EEPROM.read(x)]))

BTW - what Arduino board has more than 2kB of EEPROM?

Thanks, i'm using Atmega2560, he https://store.arduino.cc/usa/mega-2560-r3, your EEPROM is 4kb


text:
Read Simultaneously RFID TAG with multiple RFID Reader [MFRC522]
i have a project that use two RFID Reader, the project for counting tag from conveyor belt, in this case the reader will placed in the middle of the conveyor belt and the reader faces each other.
So i have question, can two RFID Reader reading one or many tag simultaneously? I tried before but when i tried to scan, the two readers did not respond, but if i scan one tag and one reader it will work correctly.
For example:
i have readers 0 and readers 1, and two variables count0 and count1, remember the readers faces each others, so i put one tag in the middle of reader0 and reader1, if the reader 0 scan the tag, count0 will increase to 1 and if reader 1 scan the tag in the SAME TIME it wouldn’t be counting because the reader 0 has scan that tag.
but in my case, the readers(0 and 1) didnt response if i put the tag in the middle of readers.
i use this tutorial for my project https://youtu.be/HmGmFknAIqc
and for this project the data count0 and count1 i send it to nodemcu using SoftwareSerial(5,6).
Im new for using Arduino and i still learn about it(i dont understand too much)
Heres my arduino code
/**
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read data from more than one PICC to serial.
 * --------------------------------------------------------------------------------------------------------------------
 * This is a MFRC522 library example; for further details and other examples see: https://github.com/miguelbalboa/rfid
 *
 * Example sketch/program showing how to read data from more than one PICC (that is: a RFID Tag or Card) using a
 * MFRC522 based RFID Reader on the Arduino SPI interface.
 *
 * Warning: This may not work! Multiple devices at one SPI are difficult and cause many trouble!! Engineering skill
 *          and knowledge are required!
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS 1    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI SS 2    SDA(SS)      ** custom, take a unused pin, only HIGH/LOW required **
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 */
#include <Wire.h>
#include <SPI.h>
#include <MFRC522.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal_I2C.h> //library penampil LCD

#define RST_PIN         9          // Configurable, see typical pin layout above
#define SS_1_PIN        10         // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 2
#define SS_2_PIN        8          // Configurable, take a unused pin, only HIGH/LOW required, must be diffrent to SS 1

#define NR_OF_READERS   2

LiquidCrystal_I2C lcd(0x27,20,4); //0x3f dapat dicari dengan i2c scanner
SoftwareSerial s(5,6);
//SoftwareSerial s1(2,3);

byte ssPins[] = {SS_1_PIN, SS_2_PIN};

MFRC522 mfrc522[NR_OF_READERS];   // Create MFRC522 instance.
int i = 1;
byte code[10];
String uidString;
int count0 = 0;
int count1 = 0;

/**
 * Initialize.
 */
void setup() {
  s.begin(9600);
 // s1.begin(9600);
  Serial.begin(9600); // Initialize serial communications with the PC
  while (!Serial);
  SPI.begin();        // Init SPI bus

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    mfrc522[reader].PCD_Init(ssPins[reader], RST_PIN); // Init each MFRC522 card
    Serial.print(F("Reader "));
    Serial.print(reader);
    Serial.print(F(": "));
    mfrc522[reader].PCD_DumpVersionToSerial();
  }

//  lcd.init();
//  lcd.init();
//  lcd.backlight(); //menghidupkan lampu latar LCD
//  lcd.setCursor (3,0);
//  lcd.print("Final Project");
//  delay (1000);
//  lcd.clear();
}

/**
 * Main loop.
 */
void loop() {
//  lcd.setCursor (0,0);
//  lcd.print("SCAN RFID");

  for (uint8_t reader = 0; reader < NR_OF_READERS; reader++) {
    // Look for new cards
    if(reader == 0){
      reader0(reader);
    }else if(reader == 1){
      reader1(reader);
    }
  }
}

/** SCAN RFID TAG READER0 */
void reader0(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      // Show some details of the PICC (that is: the tag/card)
      Serial.println();
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count0++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count0);
      Serial.println();
      s.write(count0);
       }

      mfrc522[reader].PICC_HaltA();
      mfrc522[reader].PCD_StopCrypto1();
}

/** SCAN RFID TAG READER1 */
void reader1(int reader){
    if (mfrc522[reader].PICC_IsNewCardPresent() && mfrc522[reader].PICC_ReadCardSerial()) {
      Serial.println();
      Serial.print(F("Reader "));
      Serial.print(reader);
      Serial.println();
      // Show some details of the PICC (that is: the tag/card)
      Serial.print(F("Card UID = "));
      dump_byte_array(mfrc522[reader].uid.uidByte, mfrc522[reader].uid.size);
      Serial.println();
//      Serial.print(F("PICC type: "));
//      MFRC522::PICC_Type piccType = mfrc522[reader].PICC_GetType(mfrc522[reader].uid.sak);
//      Serial.println(mfrc522[reader].PICC_GetTypeName(piccType));
      count1++;
      lcd.setCursor (0,0);

      Serial.print("Counter ");
      Serial.print(reader);
      Serial.print(" = ");
      Serial.print(count1);
      Serial.println();
      s.write(count1);
    }

      mfrc522[reader].PICC_HaltA();
      // Stop encryption on PCD
      mfrc522[reader].PCD_StopCrypto1();
}

/**
 * Helper routine to dump a byte array as hex values to Serial.
 */
void dump_byte_array(byte *buffer, byte bufferSize) {
  for (byte i = 0; i < bufferSize; i++) {
    Serial.print(buffer[i] < 0x10 ? " 0" : " ");
    Serial.print(buffer[i], HEX);
  }
}

anyway sorry for my bad english :D

Take a look at this this link it might be of a help to you. It uses four RFID readers at the same time

I'm just starting a project using RFID tags to track cars and engines on a model railroad.
Although I haven't gotten very far yet, my first thought was to use a multiplexer to select which reader I receive data from at any given time. It won't be simultaneous but I should be able to read a dozen or more per second which is probably enough.

That's because you can only listen at one SoftwareSerial interface at a time. On the other interface you will receive nothing.
The SoftwareSerial library uses interrupts to watch at the pins. These interrupts cannot easily be shared between different interfaces, thus the SoftwareSerial library doesn't support it.
You can do 2 things:

You could ditch the code for reporting to the serial monitor (so no debugging code and no interaction with the serial monitor on the PC) and only use the LCD for displaying information. Then you can use the free hardware serial port to communicate with one of the RFID readers. The other can be services through a single SoftwareSerial interface.
You could ditch the Uno and buy an Arduino Mega, which has 4 hardware serial ports. Then you can connect both RFID readers to hardware serial interfaces, using the first serial interface for communication with the PC and still having one interface left. This would be my preferred way.

Sorry, did you mean SoftwareSerial that i used in there? i use SoftwareSerial for sending data to nodemcu and then nodemcu will send to thingspeak, the code hasnt revised, i only use SoftwareSerial(5,6) and for now i didnt use LCD. Im new in Arduino i dont understand too much

i use this tutorial https://youtu.be/HmGmFknAIqc

mfrc522 is not as common any more, but if you want to use them rather then rdm6300 (more expensive device, but cheaper tags), then you can
Mfrc522 uses spi interface which means that each slave needs its own slave select port from arduino to enable arduino to chose whom its talking to at which point.
You should read this about multiple SPI devices
because SPI is a synchronous communication I would recommend one mcu per reader (nanos' or pro-minis are cheap) and they can communicate results to central arduino