text:
Comments change compiled behavior (sysTickHook weak reference override)
I have a very simple routine that lights up the built-in LED (pin 13) when a system tick timer fires off its interrupt.
I override the weak reference to int sysTickHook(void) found in hooks.c. I found that in generalfor this to work I need to use extern "C" linkage
The part that is bewildering is that this interrupt fires off fine without extern "C" if there are the comments above it as shown below. This is the minimal reproducible example I can find.  Can someone explain this?
I'm using the plain old Arduino IDE 1.8.16.
void setup() {
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
}

void loop() {}

// {          -- if you remove this line sysTickHook will not be called
// extern "C" -- if you remove this line sysTickHook will not be called
int sysTickHook()
{
  digitalWrite(13,HIGH);
  return 0;
}

It's probably the function prototypes the IDE puts in that're breaking it.

How would those be affected by the presence of a comment?

I would look into it further, but if I were going to put the effort into that I'd want to know what board support package you were using and what board was selected.

@timemage I havn't installed anything third party nor modified any of the installed libraries. I added via the board manager "Arduino SAM boards 1.6.12". To compile and upload I am just using the "Arduino Due (Programming Port)" drop down. The verbose compiation says Using board 'arduino_due_x_dbg' from platform What other info can I provide?

The problem is the preprocessor in the IDE. It's not clever enough to work out the extern "C" when adding function prototypes.
With your comments you end up with:
#include <Arduino.h>
#line 1 "/home/matt/t/t.ino"
#line 1 "/home/matt/t/t.ino"
void setup();
#line 6 "/home/matt/t/t.ino"
void loop();
#line 10 "/home/matt/t/t.ino"
 extern "C" int sysTickHook(); // << The extern gets added here from the comment
#line 1 "/home/matt/t/t.ino"
void setup() {
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
}

void loop() {}

// {          -- if you remove this line sysTickHook will not be called
// extern "C" -- if you remove this line sysTickHook will not be called
int sysTickHook()
{
  digitalWrite(13,HIGH);
  return 0;
}

It finds the extern in the comment and thinks it's real code. If you remove the comment markers it ends up with broken code, as you have a stray { in there. If you remove the comments entirely you end up with the function in the C++ linkage, which changes the function name internally and doesn't then override the weak function. The same happens if you remove just the first comment.
Basically having those comments breaks the preprocessor in such a way that it works.  The proper way of doing it is:
void setup() {
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW);
}

void loop() {}

extern "C" {
  int sysTickHook()
  {
    digitalWrite(13,HIGH);
    return 0;
  }
}

Treating comments as code is a pretty huge bug! Can the Arduino IDE preprocessor really
be broken in this way?

@AdamV.Steele Sure it can. It's less broken than it used to be - it used to even put the prototypes in completely the wrong place and broke any attempt at using structs as parameters.

@AdamV.Steele, lol, welcome to Arduino.


text:
Serial.write - sedd ascii characters with hex value in the same line
Working on making a controller for a haunted house prop. Trying to get it to interface with a device.
Was able to use a serial analyzer to see what commands and values are being sent.
the hex codes being sent over serial for manual control is " 40 4d 01" which translates to "@M[?]"
the third byte 01 is the configuration state you want to have it change to. I'm using a byte to store the value between 0-255.
I'm stumped at how to send 2 ASCII characters but in the same Serial.write() command send a raw value, or at how to send them all as hex. I'm sure this is straight forward and I'm just unaware of some simple function.

hex is just a human representation of binary ... it is easier to write 4d instead of 01001101 ... it is just a number ... decimal 77

If you see "@M[?]", which means your are reading it as ASCII. 40 hex in ASCII is '@'. You probably send the data correctly if you are using Serail.write() but when you read the data with uint8_t incomingByte = Serial.read(), the return would be in byte(i.e. uint8_t) instead of char, to see the correct HEX, use Serial.print(incomingByte, HEX);.

First of all, I will challenge your assumption that you have to send the
three bytes in the same call to Serial.write(). There is no real
advantage in doing so. Serial output is handled through a memory buffer
that is consumed by the serial port within an interrupt service routine.
Serial.write() only writes to that memory buffer. Thus, you can
simply:
Serial.write("@M");
Serial.write(1);

and the receiver will not see the difference. There will be no gap
between the 'M' and the 1. There is no notion of “messages” or
“frames” on a serial link, unless an upper layer protocol adds its own
framing, which is not the case here.
Next, if you really want to issue a single call (futile as this is), you
could
Serial.write("@M\1");

This, however, will not work if the last byte is zero. The method shown
by the busybee is more general ans is able to send a zero-valued byte.

You can use a byte array for this:
    // at the appropriate place in your code:
    byte message[] = { '@', 'M', 0x01 };
    Serial.write(message, sizeof message);

If you need, you can prepare the array and just assign the value:
byte message[] = { '@', 'M', 0 };

// ...

    byte value = 0x01; // or any other assignment

    // at the appropriate place in your code:
    message[2] = value;
    Serial.write(message, sizeof message);

source: Stack Exchange

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

sort: votes


text:
Clearing string buffer with memset after a serial read
In using the SerialTransfer.h / pySerialTransfer libraries to send commands between my laptop and an Arduino Mega, I am sending multiple sequential strings between the devices. However, I'm having trouble "clearing" the receiving buffer on the Arduino side - it never shrinks, despite a few different attempts to clear the string (memset; a for loop).
I'm sending a string to the Arduino of the format , where there are anywhere from 1 to 5 asterisks.  Then the Arduino is simply sending the exact same string back, without any processing (as of yet).  And in the python terminal, I'm printing it all out; this is what I get:
SENT (17 bytes): <rand_len_str=**>
RECD (17 bytes): <rand_len_str=**>

SENT (18 bytes): <rand_len_str=***>
RECD (18 bytes): <rand_len_str=***>

SENT (19 bytes): <rand_len_str=****>
RECD (19 bytes): <rand_len_str=****>

SENT (17 bytes): <rand_len_str=**>
RECD (19 bytes): <rand_len_str=**>*>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

As long as the string is growing, all is well - but see the error in the 4th pair, with the extra *> characters, etc.
The following is my Arduino code; I've tried to reset the receiving string using memset, but this seems not to be working.
#include "SerialTransfer.h"

SerialTransfer myTransfer;

const int CMD_LEN = 200;
char buff[CMD_LEN];
char received_str[CMD_LEN];

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

void loop()
{
  if(myTransfer.available())
  {
    //////////////////////////////////////////////
    // handle call from Python

    memset(received_str, '\0', CMD_LEN*sizeof(char));
    myTransfer.rxObj(received_str, CMD_LEN);

    sprintf(buff, "%s", received_str);
    //////////////////////////////////////////////

    //////////////////////////////////////////////
    // send response
    myTransfer.txObj(buff, strlen(buff));
    myTransfer.sendData(strlen(buff));
    //////////////////////////////////////////////
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}

I didn't see anything in SerialTransfer.h about clearing the rxObj; I can always just use the first terminating > character to parse the command - but I imagine there is a cleaner / better solution in clearing the buffer, or at least, I'd like to understand what's going on! Thanks in advance.

what mean '\0' in this line? memset(received_str, '\0', CMD_LEN*sizeof(char));

Instead of clearing your buffers, make use of the bytesRead property.  Have a look at how they print the received string in the example code from the library using a for loop.  I don't know that it is null terminated or anything.
Example from the library's github page:
#include "SerialTransfer.h"

SerialTransfer myTransfer;

void setup()
{
  Serial.begin(115200);
  Serial1.begin(115200);
  myTransfer.begin(Serial1);
}

void loop()
{
  if(myTransfer.available())
  {
    Serial.println("New Data");
    for(byte i = 0; i < myTransfer.bytesRead; i++)
      Serial.write(myTransfer.rxBuff[i]);
    Serial.println();
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }

Thanks for the pointer - that did the trick.  Applying it to my original code, if I update the few lines around handle call from Python to the following, it works as intended.
    //////////////////////////////////////////////
    // handle call from Python

    myTransfer.rxObj(received_str, CMD_LEN);
    strncpy(buff, received_str, myTransfer.bytesRead);
    buff[myTransfer.bytesRead] = '\0';

    //////////////////////////////////////////////

Thanks again!

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


text:
control 12v motor with NPN transistor via arduino

i want to control this 12v motor via arduino:

Power source is 12v 5A
motor will work 5 seconds in every 5 minutes and will be activated throught arduino mega
i will try to use bd679a darlington transistor:

Collector - Base Voltage (Vcbo)  80 V
Collector - Emitter Voltage (Vceo)   80 V
Collector Current (Ic)   4 A
Power Dissipation (Pd) [Tcase≤25°C]  40 W
Transition Frequency (fТ)    10 MHz
Min. DC current gain (β) 750
Integrated diode Yes
Case    TO-126
Package type    -14h

Do i need to add diode(and will that drop voltage ) ?
also do i need any ressistors and why?

what research have you done? ... there are many tutorials about DC motor control on the web

someone tell they use 12k on DC- and arduino   but no one tell why and how much W resistor should be

also they use 330k resistor from arduino pin to transistor and when i go to buy it ask me to chose 1/4W 1/2W 1W ...  which one should i chose

any of those would work

transistor has Integrated diode , do i need do add any other diode to this diagram

here is one of the tutorials ... https://docs.arduino.cc/learn/electronics/transistor-motor-control

Looks like a relative simple answer is needed but I do not do well with word problems and pictures. Please post a real schematic as you have wired it.

You are missing 2 things:

You should add a resistor between the Arduino digital IO pin and the base of the transistor. Bipolar transistors are current amplifiers. Normally for driving motors with a microcontroller you want the transistor to operate in saturation anyway, so there is no need to fine tune the resistor. It is there for protecting the output pin of the Arduino from over current. The calculation is easy: Resistance is voltage divided by current R = U / I. The voltage is 5V for an Arduino Mega (output voltage of the digital IO pins is equal to the operating voltage of the Mega, thus 5V). The current here is the max current, that the output pin can withstand (you find such information in the datasheet of the microcontroller). It is 20mA for continuous load.
So R = 5V / 20mA = 250 Ohm. Thus you need a resistor with at least 250 Ohm. 330 Ohm is normally readily available, so often people use one of these.
You also asked about how many wants it should withstand. This is also easy to calculate: Power (in Watts) is voltage multiplied by current. So P = U * I = 5V * 20mA = 0.1W. So in this configuration the resistor will not ever need to withstand more than 0.1W. So 1/4W is enough.

When driving motors you should include a flyback diode. This is a diode in reverse direction connected across the terminals of the motor. A motor is an inductive load (since it basically consists of some coils and magnets). Driving it with a varying voltage (like you need for controlling the motors speed or just to start and stop the motor) will induce reverse voltage spikes. These might damage your transistor and/or the Arduino. With the flyback diode connnected these voltage spikes can safely dissipate through that diode and not causing any harm.

So the circuit looks like this:

simulate this circuit – Schematic created using CircuitLab

This is an emitter follower circuit, you will only get the base voltage ~ -0.70 volts depending on the gain, it will not switch. You need to either go to a low side switch or a PNP transistor and the emitter would go to +12. A P-Channel MOSFET would also work. Check your calculations on the 1N4148, under stall condition I believe it will fail.

im using bd679a darlington transistor , can it damage  the arduino   if i dont add 330ohm resistor . is that a MUST or optional?

@wuqnyqow: The base resistor is not optional.


text:
can i convert a pin into ground
i recently started using Arduino uno , but to my despair , the ground pin , without which i cant do any project (or can i ) , so i thought of a possible solution , what if i could program the board to make a pin act as a ground , so what to do
straight 2 questions , what to do to convert any pin into ground
or can i ignore using the provided ground pin .
i have already tried fixing the pin but it cant be fixed because a detached pin has got stuck into it

There is more than one ground pin on the arduino.  Just use another one.  You can make a pin into ground, that’s what happens when you write a pin LOW, but only for a very limited amount of current.  So it depends on what you want to do there.  But really, just use one of the other ground pins.

thanks for help , but can u help me furhter , i am a total starter , where is this second grnd , and actually i just connect my laptop for v+

there are 5 ground pins on Uno. two between Vin and 5 V. one next to pin 13 and two on the ICSP headers. so what happen to the ground pin?

Look at the board.  The pins are labeled.  You should be able to find them.

yeah ur comment was useful , i found all of then , but still as an alternative , if i ever mess up with my board , can i convert any pin into ground

You can sink a very limited amount of current to a GPIO pin by setting it to a digital output and setting the value to LOW. However, you should only sink about 20 mA into it (40 mA absolute max). That's a very small amount of current for powering devices. It would be easy to exceed that limit and burn out the pin. Also, when you first power up the Arduino the pin will probably be open, and if you ever set it to HIGH it will be a 5V source instead of a ground.

In short, don't try to use a GPIO pin as a power ground. The board has a number of ground connections. You can attach a wire to one of those and then connect multiple wires to that single wire. There is no harm in doing that.

Can I convert any pin into ground

Any of the digital outputs can be set LOW but there is a limit on how much current they can sink,
This makes this approach unsuitable for most use cases other than charlieplexing LEDs and similar low-current applications.
It would be better to

use any of the other ground connections.

two between Vin and 5V
one between Aref and 13
one on the 2x3-pin ICSP header for the 328
one on the unlabelled 2x3-pin ICSP header for the 16U2
one in the power jack

replace the damaged header using solder-wick and a soldering-iron.
solder a wire from a suitable ground pad on the PCB

e.g. from the ground pad for the 2.1mm power connector.

The ATmega328P data sheet says

Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady
state conditions (non-transient), the following must be observed:
ATmega328P:
1] The sum of all IOL, for ports C0 - C5, should not exceed 100mA.
2] The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
3] The sum of all IOL, for ports D0 - D4, should not exceed 100mA.
If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition

