text:
Trouble with NRF24L01
I've been trying on and off to try and get my nrf24l01's working for some time and they never seem to work. Right now I'm just trying to turn a led on and off over the radio and it isn't working.
Here's the code for the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define button 5
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
boolean buttonState = 0;
void setup() {
  pinMode(5, INPUT_PULLUP);
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {

  buttonState = digitalRead(button);
  radio.write(&buttonState, sizeof(buttonState));
}

And here's the code for the receiver
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

int led = 2;
RF24 radio(7, 8); // CE, CSN
boolean buttonState = 0;
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
 radio.startListening();
  while (!radio.available());
  radio.read(&buttonState, sizeof(buttonState));
  if (buttonState == HIGH)
  {
    digitalWrite(led, HIGH);
  }
  else
  {
    digitalWrite(led, LOW);
  }
}

I have the voltage regulator which steps the 5v arduino to 3.3 to the chip so I don't think not having a capacitor (what others recommended) is a problem. I have both radio chips hooked up to arduino nanos.
For the transmitter and receiver I have CE=7,CSN=8, SCK=13, MO=11, and MI=12
I also know that my led is working and the code for my button is working. Is there a problem with my code or is there a chance that my chips are broken even if im using a voltage regulator

The capacitor is not used to regulate the voltage per say, it is used to make sure the supplied voltage is 'clean'   when the radio transmits it draws 'a lot' of current real fast, and if the regulator cannot keep up with that spike, the voltage drops.   I have found that using a capacitor with these radios clears up some issues.

Interesting. I have been having an issue with nRF24L01's as well so I tried your code (modified to work toggling the transmitter and printing the output). You are possibly getting the same issue as me (nRF24L01 continuously reading closed pipe) so I modified your code as follows:
void loop() {
 uint8_t pipeNum;
 radio.startListening();
  while (!radio.available(&pipeNum));
  radio.read(&buttonState, sizeof(buttonState));
  if (pipeNum < 2) {
    if (buttonState == HIGH)
    {
      digitalWrite(led, HIGH);
      Serial.println("ON");
    }
    else
    {
      digitalWrite(led, LOW);
      Serial.println("OFF");
    }
  }
}

and then it worked for me. PS: I normally add a "while (!Serial);" line after Serial.begin to hold off output until the monitor is established.

It is not easy to find the problem remotely. Here is what I would do:

My first problem have always been connections. I gave up using breadboards and other connectors. Use soldering instead to be sure your circuit is properly connected.
Add some Serial.println() in both codes to see what exactly is going to be sent, and what has been received.
On the sender code, add a delay(100) to the loop. That would give the module buffers a chance to process.
You can improve it more by checking for the button value you read with the old value, and only send the value if the state has changed.

Check these things first:

Is your power supply give a constant 3.3V and a minimum of
0.5A(500mA)?
Are you on the right serial baud rate?
Is the path from the radio to the Arduino as short as possible?
Are your MISO and MOSI wires twined into each other?
Try changing your CE to pin 9 and CSN to pin 10.

If none of these things help then, please tell me what library you are using. I had a lot of issues with the RF24 library so maybe try using the NRFLite library.

Pretty sure your issue is you're not using the capacitor. I used a 10uF capacitor and it works great.

You put the capacitor on pins 1 and 2, make sure ground is on pin 1.
The capacitor is to make sure there is enough power being supplied when it needs it. Without the capacitor it causes unreliable communication.
If you have other issues this is a great summary video on using the NRF24L01+ transceivers: https://www.youtube.com/watch?v=kDTJULtFPgE


text:
I am not able to set the correct configuration of sound module
I have been trying to make sound reactive LED lights but my sound module is detecting only very close voice the LED react only when I press it to the speaker with my hands I have tried to set the potentiometer many times but I got unsuccessful I have connected the Analogue output to Arduino.
The voice module I used:

I have used the following code-

#include <FastLED.h>

/** BASIC CONFIGURATION  **/

//The amount of LEDs in the setup
#define NUM_LEDS 10
//The pin that controls the LEDs
#define LED_PIN 6
//The pin that we read sensor values form
#define ANALOG_READ 0

//Confirmed microphone low value, and max value
#define MIC_LOW 0.0
#define MIC_HIGH 737.0
/** Other macros */
//How many previous sensor values effects the operating average?
#define AVGLEN 15
//How many previous sensor values decides if we are on a peak/HIGH (e.g. in a song)
#define LONG_SECTOR 5

//Mneumonics
#define HIGH  3
#define NORMAL 2

//How long do we keep the "current average" sound, before restarting the measuring
#define MSECS 2000
#define CYCLES MSECS / DELAY

/*Sometimes readings are wrong or strange. How much is a reading allowed
to deviate from the average to not be discarded? **/
#define DEV_THRESH 0.8

//Arduino loop delay
#define DELAY 1

float fscale( float originalMin, float originalMax, float newBegin, float newEnd, float inputValue, float curve);
void insert(int val, int *avgs, int len);
int compute_average(int *avgs, int len);
void visualize_music();

//How many LEDs to we display
int curshow = NUM_LEDS;

/*Not really used yet. Thought to be able to switch between sound reactive
mode, and general gradient pulsing/static color*/
int mode = 0;

//Showing different colors based on the mode.
int songmode = NORMAL;

//Average sound measurement the last CYCLES
unsigned long song_avg;

//The amount of iterations since the song_avg was reset
int iter = 0;

//The speed the LEDs fade to black if not relit
float fade_scale = 1.2;

//Led array
CRGB leds[NUM_LEDS];

/*Short sound avg used to "normalize" the input values.
We use the short average instead of using the sensor input directly */
int avgs[AVGLEN] = {-1};

//Longer sound avg
int long_avg[LONG_SECTOR] = {-1};

//Keeping track how often, and how long times we hit a certain mode
struct time_keeping {
  unsigned long times_start;
  short times;
};

//How much to increment or decrement each color every cycle
struct color {
  int r;
  int g;
  int b;
};

struct time_keeping high;
struct color Color;

void setup() {
  Serial.begin(9600);
  //Set all lights to make sure all are working as expected
  FastLED.addLeds<NEOPIXEL, LED_PIN>(leds, NUM_LEDS);
  for (int i = 0; i < NUM_LEDS; i++)
    leds[i] = CRGB(0, 0, 255);
  FastLED.show();
  delay(1000);

  //bootstrap average with some low values
  for (int i = 0; i < AVGLEN; i++) {
    insert(250, avgs, AVGLEN);
  }

  //Initial values
  high.times = 0;
  high.times_start = millis();
  Color.r = 0;
  Color.g = 0;
  Color.b = 1;
}

/*With this we can change the mode if we want to implement a general
lamp feature, with for instance general pulsing. Maybe if the
sound is low for a while? */
void loop() {
  switch(mode) {
    case 0:
      visualize_music();
      break;
    default:
      break;
  }
    delay(DELAY);       // delay in between reads for stability
}

/**Funtion to check if the lamp should either enter a HIGH mode,
or revert to NORMAL if already in HIGH. If the sensors report values
that are higher than 1.1 times the average values, and this has happened
more than 30 times the last few milliseconds, it will enter HIGH mode.
TODO: Not very well written, remove hardcoded values, and make it more
reusable and configurable.  */
void check_high(int avg) {
  if (avg > (song_avg/iter * 1.1))  {
    if (high.times != 0) {
      if (millis() - high.times_start > 200.0) {
        high.times = 0;
        songmode = NORMAL;
      } else {
        high.times_start = millis();
        high.times++;
      }
    } else {
      high.times++;
      high.times_start = millis();

    }
  }
  if (high.times > 30 && millis() - high.times_start < 50.0)
    songmode = HIGH;
  else if (millis() - high.times_start > 200) {
    high.times = 0;
    songmode = NORMAL;
  }
}

//Main function for visualizing the sounds in the lamp
void visualize_music() {
  int sensor_value, mapped, avg, longavg;

  //Actual sensor value
  sensor_value = analogRead(ANALOG_READ);

  //If 0, discard immediately. Probably not right and save CPU.
  if (sensor_value == 0)
    return;

  //Discard readings that deviates too much from the past avg.
  mapped = (float)fscale(MIC_LOW, MIC_HIGH, MIC_LOW, (float)MIC_HIGH, (float)sensor_value, 2.0);
  avg = compute_average(avgs, AVGLEN);

  if (((avg - mapped) > avg*DEV_THRESH)) //|| ((avg - mapped) < -avg*DEV_THRESH))
    return;

  //Insert new avg. values
  insert(mapped, avgs, AVGLEN);
  insert(avg, long_avg, LONG_SECTOR);

  //Compute the "song average" sensor value
  song_avg += avg;
  iter++;
  if (iter > CYCLES) {
    song_avg = song_avg / iter;
    iter = 1;
  }

  longavg = compute_average(long_avg, LONG_SECTOR);

  //Check if we enter HIGH mode
  check_high(longavg);

  if (songmode == HIGH) {
    fade_scale = 3;
    Color.r =  8;
    Color.g = 1;
    Color.b = -2;
  }
  else if (songmode == NORMAL) {
    fade_scale = 3;
    Color.r = -1;
    Color.b = 6;
    Color.g = -2;
  }

  //Decides how many of the LEDs will be lit
  curshow = fscale(MIC_LOW, MIC_HIGH, 0.0, (float)NUM_LEDS, (float)avg, -1);

  /*Set the different leds. Control for too high and too low values.
          Fun thing to try: Dont account for overflow in one direction,
    some interesting light effects appear! */
  for (int i = 0; i < NUM_LEDS; i++)
    //The leds we want to show
    if (i < curshow) {
      if (leds[i].r + Color.r > 255)
        leds[i].r = 255;
      else if (leds[i].r + Color.r < 0)
        leds[i].r = 0;
      else
        leds[i].r = leds[i].r + Color.r;

      if (leds[i].g + Color.g > 255)
        leds[i].g = 255;
      else if (leds[i].g + Color.g < 0)
        leds[i].g = 0;
      else
        leds[i].g = leds[i].g + Color.g;

      if (leds[i].b + Color.b > 255)
        leds[i].b = 255;
      else if (leds[i].b + Color.b < 0)
        leds[i].b = 0;
      else
        leds[i].b = leds[i].b + Color.b;

    //All the other LEDs begin their fading journey to eventual total darkness
    } else {
      leds[i] = CRGB(leds[i].r/fade_scale, leds[i].g/fade_scale, leds[i].b/fade_scale);
    }
  FastLED.show();
}
//Compute average of a int array, given the starting pointer and the length
int compute_average(int *avgs, int len) {
  int sum = 0;
  for (int i = 0; i < len; i++)
    sum += avgs[i];

  return (int)(sum / len);

}

//Insert a value into an array, and shift it down removing
//the first value if array already full
void insert(int val, int *avgs, int len) {
  for (int i = 0; i < len; i++) {
    if (avgs[i] == -1) {
      avgs[i] = val;
      return;
    }
  }

  for (int i = 1; i < len; i++) {
    avgs[i - 1] = avgs[i];
  }
  avgs[len - 1] = val;
}

//Function imported from the arduino website.
//Basically map, but with a curve on the scale (can be non-uniform).
float fscale( float originalMin, float originalMax, float newBegin, float
    newEnd, float inputValue, float curve){

  float OriginalRange = 0;
  float NewRange = 0;
  float zeroRefCurVal = 0;
  float normalizedCurVal = 0;
  float rangedValue = 0;
  boolean invFlag = 0;

  // condition curve parameter
  // limit range

  if (curve > 10) curve = 10;
  if (curve < -10) curve = -10;

  curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
  curve = pow(10, curve); // convert linear scale into lograthimic exponent for other pow function

  // Check for out of range inputValues
  if (inputValue < originalMin) {
    inputValue = originalMin;
  }
  if (inputValue > originalMax) {
    inputValue = originalMax;
  }

  // Zero Refference the values
  OriginalRange = originalMax - originalMin;

  if (newEnd > newBegin){
    NewRange = newEnd - newBegin;
  }
  else
  {
    NewRange = newBegin - newEnd;
    invFlag = 1;
  }

  zeroRefCurVal = inputValue - originalMin;
  normalizedCurVal  =  zeroRefCurVal / OriginalRange;   // normalize to 0 - 1 float

  // Check for originalMin > originalMax  - the math for all other cases i.e. negative numbers seems to work out fine
  if (originalMin > originalMax ) {
    return 0;
  }

  if (invFlag == 0){
    rangedValue =  (pow(normalizedCurVal, curve) * NewRange) + newBegin;

  }
  else     // invert the ranges
  {
    rangedValue =  newBegin - (pow(normalizedCurVal, curve) * NewRange);
  }

  return rangedValue;
}

The product page states that the module provides a “signal output” and is based on the LM393 (which is a comparator). Your code seems to expect an analog value.

The potentiometer is only supposed to modify the threshold at which the Digital Output Pin will output a HIGH or LOW value. The Analog Output Pin should be not altered by the potentiometer.
I think your sound module might not be the best for your project, if you are working with weak audio signals. It suits more for projects like clap detectors and such. You might be able to use that sensor for detect weaker signals if you put an audio amplifier after the Analog Output Pin, or change the Analog Reference value on the Arduino.

can suggest me a sound module perfect for this project..

source: Stack Exchange

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

sort: votes


text:
Arduino HTTP Request Fails Slow Cellular Connection
Setup:

Arduino Mega 2560 w/ Wiznet W5500 Ethernet Sheild
Using TP-Link TL-MR6400 LTE router to connect to internet over cellular connection in Uganda.

Using an HTTP Post with the following,

client.println("POST /hook HTTP/1.1");
client.print("Host: "); client.println(server);
client.println("Accept: */*");
client.print("Content-Type: text/html;");
client.println("User-Agent: Arduino/1.0");
client.println("Connection: close");
client.print("Content-Length: ");
client.println(PostData.length());
client.println();
client.println(PostData);

where PostData is a String and Ethernet2 is the library used.
This works just fine from the US to the same AWS server, or a https://requestbin.com/ instance.