So no more than 20mA from or into any single pin over a long time. And no more than a total of 100 mA from or into a group of pins.


text:
Relay with NodeMCU is not working
I'm using a Relay Channel and NodeMCU(8266-WIFI). When i trigger the connection, LED Turns ON in Node MCU But the Relay connection is not working. I'm not sure what is the issue, Please help to fix it..
My Pin connection as follows.

NodeMCU (VIN) -> Relay (VCC)
NodeMCU (G) -> Relay (G)
NodeMCU (D1) -> Relay (IN4)

My code as follows,
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <FirebaseCloudMessaging.h>
#include <Firebase.h>
#include <FirebaseHttpClient.h>
#include <FirebaseArduino.h>
#include <FirebaseError.h>
#include <FirebaseObject.h>

// Set these to run example.
#define FIREBASE_HOST "xxx-xxxx.firebaseio.com"
#define FIREBASE_AUTH "xxxxxx"
#define WIFI_SSID "xxxx"
#define WIFI_PASSWORD "xxxxx"

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

  // connect to wifi.
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  Serial.print("connecting");
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("connected: ");
  Serial.println(WiFi.localIP());

  pinMode(D1, OUTPUT);
  pinMode(LED_BUILTIN, OUTPUT);

  Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);
  Firebase.set("LED_STATUS",0);
}

int n = 0;

void loop() {
  // Get value
  n=Firebase.getInt("LED_STATUS");

  if (n==1) {
     digitalWrite(D1, LOW);
     digitalWrite(LED_BUILTIN, LOW);
     Serial.print("LED is ON ");
     Serial.println(Firebase.getInt("LED_STATUS"));
     delay(1000);
  }
 else{
   //LED_BUILTIN
   digitalWrite(D1, HIGH);
   digitalWrite(LED_BUILTIN, HIGH);
   Serial.print("LED is OFF ");
   Serial.println(Firebase.getInt("LED_STATUS"));
   delay(1000);
 }

}

the red wire is not connected to anything

you mean the Main power Red wire right ?I removed the connection to take photo..

What version of the NodeMCU is that?

On back of board it mentioned, "Node MCU V3"
and in front top right corner , ver 0.1

Does the relay work when you connect IN4 to Vcc ?

No. That is the problem, When i trigger the power, the relay port is not closing and light bulb is not getting power

Can the relay module work with 3.3V logic signal?

If you attach and detach IN4 to VCC on the NodeMCU, does the relay click when you attach it? If it doesn't, and you still have VCC on the relay board connected to VIN(5V) on the NodeMCU, and GND on the relay board connected to GND on the NodeMCU, something is wrong with either your wiring or the board. Try another IN on the board and see if one is faulty. Those modules will work fine with 3v3 control signal coming from the NodeMCU due to the opto-isolator on the inputs of the relay board. If it does click, something is wrong with your code.

@chris could you explain a bit more please. I'm a very beginner. i bought a 5v relay board, but i'm not sure what output nodeMCU provides, I hope it is same 5v ?

@peter-feerick : Click ? U mean a click sound will come when i connect IN4 to vcc on NodeMCU ?

But VCC is connected to VIN right ?

@GaneshKumar Yes, a click sound from the relay, as it is a electro-mechanical switch, hence you should hear when it activates/deactivates. The yellow jumper to the side connects the VCC used to power the relays to the VCC used for the rest of the electronics on the module. The jumper is there because sometimes you don't have enough power, so you pull that jumper off, and use a second power source. If you put a GND or a VCC signal to one of the IN pins, that relay should either turn on or off.

I found that the 3V isn't enough to power the relay.
https://www.instructables.com/Getting-Started-With-ESP8266LiLon-NodeMCU-V3Flashi/ shows the board supplies USB power (pin VU).
You can remove the jumper that connects signal voltage to relay power and connect the relay board to the USB power.
After that change I could turn the relays on and off, but I could not reliably power 4 relays, 2 relays as shown below seems fine.


text:
Unable to read Arduino+ESP8266 full get Response
Using below code I am able to invoke HTTP Get request, but I am not able to read full HTTP Response. Observing only output like( +IPD,0,141:HTTP/1.7. ). Please let me know how can I read full response?
Any Idea what is the issue?
#include <SoftwareSerial.h>

#define RX 2
#define TX 3
String WIFI_SSID = "xyz";       // Your WiFi ssid
String PASSWORD = "xys";         // Password

String HOST = "192.168.0.156";
String PATH = "/test";
String PORT = "8080";

int countTrueCommand;
int countTimeCommand;
boolean found = false;

SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  esp8266.println("AT");
  Serial.println(esp8266.read());
  sendCommandToESP8266("AT", 5, "OK");
  sendCommandToESP8266("AT+CWMODE=1", 5, "OK");
  sendCommandToESP8266("AT+CWJAP=\"" + WIFI_SSID + "\",\"" + PASSWORD + "\"", 20, "OK");
}

void loop() {
  String postRequest = "GET " + PATH  + " HTTP/1.1\r\n" +
                       "Host: " + HOST + "\r\n" +
                       "Accept: *" + "/" + "*\r\n" +
                       "\r\n";

  sendCommandToESP8266("AT+CIPMUX=1", 5, "OK");
  sendCommandToESP8266("AT+CIPSTART=0,\"TCP\",\"" + HOST + "\"," + PORT, 15, "OK");
  String cipSend = "AT+CIPSEND=0," + String(postRequest.length());
  sendCommandToESP8266(cipSend, 4, ">");
  sendData(postRequest);
  readESP8266(8000);
  sendCommandToESP8266("AT+CIPCLOSE=0", 5, "OK");
}

void sendCommandToESP8266(String command, int maxTime, char readReplay[]) {
  Serial.print(countTrueCommand);
  Serial.print(". at command => ");
  Serial.print(command);
  Serial.print(" ");
  while (countTimeCommand < (maxTime * 1))
  {
    esp8266.println(command);
    if (esp8266.find(readReplay))
    {
      found = true;
      break;
    }

    countTimeCommand++;
  }

  if (found == true)
  {
    Serial.println("Success");
    countTrueCommand++;
    countTimeCommand = 0;
  }

  if (found == false)
  {
    Serial.println("Fail");
    countTrueCommand = 0;
    countTimeCommand = 0;
  }

  found = false;
}

void sendData(String postRequest) {
  Serial.println(postRequest);
  esp8266.println(postRequest);
  delay(1500);
  countTrueCommand++;
}

void readESP8266(const int timeout)
{
  String reponse = "";
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      reponse+=esp8266.readString();
    }
  }
  Serial.print(reponse);
}