When testing from Uganda using a Raspberry Pi and curl it works fine.
$ curl -vs -d 'ABCDEFG' -H "User-Agent: Arduino/1.0"  -H "Content-Type: text/html" -H "Connection: close"   http://<server here>/hook
*   Trying <ip here>...
* TCP_NODELAY set
* Connected to <server here> (<ip here>) port 80 (#0)
> POST /tg HTTP/1.1
> Host: <server here>
> Accept: */*
> User-Agent: Arduino/1.0
> Content-Type: text/html
> Connection: close
> Content-Length: 7
>
* upload completely sent off: 7 out of 7 bytes
< HTTP/1.1 200 OK
< Access-Control-Allow-Origin: *
< Content-Type: application/json; charset=utf-8
< Date: Tue, 06 Aug 2019 21:06:49 GMT
< x-pd-status: sent to primary
< X-Powered-By: Express
< Content-Length: 16
< Connection: Close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{"success":true}

I even tried an HTTP GET example from the Ethernet2 library,
https://www.arduino.cc/en/Tutorial/WebClientRepeating
It worked just fine in the US but in Uganda I get,
My IP address: 192.168.1.177

connecting...

connecting...

connecting...

I increased the time between requests here to 100 seconds where it is listening for the whole time inbetween.
It seems that client.connect(server, 80) is successful and the client.print messages go through but the message never reaches the server so there is no response. My AWS server does not recieve the request and this is the same for the requestbin instance. This behavior is mirrored in all my Arduino tests.
I thought the ISP might be blocking but the RPi can send nearly the same message. I thought maybe a timeout somewhere but I can not find where with my tests. I thought my message was too long but I reduced the size to only 10 characters with the same results.

Trying to figure out why the Arduino HTTP request cannot reach any webhooks from Uganda and how to fix it if possible. Different ISP, slower connection, cellular connection?
Any help would be appreciated.

@jsotola yes, I am able to connect to either server using a raspberry pi on the same network as the arduino in Uganda (connected to the same router). I am also able to connect to both servers with both attempted Arduino sketches from the US. I am here considering a raspberry pi as a computer.

my apologies, i did not read your post carefully ... you already explained that the Pi is connecting correctly

try the Ethernet library

The only things I can think of to try HTTP/1.0 instead of HTTP/1.1. Or maybe combining all the client.prints so everything is send in a single packet, instead of possibly multiple (I couldn't figure out if that is even the case).

yes, use buffering https://github.com/jandrassy/StreamLib/blob/master/README.md

@Juraj Your solution worked for me, if you post an answer I will accept it. As background, I tried the Ethernet lib vs. Ethernet2, I tried HTTP/1.0 vs HTTP/1.1, also adding just a client.flush() statement after my requests. I tried using just an IP address to avoid the DNS requests and speeding things up by using a different, faster, DNS like 1.1.1.1 or 8.8.8.8. Finally the two things that helped were, keeping the connection open whenever possible with Connection: Keep-Alive and the StreamLib library ChunkedPrint example.

Buffering and flush()
Many arduino libraries suffer of slow communication because the authors didn't use buffering. To not to send every small piece of data over a connection with overhead of protocol bytes use buffering. Data are collected until the buffer is full and then the collected data are send and the buffer is ready for next bytes. The flush() functions sends the buffer even if it is not full, but you do not have more data. (The flush() 'dilemma' was resolved and in Arduino core classes the flush() method is declared in Print class which is the Arduino standard interface for output streams.)
My StreamLib library offers a BufferedPrint class which wraps the target stream and buffers the data to be send over the target stream. Of course, do not forget to use flush() after last data printed.

HTTP data length
It is common practice in Arduino sketches to not to send the Content-length header with POST requests. In most cases it is because when the HTTP headers are send, the size of data is not known. The WebServer then doesn't know if it received all the data and waits until the connection is closed or timeout is reached. It leads to long time until a Web Server sends the response to requesting Arduino sketch.
If the data can be prepared to a string in memory, fill the Content-length HTTP header.
If the data to be send as response or in POST request wouldn't fit into available memory, ChunkedPrint from my StreamLib can be used with HTTP chunked Transfer-Encoding. And ChunkedPrint is an extension of BufferedPrint so the Web Server handles your request without hesitating.

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


text:
How to measure ultrasonic sensor without pulsein method?
I am a front-end developer so I don't really know Arduino. Anyway, my teacher gave me a project.
In short, I have to measure distance with HC-SR04. But the problem is that the teacher wants me to use a timer. But I can't understand how can I do that.
Thank you for helping.

It sounds like you are being assigned to read the ATmega data sheet or programmer's manual and make direct use of the timer peripheral, ie, do what the pulseIn code does, but do it yourself.   If you ask someone else to give you the answer, how is that more beneficial than just looking at the implementation of the pulseIn function?

Rather than give you the straight answer in code form, consider this approach. If you learn how the unit works, you will be better prepared to answer questions presented to you.
The background of an ultrasonic distance measuring device is that it sends out a signal, in the form of sound you cannot hear. The device then listens for any echoes (bounce-back) of that pulse within a certain time period. This time period represents the distance range that the device can register. If the electronics are of poor quality, the minimum distance will be larger than if the device was of higher quality, as the amount of time for the pulse to bounce from a close-in object is going to be very short. The electronics have to be very fast to read such a short period of time.
There are libraries for ultrasonic devices such as the one you note, but that's the "easy way" to use it. If you perform appropriate searches, you will find there are references how to use direct timing for this device, which will satisfy the requirement you have been given.
I could perform the search and provide you a link, but that's half the work. Consider to use terms including your device identifier along with code and timing and you may find useful links. It is also very possible that you will find someone's pre-written code using the timing method.

One feature of the commonly used module is that shortly after the TRIG pin falls, the the module raises it's ECHO pin and holds it HIGH until it detects the end of the echo.  The pulse on the ECHO pin isn't the actual echo of the pulse, it is a pulse manufactured by the module which measures from the end of the transmitted pulse to the end of the reflected pulse.

The solution is, You need to implement custome pulse in funtion
unsigned long rdPulseIn(int pin, int value, int timeout) { // the following comments assume that we're passing HIGH as value. timeout is in milliseconds

    unsigned long now = micros();
    while(digitalRead(pin) == value) { // wait if pin is already HIGH when the function is called, but timeout if it never goes LOW
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }

    now = micros(); // could delete this line if you want only one timeout period from the start until the actual pulse width timing starts
    while (digitalRead(pin) != value) { // pin is LOW, wait for it to go HIGH befor we start timing, but timeout if it never goes HIGH within the timeout period
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }

    now = micros();
    while (digitalRead(pin) == value) { // start timing the HIGH pulse width, but time out if over timeout milliseconds
        if (micros() - now > (timeout*1000)) {
            return 0;
        }
    }
    return micros() - now;
}

You can read distance
long mm = rdPulseIn(echoPin, HIGH, 37)/5.82; // distance in mm

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

authors: عبدالرحمن العيدروس


text:
WiFi.status() hangs / resets board
Using one of the RobotDyn boards with onboard WiFi and a Generic ESP8266 module.
I can load the sketch, but when WiFi.status() is called to see if WiFi enabled, the sketch hangs, rebooting the board after ten seconds are so.

void setup() {
  Serial.begin( 115200 );
  Serial.println( "begin - wifi status: " );
  // program hangs here - - - - - - -
  int status = WiFi.status();
  Serial.println( status );
}

I think it might be a problem with the code you are using, prior to version 2.2.0 of the "ESP Core" the first block of code worked, since only the second version works.
It seems that you can get around it by rather than doing this:
 WiFi.begin(ssid, password); // connect to the network
 while (WiFi.status() != WL_CONNECTED)
 {
     delay(500);
 }

You should do this:
if (WiFi.status() != WL_CONNECTED)
{
     WiFi.begin(ssid, password); // connect to the network
     delay (500);
}

Does that look it might be a likely cause?
Sources
 1 2

No. I wish to know if WiFi available, so issues int status = WiFi.status();. The sketch hangs on this line. (Have added this to question for clarity.)

Think I found the cause!
I previously had

#include <WiFi.h>

but now using

#include <ESP2866WiFi.h>

This seems to work
I was unaware of the two library sets. Since I use both Arduino MiniPro and versions of NodeMCU, am now going through the libraries and determining what breaks.
IMHO, in regard to libraries, NodeMCU Lua libraries are far, far better than Arduino's C++ libraries.

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


text:
Is it better to use Vraw or Vcc on Mini Pro?
I have 12V and 5V power available. Is it better to feed the 5V through the Vcc pin or either the 12V or 5V through the Vraw pin?

Use the 5V connected to the Vcc pin.
If you use the Vraw pin, the voltage goes through a voltage regulator. This voltage regulator will convert the higher voltage down to 5V by converting the extra volts to heat. So in case of using 12V you'd be throwing away around 60% of the power. Which is both wasteful, and will heat up the regulator quite a bit (depending on the load).

But with feeding 5V, would there be a difference between the Vcc and Vraw? Or does the voltage regulator automatically incur a 1.2V penalty?

Voltage regulators always have a certain dropout voltage. So you always have to provide a voltage a bit higher that the output voltage of the regulator.


text:
EEPROM put and get not working on ESP8266 (NodeMCU)
The Arduino documentation provides two examples to store data in the EEPROM.
https://www.arduino.cc/en/Reference/EEPROMPut stores data in the EEPROM and the EEPROMGet example reads the data back and writes it out.
These examples work fine on my Arduino Uno, but on my ESP8266 (NodeMCU) the EEPROMGet example code is unable to retrieve the data EEPROMPut should have stored previously. Instead it's just returning some random bits and bytes.

Any ideas? I haven't found anything about known incompatibilities related to the ESP8266 boards...

The ESP8266 doesn't have any EEPROM. Instead it emulates it using Flash.
In order not to wear out your flash you have to "commit" changes to the flash once they have been queued for writing - otherwise they will be lost.
Instead of using the Arduino examples you should be using the ESP8266 specific examples included with the ESP8266 EEPROM emulation library (but also here).


text:
How to identify connection lost on HC-06?
I am making an RC car on Arduino Uno. I have connected an L298N motor driver to an Arduino Uno to control 2 DC motors. I also connected an HC-06 to the Uno to receive commands from an Android smartphone. Everything is working fine. But if a connection is lost (because of low battery or disconnected on Android application), when the RC car is moving it is not stopping. It stops only when there is connection and "s"(stop) command is received via Bluetooth.
int in1 = 4;
int in2 = 5;
int in3 = 6;
int in4 = 7;

void setup() {
  Serial.begin(9600);
  pinMode (in1, OUTPUT);
  pinMode (in2, OUTPUT);
  pinMode (in3, OUTPUT);
  pinMode (in4, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int command = Serial.read();
    move(command);
  }
}

void move(int command) {
    if (command == 'f') forward();
    else if (command == 'b') backward();
    else if (command == 'l') left();
    else if (command == 'L') leftback();
    else if (command == 'r') right();
    else if (command == 'R') rightback();
    else if (command == 's') stop();
}

Now what I want is to identify whether there is connection or it is lost. For example:
if(Serial.connectionLost()) stop();

Is there such a function to identify the connection state? If not, is it possible to implement this function in another way?

My first one or couple of HC-06es brought its LED signal out to a pin on the base board, labeled "STATE" on mine. I tested the LED state on every loop and if it was changing regularly, took that to indicate whether it was waiting for a connection.
Later modules no longer bring out the LED signal but it is available on module's edge-pin 24, according to a (now 6yo) datasheet.

By cutting the plastic sleeve and bringing out the signal to the baseboard again, you use it to monitor the connection.

Two possible ways I see:

Connect the HC-06 LED anode (or cathode, depending on how it's driven) to an Arduino input pin. Since you can tell from the blink frequency if the module is paired with your phone or not, you can use that (through interrupts maybe) as a means to know if you're still connected to your phone.
Find a way to configure the android app (or write your own app) to either regularly ping your Arduino or to respond to ping requests from the Arduino. If the Arduino fails to get a ping request (in the first case) or a ping response (in the second case) after some pre-agreed interval, it decides the connection has been broken and halts the RC car.

Second way is less messy but may require some android programming skills on your part. I remember coming across an app in the Play Store that sends '#' constantly even when idle, with your own characters in between. That would work as well as a ping, if you could find something similar, and the only programming you'd need to do would be on the Arduino's side.

The second option is also often known as "Keep alive". Send a char from the Arduino to the Android App, and the Android App send a knowledge back, Example : Arduino send "Alive" -> Android. Android reply "Yes" to the Arduino.


text:
Switch Control Between Two Different Techniques
I have implemented PID control of a generator governor to maintain a constant RPM using an Arduino Uno. It works pretty well, but there is a tradeoff between stabilty and response time. Using PID values that allow it to respond without oscillation is also about half as fast as the old mechanical governor.
I came up with a plan to use a CT to sense the AC amps and have the Uno rapid the throttle servo to a known value determined manually. Either using a lookup table or an interpolation algorithm, I haven't yet checked the linearity of the amps vs. throttle angle. The idea is to use a table (or interpolation) to get the governor close, and then let the PID fine tune it.
My hangup is that I'm not sure how to switch between lookup control and PID control as needed.
Pseudo-code:
analogRead(AMPS);
myservo.write(table_Val);
somehow_switch_to_PID;
myservo.write(PID_value);

You can use an if condition, checking if you reached the target RPM within the fine tune range.

If I use some method of getting the RPMs close, won't the PID just swing to one extreme or the other trying to adjust the value with no success because the "get close" operation is in control? I mean, the PID is looking at the RPMs and giving an output but that output is being ignored because another operation has servo control. By the time PID is in control, shouldn't the output have gone full tilt trying to make a change, and now will just slam the servo to that erroneous value?

the PID is looking at the RPMs and giving an output but that output is
  being ignored because another operation has servo control.

PID is not something, that happens somewhere in the background without you having any control. On the Arduino it is done in software, so you can totally control it. Why should you run a PID calculation, if you don't use the value? The solution is to simply only do the appropriate calculation depending on the RPM at any given time. No need to do 2 calculations at the same time. I will form that into a code with explanations:
You have 2 ways of calculating the needed servo values:

Your "getting close" method
The PID method

To switch between those methods you need to make a decision based on the RPM. If the RPM is outside of your interval, the first method is used. If it is inside, the second will be used. Decision/conditionals are often wrote with an if else statement. Look at this (not tested) code snippet:
int target_rpm = 700;
int half_interval = 20;
int current_servo_pos = 0;

void loop(){
    current_rpm = analogRead(AMPS);

    if(current_rpm > target_rpm - half_interval && current_rpm < target_rpm + half_interval){
        // Do the PID calculation here and save the result in current_servo_pos
    } else {
        // Do the "getting close" calculation here and save the result in current_servo_pos
    }

    myservo.write(current_servo_pos);
}

I didn't go into detail about the actual calculation, since that is not important here. You may use any calculation, that you like there. For PID you can find libraries, that do the calculation for you, for example here at github.
The code will simply decide based on the RPM, what calculation should be used. If the RPM goes out of the interval for some reason (maybe is was disturbed and lost some speed), it will automatically use the "getting close" method until it is again inside of the interval.
Note: The numbers, that I used here, are arbitrary. You should change them to what ever you need.

Thanks again Chris! I haven't been successful using the PID outside of void loop(). If I place the PID parameters anywhere else, it doesn't respond. I'll get the code currently in use later today. But that's why I asked about the PID calc already having an output. I can write the PID output into anything I want in any function, but trying to call the PID outside of void loop() has been fruitless.

Yes, please add your code to your question. That way I can add more to my answer to help you with that.


text:
Which Arduino board would be sufficient for the following simulink project?
I'm trying to run a Fuzzy Logic MPPT Algorithm in Arduino UNO, here's the Simulink File
However when I try to upload the code, I get the following error

Is this project possible with UNO, if yes, what shall I do? Else which Arduino board would be suitable for this project?

We cannot answer about your Simulink program (since this site is only about Arduino). But currently you are using 3 times the RAM an Uno has. You can try to optimize your Simulink program, though I doubt that you will be able to reduce the needed memory that much.
So you should switch to a board with significantly more RAM. There are many to choose from, with different RAM, flash, peripherals, pin numbers. Write down all your requirements and then look for a fitting board


text:
Attiny84 with external eeprom-write and read beyond 255
Just starting with external EEPROM and ATTiny's.  I am successfully writing and reading to the 24LC64 chip using the following code with TinyWireM (thanks to other help on the forums). However, I really need to store integers up to 8500.
I'm assuming I need to store the number as 2 bytes and reassemble them when needed, just dont have the knowledge yet to do so.  Any help is truly appreciated...
    //------------------I2C EEPROM-----------------------
void writeAddress(int address, int val)
{
  TinyWireM.beginTransmission(EEPROM_I2C_ADDRESS);
  TinyWireM.send(address >> 8);   // MSB
  TinyWireM.send(address & 0xFF); // LSB
  TinyWireM.send(val);
  TinyWireM.endTransmission();
  delay(10);
}

byte readAddress(int address)
{
  byte rdata = 0xFF;

  TinyWireM.beginTransmission(EEPROM_I2C_ADDRESS);
  TinyWireM.send(address >> 8);   // MSB
  TinyWireM.send(address & 0xFF); // LSB
  TinyWireM.endTransmission();
  TinyWireM.requestFrom(EEPROM_I2C_ADDRESS, 2);

 if (TinyWireM.available())
  {
    rdata = TinyWireM.receive();
  }
  return rdata;
}

You are already sending a 2-byte memory address to the EEPROM. It should work to do the same operations with the value to save. Research about the bitwise operators, especially the shift operator >>, the AND operator & and the OR operator |.

Thats the frustrating part of it.  I totally get that and I actually now am able to send the two bytes to the two registers.  I just cant figure out the TinyWireM syntax to read the values from the 2nd address.  I'm looking for a way to tell ask for the data in (address + 1 & 0xFF) and I keep getting the data from the only the first address.

@VinnyP this site is not a forum ... all of what you said in a comment belongs in the question at the top of this page ... please edit your question and then delete the comment

You asked for two bytes of data with TinyWireM.requestFrom(EEPROM_I2C_ADDRESS, 2);, but your function and your rdata is a byte instead of an int, and you only get one byte with TinyWireM.receive();.


text:
Can I power Arduino with 12V 1.2A adapter
I am new to arduino and i am making a smart energy meter for my home. I want to run the arduino months so, how to power arduino with a adapter, I have a 12V 1.2A adapter is it ok to power arduino with it or not?.
Thanks in advance.
As i said i want to run it long time.

read the documenation pertaining to your version of arduino

I have arduino smd

this one or other? https://store.arduino.cc/arduino-uno-smd-rev3

Yes, you can power an Arduino with 12V into the barrel connector. It will then use it's internal voltage regulator to drop that to the 5V it needs internally. However, that is on the high side of it's recommended range, and will make the Arduino's voltage regulator run hot. A 7.5V supply would be better, and you could probably get more total current out of the 5V regulator without overheating if you fed it 6V or 7.5V instead of 12V. (6V is the lower limit. >= 7V is better.)
(A linear voltage regulator like the one in most Arduino boards essentially uses a transistor as a variable resistor to lower the voltage from the input voltage to 5V, which converts the excess voltage to heat. The higher the input voltage, and the more current you draw from the regulator, the more heat it generates.)

The 12V power supply is unlikely getting hot (without loading it near it's full power). But the on board voltage regulator is different story. Also there is no linear power supply on the arduino board, it's just the linear voltage regulator. Just for correcting terminology.

That's what I meant. Good call on the wrong term. I'll fix stat

If it is an Arduino Uno Rev3 SMD, the documentation (see Juraj's comment) is of relevance here, click the tab "Tech Specs" to find:

Operating Voltage     5V
Input Voltage (recommended)   7-12V
Input Voltage (limit)     6-20V

While the microcontroller's (ATmega328P) operating voltage is 5 V there is an on-board voltage regulator to make the board work within the input voltage range of 6 to 20 V (max limits) or the recommended range of 7 to 12 V.
Operating this Arduino with a 12 V power adapter is within spec and therefore safe to do. The current rating of the adapter of 1.2 A is also more than sufficient to run the Arduino.


text:
I2C interference SENSOR(SCL+SDA) and MasterSlave comm
I am building a weather station with an Arduino slave (dedicated to a rain gauge - depicted below as a reed switch) and a NodeMCU master with some additional sensors.

One such sensor, a BMP280 uses D1 and D2 as SCL and SDA, while slave control is using D3 and D4 for communication with Arduino.
When I enable Wire.begin for slave communication, my BMP280 readings go nuts

#include <Adafruit_BMP280.h>

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bmp;

// masterSlave
#include <Wire.h>
#define I2CAddressESPWifi 8
...

void setup() {

    if (!bmp.begin()) {
        Serial.println("Could not find a valid BMP280 sensor, check wiring!");
        while (1);
    }

    // masterSlave - generates problem with BMP280...
    Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

BMP280 Temp = -136.42 *C
Pressure = 125136.25 Pa

as opposed to this reading when Wire.begin is commented out.
    // COMMENTED OUT FOR DEBUGGING
    //masterSlave - generates problem with BMP280...
    //Wire.begin(0,2);//Change to Wire.begin() for non ESP. D3 SDA  D4 SCL

BMP280 Temp = 20.01 *C
Pressure = 93464.36 Pa

I attempted setting D3 and D4 to LOW while reading from BMP280, but it had no effect on readings.

Hint#1: I2C pullup resistors.

share your full sketch here.

The I2C is designed for short distances on a PCB. How far will be the slave?

@Juraj some few centimeters - same board (there's a 10m extension cable for the rain gauge -  that part is working perfectly).

@MikaelPatel I'll play some more with the pullup resistor and get back to you.

@Vaibhav 1300 lines of code...  Which parts interest most?  until setup?

The Adafruit BMP280 library uses the Wire library. It calls begin() at default pins (D1, D2). And then you begin() the same Wire object at different pins. From that moment the BMP280 library can't communicate with the sensor.
The I2C (a.k.a. TwoWire or Wire) is a bus. Many devices can be wired to the same pair of pins. They must listen on different addresses. So wire both devices to the D1, D2 and use in slave Arduino an address different then the address of the sensor.
The esp8266 and the sensor are 3.3 V devices. The Uno is a 5 V device. You should use logic level conversion on SDA/SCL to Uno.

So, as far as I2C is concerned, the sensor can be addressed as a slave.  I'll try that and get back to you by the end of the day.  Makes total sense.  UPVOTED

not "to be addressed". but "having an address". some sensors have fixed address, some have a choice from a few addreses

yeah, i'll check up on that.  I'll start by changing the slave's address (currently 8)

the default I2C address of the Adafruit BMP280 is 0x77

I attempted this solution with no result.

this is not a solution but an explanation. what is wrong after you use the Wire library on one set of pins?

when i place the slave and the sendor on the same set of pins is that the sensor is not recognized.

on D1, D1 and you removed Wire.begin(0, 2)?

yes, i did.  everything using D1 and D2, removed Wire.begin(0,2).  Sensor works without slave, but when slave is wired in, sensor stops being recognized

@tonygil, the slave Arduino works without the sensor on esp8266?

50 bonus points for effort, even though i havent at, at this time, been able to confirm or disprove this answer because of other incidental issues which arise AND because of my limited knowledge of Wire library.

I added a note about logic level conversion. and thank you.

got it working.  fixed connections and set a small delay before reading

As per your descriptions, I'm answering here. There is a fact we forget about the load capacitance calculation for selecting I2C pull-ups. It's calculated when more than one slave and variant to distance. Check the jumpers and for pullups try 10k or 4.7K or better you can calculate. It's better to provide a small delay after the wire.begin() function to stabilize the module

would you care to scribble that on the fritzing diagram in the question?

The solution I implemented uses the BMP280 sensor in SPI mode, connected as follows:

with this code before setup
#include <Adafruit_BMP280.h>
#define BMP_SCK D5
#define BMP_MISO D8
#define BMP_MOSI D6
#define BMP_CS D7

//Adafruit_BMP280 bmp; // I2C
//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI
Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO,  BMP_SCK);

which doesnt EXACTLY answer my answer, though it solves the practical problem (just in case anyone wants a workaround).  ;)


text:
Compiling code via terminal
How can I compile my code via terminal? I am working on a Chrome app that allows you to write, compile, and upload code to an Arduino, and I need to know this so I can use the command line compiler on my Linux server. Mac or Linux terminal, it doesn't matter.

I'm not really sure what exactly you need but to compile in the command line you need something like avr-gcc.

Check out platformio.org it's the best solution out there for command line compiling.

See my answer to a related question for an example PlatformIO CLI session.

There is an Arduino CLI (command line interface):
https://github.com/arduino/arduino-cli
You use commands such as to access Arduino IDE functions:
arduino-cli compile --fqbn arduino:avr:leonardo sketch
and
arduino-cli upload -pCOM14 --fqbn arduino:avr:leonardo sketch
(obviously port will be different under Linux)

Assuming an AVR-based Arduino, you would need the avr-gcc compiler, the
avr-libc and the Arduino libraries. Also avrdude if you want to upload.
The only issue is that the commands used for the build process are quite
long (lots of options). You can see them by enabling verbose compilation
in the IDE. Thus you will probably want some way to automate the whole
thing.
There are several options for this. The most straightforward seems to be
the arduino-builder command-line tool. This is part of the Arduino
project and should ensure maximum compatibility. Otherwise you could use
a plain old Makefile. I personally use Sudar Muthu' Makefile. It can
be installed on a Debian-based Linux distribution by:
sudo apt install arduino-mk

It is not fully compatible with the classic Arduino build process
though: it does automatically include <Arduino.h> into your sketch,
but it does not add forward declarations. Some prefer it this way, as
the automatic inclusion of forward declarations is somewhat buggy and
does not play well with some C++ features.


text:
NEO 6M doenst provide coordinates
I do a school project (CanSat) it's an international project. But my problem is my GPS. I tried 2 different codes. Both they say the GPS is connected. They GPS led doesn't provide any light.
wiring:
UBlox Neo 6M
Arduino leonardo
Rx (GPS) to port 8
Tx (GPS) to port 9
Vcc to Vcc
Gnd to Gnd
Btw I sit near the window.
First code:
The gps.encode(c) is always false/0 I don't know why this one doesn't work.
#include <SoftwareSerial.h>
#include <TinyGPS.h>

SoftwareSerial mySerial(9, 8);
TinyGPS gps;

void gpsdump(TinyGPS &gps);
void printFloat(double f, int digits = 2);

void setup()
{
  // Oploen serial communications and wait for port to open:
  Serial.begin(9600);
  // set the data rate for the SoftwareSerial port
  mySerial.begin(9600);
  delay(1000);
  Serial.println("uBlox Neo 6M");
  Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
  Serial.println("by Mikal Hart");
  Serial.println();
  Serial.print("Sizeof(gpsobject) = ");
  Serial.println(sizeof(TinyGPS));
  Serial.println();
}

void loop() // run over and over
{
  bool newdata = false;
  unsigned long start = millis();
  // Every 5 seconds we print an update
  while (millis() - start < 5000)
  {
    if (mySerial.available()){
      char c = mySerial.read();
     // Serial.println(c);  // uncomment to see raw GPS data
      if (gps.encode(c)){
        newdata = true;
        break;  // uncomment to print new data immediately!
      }
    }
  }

  if (newdata)
  {
    Serial.println("Acquired Data");
    Serial.println("-------------");
    gpsdump(gps);
    Serial.println("-------------");
    Serial.println();
  }

}

void gpsdump(TinyGPS &gps)
{
  long lat, lon;
  float flat, flon;
  unsigned long age, date, time, chars;
  int year;
  byte month, day, hour, minute, second, hundredths;
  unsigned short sentences, failed;

  gps.get_position(&lat, &lon, &age);
  Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  // On Arduino, GPS characters may be lost during lengthy Serial.print()
  // On Teensy, Serial prints to USB, which has large output buffering and
  //   runs very fast, so it's not necessary to worry about missing 4800
  //   baud GPS characters.

  gps.f_get_position(&flat, &flon, &age);
  Serial.print("Lat/Long(float): "); printFloat(flat, 5); Serial.print(", "); printFloat(flon, 5);
    Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.get_datetime(&date, &time, &age);
  Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print(" Time(hhmmsscc): ");
    Serial.print(time);
  Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");

  gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
  Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/");
    Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
  Serial.print("  Time: "); Serial.print(static_cast<int>(hour+8));  Serial.print(":"); //Serial.print("UTC +08:00 Malaysia");
    Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second));
    Serial.print("."); Serial.print(static_cast<int>(hundredths)); Serial.print(" UTC +08:00 Malaysia");
  Serial.print("  Fix age: ");  Serial.print(age); Serial.println("ms.");

  Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): ");
    Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed());
  Serial.print("Alt(float): "); printFloat(gps.f_altitude()); Serial.print(" Course(float): ");
    printFloat(gps.f_course()); Serial.println();
  Serial.print("Speed(knots): "); printFloat(gps.f_speed_knots()); Serial.print(" (mph): ");
    printFloat(gps.f_speed_mph());
  Serial.print(" (mps): "); printFloat(gps.f_speed_mps()); Serial.print(" (kmph): ");
    printFloat(gps.f_speed_kmph()); Serial.println();

  gps.stats(&chars, &sentences, &failed);
  Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: ");
    Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed);
}

void printFloat(double number, int digits)
{
  // Handle negative numbers
  if (number < 0.0)
  {
     Serial.print('-');
     number = -number;
  }

  // Round correctly so that print(1.999, 2) prints as "2.00"
  double rounding = 0.5;
  for (uint8_t i=0; i<digits; ++i)
    rounding /= 10.0;

  number += rounding;

  // Extract the integer part of the number and print it
  unsigned long int_part = (unsigned long)number;
  double remainder = number - (double)int_part;
  Serial.print(int_part);

  // Print the decimal point, but only if there are digits beyond
  if (digits > 0)
    Serial.print(".");

  // Extract digits from the remainder one at a time
  while (digits-- > 0)
  {
    remainder *= 10.0;
    int toPrint = int(remainder);
    Serial.print(toPrint);
    remainder -= toPrint;
  }
}

Second code:
Location is invailed but i will get the time with an 1 hour and some minuts diffrence.
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
/*
   This sample sketch demonstrates the normal use of a TinyGPS++ (TinyGPSPlus) object.
   It requires the use of SoftwareSerial, and assumes that you have a
   4800-baud serial GPS device hooked up on pins 4(rx) and 3(tx).
*/
static const int RXPin = 9, TXPin = 8;
static const uint32_t GPSBaud = 9600;

// The TinyGPS++ object
TinyGPSPlus gps;

// The serial connection to the GPS device
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(9600);
  ss.begin(GPSBaud);

  Serial.println(F("DeviceExample.ino"));
  Serial.println(F("A simple demonstration of TinyGPS++ with an attached GPS module"));
  Serial.print(F("Testing TinyGPS++ library v. ")); Serial.println(TinyGPSPlus::libraryVersion());
  Serial.println(F("by Mikal Hart"));
  Serial.println();
}

void loop()
{
  // This sketch displays information every time a new sentence is correctly encoded.
  while (ss.available() > 0)
    if (gps.encode(ss.read()))
      displayInfo();

  if (millis() > 5000 && gps.charsProcessed() < 10)
  {
    Serial.println(F("No GPS detected: check wiring."));
    while(true);
  }
}

void displayInfo()
{
  Serial.print(F("Location: "));
  if (gps.location.isValid())
  {
    Serial.print(gps.location.lat(), 6);
    Serial.print(F(","));
    Serial.print(gps.location.lng(), 6);
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F("  Date/Time: "));
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print(F("/"));
    Serial.print(gps.date.day());
    Serial.print(F("/"));
    Serial.print(gps.date.year());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.print(F(" "));
  if (gps.time.isValid())
  {
    if (gps.time.hour() < 10) Serial.print(F("0"));
    Serial.print(gps.time.hour());
    Serial.print(F(":"));
    if (gps.time.minute() < 10) Serial.print(F("0"));
    Serial.print(gps.time.minute());
    Serial.print(F(":"));
    if (gps.time.second() < 10) Serial.print(F("0"));
    Serial.print(gps.time.second());
    Serial.print(F("."));
    if (gps.time.centisecond() < 10) Serial.print(F("0"));
    Serial.print(gps.time.centisecond());
  }
  else
  {
    Serial.print(F("INVALID"));
  }

  Serial.println();
}