Output:
Success
1. at command => AT+CWMODE=1 Success
2. at command => AT+CWJAP="xyz","xys" Success
3. at command => AT+CIPMUX=1 Success
4. at command => AT+CIPSTART=0,"TCP","192.168.0.156",8080 Success
5. at command => AT+CIPSEND=0,56 Success
GET /test HTTP/1.1
Host: 192.168.0.156
Accept: */*

busy s...

Recv 56 bytes

SEND OK

+IPD,0,141:HTTP/1.7. at command => AT+CIPCLOSE=0 Success

+IPD,0,141 means there are 141 bytes data return from the response, your code simply closed too early without read and parsing the data.

But I have already added delay of 8 sec, shall I add more delay?? readESP8266(8000); If you can provide any code that will be helpful

It is not about the delay (actually 8s is way too long), it is about continue to read the data, sorry I don't have time to write the code for you, but you can read one of my library on reading and parsing the response.

@hcheung Thanks for your help, I was able to perform HTTP GET request using LiteESP8266Client.h but 1 issue I am facing is after few call probably Arduino memory is becoming full, any idea how we can fix that

Finally the HTTP Get request with Arduino Uno + ESP8266 Wifi shield which is working is below:
// This is a demo example using a public http server for testing both GET and POST requests
#include <Arduino.h>
#include <LiteESP8266Client.h>

#define PACKET_MTU 1500    // Standard network MTU is 1500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
const char password[] PROGMEM = "abc";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /test HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";

void setupStationMode() {
  Serial.print("Setup station mode... ");
  if (radio.set_station_mode()) {
    Serial.println("success");
  } else {
    Serial.println("failed");
  }
}

void joinAP() {
  Serial.print("Join AP ");
  Serial.print(ssid);
  Serial.print("... ");
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println("Success");
  } else {
    Serial.println("Failed");
  }
}

void establishTcpConnect() {
  Serial.print("Establish TCP Connection... ");
  if (radio.connect_progmem(host, port)) {
    Serial.println( "Success");
  } else {
    Serial.println( "Failed");
  }
}

void getHttpPacket() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println("Packet Received...");
      Serial.println(data);
    } else {
      Serial.println(error_data_null);
    }
  }
  free(data);
}

void httpGet() {
  Serial.println("Sending GET request... ");
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setup() {
  delay(2000);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};

  setupStationMode();
  joinAP();
}

void loop() {
  establishTcpConnect();

  httpGet();
  getHttpPacket();
  }

Output:
Setup station mode... success
Join AP ⸮... Success
Establish TCP Connection... Success
Sending GET request...
Packet Received...
HTTP/1.1 200
Content-Type: text/plain;charset=UTF-8
Content-Length: 27
Date: Fri, 07 Aug 2020 13:04:03 GMT
Connection: close

Greetings from Spring Boot!

But one issue I am facing is after few call the HTTP invocation is getting stopped probably memory being full. Will check this.

If you run the example on the httpbin.org test site, do you face the same problem?

BTW, don't post your new problem as an "answer", since your code is deviated and totally different from your original question, you should post it as a new question.

The problem could be coming from your server at 192.168.0.156/test, so you should run your sketch on httpbin.org server to make the problem is not caused by this client sketch first.

Posted new Question: https://arduino.stackexchange.com/questions/77353/arduino-esp8266-wifi-shield-get-request-with-liteesp8266client-stops-after-few-h . Though output of 192.168.0.156/test is quite small

@hcheung tried with other REST server as suggested and same issue is observed:

I have updated response here: https://arduino.stackexchange.com/questions/77353/arduino-esp8266-wifi-shield-get-request-with-liteesp8266client-stops-after-few-h


text:
Neo 6M + ESP32 unable to take a fix on battery but works fine with laptop USB
I am using Neo 6M GPS module with ESP32 and 2 X 3.5V(7 v in series) 18650 lithium ion battery stepped down to 5V using LM2596 buck converter.
Problem which I am facing is when I power ESP32 using 5V output of LM2596 by connecting Vin pin and powering Neo6M using 5V output of buck converter or 3.3 V of ESP32 then my Neo 6M is unable to fix on satellite, however when removing battery and LM2596 and powering ESP32 using laptop usb cable and Neo 6M using 3V pin of ESP32 then its able to take a fix in 1 minute.
Any idea what mistake I could be doing.
Note - When using battery ESP32 is working as normal and able to connect to wifi and submit Tiny GPS++ output everysecond.
Please let me know in case more information required.

You have several problems. You are telling me it is power related as the ESP runs fine but the Neo 6M failed. Reason the Neo 6M does not tolerate as wide a voltage range as the ESP32. Using a Buck converter is a mistook, you should use a SEPIC (bicl/boost in one), this will maintain the voltage to your project as the battery voltage changes with its charge etc. With the correct SEPIC converter you can parallel the batteries giving you more instantaneous current. The buck converter needs head room, that is so much voltage above the output to work properly. I doubt it is less than 2v. Using small wires will esterbate your problems. The 10uF was a good idea but you also want to add something for high frequency. This should get you going.

With full battery charge to 3.7V this issue was resolved also using 10uf capacitor between vcc and ground help to improve


text:
how can i send get and post request from esp01 using arduino uno
I am using an esp8266 01 module with the Arduino Uno to establish a communication between the Arduino and my web site. I actually don't know how to send Rest HTTP requests from the Arduino to get data from my web site. I have done research but all I got is codes using nodemcu so I was wondering will the code of nodeMCU work fine on the Arduino using ESP01 and if not then how can I send get and post request from the Arduino using esp01
this the code that I found
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

const char* ssid = "SERVER NAME";
const char* password = "SERVER PASSWORD";

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

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(1000);
    Serial.println("Connecting...");
  }
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    HTTPClient http; //Object of class HTTPClient
    http.begin("http://jsonplaceholder.typicode.com/users/1");
    int httpCode = http.GET();

    if (httpCode > 0)
    {
      const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(3) + JSON_OBJECT_SIZE(5) + JSON_OBJECT_SIZE(8) + 370;
      DynamicJsonBuffer jsonBuffer(bufferSize);
      JsonObject& root = jsonBuffer.parseObject(http.getString());

      int id = root["id"];
      const char* name = root["name"];
      const char* username = root["username"];
      const char* email = root["email"];

      Serial.print("Name:");
      Serial.println(name);
      Serial.print("Username:");
      Serial.println(username);
      Serial.print("Email:");
      Serial.println(email);
    }
    http.end(); //Close connection
  }
  delay(60000);
}

use the WiFiEsp library

can you tell me what this library can offer to me

it works on Arduino over esp8266 AT commands with standard Arduino networking API used in the sketch you added to the question

can you tell me how can I use it

wire the esp-01 to the same way as sketches witch use the AT commands. install the WiFiEsp library in Library Manager and see the examples

thank you very much

i tried what you sid but when i run the code i code a lot of ??????? what does that means

it could be wrong baud rate. does the baud rate in sketch match the baud rate of the AT firmware? you should use 9600 baud

i changed it to 9600 but now i got [WiFiEsp] Initializing ESP module
[WiFiEsp] >>> TIMEOUT >>>
[WiFiEsp] Warning: Unsupported firmware

send AT+UART_DEF=9600,8,1,0,0 to AT firmware. it will change the default baud rate

what AT firmware version do you have? it reports unsupported for the latest AT firmware. you can ignore it then

Let us continue this discussion in chat.


text:
esp8266 code not working anymore
hi i have developed year age an Adruino application that allows me send and receive data from a mobile application using esp8266 esp01 back then it worked really well but now i tried to rerun the same code using a different esp8266 esp01 the app won't work so i was wondering if the firmware flash has to do something with it because flashed the first esp firmware and the second is not but a friend of mine worked with the second one fine so here is my code
float Temperatur;
  String Temperatur1;
#include <SoftwareSerial.h>

#define DEBUG true

       SoftwareSerial esp8266(8,9);
void setup()
{
  Serial.begin(9600);
        esp8266.begin(9600); // your esp's baud rate might be different

  pinMode(11,OUTPUT);
  digitalWrite(11,LOW);

  pinMode(12,OUTPUT);
  digitalWrite(12,LOW);

Serial.println("Server START");
  sendCommand("AT+RST\r\n",2000,DEBUG); // reset module
  sendCommand("AT+CWMODE=2\r\n",1000,DEBUG); // configure as access point
 //sendCommand("AT+CWJAP=\"AF23_WI-FI_476C\",\"A776RAEQ\"\r\n",3000,DEBUG);
  delay(10000);
  sendCommand("AT+CIFSR\r\n",1000,DEBUG); // get ip address
  sendCommand("AT+CIPMUX=1\r\n",1000,DEBUG); // configure for multiple connections
  sendCommand("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80

  Serial.println("Server Ready");
}

void loop()
{
  /*
  Temperatur=(5.0*analogRead(A0)*100.0)/1024;
   Serial.println(Temperatur);
  Temperatur1=(5.0*analogRead(A0)*100.0)/1024.0;
   Serial.println(Temperatur1);

  if(Temperatur > 50)

   {digitalWrite(11, HIGH);
    digitalWrite(12,LOW);}
    */
  if(esp8266.available()) // check if the esp is sending a message
  {

     Serial.println("esp avai");
    if(esp8266.find((char*)"+IPD,"))
    {Serial.println("found ipd");
     delay(1000); // wait for the serial buffer to fill up (read all the serial data)
     // get the connection id so that we can then disconnect
     int connectionId = esp8266.read()-48; // subtract 48 because the read() function returns
                                           // the ASCII decimal value and 0 (the first decimal number) starts at 48
//      sendHTTPResponse(connectionId,Temperatur);
     esp8266.find((char*)"pin="); // advance cursor to "pin="

     int pinNumber = (esp8266.read()-48); // get first number i.e. if the pin 13 then the 1st number is 1
     int secondNumber = (esp8266.read()-48);
     if(secondNumber>=0 && secondNumber<=9)
     {
      pinNumber*=10;
      pinNumber +=secondNumber; // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number
     }

  if((pinNumber==12)&&(pinNumber!=11))
     {digitalWrite(12, HIGH);
     digitalWrite(11,LOW);}
    if((pinNumber==11)&&(pinNumber!=12))
     {digitalWrite(12, LOW);
     digitalWrite(11,HIGH);}
    if((pinNumber==13)&&(pinNumber!=12)&&(pinNumber!=11))
     {digitalWrite(12, LOW);
     digitalWrite(11,LOW);}

     // build string that is send back to device that is requesting pin toggle
     String content;

     if(pinNumber==11)
     {
       content = "L'exutoire est en cours d'ouverture";
     }
     else if(pinNumber==12)
     {
       content = "L'exutoire est en cours de fermeture";
     }
     else if (pinNumber==13)
   {  content = " Il est arrêter ";}

       else if (pinNumber==10)
   {  content =  Temperatur1 ;}
     sendHTTPResponse(connectionId,content);
    }
  }else {
    Serial.println("not available");
  }
}

/*
* Name: sendData
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendData(String command, const int timeout, boolean debug)
{
    String response = "";

    int dataSize = command.length();
    char data[dataSize];
    command.toCharArray(data,dataSize);

    esp8266.write(data,dataSize); // send the read character to the esp8266
    if(debug)
    {
      Serial.println("\r\n====== HTTP Response From Arduino ======");
      Serial.write(data,dataSize);
      Serial.println("\r\n========================================");
    }

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

/*
* Name: sendHTTPResponse
* Description: Function that sends HTTP 200, HTML UTF-8 response
*/
void sendHTTPResponse(int connectionId, String content)
{

     // build HTTP response
     String httpResponse;
     String httpHeader;
     // HTTP Header
     httpHeader = "HTTP/1.1 200 OK\r\nContent-Type: text/html; charset=UTF-8\r\n";
     httpHeader += "Content-Length: ";
     httpHeader += content.length();
     httpHeader += "\r\n";
     httpHeader +="Connection: close\r\n\r\n";
     httpResponse = httpHeader + content + " "; // There is a bug in this code: the last character of "content" is not sent, I cheated by adding this extra space
     sendCIPData(connectionId,httpResponse);
}

/*
* Name: sendCIPDATA
* Description: sends a CIPSEND=<connectionId>,<data> command
*
*/
void sendCIPData(int connectionId, String data)
{
   String cipSend = "AT+CIPSEND=";
   cipSend += connectionId;
   cipSend += ",";
   cipSend +=data.length();
   cipSend +="\r\n";
   sendCommand(cipSend,1000,DEBUG);
   sendData(data,1000,DEBUG);
}

/*
* Name: sendCommand
* Description: Function used to send data to ESP8266.
* Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
* Returns: The response from the esp8266 (if there is a reponse)
*/
String sendCommand(String command, const int timeout, boolean debug)
{
    String response = "";

    esp8266.print(command); // send the read character to the esp8266

    long int time = millis();

    while( (time+timeout) > millis())
    {
      while(esp8266.available())
      {

        // The esp has data so display its output to the serial window
        char c = esp8266.read(); // read the next character.
        response+=c;
      }
    }

    if(debug)
    {
      Serial.print(response);
    }

    return response;
}