another small weird thing is, that if I upload the code to the Arduino the Serial monitor says normally COM6(Arduino leonardo), but when it is just finished it goes to COM6 only but the program still works.
I will appreciate all the help I can get :)

Why use software serial if you have hardware serial available?

I don't know really the diffrence between Software serial and hardware serial if you can explain the diffrence when to use the one insteed of the otherone than would that be nice. But besides that it aren't my codes. I found the codes and I saw in the comments of that side that the codes worked.
the first code the gps.encode(c) is false, if I want the raw gps data I do Serial.println(c); where I get the raw gps date but it wouldn't encode so the code can proceed. So my question is there something wrong with the code or could there made an improving.

How about outside with clear sky?  Does the "They GPS led doesn't provide any light" indicate that the module isn't getting a fix?


text:
MFRC522 ReadNUID example reboots unless I include a null if statement
I'm fairly new to Arduino (and C), but not to embedded electronics and programming.
I'm using an MFRC522 module (the common one) with a Nano, and getting some strange results. They are on a very simple custom PCB I've made (the only parts on it, except for a couple of LEDs on D4 & D5)
I'm using SS_PIN on 8, and RST_PIN on 7, which is changed from 10 & 9, because the board will also be using an NRF24L01 module on the SPI bus (not fitted yet).
And I'm using the MFRC522 library.
The DumpInfo example in the library works fine, but not the ReadNUID example.
When I bring a tag/card near the reader, the sketch (sometimes) gets some of its output to the serial monitor, but then (always) the board reboots and the startup messages appear again. This happens continuously while the card is near.
I have the RFID IRQ connected to pin D3, and while thinking that may be causing the problem, and trying all sorts of stuff, I found that it wasn't. In the process I did get the sketch to work, and have distilled the fix down to two seemingly superfluous lines of code:-
Added a null if statement at the start of loop:-