at first i got no response from the esp  then i tried to change esp8266.begin(9600); to 115200  i got this
    Server START
    AZ+RST

    OK‡

     ets Jan  8 2013,rst cause;2, boot modd:(3,7)

    loaf 0x40100000, len 2408, soom 16
    tail 8
    chksum 0xe5
    load 0x3ffe8000, len 776, room 0
    tail 8
    chksum 0a tail 8m8r   S5o
Œãœ
AT+CWMODQO¦CC¡C¡jªHüAT+CIFSR
+CHFSR:APIP,"182.168.4.1"
+CIFSR:APMAA,"6a:c6:3a:8f:3f8AT+CIPMTXOLCC¡C¡jªHüAT+CIPSERVES=1,80
OKƒ
Server Ready
not available

Newer ESP8266 boards have a newer version of the AT firmware on them by default. This runs at 115200 baud compared to the 9600 baud of the old ones.
However, you cannot run SoftwareSerial reliably at 115200 baud.
You need to reconfigure the ESP-01 to run at 9600 baud using the AT commands.
There are a number of different commands depending on the firmware version. One of these may work:
AT+IPR=9600
AT+UART_DEF=9600,8,1,0,0
AT+CIOBAUD=9600

thank you very much i tried to add one of them but nothing changes in fact i no longer get responses neither at 115200 baud.nor at 9600 baud and the blue led of the esp-01 is lightning

That is a common complaint. You may want to re-flash the firmware on there. There's plenty of tutorials around for how to do that.


text:
Should L, TX, RX led light on while connected with laptop
Dear Sir,
               I need to know that should led light named as L, TX, RX should be on when we connect it with laptop?
Because when I connect it with laptop led light turns on for 1 or 2 second then turns off. That's why I am asking you this question.
                 Hoping for a favourable answer.
Your's faithful,
Nir Patel.

that would really depend on the device ... right now we have no idea what device you are talking about

On Arduino Uno (and most basic Arduinos), the 'L' LED is operated by whatever code is on the Arduino. RX and TX flicker whenever the Arduino is sending data to the PC (TX) or is receiving data from the PC (RX).
If you have never re-programmed your Arduino, it is running whatever code was in it when it was shipped to you. It sounds like your Arduino has a bootloader but no code yet. The bootloader listens for the PC to try upload a new program. While it is listening, it blinks the L LED.
If the PC tries to upload, you will see the RX and TX lights flicker as the two communicate, until the upload is finished. Then whatever program was uploaded will run, and it will control the LEDs.
If the PC doesn't try to upload a new program within a few seconds (how long depends on which bootloader version is in the Arduino), the bootloader will start whatever program is already in the Arduino. Again, that program will then control the LEDs.


text:
Showing GPS Values on I2C LCD using Arduino and ESP8266
I am working with Arduino. I'm using 2 Arduino boards along with 2 ESP8266 modules to transfer data from one Arduino to another Arduino. I want to transfer GPS values from system 1 to system 2 using Wi-Fi module ESP8266 along with Arduino UNO. I've written the main codes for server and client end. I'm not able to print anything on LCD if I'm using ESP8266 and selected 'generic ESP8266' boards.

do the examples of the LCD library work on the Arduino with the LCD?

you describe three possible areas of failure ... fail to read data from GPS ... fail to transfer data between arduinos ... fail to display data on LCD ....... which of the three is the actual failure? .... if it is one area of failure, then why are you not asking a specific question about it?


text:
Read write with half duplex SPI
I'm currently struggling interfacing an SPI device using just 3 pins (CLK, DATA, NSS).
Wiring up? Connecting MOSI/MISO together?
How do i read since it's half duplex?
In ESP32 there are flags which can be set (SPI_TRANS_USE_RXDATA, SPI_TRANS_USE_TXDATA). How can i accomplish this in the Arduino environment? i didn't see a such option and the API seems a little bit limited.
Thanks for any advice.

All you need is a single resistor.

simulate this circuit – Schematic created using CircuitLab
When DATA is an input the data from MOSI passes through the resistor to both DATA and MISO.  When DATA is an output the data from DATA goes to MISO and voltage is dropped safely across R1 to the sink or source of MOSI depending on what state it is in.
In other words, when DATA is input it receives from MOSI. When DATA is output MOSI is ignored.
Code wise, it's no different to any other transfer. You just never have any valid data to transfer while receiving. So just transfer anything (0xFF is a common choice).
For example, if you need to send 0x38 first then receive two bytes, you would:
SPI.transfer(0x38);
uint8_t byte1 = SPI.transfer(0xFF);
uint8_t byte2 = SPI.transfer(0xFF);

Thanks, worked great! +1


text:
Arduino - manually ceate objects (e.g. WiFi library)
By default, if i include the WiFi library, the object WiFi will be registered globally. How can i disable this behavior without changing the library file itself? (removing the definition "extern ...")
Or is there a way to delete the objects right after the inclusion? I just want to create the object manually when needed to save memory.

it shouldn't be in build result, if it is not used

you can check the .map file for code excluded and code included in the final build

I am not sure, if it would save enought memory to be worth the problems (it is just few bytes, buffers are created anyway), but lets say so.
Then you need modify the library to not creating the object, as it is allocated statically and cannot be removed later (and reclaim its memory). To protect all other projects it would be probably best to use special #define to disable it only in memory critical projects - so the Wire.h should contain something like
#ifndef EXCLUDE_WIRE
extern TwoWire Wire;
#endif

and your program (critical.ino) should start with
#define EXCLUDE_WIRE
#include <Wire.h>

and then somewhere in loop / other function use
TwoWire Wire;

as local variable. If you need to call other functions with it, then you have to send its address as a parameter.
Anyway you will not save nearly any memory, as nearly all variables in TwoWire ((and namely buffers) are static and so class variables and so are common for all instacies of TwoWire and allocated automatically if there is (possibly used) any instance of TwoWire anywhere in your program.
So it would be better to create your own library to use the same functionality, but make sure, that all such variables are instance variables and properly created and released at the right time. This would also allowe for changing the buffer sizes, if needed.
As it is under LGPL 2.0+ you are legally allowed to do that (provided you fullfill all licence conditions).

Thanks.I already thought i've to go that way. Even if this makes much more work, i can also strip down everything i don't need. My sketch space is is also running on limit ;)

Note that if you don't use the global Wire variable, it will be stripped away by the linker and will not use any memory. There is strictly no point in modifying the library source to remove it.

@elebb: You may be able to save some memory by stripping unused functionality from the library methods that you do use, and by removing unused data members. You will not, however, save anything by removing unused methods or global variables: the linker already does that for you. Essentially, the Arduino IDE is already applying this optimization technique.

If I understood it correctly, that the intended use was to have NOT one global Wire object all the time, but create it in case you need to use it and destroy it afterwards to save RAM, while other part of program will in other time use that same RAM for something else and then free it. Just the same way, as the same byte in RAM is used as part of local integer variable in one function and in other time as say local char variable of totally unrelated function, in other time it could be part of return address of third function, while in mean time it is just part of free RAM for stack.


text:
How to generate musical notes using an uno without using tone() function? Can anyone share the embedded c language code for it?
I also want to know how can we make it without functions like digitalwrite

read this https://www.arduino.cc/en/Reference/PortManipulation

but then it is not Arduino, if you don't use Arduino functions and the question is off-topic

I don't see what is off-topic about it, if he has an Arduino and wants to make it do stuff. Surely he doesn't necessarily have to use the Tone library, or necessarily do digitalWrite? Ultimately every library will eventually use the hardware registers, and you wouldn't say that the libraries are off-topic, would you?

@NickGammon, OP wants an AVR C program with main() (embedded C language code) and it looks like an assignment from school. If I write the low level part of an Arduino library I use the underlying technology which is not Arduino and if it is AVR and I have a question about it, I go to avrfreaks forum

Perhaps you are right about the assignment, but there is nothing inherently bad about helping people to enlightenment. :)

Yes, that's easy enough to do. I wrote a library to do that, as described here.
Basically you could make a class like this:
class TonePlayer
  {
  // addresses of output ports - NULL if not applicable
  volatile byte * const timerRegA_;
  volatile byte * const timerRegB_;
  volatile byte * const timerOCRH_;
  volatile byte * const timerOCRL_;
  volatile byte * const timerTCNTH_;
  volatile byte * const timerTCNTL_;

  public:
    // constructor
    TonePlayer (
          // ports
          volatile byte & timerRegA,
          volatile byte & timerRegB,
          volatile byte & timerOCRH,
          volatile byte & timerOCRL,
          volatile byte & timerTCNTH,
          volatile byte & timerTCNTL)
       :
         timerRegA_  (&timerRegA),
         timerRegB_  (&timerRegB),
         timerOCRH_  (&timerOCRH),
         timerOCRL_  (&timerOCRL),
         timerTCNTH_ (&timerTCNTH),
         timerTCNTL_ (&timerTCNTH)
  { }

    void tone (const unsigned int Hz);
    void noTone ();

  };  // end of TonePlayer

Then implement the two functions like this:
void TonePlayer::tone (const unsigned int Hz)
{
  // it takes two toggles for one "cycle"
  unsigned long ocr = F_CPU / Hz / 2;
  byte prescaler = _BV (CS10);  // start with prescaler of 1  (bits are the same for all timers)

  // too large? prescale it
  if (ocr > 0xFFFF)
    {
    prescaler |= _BV (CS11);    // now prescaler of 64
    ocr /= 64;
    }

  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;

  // reset counter
  *timerTCNTH_ = 0;
  *timerTCNTL_ = 0;

  // what to count up to
  *timerOCRH_ = highByte (ocr);
  *timerOCRL_ = lowByte (ocr);

  *timerRegA_ = _BV (COM1A0);             // toggle output pin
  *timerRegB_ = _BV (WGM12) | prescaler;  // CTC
  }  // end of TonePlayer::tone

void TonePlayer::noTone ()
  {
  // stop timer
  *timerRegA_ = 0;
  *timerRegB_ = 0;
  } // end of TonePlayer::noTone

And now call it:
TonePlayer tone1 (TCCR1A, TCCR1B, OCR1AH, OCR1AL, TCNT1H, TCNT1L);  // pin D9 (Uno), D11 (Mega)

void setup()
  {
  pinMode (9, OUTPUT);  // output pin is fixed (OC1A)

  tone1.tone (220);  // 220 Hz
  delay (500);
  tone1.noTone ();

  tone1.tone (440);
  delay (500);
  tone1.noTone ();

  tone1.tone (880);
  delay (500);
  tone1.noTone ();
  }

void loop() { }

In this example you plug your speaker into D9 (digital pin 9) on your Uno, with the other pin going to ground. Since this plays tones using the hardware timers you can do other things in your loop without affecting the tones.

from Atmega328 datasheet TCNT1 = 0x1FF; " Note that when using “C”, the compiler handles the 16-bit access"

Ah yes, I might have been overly cautious there.

I made a 13 note piano-like (well, more organ-like) tones instrument here
https://forum.arduino.cc/index.php?topic=179761.0
Youtube clip of it in action
https://www.youtube.com/watch?v=4c8idXN4Pg0
Only 8 notes in the clip, that was all the buttons I had at the time.
I used a '1284P processor instead of '328P so it could have 13 inputs & 13 outputs, without jumping up to a 2560.
There is nothing wrong with using Direct Port Manipulation in the Arduino IDE environment. Arduino is just C++ with some things made easier for the user with functions, macros, etc.
Here's the code.
/* Crossroads, 26 July 2013
 test for creating multiple simultaneous notes using micros()
 press a key, get a note. Use external analog mixer (summing op amp) for sound mixdown to single output to a speaker
 need a higher pin count device - this code is for '1284P - with specific pin mappings, not written for uC portability
 play 13 notes for now, C4 up to C5
 note info from http://www.sengpielaudio.com/calculator-notenames.htm
 Input keys: pin2=C4, 3=C#4, 30=D4, 8=D#4, 9=E5, 31=F5, 4=F5#, 5=G5, 6=G5#, 7=A5, 10=A5#, 11=B5, 12=C5
 Output notes: pin 16=C4, 17=C#4, 18=D4, 19=D#4, 20=E5, 21=F5, 22=F5#, 23=G5, 24=G5#, 25=A5, 26=A5#, 27=B5, 28=C5
 Ordering is funny due to Bobuino mapping, and having PortA output bits follow portD input bits, portC output bits follow portB input bits
 0,1 reserved for serial
 13,14,15,29, unused, maybe make 1 of 9 octave select? Piano has 7 full C to B octaves, 2 partials
 */
// array of 1/2 period of the notes in microseconds
// so a C8 note would be 119uS High, 119uS low for example
unsigned long noteArray[] = {
  119, // C8, highest note - note 0
  127,134,142,150,159,169,179,190,201,213,225,239, // B7, A#7,A7, G#7, G7, F#7, F7, E7, D#7, D7, C#7, C7 - notes 1-12
  253,268,284,301,318,338,356,379,402,426,451,478, //  B6 down to C6 - notes 13-24
  506,536,568,602,638,676,716,758,804,851,902,965, // B5 down to C5 - notes 25-36
  1012,1073,1136,1204,1276,1351,1432,1517,1607,1703,1804,1911, // B4 down to C4 - notes 37-48
  2025,2145,2272,2408,2551,2703,2863,3034,3214,3405,3607,3822, // B3 down to C3 - notes 49-60
  4050,4290,4545,4816,5102,5405,5727,6067,6428,6810,7215,7645,  // B2 down to C2 - notes 61-72
  8099,8581,9091,9631,10204,10811,11454,12135,12856,13621,14431,15289,  //  B1 down to C1 - notes -73-84
  16198,17161,18182, // B0, A#0, A0 - 85-86-87
};  // really need to flip this whole thing over so that 0 is lowest note & 87 is  highest
byte keyArray[]={
  2,3,30,8,9,31,4,5,6,7,10,11,12,13,}; //Ports D2,D3,D4,D5,D6,D7,B0,B1,B2,B3,B4,B5,B6, added b7 - notes 48, 47,46,45,44,43,42,41,40,39,38,37,36
byte outputArray[] = {
  14,15,16,17,18,19,22,23,24,25,26,27,28, 21,22,29}; // Ports A0,A1,A2,A3,A4,A5,C0,C1,C2,C3,C4,C5,C6, added a6, a7, c7
// ports selected for consistency for bits used from input to output from D in to A out, and B in to C out
byte keyActive[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // 1 indicates key is pressed
//byte octaveSelect[] = {
// 13,21,22,29}; // b7,a6,a7,c7 -  0 to 9 - future use
// ATMEL ATMEGA1284P on Bobuino
//
//                       +---\/---+
//           (D 4) PB0 1 |        | 40 PA0 (D 21) AI 7
//           (D 5) PB1 2 |        | 39 PA1 (D 20) AI 6
//      INT2 (D 6) PB2 3 |        | 38 PA2 (D 19) AI 5
//       PWM (D 7) PB3 4 |        | 37 PA3 (D 18) AI 4
//   PWM/SS (D 10) PB4 5 |        | 36 PA4 (D 17) AI 3
//     MOSI (D 11) PB5 6 |        | 35 PA5 (D 16) AI 2
// PWM/MISO (D 12) PB6 7 |        | 34 PA6 (D 15) AI 1
//  PWM/SCK (D 13) PB7 8 |        | 33 PA7 (D 14) AI 0
//                 RST 9 |        | 32 AREF
//                VCC 10 |        | 31 GND
//                GND 11 |        | 30 AVCC
//              XTAL2 12 |        | 29 PC7 (D 29)
//              XTAL1 13 |        | 28 PC6 (D 28)
//      RX0 (D 0) PD0 14 |        | 27 PC5 (D 27) TDI
//      TX0 (D 1) PD1 15 |        | 26 PC4 (D 26) TDO
// INT0 RX1 (D 2) PD2 16 |        | 25 PC3 (D 25) TMS
// INT1 TX1 (D 3) PD3 17 |        | 24 PC2 (D 24) TCK
//     PWM (D 30) PD4 18 |        | 23 PC1 (D 23) SDA
//      PWM (D 8) PD5 19 |        | 22 PC0 (D 22) SCL
//      PWM (D 9) PD6 20 |        | 21 PD7 (D 31) PWM
//                       +--------+
//
byte x;
byte portDkeys;
byte portBkeys;
byte portAnotes;
byte portCnotes;
unsigned long currentTime;
unsigned long changeTime[]= {
  0,0,0,0,0,0,0,0,0,0,0,0,0,}; // track when to flip output
unsigned long duration;
/* consistency check
 INDEX, NOTE, port In, port Out
 0, C4,       D2, A2           read 04 write 04 FB 1111 1011 Middle C
 1, C#4,      D3, A3           read 08 write 08 F7 1111 0111
 2, D4,       D4, A4           read 10 write 10 EF 1110 1111
 3, D#4,      D5, A5           read 20 write 20 DF 1101 1111
 4, E4,       D6, A6           read 40 write 40 BF 1011 1111
 5, F4,       D7, A7           read 80 write 80 7F 0111 1111
 6, F#4,      B0, C0           read 01 write 01 FE 1111 1110
 7, G4,       B1, C1           read 02 write 02 FD 1111 1101
 8, G#4,      B2, C2           read 04 write 04 FB 1111 1011
 9, A4,       B3, C3           read 08 write 08 F7 1111 0111  Concert A
 10, A#4,     B4, C4           read 10 write 10 EF 1110 1111
 11, B4,      B5, C5           read 20 write 20 DF 1101 1111
 12, C5,      B6, C6           read 40 write 40 BF 1011 1111
 */
/*************/
void setup(){
  //Serial.begin (115200); // for debug testing
  for (x=0; x<14; x=x+1){ // input pins with pullup
    pinMode(keyArray[x], INPUT);
    digitalWrite (keyArray[x], HIGH);
  }
  for (x=0; x<17; x=x+1){
    pinMode(outputArray[x], OUTPUT); // output pins
  }
  //  for (x=0; x<4; x=x+1){ // future use maybe
  //    pinMode(octaveSelect[x], INPUT); // input pins with pullups
  //    digitalWrite (octaveSelect[x], HIGH);
  //  }
} // end setup

/***********/
void loop(){
  //Serial.print (" ");
  // if key is pressed, determine time for next transition
  // if key is not pressed, no transition, use AC coupling into summing op-amp for no output
  // idea is to allow multiple notes to be created simultaneoulsy. Can the reading & if's all be done fast enough?
  portDkeys = PIND; // Read the input keys - using direct port manipulation for speed
  portBkeys = PINB;
  currentTime = micros();

  // Didn't make this part of a larger loop/array lookup because that adds 12-15uS for each pass thru the loop

  /* Check if key for note C4 is pressed, key0  */

  if ((portDkeys & 0x04) == 0){ // key is pressed D2 -> A2
     if (keyActive[0]==0){
       keyActive[0] = 1;
       changeTime[0] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[0])>=noteArray[48]){ // time for a period toggle?
      changeTime[0] = changeTime[0] + noteArray[48];    // setup time for the next toggle
      PINA=0x04;  // write a 1 to PINx toggles an output bit - NickGammon to the rescue again!
    }
  }
  else{keyActive[0] = 0;}

  /* Check if key for note C#4 is pressed, key1  */

  if ((portDkeys & 0x08) == 0){ // key is pressed D3 -> A3
       if (keyActive[1]==0){
       keyActive[1] = 1;
       changeTime[1] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[1])>=noteArray[47]){
      changeTime[1] = changeTime[1] + noteArray[47];
      PINA = 0x08;
    }
  }
  else{keyActive[1] = 0;}

  /* Check if key for note D4 is pressed, key2  */

  if ((portDkeys & 0x10) == 0){ // key is pressed D4 -> A4
       if (keyActive[2]==0){
       keyActive[2] = 1;
       changeTime[2] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[2])>=noteArray[46]){
      changeTime[2] = changeTime[2] + noteArray[46];
      PINA = 0x10;
    }
  }
  else{keyActive[2] = 0;}

  /* Check if key for note D#4 is pressed, key3  */

  if ((portDkeys & 0x20) == 0){ // key is pressed D5 -> A5
       if (keyActive[3]==0){
       keyActive[3] = 1;
       changeTime[3] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[3])>=noteArray[45]){
      changeTime[3] = changeTime[3] + noteArray[45];
      PINA = 0x20;
    }
  }
  else{keyActive[3] = 0;}

  /* Check if key for note E4 is pressed, key4  */

  if ((portDkeys & 0x40) == 0){ // key is pressed D6 -> A6
       if (keyActive[4]==0){
       keyActive[4] = 1;
       changeTime[4] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[4])>=noteArray[44]){
      changeTime[4] = changeTime[4] + noteArray[44];
      PINA = 0x40;
    }
  }
  else{keyActive[4] = 0;}

  /* Check if key for note F4 is pressed, key5  */

  if ((portDkeys & 0x80) == 0){ // key is pressed D7 -> A7
       if (keyActive[5]==0){
       keyActive[5] = 1;
       changeTime[5] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[5])>=noteArray[43]){
      changeTime[5] = changeTime[5] + noteArray[43];
      PINA = 0x80;
    }
  }
  else{keyActive[5] = 0;}

  /*  Now Port B & Port C */
  /* Check if key for note F#4 is pressed, key6  */

  if ((portBkeys & 0x01) == 0){ // key is pressed B0 -> C0
       if (keyActive[6]==0){
       keyActive[6] = 1;
       changeTime[6] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[6])>=noteArray[42]){
      changeTime[6] = changeTime[6] + noteArray[42];
      PINC = 0x01;
    }
  }
  else{keyActive[6] = 0;}

  /* Check if key for note G4 is pressed, key7  */

  if ((portBkeys & 0x02) == 0){ // key is pressed B1 -> C1
       if (keyActive[7]==0){
       keyActive[7] = 1;
       changeTime[7] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[7])>=noteArray[41]){
      changeTime[7] = changeTime[7] + noteArray[41];
      PINC = 0x02;
    }
  }
  else{keyActive[7] = 0;}

  /* Check if key for note G#4 is pressed, key8  */

  if ((portBkeys & 0x04) == 0){ // key is pressed B2 -> C2
       if (keyActive[8]==0){
       keyActive[8] = 1;
       changeTime[8] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[8])>=noteArray[40]){
      changeTime[8] = changeTime[8] + noteArray[40];
      PINC = 0x04;
    }
  }
  else{keyActive[8] = 0;}

  /* Check if key for note A4 is pressed, key9  */

  if ((portBkeys & 0x08) == 0){ // key is pressed B3 -> C3
       if (keyActive[9]==0){
       keyActive[9] = 1;
       changeTime[9] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[9])>=noteArray[39]){
      changeTime[9] = changeTime[9] + noteArray[39];
      PINC = 0x08;
    }
  }
  else{keyActive[9] = 0;}

  /* Check if key for note A#4 is pressed, key10  */

  if ((portBkeys & 0x10) == 0){ // key is pressed B4 -> C4
       if (keyActive[10]==0){
       keyActive[10] = 1;
       changeTime[10] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[10])>=noteArray[38]){
      changeTime[10] = changeTime[10] + noteArray[38];
      PINC = 0x10;
    }
  }
  else{keyActive[10] = 0;}

  /* Check if key for note B4 is pressed, key11  */

  if ((portBkeys & 0x20) == 0){ // key is pressed B5 -> C5
       if (keyActive[11]==0){
       keyActive[11] = 1;
       changeTime[11] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[11])>=noteArray[37]){
      changeTime[11] = changeTime[11] + noteArray[37];
      PINC = 0x20;
    }
  }
  else{keyActive[11] = 0;}

  /* Check if key for note C5 is pressed, key12  */

  if ((portBkeys & 0x40) == 0){ // key is pressed B6 -> C6
       if (keyActive[12]==0){
       keyActive[12] = 1;
       changeTime[12] = currentTime;
     }
    // see if time to change hi to lo, or lo to hi
    if ( (currentTime - changeTime[12])>=noteArray[36]){
      changeTime[12] = changeTime[12] + noteArray[36];
      PINC = 0x40;
    }
  }
  else{keyActive[12] = 0;}

} // end loop