if (GotIRQ) {}

and defined a volatile variable for it to test:-
volatile boolean GotIRQ=false;

Doesn't work if it's not volatile. (A clue?)
What Gives? Some dumb newbie mistake?
(I could post the entire code if required, but I've started again from the original source, and only made the 2 changes and 2 additions described above)
Here is the code:-
/*
 * --------------------------------------------------------------------------------------------------------------------
 * Example sketch/program showing how to read new NUID from a 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 the read data from a PICC (that is: a RFID Tag or Card) using a MFRC522 based RFID
 * Reader on the Arduino SPI interface.
 *
 * When the Arduino and the MFRC522 module are connected (see the pin layout below), load this sketch into Arduino IDE
 * then verify/compile and upload it. To see the output: use Tools, Serial Monitor of the IDE (hit Ctrl+Shft+M). When
 * you present a PICC (that is: a RFID Tag or Card) at reading distance of the MFRC522 Reader/PCD, the serial output
 * will show the type, and the NUID if a new card has been detected. Note: you may see "Timeout in communication" messages
 * when removing the PICC from reading distance too early.
 *
 * @license Released into the public domain.
 *
 * Typical pin layout used:
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno           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      SDA(SS)      10            53        D10        10               10
 * 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 <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
  Serial.print(F("Using the following key:"));
  printHex(key.keyByte, MFRC522::MF_KEY_SIZE);
}

void loop() {
  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Check is the PICC of Classic MIFARE type
  if (piccType != MFRC522::PICC_TYPE_MIFARE_MINI &&
    piccType != MFRC522::PICC_TYPE_MIFARE_1K &&
    piccType != MFRC522::PICC_TYPE_MIFARE_4K) {
    Serial.println(F("Your tag is not of type MIFARE Classic."));
    return;
  }

  if (rfid.uid.uidByte[0] != nuidPICC[0] ||
    rfid.uid.uidByte[1] != nuidPICC[1] ||
    rfid.uid.uidByte[2] != nuidPICC[2] ||
    rfid.uid.uidByte[3] != nuidPICC[3] ) {
    Serial.println(F("A new card has been detected."));

    // Store NUID into nuidPICC array
    for (byte i = 0; i < 4; i++) {
      nuidPICC[i] = rfid.uid.uidByte[i];
    }

    Serial.println(F("The NUID tag is:"));
    Serial.print(F("In hex: "));
    printHex(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
    Serial.print(F("In dec: "));
    printDec(rfid.uid.uidByte, rfid.uid.size);
    Serial.println();
  }
  else Serial.println(F("Card read previously."));

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

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

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

OK, trying to cut down to a minimal example has proved useful. It seems the problem is caused by the loop that stores the NUID, but not if the superfluous if statement is present. The code is :-
// Cut down version of MFRC522 library ReadNUID example that exhibits strangle
// problem of rebooting the board when a card is near the reader.
// But only if:-
// * the Store NUID loop is included
// and
// * the superfluous "if" statement at start of loop() is NOT present.
// Changes from original example are indicated by comments starting with "//QQ"
// (plus a lot of removed code)

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 8   //QQ This changed from 10
#define RST_PIN 7   //QQ This changed from 9

MFRC522 rfid(SS_PIN, RST_PIN); // Instance of the class

MFRC522::MIFARE_Key key;

volatile boolean GotIRQ=false; //QQ needed for null if statement

// Init array that will store new NUID
byte nuidPICC[3];

void setup() {
  Serial.begin(9600);
  SPI.begin(); // Init SPI bus
  rfid.PCD_Init(); // Init MFRC522

  for (byte i = 0; i < 6; i++) {
    key.keyByte[i] = 0xFF;
  }

  Serial.println(F("This code scan the MIFARE Classsic NUID."));
}

void loop() {
//  if (GotIRQ) {}   //QQ If this is not included, board resets when a RFID tag is detected

  // Look for new cards
  if ( ! rfid.PICC_IsNewCardPresent())
    return;

  // Verify if the NUID has been readed
  if ( ! rfid.PICC_ReadCardSerial())
    return;

  Serial.print(F("PICC type: "));
  MFRC522::PICC_Type piccType = rfid.PICC_GetType(rfid.uid.sak);
  Serial.println(rfid.PICC_GetTypeName(piccType));

  // Store NUID into nuidPICC array //QQ does not fail if this loop is excluded
  for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

  // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
}

Please can you post a minimal verifiable example of code.  Sorry but just adding two lines means nothing.

Welcome to Arduino SE.  Be sure to take the tour to see how things work here:  https://arduino.stackexchange.com/Tour

"minimal verifiable example of code". I wanted to use code that many would be familiar with, and just show the simple change I made that brings on the problem. I'll try to reduce it, but then we don't have a familiar starting point. just adding two lines means nothing.

This comment system is confusing. I just wanted to start a new line, but it kept posting each time, so my comment could be gibberish, and then it timed out on me.

Added my modified example code, and a minimal version of it. It seems the loop that stores the NUID causes the problem (new problem), and including the null if statement fixes it (original problem)

I've included this code into another sketch, also using SPI to talk to an NRF24L01, and again a (different) problem appears when the code to store the NUID is present. "i=0; i<4;" means the loop with execute 4 times with i=0,1,2,3. Correct? But If I change the array declaration to "byte NUID[4]", the problem goes away. But that's 5 bytes, no?, so there should be no overrun with NUID[3]?

You've defined this array to have three elements:
byte nuidPICC[3];

those three elements are numbered 0, 1, and 2.
In this for loop:
for (byte i = 0; i < 4; i++) {
    nuidPICC[i] = rfid.uid.uidByte[i];
  }

you are writing to position 3, which is out of bounds for that array.
Once you write out of bounds on an array the behavior is undefined.  Resetting is one common result.  But anything could happen.

I'm assuming that the extra byte in the array is needed, possibly for a null terminator or whatever, and that the example code has a bug. I've had no further problems since changing the NUID[3] to NUID[4], so I'll leave this at that.


text:
Do serial ports on Arduino UNO / Leonardo initialize differently?
What are the differences in serial communication between PC <---> Arduino UNO (ATMEGA328p) and PC <---> Arduino Leonardo (ATMEGA32u4)?
I am asking because of a problem related to using these two Arduino boards for data logging in the following way:

PC sends a specific char string to Arduino, via serial port, to initialize datalogging
Arduino measures data, let's say a fixed number of ADC readings
Arduino stops measuring, sends data back to the PC over serial port
Arduino waits until new serial data are received before logging new data

If I send/receive data via the Arduino IDE serial monitor, this procedure works on both boards.  However, I want a separate GUI program (Qt) to handle the serial communication, where one clicks a button to send the data in step 1, and plot the data from step 3 on a graph.
I wrote a simple Qt GUI where a button is clicked, and the measured data are printed to the GUI screen.  Observations while testing it:

Arduino UNO as datalogger: Arduino is plugged into USB socket of PC, then I launch the GUI, then click button to start data acquisition.  The data are shown.  Program appears to work fine.
Arduino Leonardo as datalogger: Arduino is plugged into USB socket of PC, then I launch the GUI, then click button to start data acquisition.  The data are not received, program hangs.

Then

Arduino Leonardo as datalogger: Arduino is plugged into USB socket of PC, Open Arduino IDE serial monitor, send command to acquire data.  Then close Arduino IDE serial monitor, launch the GUI, click button to start data acquisition.  The GUI program now works.

Long story, but basically there appears to be a difference when using the two Arduino boards with external programs to do serial communication.  Can someone outline the differences and why Leonardo needs the "jump start" I described above using Arduino serial monitor?  Ultimately I want to fix the problem and avoid that hack.
Reluctant to post Qt code on Arduino stack exchange, but here is how I start the serial port:

ui->setupUi(this);
microcontroller_is_available = false;
microcontroller_port_name = "false";
microcontroller = new QSerialPort(this);
qDebug() << "Number of available ports: " << QSerialPortInfo::availablePorts().length();
foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
    qDebug() << "Has product ID " << serialPortInfo.hasProductIdentifier();
    if(serialPortInfo.hasProductIdentifier()){qDebug() << "Product ID: " << serialPortInfo.productIdentifier();}
    qDebug() << "Has vendor ID " << serialPortInfo.hasVendorIdentifier();
    if(serialPortInfo.hasVendorIdentifier()){qDebug() << "Vendor ID: " << serialPortInfo.vendorIdentifier();}
}

foreach (const QSerialPortInfo &serialPortInfo, QSerialPortInfo::availablePorts()) {
   if(serialPortInfo.hasVendorIdentifier() && serialPortInfo.hasProductIdentifier()){
       if(serialPortInfo.vendorIdentifier() == micro_vendor_id){
           if(serialPortInfo.productIdentifier() == micro_product_id){
              microcontroller_port_name = serialPortInfo.portName();
              microcontroller_is_available = true;
           }
       }
   }
}

if(microcontroller_is_available){  // open and configure serialport
    microcontroller->setPortName(microcontroller_port_name);
    microcontroller->open(QSerialPort::ReadWrite);
    microcontroller->setBaudRate(QSerialPort::Baud115200);
    microcontroller->setDataBits(QSerialPort::Data8);
    microcontroller->setParity(QSerialPort::NoParity);
    microcontroller->setStopBits(QSerialPort::OneStop);
    microcontroller->setFlowControl(QSerialPort::NoFlowControl);
}
else{QMessageBox::warning(this, "Port error", "Cannot connect DAQ.");}

Setup part of my Arduino code:
void setup(){
  DDRB  |= B11111111;  // (654210 outputs, miso input)
  PORTB &= ~_BV(RF_AMPL);
  DDRD  |= B1100010;
  PORTD |= (_BV(SRAM_HOLD) | _BV(SRAM_SS1));
  ADCSRA=0;
  SPCR = B01010000;           // SPI init (could get away with 11010000 on 328p but not 32u4)
  SPSR = B00000001;
  PORTD &= ~_BV(SRAM_SS1);     // Slave init
  SPDR=WRMR;  while(!(SPSR & (1<<SPIF)));
  SPDR=SEQUENTIAL_MODE; while(!(SPSR & (1<<SPIF)));
  PORTD |= _BV(SRAM_SS1);
  __builtin_avr_delay_cycles(160);
  PORTD &= ~_BV(SRAM_SS1);
  SPDR=RDMR; while(!(SPSR & (1<<SPIF)));
  SPDR=0x00; while(!(SPSR & (1<<SPIF)));
  PORTD |= (_BV(SRAM_HOLD) | _BV(SRAM_SS1));
  state1=0;
  count=0;
  pulse_count=0;
  serial_counter=0;
  Serial.begin(115200);  while(!Serial){}
}

https://www.arduino.cc/en/Guide/ArduinoLeonardoMicro#toc11

Is there a reason why you're not using the SPI library?

I need SPI that is faster than the Arduino SPI library gives.

what happens if you plug in leonardo -- then reset leonardo -- then start GUI  . . . . . . . . . . . . . . . or,  plug in -- start GUI -- reset ?

I solved this by resetting the Arduino (open serial port at 1200 baud, then close serial port) when launching the Qt program.
Here is the relevant part of the Qt program:
        microcontroller->setPortName(microcontroller_port_name);
        microcontroller->open(QSerialPort::ReadWrite);
        microcontroller->setBaudRate(QSerialPort::Baud1200);
        microcontroller->setDataBits(QSerialPort::Data8);
        microcontroller->setParity(QSerialPort::NoParity);
        microcontroller->setStopBits(QSerialPort::OneStop);
        microcontroller->setFlowControl(QSerialPort::HardwareControl);

        qDebug() << "open 1200 baud";
        Sleep(10);
        microcontroller->close();
        Sleep(10);

        microcontroller->open(QSerialPort::ReadWrite);
        microcontroller->setBaudRate(QSerialPort::Baud115200);
        microcontroller->setDataBits(QSerialPort::Data8);
        microcontroller->setParity(QSerialPort::NoParity);
        microcontroller->setStopBits(QSerialPort::OneStop);
        microcontroller->setFlowControl(QSerialPort::HardwareControl);

Now whenever I launch the Qt program, the Arduino is ready to accept serial data.

It's OK to accept your answer if it is the solution to the problem.

Yes, there are differences.

The Uno has an ATMega16U2 as a USB to UART bridge.  When you open the serial port the ATMega16U2 signals to the ATMega328p to reset and start your sketch from the beginning.
The Leonardo has an ATMega32U4 as the main MCU which is directly connected to the USB port.  When you open the serial port you connect to your program wherever it happens to be at the time.

The key thing there is that when you open the Uno's port the board reboots and your sketch restarts. When you open the Leonardo's port the board doesn't reset and your sketch is wherever your sketch happens to be.
So: you have to ensure that your sketch doesn't rely on things in setup() or early on in its execution for making the serial connection work.

I already followed the Arduino guide to use Serial.begin(115200);  while(!Serial){}.  Setup code posted above (minus pin definitions).  Can you see anything obviously wrong?  Same Arduino sketch is used for UNO and Leonardo.

Would it be possible on Leonardo device to print a file / data via serial to the PC using the USB port? So basically writing a file to the PC. I would love to know how if that is possible instead of only using the ATMega32U4 with the Keyboard library.

To answer my own question, I think I will give Lufa a try: https://github.com/Palatis/Arduino-Lufa


text:
How to choose alternate I2C pins on ESP32?
I'm a begginer with Arduino and this may be a basic question but I'm facing an issue.
I'm using a HTU21D sensor with an ESP32. This sensor use I2C communication. Inside the Arduino library, there is this function to start to collect data:

//Start I2C communication
void HTU21D::begin(TwoWire &wirePort)
{
  _i2cPort = &wirePort; //Grab which port the user wants us to use

  _i2cPort->begin();
}

As you can see, we can set in this function which port we want to use. Perfect. But my probleme is that I don't know how to use the type TwoWire. I checked some documentation but I was still unable to find a solution. I want to use GPIO_16 as SDA and GPIO_17 as SCL.
So I tried something like that without result: htu21d.begin(Wire(16, 17));
How to set SDA and SCL pin in TwoWire type ? (in my case GPIO_16 and GPIO_17)

did you try htu21d.begin(Wire);? Wire is an object, an instance of TwoWire class. it is defined in Wire.h at the end

But how do I tell Wire that I want to use pin 16 as SDA and pin 17 as SCL ?

found this void TwoWire::begin(int sdaPin, int sclPin, uint32_t frequency) here https://github.com/espressif/arduino-esp32/blob/master/libraries/Wire/src/Wire.cpp#L49-L63

you call Wire.begin

I was able to resolve my issue thanks to Juraj comment.
I did :
Wire.begin(16, 17);
htu21d.begin(Wire);

worked for me too, thanks, Wire.begin(SDA, SCK); for ssd1306 library for oled .

Some of the ESP32 pins do not support SPI. You can only use pins 11,12,13,18,23,24,25,26,29 and 30 as SDA or SCK.

Here is the example of how you can change esp8266 i2c pins. I used it for my ESP8266 and bme280, but the same for Arduino and other sensors.
#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

void setup() {
  Wire.pins(12,2); //new SDA SCL pins (D6 and D4 for esp8266)

  Serial.begin(115200);
  delay(100);

  bme.begin(0x76, &Wire); //here is the address for my bme280 and instance of TwoWire object
}

For my ESP8266 I tried to use GPIO0 for SDA and GPIO2 for SCL, but no luck. Probably because GPIO0 is a Flash pin. Changing SDA to GPIO12 (or D6 pin) helped me.


text:
Why the SoftwareSerial is not working properly on Arduino Pro Mini 3v3?
I uploaded regular pass through code for Serial and SoftwareSerial to communicate with my AT command based module.
Writing to SoftwareSerial seems to be working but reading not.
As I write "AT", the module returns me "-5" which should be "OK".
As I write "asdad" the module returns something similar ot "invalid syntax" but very messy.

#include <SoftwareSerial.h>
SoftwareSerial ss(rx, tx);

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

void loop() {
  while (Serial.available()) ss.write(Serial.read());
  while (ss.available()) Serial.write(ss.read());
}

the sketch is OK. something else is wrong. do you have 9600 baud set in Serial Monitor? and both line ends? is the wiring good?

What pins are you using for tx and rx?

@A. L. K., I think we are all making assumptions here.  Please clear some things up by answering if it is the Arduino which is sending the "AT" or if it is the Arduino which is receiving the "AT" and sending back incorrect characters.

With SoftwareSerial 9600 baud is about the maximum rate you can reliably run at when using a 5V 16MHz Arduino. You are using an 8MHz one at 3.3V, so you can expect that speed cap to be halved.
Don't use SoftwareSerial. Ever. Full stop. There is no call to ever use it. If you don't have enough real UART ports on your board then you are using the wrong board. Don't just use a board because it's the one that everyone uses. Look at what you want to do and then pick a suitable board that fits your needs. There are many many 3.3V boards available with multiple (or even one single spare) UARTs - for example the Fubarino Mini, the Teensy 3.x, Any number of ESP32 based boards - all with a similar footprint to the Pro Mini, and with a huge amount more power to boot.

Thank you. Can you recommend me some board like pro mini 3v3 but with more hw serial ports including sleep with external interrupt wake up and timed wake up.

Teensy boards are probably the best supported.

You may get better results if you do not nest the read and write function calls as you did.  That is, read everything then write everything.
The reason for this is that softwareserial.read() returns 1 character.  If you immediately turn around and pass that character to softwareserial.write() you will devote the resources of the processor to sending that character.  In the meantime if another character is sent to the processor the processor will not see it or will only see part of it.
That said, you will likely get better results if you use a better embedded processor with dedicated serial port hardware for each port your project requires. Such as the Mega 2560 processor on the Arduino Mega.
Moving away from a cheap processor to one with enough hardware is a valid solution. Because, with another hardware serial port, the processor is only needed to read & write a character to & from the hardware using one command for each of these operations, not waste time reading & waiting each bit of a charater.  A hardware serial port or UART can cut the effort of receiving & sending a character by the processor by more than an order of magnitude.

with AT firmware you send a command and then you get a response. so while is ok. the rest of the Answer is not related to the Question

@Juraj, I have improved my answer by explainning why a serial port implemented in software finds it difficult to run fast.  I also explained why a HW UART is better for faster communications.


text:
Trying to communicate with an ESP8266
G'day guys, I'm trying to get an ESP8266 to work with an Arduino Uno.Here is the wiring.
When I go to the serial monitor (115200 baud) and type: AT, there is not response from the ESP8266.Is there something that I am missing?I also have a servo motor connected, it works fine.

include "Arduino.h"
include "ESP8266.h"
include "dweet.h"
include "Servo.h"

define ESP8266_PIN_RX 10
define ESP8266_PIN_TX 11
define SERVO9G_PIN_SIG 2

const int servo9gRestPosition   = 20;
const int servo9gTargetPosition = 150;
const char *SSID     = "Wireless Network";
const char *PASSWORD = "wireless_password";

ESP8266 wifi(ESP8266_PIN_RX,ESP8266_PIN_TX);
Servo servo9g;

const int timeout = 10000;
char menuOption = 0;
long time0;

void setup()
{
   Serial.begin(9600);
   while (!Serial); //await connection.
   Serial.println("start");

   wifi.init(SSID, PASSWORD);
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gRestPosition);
   delay(100);
   servo9g.detach();

}

void loop()
{
   servo9g.attach(SERVO9G_PIN_SIG);
   servo9g.write(servo9gTargetPosition);
   delay(500);
   servo9g.write(servo9gRestPosition);
   delay(500);
   servo9g.detach();
}

I'm using the ESP8266 Library.When trying to connect it just says Initializing device...

"115200baud" and Serial.begin(9600);. Something doesn't match. Also powering a motor from an Arduino is never a good idea.

G'day mate, I have managed to flash the firmware with what I hope is the latest, I did the AT command and it said Ok, however when I did the command that allows you to see wireless networks, it says error. Also how do you reckon I hook the motor up? I read that the motor is 5v so i would have thought that it would be ok?

@user1234433222 thats another question

Unless you have some project constraints which make it mandatory to use naked ESP8266, why not use a NodeMCU to communicate with the Arduino in a master/slave relation over I2C?

#include <Wire.h>
#define I2CAddressESPWifi 8

in setup()
Wire.begin(D1,D2); // SCL D1 SDA D2

then call from anywhere inside your loop() call this function
char readSlave(int x) { // send current time
  String xY = String(x);
  char c;
  int charArrayLength = xY.length()+1;
  char bufferChar[charArrayLength];
  Wire.beginTransmission(8);
  xY.toCharArray(bufferChar, charArrayLength);
  Wire.write(bufferChar);
  Wire.endTransmission();
  delay(10);
  Serial.print("wire sent: [");
  Serial.print(x);
  delay(50);//Wait for Slave to calculate response.
  int counter = 0;
  char buffMe[32];
  int bytesIn = Wire.requestFrom(8,32);
  while (Wire.available()) {
    delay(2);
    buffMe[counter] = Wire.read();
    /*
    c = Wire.read();
    Serial.print(c);
    */
    counter++;
  }
  delay(10);
  Wire.endTransmission();
  delay(500);
  Serial.print("] bytesIn: [");
  Serial.print(bytesIn);
  Serial.print("] buffMe: [");
  Serial.print(buffMe);
  Serial.print("]");
  return buffMe;
}