Nice video! You could post your rather short code into your answer so that it doesn't totally rely on links. :) This is, after all, a completely alternative way of doing it to the one I showed (which doesn't allow multiple notes at once).

Just select the code, hit Ctrl+K (K for Kode). That indents it 4 spaces and formats it for you. I did it for you. :)

Cool! I didn't realize that could be done.  Thanks Nick!


text:
Can I solder wall cord directly to servo?
I have a servo which requires 7.4v and a wall power cord which says the output is 7.4v but the connector does not fit that of the servo. Is it safe to snip off the end of the wall cord and solder the internal wires directly to the servo?

would you have asked this question if the connector fit?

@jsotola - no, I would assume using the products as designed is probably safe.

First choice: Attach compatible, polarized connectors to both pigtails.
Alternatively, you can solder it up but the result is certainly less convenient to use. I like heat-shrink tubing for insulating wire-to-wire solder joints, one over each solder joint and a third, slightly larger one over both. (My favorite way to screw this up is to forget to push all three shrink tubes over the wires before I solder the joints. :)

Yeah, i also like it when I forget to put on the heat-shrink before soldering. Makes me feel really clever.


text:
ignoring potentiometer value variations
I've got a 50k potentiometer connected to an Arduino Uno. The user should adjust the hue of an Adafruit NeoPixelStrip.
I've got the following code inside the loop function:
int hue = analogRead(poti1);
int mappedHue = map(hue, 0, 1023, 0, 65535);

neoPixelStrip.fill(neoPixelStrip.gamma32(neoPixelStrip.ColorHSV(mappedHue, 255, 255)));
neoPixelStrip.show();

If I turn the potentiometer knob, the colors are updating correctly and reflect the correct hue.
But if I let go of the knob, the LEDs are flickering a little (changing their hue values ever so slightly). If I print the potentiometer values to the console, they are changing a little. If I turn the potentiometer all the way to the left, the values range from 0 ... 13 or something. This change affects the hue of the pixels.
How do I ignore those value variations? I want the user to constantly change the color, so I have to read the value constantly.
Any ideas?

Have you got AREF output enabled and the pot wired between AREF and ground, not VCC and ground. That will help with noise. Also, for another alternative, look at rotary encoders.

Not quite sure what AREF is.

You have two issues going on - noise pickup, and a potentiometer with imprecise stops at one or both ends.
The pot is the easiest to fix: What are the lowest low reading and highest high reading you can reliably get when you turn it to its stops? Use those in place of '0' and '1023' in your map() function.
Improving the noise is only slightly more involved. An exponential average is an easy filter to write and quite effective at quieting noisy data, as long the signal to noise ratio is fairly low. The basic idea is you add only a fraction of each new value and keep (1 - that fraction) of the old average; so if your chosen fraction is 0.1, you only consider 10% each new datum, keeping 90% of the current average.
avg = f*avg + (1-f)*new_value
The output of this averaging filter can be slow to respond to changes if your fraction is too small, but less effective at quieting noise if your fraction is too large.
I usually use .25, or 25% of each new point and 75% of the current average, when I'm just trying to clean up minor noise, which is what you probably have.
Here is my 25% averaging filter:
int16_t xpavg(int16_t newdat, int16_t avg){

   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

As you can see, I do the arithmetic in Fixed Point - just like integer arithmetic, but with an assumed binary point 2 places to the left during the computation. And I choose a fraction that represents "nicely" in binary - 1/4 in this case - to keep the arithmetic faster (since multiplication and division can be replaced by shifting).
The function just multiplies the current average by 4 and subtracts the old average (effectively multiplying by 3), adds the new value, and divides the sum by 4. (That extra "+2" rounds the fractional bits just before we shift them away). The end result is: (3*avg + newData)/4 (== 3/4*avg + 1/4*newData).
If you were to only sample the pot every second or two, you could probably observe the delay as the filter falls behind while you turn the pot and catches up when you stop. If you're sampling at 10x/sec or less, you shouldn't be able to notice.
Update:
You need to add the function xpavg() to your code, and call it each time you read a new pot value (that is "newdat"), passing it the old average as well. It returns a new average pot value, now less affected by noise. You use that new average value instead of the raw number you just read from the pot, in your hue calculation. As Duncan offered, you can - and I do - initialize the average with a raw value from the pot. You could also start it at zero but it will take a few samples to converge on the current actual pot reading. The downside of using one raw sample to start it is that if that one value is terribly noisy, i.e. way different from the pot reading, it will still take a few samples to converge.
unsigned int AvgPot = analogRead(poti1);        // initialize pot average

// Exponential averaging functions
int16_t xpavg(int16_t newdat, int16_t avg)
{
   // (3 * avg + 1 * newdat) / 4
   return( (((avg<<2) - avg + newdat) + 2) >> 2 );
}

void setup()
{
   ;    // initializations go here
}

void loop()
{
   int hue = analogRead(poti1);
   hue = xpavg(poti1, PotAvg);
   int mappedHue = map(hue, 0, 1023, 0, 65535);

   neoPixelStrip.fill(neoPixelStrip.gamma32(neoPixelStrip.ColorHSV(mappedHue, 255, 255)));
   neoPixelStrip.show();
}

Sorry but i don't understand all of your post. It's a little too advanced for me. I don't know how I am going to implement this into my code. Where is that variable new_value coming from? Or what is it representing? And f? And what exactly do I have to pass as the parameter newdat? I don't know how to use your function in my code...

The idea is that you want to avoid "jitter" in the readings from your pot. An algorithm like an exponential average from this answer smooths out input values over time. You'd create a global int16_t variable (let's call it average) to hold the "rolling average" value for your pot.

Each time through your loop() function you'd read a new "raw" value from the pot, then call the xpavg() function, passing in the new pot value and the old average value. You'd then store the returned average value in your average var, and use that as the pot value. As the pot value changes, the average value will change more slowly, and will tend to ignore rapid "jittery" changes in the input.

But what is the initial value of average?

The initial value doesn't matter that much. As new values come in, the average will converge on the actual average reading. I suggest setting it to a value halfway between your max and your min value to start. Or you could initialize it with your very first analog reading.

I guess in the line hue = xpavg(poti1, PotAvg); you need to pass in hue as the first parameter, not poti1. poti1 is just a pin declaration. The flickering is gone, however, I cannot acmes the whole range of hue values. I guess it's because I would need a potentiometer past 1023 or 0 to get an average of 1023. It seems like I cannot reach the start and end points.

what about adding a capacitor?

Yes, that's another very reasonable way to filter noise. What's that they say about the guy with a hammer - that everything looks like a nail? I'm a software engineer! :)

There are many ways to remove noise, below are some ways:

Only change the value when it differs enough. Assume the range is 0-1023. Than only change the value if the input value differs more than a constant value (like 5 or 10, experiment with this to find a good value for your pot meter).
Another way is to use the average of the last x readings,  You can also combine this with the previous approach. There might be a small delay because of the averaging.

There are many more solutions, from reasonably easy to very complicated, search for removing noise in sensor data.


text:
Arduino ESP8266 GPS integration issue
I am facing issue in using 2 Serial communication device with Arduino uno. I am trying to use ESP8266, Neo 6M GPS module with Arduino UNO, but only one of device is working at a time. Is there any solution available to make this work? When I comment processGPS() and uncomment TCP related API and vice-versa then either of the device working. Any idea how we can make work both?
My code:
// This is a demo example using a public http server for testing both GET and POST requests

#include <Arduino.h>
#include <LiteESP8266Client.h>
#include "TinyGPS++.h"
#include "SoftwareSerial.h"

#define PACKET_MTU 500    // Standard network MTU is 500 bytes

LiteESP8266 radio;

const char ssid[] PROGMEM = "xyz";    //change it to your wifi SSID
const char password[] PROGMEM = "xyz";    //change it to your wifi password
const char host[] PROGMEM = "192.168.0.156";
const int port = 8080;

const char http_get_request[] PROGMEM = "GET /getLedStatus HTTP/1.1\r\n";
const char http_useragent[] PROGMEM = "User-Agent: Arduino-stm32/0.1\r\n";
const char http_content_type_json[] PROGMEM = "Content-Type: application/json\r\n";
const char http_host[] PROGMEM = "Host: 192.168.0.156\r\n";
const char http_close_connection[] PROGMEM = "Connection: close\r\n\r\n";
const char http_content_length_header[] PROGMEM = "Content-Length: ";
const char success[] PROGMEM = "success";
const char failed[] PROGMEM = "failed";
const char CRLF[] PROGMEM = "\r\n";
const char error_data_null[] PROGMEM = "Error: data came back null.";
const int ledPin=11;
// Choose two Arduino pins to use for software serial
int RXPin = 5;
int TXPin = 4;

int GPSBaud = 9600;

// Create a TinyGPS++ object
TinyGPSPlus gps;

// Create a software serial port called "gpsSerial"
SoftwareSerial gpsSerial(RXPin, TXPin);

void setupStationMode() {
  Serial.print(F("Setup station mode... "));
  if (radio.set_station_mode()) {
    Serial.println(F("success"));
  } else {
    Serial.println(F("failed"));
  }
}

void joinAP() {
  Serial.print(F("Join AP "));
  Serial.print(F("... "));
  if (radio.connect_to_ap(ssid, password)) {
    Serial.println(F("Success"));
  } else {
    Serial.println(F("Failed"));
  }
}

boolean establishTcpConnect() {
  Serial.print(F("Establish TCP Connection... "));
  if (radio.connect_progmem(host, port)) {
    Serial.println(F("Success"));
    return true;
  } else {
    Serial.println(F("Failed"));
    return false;
  }
}

void readHttpPacketAndProcessLEDStatus() {
  char *data;
  while ((data = radio.get_response_packet(PACKET_MTU, 5000))) {
    if (data) {
      Serial.println(F("Response Received..."));
      Serial.println(data);
      if(strstr(data, "ON") != NULL) {
        digitalWrite(ledPin, HIGH);
      }else{
        digitalWrite(ledPin, LOW);
      }
      free(data);//Mandatory
    } else {
      Serial.println(error_data_null);
    }
  }
}

void httpGetLedStatus() {
  Serial.println(F("Sending GET request... "));
  radio.send_progmem(http_get_request);
  radio.send_progmem(http_useragent);
  radio.send_progmem(http_host);
  radio.send_progmem(http_close_connection);
}
void setupGPS(){
  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
  Serial.println("GPS Start");//Just show to the monitor that the sketch has started
}
void setup() {
  delay(2000);
  pinMode(ledPin, OUTPUT);
  radio.begin(9600,2,3);
  Serial.begin(9600);
  while (!Serial) {};
  //setupStationMode();
  //joinAP();
  setupGPS();
}
void displayInfo()
{
  if (gps.location.isValid())
  {
    Serial.print("Latitude: ");
    Serial.println(gps.location.lat(), 6);
    Serial.print("Longitude: ");
    Serial.println(gps.location.lng(), 6);
    Serial.print("Altitude: ");
    Serial.println(gps.altitude.meters());
    Serial.println("Speed MPH:");
    Serial.println(gps.speed.mph());
  }
  else
  {
    Serial.println("Location: Not Available");
  }

  Serial.print("Date: ");
  if (gps.date.isValid())
  {
    Serial.print(gps.date.month());
    Serial.print("/");
    Serial.print(gps.date.day());
    Serial.print("/");
    Serial.println(gps.date.year());
  }
  else
  {
    Serial.println("Not Available");
  }

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

  Serial.println();
  Serial.println();
  delay(1000);
}
void processGps(){
   // This sketch displays information every time a new sentence is correctly encoded.
  if (gpsSerial.available() > 0)
    if (gps.encode(gpsSerial.read()))
      displayInfo();
}
void loop() {
  /*if(establishTcpConnect()){
    httpGetLedStatus();
    readHttpPacketAndProcessLEDStatus();
  }*/
  processGps();
  }

Both the ESP8266 and the GPS use SoftwareSerial. Using SoftwareSerial, only one port can receive data at a time. See here. For the Arduino Uno there's no simple solution. You will need different hardware that has more than one Hardware Serial port (like the Mega2560 if you want to stick to the AVRs).

Correction to my own comment: The ESP8266 doesn't actually use SoftwareSerial but the Arduino side communicating with the ESP8266 does.

Agreed with @StarCat. Why even bother with the Arduino UNO? If your ESP8266 has enough pins exposed it can run the code itself and talk directly to the GPS module with much less hassle.

@romkey, True, hence my comment about sticking to AVRs. Running directly on the ESP8266 would be much preferable. Of course I don't know what needs to be connected in addition from the GPS (displays, other peripherals?).

As mentioned by StarCat and romkey, SoftwareSerial only allows one connection at a time.
There are two potential solutions to this in my opinion, but each requires some new hardware.
Solution 1 - Replace Arduino Uno with an STM32 Blue Pill
STM32 Blue Pill has more than one hardware serial interfaces, so that you don't even need the SoftwareSerial, in fact, the LiteESP8266Client.h will auto detect if a STM32 is used or an AVR-based Arduino is used to decide whether to use HardwareSerial or SoftwareSerial, see here.
Pros:

Minimum code change. You be able to use what you have written so far and continue to use ESP-01 as a WiFi-shield;

Cons:

A little bit extra works to setup STM32duino Core for Arduino and requires either a SWDI programmer or USB-serial programmer.

Read this for getting started with STM32 and the things need to be aware of.
Solution 2 - Replace both Arduino Uno and ESP-01 with an ESP8266 Dev Board
Instead of using an ESP-01 as a WiFi shield,  get an ESP12-based development board as an Arduino to replace both the Arduino Uno and ESP-01. In this case, you run Arduino sketch directly on the board and replace the AT firmware with Arduino bootloader.
Pros:

Integrated Arduino Uno with ESP wireless functionality into one hardware.

Cons:

Need complete re-write of your application.

ESP8266 Arduino github should have sufficient information for getting started.

why STM32? Arduino has ARM boards

Why not an ESP32?

@Juraj Personally I never used any SAMD boards so can't comment on that.


text:
MKR WIFI 1010 Providing 3.3V to breadboard
The Arduino MKR WIFI 1010 product page says "The microcontroller on the MKR WIFI 1010 runs at 3.3V, which means that you must never apply more than 3.3V to its Digital and Analog pins. Care must be taken when connecting sensors and actuators to assure that this limit of 3.3V is never exceeded. Connecting higher voltage signals, like the 5V commonly used with the other Arduino boards, will damage the MKR WIFI 1010."
and yet it only has a 5V pin. I have a sensor that requires a 3.3V pin so I'm guessing my only option is to use a Logic Level Converter.
My question is if the MKR Digital and Analog pins can only take 3.3V, why is there only a 5V pin instead of a 3.3V pin to connect to a breadboard?

I agree that it is unclear and the documentation is not complete, but the VCC pin is the 3.3V output meant to power sensors. In the documentation tab of the MKR ZERO is explanation: https://store.arduino.cc/arduino-mkrzero

Thanks @Jot If you add that as an answer I'll mark it as the solution.

In short: VCC = 3.3V
The Arduino MKR WiFi 1010 board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.
The page of the Arduino MKR ZERO has more information in the "documentation" tab. The VIN pin is the 5V power input, the 5V pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and VCC is the regulated 3.3V output.
The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.


text:
NeoICSerial and SPI on the Uno - pin 10
The NeoICSerial documentation contains a table that states for the Uno:

Transmit: 9
Receive: 8
PWM Unusable: 10

Pin 8 and 9 are used for the serial connection. Pin 10 is part of the pins for the SPI on the Uno. Does this mean SPI connections can't be used together with NeoICSerial or is this specific for using pin 10 for PWM?

The "Unusable 10" is explained in AltSoftSerial library

The "Unusable PWM" pins can be used normally, with digitalRead() or
  digitalWrite(), but their PWM function controlled by analogWrite()
  will not work properly, because AltSoftSerial uses the timer which
  controls that pin's PWM feature.

Pin 10 on Uno is SPI slave select if the Uno is SPI slave (then it is an INPUT).
If the Uno is SPI master, this pin must be set as OUTPUT. For this reason it is usual to use pin 10 as slave select for the (first) SPI slave. SPI shields have this pin hardwired as slave select for the (first) SPI device on the shield.

NeoICSerial is interrupt driven - does this create a limitation between using pins 8, 9 and 10? I'm a bit puzzled by the table in the documentation and don't see where the limitation is coming from. The documentation states: "This class can only use one predefined Input Capture pin. Each MCU and board has a pre-determined pin"


text:
Using Arduino as a standalone compiler
I mostly program in C/C++ so I conviniently have a GCC compiler for all my compilations. I was wondering if there is a special compiler for Arduino that can be used just like the GCC Compiler? Because just taking a .ino sketch and passing it to the comiler with a few arguments will be a lot easier for me that all those things in the IDE, and furthermore I use Sublime Text as my text editor. And making a C program work in Sublime is as simple as providing it a path to the compiler. So I would like a portable smaller version of the Arduino Compiler that is NOT the whole IDE folder. Hope I get nice answers!! Thanks in advance.

Do you want to use Arduino libraries and other "Arduino enhancements", or are you OK with just using plain C/C++ and AVR headers?

I use it for mostly robotics applications and use atleast 10 sensors at once so libraries are a must...

First of all: The Arduino IDE brings its own GCC compiler. It is a version, that can compile for the AVR platform (don't know, if the standard version is capable of that).
When you activate verbose output for compilation in the preferences of your Arduino IDE, you can actually see, what calls to GCC the IDE is doing. You could use that to replicate it.
If you only want to use the sublime text editor for programming and not rebuilding the compilation environment of Arduino for fun (which I wouldn't able to help with), you might wanna have a look at the Arduino-cli. It gives you a tool to invoke important function, that normally the IDE does, via commandline (like installing cores and libraries, compiling and uploading). Thats what I'm currently using with sublime for programming in Arduino. It allows me to invoke building an uploading from sublime without having the Arduino IDE open.
If you want to go that way, here are the sublime-build files, that I use for my Arduino Nanos and ATtiny84s. Maybe you can adapt them for your needs. (Note: I omitted multiple variants, that I use to upload on different com ports, because the com port is the only thing, that changes there. Also I'm on Ubuntu, so on Windows or Mac it might look a bit different)
For the Nano:
{
    "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn arduino:avr:nano && arduino-cli upload -v --fqbn arduino:avr:nano:cpu=atmega328old --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "Compile & Upload ttyUSB0"
        }
    ]
}

For the ATtiny84:
{
    "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84"],
    "working_dir": "$file_path",
    "shell":true,
    "file_patterns":["*.ino"],
    "variants": [
        {
            "cmd" : ["arduino-cli compile --fqbn ATTinyCore:avr:attinyx4:chip=84 && arduino-cli upload -v --fqbn ATTinyCore:avr:attinyx4:chip=84 --programmer arduinoasisp --port /dev/ttyUSB0"],
            "working_dir": "$file_path",
            "shell":true,
            "name": "ATtiny84: Compile & Upload ttyUSB0"
        }
    ]
}

Thank you @chrisl I am positive that Arduino-CLI will be of great use to me, I checked it out and maybe that is more or less what I wanted, the idea of carrying around 500mbs of files in form of arduino ide is very bad for me and so I wanted a small compiler like interface. The folks at Arduino have done a good job at the CLI version so that might help. Thanks again!!

This is also available as a package for Sublime Text 3!!