and your arduino will be waiting (setup)
Serial.begin(9600);
// slave listens for call from master NodeMCU
Wire.begin(I2CAddressESPWifi);  // predefined as `8` or whatever address you choose
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);

and at the end of your code
void receiveEvent(int howMany) {
  if (howMany) {
    Serial.print("bytes[");
    Serial.print(howMany);
    Serial.print("] Received[");
    char charIn[howMany];
    int counter = 0;
    while (Wire.available()) {
      char c = Wire.read();
      charIn[counter] = c;
      //Serial.print(c);
      counter++;
    }
    delay(10);
    //do something with command from master
  }
}
void requestEvent() {
  char bufferChar[20] = "slave answer string";  // automatically null terminated extra character at end
  Serial.println(bufferChar);
  Wire.write(bufferChar);
}

thank you, I will purchase one and see how I go :)


text:
Weird behavior (Couldn't pull the pin LOW)
I was trying to implement my own code to control a stepper motor on arduino uno, however I noticed that the pins were always HIGH despite what was written to them. I started to erase the code to leave only the crucial part to troubleshoot it and was left with the following
#define IN1  8
#define IN2  9
#define IN3  10
#define IN4  11
long int *period;

void setup() {
pinMode(IN1, OUTPUT);
pinMode(IN2, OUTPUT);
pinMode(IN3, OUTPUT);
pinMode(IN4, OUTPUT);
*period=256;
}

void loop() {
 digitalWrite(IN1, LOW);
 digitalWrite(IN2, LOW);
 digitalWrite(IN3, LOW);
 digitalWrite(IN4, HIGH);
}

The period statements were leftovers from the previous code, and didn't think of them too much but once I deleted them the code started working. More over, the code worked if the period value was below 256. Once it reached 256 the pins weren't pulling low.
The problem is solved now, however I am interested why would a value of a variable cause such a behavior?

You have created a pointer, but didn't tell the compiler where that pointer is pointing to. Then you write a value to where the pointer is pointing to.

until 255 overwrites 1 byte in random location in memory. 256 overwrites two bytes

@Juraj always 4 bytes are written (or the number of bytes that contains a long int), even if values < 256 are written (than the other MSB bytes) will be filled with 0.

@MichelKeijzers, perhaps the byte affected by 256 should be zero. with 255 it stays zero. with 256 it is 1. it simply happens that the sketch works if he uses 255 and doesn't work with 256. I explained the difference

You are creating a pointer variable, not a normal variable.
That pointer variable is, until told otherwise, pointing at address 0x00.  It covers 4 bytes.
Addresses 0x00 to 0x1F are the internal CPU registers R0 to R31.  Your pointer variable points to R0 plus three more addresses above it (a long is 4 bytes in total).
So when you write to your pointer you are directly writing to CPU registers R0, R1, R2 and R3.
According to the AVR-GCC ABI:

R0 is the scratch register
R1 is the zero register
R2 & R3 are general purpose (call-saved) registers.

So if you write 255 to your pointer variable you are doing:
R0 = 255
R1 = 0
R2 = 0
R3 = 0

And that's no big deal: some things may go a little awry, but nothing major.
However, writing 256 results in:
R0 = 0
R1 = 1
R2 = 0
R3 = 0

The big thing here is that the zero register R1 is now 1, not zero.  The ABI states:

R1 always contains zero. During an insn the content might be destroyed, e.g. by a MUL instruction that uses R0/R1 as implicit output register. If an insn destroys R1, the insn must restore R1 to zero afterwards. This register must be saved in ISR prologues and must then be set to zero because R1 might contain values other than zero. The ISR epilogue restores the value. In inline assembler you can use __zero_reg__ for the zero register.

So R1 must be zero except for a brief moment when you use it for something else.  Since you're setting it to 1 and leaving it as one, any other operations that then rely on that register being zero will have a hard time knowing just what they are doing.
Having a "zero" register is a common thing. There are many times (especially in a RISC architecture) when you want the number zero - and having a register that is guaranteed to always be zero saves a lot of time. For instance, in MIPS the register $0 is hard-wired to be zero and can never change.  AVR doesn't have that luxury, but the GCC compiler imposes the rule for R1 which you have to abide by - since there are huge amounts of library code and other auto-generated code that rely on that register being zero.
So when it's set to one, all gloves are off, and no one can ever really know just what is happening - you'd have to disassemble the code (or get an intermediate listing out of the compiler) to see just what is using R1, and work out what the effect of that being 1 instead of 0 would be.
As an example, digitalWrite has this:
        if (val == LOW) {
 370:   11 11     cpse r17, r1
 372:   05 c0     rjmp .+10          ; 0x37e <digitalWrite+0x50>

That's "COMPARE SKIP IF EQUAL".  It's looking at the value you pass (val) to see if it's equal to zero - by using R1 as the zero value. But if R1 isn't zero then it will never know that what you passed as LOW is LOW - instead it would find HIGH as LOW, since HIGH is 1 and R1 is 1.  So you've basically swapped HIGH and LOW over as far as digitalWrite is concerned.
There are also places where the number 255 is wanted.  This is easy to generate with "eor r1,r1" - exclusive-or of the zero register. EOR turns bits off that are on and on that are off - so zero becomes 255. Except if zero is actually 1, you end up with 254 not 255, and more strange things happen.

You have an uninitialized pointer:
long int *period;

It will point to zero (or a register map, see comment Edgar Bonnet below), but you write 256 to it.
Since a long pointer points to 4 bytes, if you write values upto 255 only one byte will be filled (and others are 0), when you write a value from 256, another byte will be filled with a non-zero value.
Anyway, uninitialized pointers can result in strange effects, so initialize it like:
long int period;

long int* periodPointer = .

And set the content by
*periodPointer = 256;

Re “an undetermined address”: this is not the case here. Being a global, it is guaranteed to be initialized to zero by the C runtime. On an Uno, address zero is mapped to the register file, which can indeed produce weird results.

@EdgarBonet Thanks (didn't know about the register file, I should have known about the global). Just I'm always used to initialize every variable myself.

Thanks for the info and advice! But I just don't understand how whatever the variable contains or how the pointer is initialized would affect the pin state. Is the pin register somehow affected by the code?

That can be hard to find out ... however, what is most important, you hare changing 4 bytes 'somewhere' in the Arduino. This can (in theory) mean some execution code is changed, that the pin registers are changed, that some variables used either by the program or by the library are changed. To really find it out, you should check the value of the pointer, and (manually?) create a memory map of the Arduino (if at all possible).

Addresses 0x00 to 0x1F are the internal CPU registers R0 to R31. By writing to 0x00-0x03 you are affecting R0, R1, R2 and R3. R1, according to the AVR-GCC ABI should always be 0. It can be used temporarily, but you must reset it to zero afterwards. Since 256 will set R1 to 1, R1 is no longer zero - so all future operations that assume it is zero will be incorrect. And chaos ensues.