This is not an answer that fully meets what you ask, but it is too big for a comment, and it helps you somewhat, at least using your Sublime editor.
What annoys me most in the Arduino IDE is the lack of supporting multiple files (having horizontal tabs make the number of files to see max 6 or 7, and using .h/.cpp files easily goes most beyond that number).
My preference is using Visual Studio as editor and I do. In your case you can use Sublime editor. Make sure that the .ino file doesn't change (i.e. only make a forward to your C++ classes or code in other classes). This is to prevent synchronization problems between the Arduino IDE and Visual Studio.
Simultaneously start up the Arduino IDE, and do the compilation from here. Only read the .ino file, while the other files are in the same directory (structure), and can be edited by Sublime editor.
So it doesn't use GCC, but the Arduino IDE is only used for compiling/running, and all editing work is done on your editor.
Besides that, in Visual Studio I created (at least for one project) stubs so I can run it on the PC as well as 'test' project. For this you can use your gcc compiler.

I tried using the "Use external editor" in the Arduino IDE but that is not what I wanted. I looked into the Arduino-CLI projest on github and maybe thats what I was looking for. Thanks for the effort though.

No problem, I upvote chrisl's answer which seems more suitable for you.

Yes that would be great, thanks

If you are working in Windows, I recommend VS2019 Community Edition (free) plus the Visual Micro extension.  Gives you all the intellisense features of VS, tabbed edit windows, the works.  I came to the Arduino world from Windows programming with C++ & C#, so I was already familiar with the Visual Studio line of IDE's, but I wouldn't have it any other way now.


text:
Replace Arduino bootloader
My Arduino board is malfunctioning in its bootloading and I thought weather I can overwrite the previous bootloader on the atmega. I mean to ask than can I simply reinstall bootloader on a chip that already has a bootloader installed.

yes. you need an ISP programmer or other Arduino with "Arduino as ISP" sketch.

Yes you can. A Programmer that is driven from a PC and connects to SCK/MOSI/MISO/Reset/Power/Gnd (the ICSP header on an Uno/Mega), or a Standalone Programmer that can program a bootload program stored on an SD card and connects to the same ICSP pins, is needed to access the bootload memory to load/reload the bootloader.


text:
My ArI was using a potentiometer and the system shorted maybe. Do I have to replace the USB interface chip? It doesn't reset also
See I was using a micro analog rotary potentiometer to control a servo. The pot was in a pcb. The 5v output and gnd were connected to arduino from the pot. The third pin and 5v got touched and it got fused. The Rx and TX led glowed constantly till I disconnected the 12v input.

12V input + short on 5V = possible dead 5V regulator (if it didn't go into thermal shutdown). Possible dead 5V regulator = unknown voltage on 5V rail (could be as high as 12V). High voltage on 5V rail = dead Arduino.

What to do now? Buy a new one?

Unless you like diagnosing hardware faults and doing surface mount soldering then that's the easiest option. If the PC can still see the board the USB chip is OK. The main MCU may be dead though.


text:
Voltage measure range of an arduino?
I recently thought of using an Arduino to measure voltage and I stumbled across the problem that what is the max voltage I can measure??? It is an Arduino Uno and I am thinking that I would also display the voltage measured on a 16 * 2 LCD screen.My guess is max of 5 volts but if this is correct how can I increase its range?

Without any further configuration, the ADC (Analog Digital Converter) of the Atmega328P (which is build onto the Arduino Uno) uses Vcc as voltage reference (meaning 5V in the case of the Arduino Uno). A voltage of 5V will result in the maximal value (which is 1023, since this is a 10bit ADC). So the voltage range in this case is 0 to 5V.
The Arduino Uno has an extra pin, where you can supply an own reference voltage. But it's limit is tied to the ADCs supply voltage AVcc, which is 5V for the Arduino Uno rev3 (as shown in the schematics of the Uno). The reference voltage should then be in the range of 1V to AVcc. So this still gives you only a range of 0V to 5V or smaller.
When you use a standalone Atmega328P, you can make AVcc a bit higher than the chips supply voltage Vcc, but at maximum Vcc + 0.3V.
You can check all these numbers by looking into the datasheet of the Atmega328P, chapter 28.9 (Electrical Characteristics --> ADC Characteristics).

How to increase this range depends greatly on your requirements. If you simply need a constant higher range, you can simply put a voltage divider in front of the analog input. Or you can use a more complex circuit involving an op-amp (amplifier ciruit, here with amplification factor below 1). You can even build this to be variable.
Should it be, that your wanted voltage range exceeds the 5V greatly, for example, if you want to measure mains voltage (230V for most europe, 110V in USA), you should definitely take great care and never connect this directly to electronic like the Arduino. High voltages (especially at high possible currents) should always be handled with great care.

The ATmega328's (it's the microcontroller on the uno) absolut maximum rating is Vcc + 0.5V for any pin (except the reset pin) while Vcc must not be higher than 6V.
In order to measure higher voltages you have to use a voltage divider (read this) to adjust the input voltage to the range 0V - Vcc.

Not 100% right. That value is the absolute maximum rating, which is what voltage you should not exceed. The ADC will read values between Vref- and Vref+. Usually Vref- is ground, while Vref+ is usually set to Vcc (unless you use the internal voltage reference, which is way lower). See chrisl answer for more details


text:
Is every Arduino comes with onboard compass?
The doubt was came in mind after seeing Arduino documentation. I have to turn my Arduino uno robot 20 degrees without using encoders. So I surfed on Internet for how can I do that. Interestingly I found the reference available on above link. They are not saying about any specific Arduino board. So I have to know that can I do this stuff on my Arduino uno? Also I have to know is that every Arduino comes with onboard compass?

No, there is no built-in compass on an arduino microcontroller.  However, you can interface the arduino with a magnetometer sensor to measure the direction of the earth's magnetic field, and use that as a compass.

If you simply want to obtain a controlled rotation then use a stepper motor.

the documentation is for this hardware https://store.arduino.cc/arduino-robot

No current Arduino board comes with an on-board compass. That function description comes from the documentation for the Arduino Robot, which is a retired product.
There may be other "maker" dev boards, such as the Adafruit Circuit Playground Express which have on-board compass peripherals.


text:
Arduino's stuck on COM1 and Device Manager Crashing
I just added a few new arduinos, and they are all loading on COM1. Here are some of the strange behaviors:

Three arduinos plugged in, and they are all on COM1. I've never seen multiple devices loading on the same port.
I have other arduinos that still load on the port they were assigned to before. That is, i * attach 4 arduinos, and they load on COM9-12, which is how they have loaded for months.
in Device Manager, when i try to change the COM port, when i click Ok, device manager exits.
when i load device manager with no board plugged in, and i select Show Hidden Devices, and I try to change the COM1 device, the dev mgr crashes again.

The boards are Elegoo Uno R3. Windows 10, ThinkPad T490s. I have been running arduinos in this configuration for 2 years on this laptop with no issues.
Help would be much appreciated. My project has ground to a halt for days!

Do they all identify with the same serial number?

at some point, usb port hardware and com port numbering are associated.  test for this is if the different arduino on same port read the same COM and same arduino on different ports read different.  Only way I can think to reset is to uninstall and reinstall some higher level (see devices by connection)

@Majenko I don't see a property called "serial number". I'm looking in the dropdown menu of device manager tab Details/Property. Trying two boards, the  Location is Port_#0002.Hub_#0005 and Port_#0003.Hub_#0005. The is also a property called "Device Instance Path" that is for one of them "USB\VID_2341&PID_0043\95036303235351312061" and they are different.

@Abel I tried swapping boards and ports, all read COM1. I'm not sure if that's what you meant. If not, please clarify.

that's the behavior I'm talking about.  to remedy, uninstall but don't delete the drivers (heck write down all the driver details just in case) at the higher levels (in devices by connection view) then rescan for hardware changes and it will reinstall. how high you have to go may depend on various things though like hubs.  by your comment, I'd aim for "Hub_#005"

@Abel I uninstalled the device in Device Manager, and rescanned. Behavior doesn't change. Device Manager quitting is very strange, and i suspect a very deep error. Reinstalling the OS is not an option. I have surrendered, and bought a new laptop for this project.

one more thing you could try is to reset the root and generic hub layers (advanced tab at properties from device manager)


text:
DFPlayer for Writing to SD Card
Can you use the DFPlayer to write to the SD card?
Link for DFPlayer: https://www.dfrobot.com/wiki/index.php/DFPlayer_Mini_SKU:DFR0299
Here's the goal of my project. I have a button that, when pressed, should a- play a song off an SD card that is hooked up to the DFPlayer and b- should log "button is pressed" to the SD card. Unfortunately, the DFPlayer library doesn't seem to have any functions for this, and I wasn't sure how to see whether the DFPlayer has the functionality to support writing onto an SD card. Are there modules that are Read-only for SD cards? If so, is the DFPlayer one of them?
PS - I'm using an Arduino Uno,
Thank you so much for your help! I am a complete novice for SD cards, so any help you give would be very much appreciated!

In short: no. The clue is in the name: "DFPlayer". It's a player. That's all it is.

whats wrong with the standard Arduino SD library? It should be able to read and write from an SD card

@esoterik, not on the DFPlayer board

why not use a second SD card? use the standard SD library with another card reader.

Thanks @Majenko, esoterik, and Juraj! I wanted to avoid buying a second sd card and reader if possible and use the DFPlayer to store information to the SD cars, but if that's not possible like you all are saying, I will go ahead and buy a new one. Thanks!

Unfortunately the DFPlayer cant write that data to the SD card. The Arduino has some non volatile memory of its own built in though. Theres 1K of EEPROM for the UNO. Notes on how to use it here: https://www.arduino.cc/en/Reference/EEPROM
If you can get what you need to done in 1K and its not important to your project that you be able to unplug the SD card and put it in another reader, then perhaps thats a nice, simple solution...


text:
IR Receiver Remote Controller for Windows
My dad watches netflix on his pc with his wireless mouse, hes gotten older and cannot hit the volume slide well enough.
I have an arduino kit (ard nano), an IR recevier and remote controller laying around (all from the arduino kit).
I want to use the remote control when you press volume down on it to make the windows volume go down.
I tried using chatgpt but have gotten nowhere, what would be the best simplest solution for this.
I was thinking it would be an easy read-in of the data from the receiver but how would you transfer this data on to windows? Is this possible, I havent found many examples online
Thank you all :)

Are there some keyboard commands that you can enter on the PC instead of manipulating a scroll bar with the mouse ? If so, state what they are here and/or check yourself if an Arduino Leonardo or Arduino Micro (both ATMega32U4 based) is capable of issuing such commands.

get a wireless keyboard that has volume buttons ... remove the electronics and place them in a small box ... discard the keyboard matrix ...  add a couple of buttons, and connect them in place of the keyboard matrix ... you can use a scrap keyboard for this, since the buttons are not needed

There are USB / HID keyboard codes for volume.  Here we see volume up is 0x80 and volume down is 0x81.
Consider obtaining an Arduino board which is capable of supporting a USB / HID port so that you can easily emulate a keyboard.  It would be best to choose a board with hardware USB / HID support.  But it may be possible to emulate (limited?) USB / HID support using software only.
There are plenty of Arduino USB / HID project (here and here are just 2 examples).  This should get you started designing an Arduino sketch which can transmit a keyboard's volume up and down control codes into one of the computer's USB ports.
And there are plenty of Arduino ASK / IR receiver projects (here and here are just 2 examples).  As there are many IR remote control codes, this part of the project might take a bit of research to uncover the codes used in the IR remote control you posses.