text:
How to speed up Due ADC
I'm doing a project where in I'm using Arduino Due to measure the time difference of arrival of signals to four piezoelectric sensors. The piezo sensors where glued on a board and we want to localize the source of taps on the boards based from the TDOA of the vibration to the piezos.
Originally, we are using interrupts to raise flags once we have detected the signals (basically, we've set a threshold on the piezo voltage to say that we've 'detected' a signal) but that seems susceptible to noises especially when the environment has loud noises (music, voices on microphones, etc.).
So what we think as a solution is to perform signal processing. However, to do this, we need to measure the voltage of the incoming signal using the ADC.
So far, my target is to make the performance of this approach comparable to that of the one where we are using interrupts. As of now, the new approach is super sensitive to the difference on the taps giving it a high POE.
As I understand it, the main difference between the two approach is that the interrupt approach has a microsecond difference between counts making the difference of the taps to about 10 to 30 microsecond. However, the Analog approach has a 20 microsecond difference between each sample for each channel, making the count difference 20 second also. Even a count difference would make it 20 us.
Is there anyway to make this time faster? I know the ADC needs time to convert and push the data to the appropriate registers but I'm just trying to find ways to make this faster. I've read on the datasheet of the Due MCU that it has 14 ADC channels plus a temp sensor at the 15th. Maybe a way of doing this could be to reduce the number of channels? I don't know how.
Are there any way to make the ADC conversion of the Arduino Due faster?

Yes, there is a possibility to configure ADC to run faster, as it can handle 1Msps. For four ADC channels it means 250ksps each (with 1us time difference between samples). It's not possible with Arduino wrappers as they are way too slow and also waits for conversion end. You have to configure it directly in MCUs registers, so start with SAM3X8 datasheet.
In short: free running mode, sequenced readings like: 0 1 2 3, with interrupt on 4th sample, interrupt handler and some processing.

Thanks @KIIV! Another question, in the free running mode, would there be any problem on reading the output registers? I mean since the ADC is freely converting and I'm still reading channel 1 (I reckon reading through SPI or I2C is slower than the actual conversion), but the ADC has new set of data, will there be any data collision or anything?

@noobiejp That's why I mentioned sequenced readings. You can configure it to go over ADC inputs in any order. And readings are stored in corresponding data registers.

difference between each sample for each channel,

That's way too slow for any mcu made since the 1980s.
Look into the datasheet and compare it via your code to see where you can pick up the speed. Typically there is a clock prescaler for the adc that you can change.
In general, the fastest would be continuous adc into dma. If you need to add multiple channels turn on scanning.

//Configure ADC
PMC->PMC_WPMR &= ~(PMC_WPMR_WPEN);    //Disable the Write Protect Mode
PMC->PMC_PCER1 |= PMC_PCER1_PID37;    //Enable ADC Peripheral Clock
PIOA->PIO_PDR |= PIO_PDR_P16;         //Disable PIO Controller
ADC->ADC_WPMR &= ~(ADC_WPMR_WPEN);    //Disable the Write Protect Mode
ADC->ADC_CHER |= ADC_CHER_CH7;        //Enable A0 pin
ADC->ADC_MR = 0;
//ADC->ADC_MR = ADC_MR_PRESCAL(2);    //ADC Clock set to 16MHz
ADC->ADC_MR = ADC_MR_PRESCAL(4);      //ADC Clock set to 8MHz
ADC->ADC_MR |= ADC_MR_TRACKTIM(3);
ADC->ADC_MR |= ADC_MR_STARTUP_SUT8;
ADC->ADC_EMR = 0;
//read ADC output
ADC->ADC_CR |= ADC_CR_START;           //Software Trigger
uint32_t adc_read = ADC->ADC_CDR[7];
you can change the parameters of prescaler to get the required speed

You can set the ADC in freerun mode to get results as fast as they can be read.
Use adc_configure_trigger for this.
adc_configure_trigger(ADC, ADC_TRIG_SW, ADC_MR_FREERUN_ON);

To enable freerun on the ADC or to configure as needed. No need anymore to set registers.
There was a bug with this function before if called more than once, but it is now fixed.
https://github.com/arduino/Arduino/issues/1819


text:
How to store incoming serial string in arduino?
In my recent project, I am working with serial data. Till now, I'm able to receive data and display on LCD. Now, suddenly I can't get any serial data. Nothing display on LCD.
My incoming string is:
{"Action":"ONE","TPS":"0.40","MAP":"0.95","LOAD":"14"}

And my code is below:
#include<LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 7, 6, 5, 4);

String response = "";
bool begin = false;

void setup()
{
  Serial.begin(9600);
  lcd.begin(16, 2);
}

void loop()
{

  while(Serial.available() || !begin)
  {
    char in = Serial.read();

    if (in == '{')
    {
      begin = true;
    }

    if(begin)
    {
      response += (in);
    }

    if(in == '}')
    {
        break;
    }
    delay(1);
  }

  lcd.setCursor(0, 0);
  lcd.print(response);
}

:)   Does your LCD work? Can you print a literal value to it?  I suspect the problem is that rather than you have forgot to set begin to false before the break statement.

@CodeGorilla Yes, my LCD working fine. And already tried put that things mean set to begin to false. But, not working.

Something changed from the time the LCD worked until when it didn't - what changed? Did you reload the code? Same code/ different code? Change any wiring, even accidentally? Short circuit something? Go back and figure out what might have changed and try to undo the change. Unless it was accidental damage, you should be able to get working again.

Did you sent some blank lines before the "{...}" data?

@JRobert Nothing changed. I tried out my previous old code. Check out everything like wiring, short circuit etc. But, nothing happened.

@LookAlterno No...

I tested your code and it works. The only way to see nothing in the LCD is that response start with a lot of spaces. Mistery.

Actually I can see what I think may be an issue with your code.
 while(Serial.available() || !begin)

This isn't right.  If there is no data available in the serial buffer but the first { hasn't been seen then go and read the non-existent data anyway?
Rather than try and explain what I mean in multiple comments I have put it all together and this is what I think your loop should be this:
/// This is un-compiled code, so you might have to fix some little issues.
/// bool begin = false;         // True when the initial { has been seen

void loop()
{
  while (finished == false)
  {
    if (Serial.available())
    {
      const char in = Serial.read();
      if (in == '{')
      {
        response = "";  // Blank the string
        begin = true;
      }
      if (begin)
      {
        response += (in); // Only write if within the {}
      }
      if (in == '}')
      {
        begin = false;   // Prevent any chars between } and { leaking through.
        lcd.setCursor(0, 0);
        lcd.print(response);
      }
    }
    delay(1);
  }

  delay(500); // Not sure what will happen if you send multiple {} to the LCD too fast.
}

I tried out your code and it's working fine. And now my code is working fine. Why ? I answer it.

I just switch from Arduino UNO to Arduino MEGA. And everything works fine. I know this is not a proper answer but I want to know why this happens. I don't understand why this happens? Can anyone explain me?

source: Stack Exchange

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

sort: votes


text:
character input for an integer variable?
Im trying out the code found here , let me quote the section of code that bothers me.
// set pin numbers for switch, joystick axes, and LED:
const int switchPin = 2;      // switch to turn on and off mouse control
const int mouseButton = 3;    // input pin for the mouse pushButton
const int xAxis = A0;         // joystick X axis
const int yAxis = A1;         // joystick Y axis
const int ledPin = 5;         // Mouse control LED

xAxis is a variable that is defined as an integer , however, it is being assigned a character(A0), How is this possible? I tried to compile and run the code and everything works well. I'm quite surprised!

A0 and A1 are not characters or what you mean probably: strings.
Because it would be written as "A0" and "A1".
The types of A0 and A1 are probably integers or another numeric type.
However, these are probably defined as (constant) integers, e.g.:
const int A0 = 100;
const int A1 = 101;

(note 100 and 101 are random numbers)
or defined by a macro. e.g.:
#define A0  100
#define A1  101

So the variables A0 and A1 are actually integers (or assigned as numeric values by a define).

Actually they are static const uint8_t

The clue is this comment:
// set pin numbers for switch, joystick axes, and LED:

and the fact that xAxis is declared a const int. Because the declaration promises that this variable will not (must not) be changed once it has been initialized, it will not be assigned any memory at run time. The compiler will treat it much like the macro:
#define xAxis A0

and do a compile-time replacement of xAxis with A0, wherever xAxis appears.
A0 is an analog channel, defined in the board-specific Arduino libraries to the Arduino pin# corresponding to it.
It is a somewhat recent idiom in C and C++ - since the inclusion of "const" in the language - to use "const int" declarations for this purpose instead of "#define" statements. The intent is the same.

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


text:
Using ArduCam library for Ov7076 camera
I am using OmniVision OV7076 camera (without FIFO) with Arduino Uno.

So I want to use Github code provided in ArduCAM repository. They have provided OV7076 FIFO version straightaway but it is using more memory.
I have used computer nerd code (provided in this tutorial Instructables OV7076 camera) and the camera had worked.
But I want to use the ArduCAM repository. It would be nice if any one could provided link for the guide or can give a little walk-through.
In the ArduCAM repository, they have make an ArduCAM class which have many methods. Thus we get rid of initialisation provided in computernerd code.
I want to use functions of the class directly. But i am unable to understand which method can be used for ov7076 camera. If you could write a starter code it would be very helpful.

I'm not able to add them in the question :(

I'll fix it up. For future reference there is a question mark in a gray circle in the top right-hand of the edit form - this will provide you with help.

I don't have much reputation that's why i'm unable to add the links. Thanks for your efforts. :D

Does this post help? http://embeddedprogrammer.blogspot.com.au/2012/07/hacking-ov7670-camera-module-sccb-cheat.html

According to this page, you should be able to post up to 2 links. I've finished editing the post, so you have your links plus more. You may be able to approve my edits.

Sorry but it is not what i want.


text:
How to extract latitude and longitude from GPS
I want to extract longitude and latitude from GSM/GPS module and then upload it to thingspeak. I am using sim808 GSM/GPS module and AT+CGPSINF=0 to get GPS location information sentence (CGPSINF: 0,6.823375,80.001038,36.300000,20170705124133.000,0,10,0.037040,47.410000
). I want to extract longitude and latitude from it. Does anyone know how to do it? I am not an expert in programming. someone told me to use strtok. But I don't know how to do it. Does anyone have any Arduino code to do this?
I tried DFRobot SIM808 library to collect GPS data. it works like charm. But the problem was, my upload code didn't work when i was using the library to collect longitude and latitude in the same code.
This is my web upload code.
#include <SoftwareSerial.h>
#include <String.h>

SoftwareSerial mySerial(10, 11);//(2,3)

void setup()
{
  mySerial.begin(2400);   // the GPRS baud rate 9600
  Serial.begin(2400);    // the GPRS baud rate 9600

  delay(1000);

  ShowSerialData();

}

void loop()
{
      Send2Pachube();
  if (mySerial.available())
    Serial.write(mySerial.read());
}
void Send2Pachube()
{
  mySerial.println("AT");//start with attention
  delay(1000);

  mySerial.println("AT+CPIN?");//check for the sim card
  delay(1000);

  mySerial.println("AT+CREG?");//check for registration and access technology of cell
  delay(1000);

  mySerial.println("AT+CGATT?");//check whether the device is attached to GPRS.0Detch,1Attch
  delay(1000);

  mySerial.println("AT+CIPSHUT");//shut packet data protocol context
  delay(1000);

  mySerial.println("AT+CIPSTATUS");// returns the current connection status
  delay(2000);

  mySerial.println("AT+CIPMUX=0"); //create multi-IP connection(0=single connection)
  delay(2000);

  ShowSerialData();

  mySerial.println("AT+CSTT=\"hutch3g\"");//start task and setting the APN,
  delay(1000);

  ShowSerialData();

  mySerial.println("AT+CIICR");//bring up wireless connection
  delay(3000);
  ShowSerialData();

  mySerial.println("AT+CIFSR");//get local IP adress
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CGPSINF=0");//get GPS
  delay(2000);
  ShowSerialData();

  mySerial.println("AT+CIPSPRT=0");//starts a TCP or UDP connection
  delay(3000);

  ShowSerialData();

  mySerial.println("AT+CIPSTART=\"TCP\",\"api.thingspeak.com\",\"80\"");//start up the connection
  delay(6000);

  ShowSerialData();

  mySerial.println("AT+CIPSEND");//begin send data to remote server
  delay(4000);
  ShowSerialData();

  String str="GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field1=100";
  mySerial.println(str);//begin send data to remote server
  delay(4000);
  ShowSerialData();

  mySerial.println((char)26);//sending
  delay(5000);//waitting for reply, important! the time is base on the condition of internet
  mySerial.println();

  ShowSerialData();

  mySerial.println("AT+CIPSHUT");//close the connection
  delay(100);
  ShowSerialData();
}
void ShowSerialData()
{
  while(mySerial.available()!=0)
    Serial.write(mySerial.read());
}

Since the library works in getting the data, maybe you should focus on getting that to work with your code.

First rather than just dumping it to the screen store the data in a char array
char dataBuffer[64];
int dataCount=0;

while ( (mySerial.available()!=0) && (dataCount<63) ) {
    dataBuffer[dataCount] = mySerial.read());
    dataCount++;
}
dataBuffer[dataCount] = 0;

then use strtok to split the string on the : and , characters
char *output;
output = strtok(dataBuffer,":");
// output will now point to everything up to the first : so "CGPSINF" for gps
int field = 0;
while (output != null) {
  field++;
  output = strtok(null,",");
// output will now point to each value in turn
// for CGPSINF:0,6.823375,80.001038,36.300000,
// when field == 1 output=="0"
// when field == 2 output=="6.823375" etc...
}


text:
How to create a simple TCP server with the analogRead value on Wemos D1 mini?
I want to create a TCP server on the Wemos that serves the analogRead value of the connected potentiometer.
The code below is based on this example.
The Wemos connects to the Wi-Fi and i'm able to ping it,
but the problem is that I can't connect to the server.
Also I don't really understand why the length of the data has to be passed with the data (serverClients[i].write(sbuf, len);). Why can't the library figure that out?
#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  Serial.begin(115200);
  Serial.print("\nConnecting to "); Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.setNoDelay(true);
  Serial.print(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0); //analog read
    String sSensorValue = String(isensorValue); //int to string
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}

I've never used a Wemos, but if you compare to the code you linked, you seem to be missing a server.begin() call.

Also, that code looks a little wonky to me. For example, the continue is completely useless. Did they want a break there?

@JohnnyMopp You have a great eye for detail!

So the problem was that I forgot the following line.
Thanks to @Johnny Mopp for pointing this out.
server.begin()

Correct code:
#include <ESP8266WiFi.h>

//how many clients should be able to telnet to this ESP8266
#define MAX_SRV_CLIENTS 2
const char* ssid = "myWifi";
const char* password = "myPassword";

WiFiServer server(23);
WiFiClient serverClients[MAX_SRV_CLIENTS];

unsigned long previousMillis = 0;
const long interval = 200;
void setup() {
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  uint8_t i = 0;
  while (WiFi.status() != WL_CONNECTED && i++ < 20) delay(500);
  if (i == 21) {
    Serial.print("Could not connect to"); Serial.println(ssid);
    while (1) delay(500);
  }
  server.begin();
  server.setNoDelay(true);
}

void loop() {
  unsigned long currentMillis = millis();
  uint8_t i;
  //check if there are any new clients
  if (server.hasClient()) {
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      //find free/disconnected spot
      if (!serverClients[i] || !serverClients[i].connected()) {
        if (serverClients[i]) serverClients[i].stop();
        serverClients[i] = server.available();
        continue;
      }
    }
    //no free/disconnected spot so reject
    WiFiClient serverClient = server.available();
    serverClient.stop();
  }

  //do every 200ms
  if (currentMillis - previousMillis >= interval) {
    previousMillis = currentMillis;

    int isensorValue = analogRead(A0);
    String sSensorValue = String(isensorValue) + "\n\r";
    size_t len = sSensorValue.length();
    uint8_t sbuf[len];
    sSensorValue.getBytes(sbuf, len);
    for (i = 0; i < MAX_SRV_CLIENTS; i++) {
      if (serverClients[i] && serverClients[i].connected()) {
        serverClients[i].write(sbuf, len);
        delay(1);
      }
    }

  }
}


text:
IR Remote code not activating ON/OFF states
The code below is for turning RGB lights on/off. The connections are as indicated in pin numbers. I found the resulting value of the buttons of the remote but when I used them in code it is not showing ON/OFF.
I assume there may be some practical errors. How to avoid such errors?
#include <IRremote.h>

int RECV_PIN = 3;
int red = 13;
int blue = 12;
int green = 11;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if (irrecv.decode(&results)) {
    long int getting = results.value;
    Serial.println(getting);
  }
  switch (results.value) {
    case 16582903:
      digitalWrite(red, HIGH);
      digitalWrite(blue, LOW);
      digitalWrite(green, LOW);
      break;
    case 16615543:
      digitalWrite(red, LOW);
      digitalWrite(blue, HIGH);
      digitalWrite(green, LOW);
      break;
    case 16599223:
      digitalWrite(red, LOW);
      digitalWrite(blue, LOW);
      digitalWrite(green, HIGH);
      break;
    default:
      Serial.println("Enter ;");
  }
  irrecv.resume(); // Receive the next value
  delay(100);
}

Try moving the switch to inside the if block.

Assuming you wiring is correct, the only mistake I could see is that your variable named "getting" used in switch is inside the if, and it should be at least in the same level of switch. Also, your resume needs to be inside the if.
#include <IRremote.h>

int RECV_PIN = 3;
int green = 11;
int blue = 12;
int red = 13;

#define code1  16582903 // Must match exactly the code generated by the IR button, would be something like 0xFF906F
#define code2  16615543
#define code3  16599223

IRrecv irrecv(RECV_PIN);
decode_results results;

void setup() {
  Serial.begin(9600);
  irrecv.enableIRIn(); // Start the receiver
  pinMode(red, OUTPUT);
  pinMode(blue, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  if(irrecv.decode(&results)) {
    //this checks to see if a code has been received
    Serial.println(results.value, HEX);
    unsigned int getting = results.value;
    Serial.println(getting);
    switch (getting) {
      case code1:
        digitalWrite(red, HIGH);
        digitalWrite(blue, LOW);
        digitalWrite(green, LOW);
        break;
      case code2:
        digitalWrite(red, LOW);
        digitalWrite(blue, HIGH);
        digitalWrite(green, LOW);
        break;
      case code3:
        digitalWrite(red, LOW);
        digitalWrite(blue, LOW);
        digitalWrite(green, HIGH);
        break;
      default:
        Serial.println("Enter ;");
    }
    irrecv.resume(); //receive the next value
  }
  delay(100);
}

Thank you for the delay(100); I was combining IR remote, with HC-SR04 with adafuit sound board. I was getting random input when IR remote was used. Adding the delay solved (after 3 days). Thank you. Thank you.

@Andres nice! Well Done.

I would change "unsigned int getting = results.value;" to "unsigned long getting = results.value;" in Andrew's sketch and use it. I don't know what "type" of Arduino you are using, but I know on the Uno and other ATMEGA based boards, unsigned ints yield a useful range of 0 to 65,535. Unsigned long will give you a range from 0 to 4,294,967,295.
If you press ANY button and hold it down for a while on some IR remotes, code 4294967295 will be sent. This is true for the "Car" remotes: https://www.amazon.ca/dp/B00SMI1GZA/ref=pe_386430_126088100_TE_item, Apple TV (2nd generation) remote, and LG 50" TV remote.
One minor issue I found with both sketches is I could not get them to compile. I had to remove the space between "#" and "include" and the spaces between "<" and ">" in "# include < IRremote.h >". I am using an older version of the IDE which may explain it. Arduino UNO. IDE Version 1.0.6.2, GCC 4.2.1 on OSX 10.6.8.

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


text:
Connecting NodeMCU with OV7076 camera
I am trying to connect an OV7076 camera with a NodeMCU, but there are no pin diagram available for it. As NodeMCU has 4 MB storage and 128 KB  memory, is there any possibility to use it?
AI thinker esp8266mod
Omnivision OV7076

You cannot connect an OV7076 camera with NodeMCU because OV7076 got 4 analog pins (VGA) and on the other hand NodeMCU got only one analog pin.


text:
How to control RC power switch with Arduino-/Adafruit-Board?
I want to control (switch on/off) a solenoid valve via an RC power switch and an Adafruit M0 Feather Bluefruit LE. The RC power switch is this one, and this is the Adafruit Board Pinout.
My assumption was that I have to wire up the servo wire connector of the power switch with the Adafruit board like I would do with an ESC and control it via PWM (my guide tells me that possible pulse widths are between 870 and 2,220 µs). I am connecting the white cable (I assume it's the impulse wire) of the power-switches' servo-connector with a PWM-capable GPIO pin and the black cable (I assume it's the minus wire) with the GND pin of the Adafruit Board, like I did with an ESC, which is working fine with the servo library of Arduino.
My problem is that the solenoid valve is showing no reaction. Am I thinking the right way or am I completely wrong?
Thank you and many thanks.

The Code for successfully controlling the escs is like: gist.github.com/vitorleal/9083802

I'm voting to close this question as off-topic because it is about RC gear not about Arduino.

I fixed the problem by myself. If you want to arm an RC power switch, do it like arming an ESC with your sketch. The servo connector wires have to be connected as follows:

(white) PWM-capable GPIO
(red) positive wire of your battery
(black) negative wire of your battery

The simple solution was that the power switches got less/no power.

"arming" as required by a typical ESC typically means running the throttle PWM up and back down to demonstrate that there's a prepared driver/pilot at the controls.  What you are describing sounds more as if you are simply providing power to a switch designed to be powered by the RC receiver rather than to power itself (and potentially also the receiver) from the motor battery.


text:
Problem with tachometer using attachInterrupt and servo
So I am creating a tachometer using black/white detector sensor. Here's the code.
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  delay(5000);
}

The code works well and it can read RPM correctly. And then from the same arduino, I am controlling a servo motor, in this case I am using GWS03N/STD/F, with this code :
#include <Servo.h>

Servo myservo;
int pos = 0;

void setup() {
  myservo.attach(9);
}

void loop() {
  myservo.write(90);
}

And this code works well too.
But, when I am trying to combine both codes, only the servo code is working well. The tachometer reading is not correct (the reading must be around 1000-1500rpm, but now it reads 3000-30krpm). I am already trying to change my tachometer interrupt to pin 2 or 3, and servo to 3, 5, 6, and 9 but still the same.
So what is wrong in here. Thank you so much.
This is my code when combining both codes.
#include <Servo.h>

Servo myservo;
int pos = 0;
unsigned long WaktuOLD;
unsigned long WaktuNOW;
int Detection = HIGH;
int Counter = HIGH;
float HitungWaktu;
float HitungRPM;

void setup() {
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(3), rpm, RISING);
  WaktuNOW = millis();
  myservo.attach(9);
}

void rpm() {
  Detection = digitalRead(3);
  if (Detection == HIGH && Counter == LOW) {
    WaktuNOW = millis();
    HitungWaktu = WaktuNOW - WaktuOLD;
    HitungRPM = 60 / (HitungWaktu / 1000);
    Counter = HIGH;
  } else if (Detection == HIGH && Counter == HIGH) {
    Counter = LOW;
    WaktuOLD = millis();
  }
}

void loop() {
  Serial.println(HitungRPM);
  myservo.write(90);
  delay(5000);
}

Your problem is probably that of interrupt conflicts.
The 8-bit Arduinos don't have any concept of interrupt priorities. When one interrupt routine is running it is impossible for any other interrupt routine to run until that first one has finished.
Interrupts have a "natural call priority" in that lower numbered pending interrupts will be called in preference to higher numbered ones, however that doesn't mean that they can interrupt each other.
The problem here is that the servo library uses a timer (and its associated interrupt) to generate the waveform.  That uses a lot of interrupt calls running all the time - and while they are running your external interrupt can't be called - at least not until the currently executing timer interrupt completes, at which point your external interrupt handler will be called since it is the highest priority.
So the results you get with all that delaying are pretty meaningless.
So what can you do?  Well, there's a number of options - all of which involve not using interrupts.

You could not use the Servo.h library and instead reconfigure the hardware PWM to the right frequency and use that for the servo
You could use one of the timers with an external clock source to count your tacho pulses (I think Timer 1 has that ability on the Uno)

Or even better: do both.  That would give you the most efficient system whereby the main CPU is only involved in getting the count from the timer periodically, and adjusting the PWM value for your servo. The rest is then done by hardware completely asynchronously.
Of course, for this you will want to study the datasheet so you know how to configure the various hardware modules.

Are there another libraries instead of "Servo.h", which may solve this issue?

Not that I am aware of, but there are plenty of tutorials around on changing the frequency of the PWM.

This may be of interest to you...

Can we use a PWMServo as same as the Servo.h ?

It depends which timers both are using. If they're on different timers then sure. If not, no.

Can we resolve the issue by using two separate Arduino Uno boards: One for sensor and one for Servo

Sure, as long as the communication between them doesn't impact either, and since that generally uses interrupts too you're probably going to run into some issues.

I must comment :-). This answer is perfect. First when I saw the bounty, I thought Tharindu throw away his points for this bounty. I never worked with servo or encoder interrupts, but I knew that 328p misses the RPM interrupts because the servo library uses interrupts to generate pulses. But I had no solution. And the possibility to substitute both controls with MCU internal peripherals is perfect.

@Juraj Yeah I got a very close idea with the answer. But still, I have no idea how to resolve my problem. Can you suggest a path to start with?

I would start with the tacho. Read the datasheet and learn how to configure timer1 to use the T1 pin as the clock input and count clock pulses.

All of those variables that are accessed inside the ISR need to be declared as volatile.
You are using a RISING interrupt, so there should be no need to test the pin in the ISR.  You can be confident that it went HIGH for the interrupt to be run.

I stand corrected.  I must have misread the pin number somehow.  Still, the variables need to be volatile.

It's a typo on one of the pin number on Detection var, I already correct it now. And I already try to volatile WaktuOLD, WaktuNOW, Detection, Counter, HitungWaktu, and HitungRPM but it still no good. I haven't try to remove Detection var though.

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


text:
Visual Studio integration with Arduino
I use Visual Studio 2015 extensively for work, so it would seem like a logical choice for getting started with Arduino programming (though my C/C++ is rusty, that may take some time to get back). From what I understand the Visual Micro Plugin is popular. Is that sort of the de facto choice for those who come from VS? Does it tie into everything so that I can handle debugging, breakpoints, deployment etc from Visual Studio? Much obliged!

I think it is the de facto standard for VS (of course the default Arduino IDE is used most).
However, I think some advanced features (like breakpoint if I recall right) is only temporarily for free and you have to pay later for a subscription.
Note however, that debugging/breakpoints are not used often anyway since mostly it's more realtime controlled than PC applications.
If you need breakpoints etc. probably the easiest is to make stubs for some libraries and first develop the application not using Arduino and later use the Visual Micro plugin. [Update: it seems breakpoints are possible with vMirco, I never got them to work though].

OK well it's only $20 for a student license so I guess if I find I like that feature I could buy it. But it does output to Visual Studio right? Like if I write print("Jello World") in my code, does that get outputted to the Visual Studio Immediate Window?

I tried it just a few times (without breakpoints) but it worked perfectly ... I have the free version (not being a student). I don't think the output is write to the immediate window but to a specific window from vMicro.

You're not going to be able to use breakpoints except in some sort of simulator (if offered) or by buying a suitable hardware interface - they won't work with just they the everyday Arduino USB port interface.

It's been about a year, but the last I checked vMicro's breakpoints worked just fine (most of the time). It works by injecting code into your debug builds IIRC.

Use Atmel's Atmel Studio 7. Uses the visual studio shell and is supported by Atmel. Also allows you to import your Arduino Sketches. Once I used it, I stopped using the Arduino IDE.

How does debugging work? Are you able to attach to the process running on the andruino and step through it? What about print() commands, how are they outputted? Thanks!

For debugging you will need a debugger like the Atmel Ice which uses debug wire and interfaces with the Atmel Studio.  It's worth the money if you do a lot of coding. As for printf, there are tutorials on how to hook standard I/O into your code. The IDE is irrelevant that that case.

so I'm confused then, what is the benefit of this plugin if it doesn't support debugging out of the box? Not even println() statements?

Its not a plugin. Is an IDE built off the Visual Studio Shell. Its free. If you want to step up your game, use Atmel Studio and buy the Atmel ICE. IMO Visual Micro is junk.

I use Visual Micro and my opinion so far is that it works better than Atmel Studio, which I cannot get to work so far (at least to compile something with libraries without any problem).

Atmel Studio uses the same vMicro plugin that VS does to get Arduino support, so there's literally no difference here unless OP is interested in doing "raw" avr development.

@RubberDuck Atmel Studio doesn't use a plugin. It's built on the visual studio shell.

@PhillyNJ in order to get Arduino support it uses the vMicro plugin. Unless I'm thinking of v6 and they added it native in v7.

@RubberDuck AS7 has been out for over a year and it's built in


text:
ESP8266 send TCP HEX packet with 4 chars
I'm building a remote for my WiFi-RGB Lights. I have an ESP8266, which should send one TCP packet with 4 chars.
My code:
#include <ESP8266WiFi.h>

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

void WiFiEvent(WiFiEvent_t event) {
  Serial.printf("[WiFi-event] event: %d\n", event);
}

void setup() {
  Serial.begin(115200);
  WiFi.disconnect(true);
  delay(1000);
  WiFi.onEvent(WiFiEvent);
  WiFi.begin(ssid, password);
}

void loop() {
  delay(1000);
  const uint16_t port = 5577;
  const char * host = "192.168.178.150";
  WiFiClient client;
  client.connect(host, port);
  client.print(char(0x71));
  client.print(char(0x24));
  client.print(char(0x0f));
  client.print(char(0xa4));
  client.flush();
  client.stop();
  delay(5000);
}

The problem: I send 4 TCP packets, while I should send 1 TCP packet with all 4 chars.
Thanks for your help.

TCP data flow is not packet oriented, rather that is detail hidden in the implementation itself; a properly implemented TCP server must accept data arriving in any combination of packets, including one character per packet, words or lines broken between packets, packets that contain the end of one thing and the start of another, etc.

You can try sending all characters in a single print() but you're basically trying to use undocumented behavior of one thing to accommodate erroneous behavior of another.

Sounds like the problem is on the receiving end. Try shift/or-ing all values into one unsigned long and send that with one call to print.

Use UDP if you want to send a data that fit in a single packet. TCP is costly due to the overhead of open/close a sesion.

After searching and experimenting on this, I believe the short answer to the question is that you need to send the command string like a buffer of characters AND put your Hex Coded command for the LED controller as an escaped string of characters.
Here is my code (it toggles the LED Controller between Green and Blue every 5 seconds, but you can extend this for other commands and colors as described at http://jpelectron.com/sample/Electronics/WiFi%20LED%20control/):
/*
Send Commands to LED Controller via Wifi Network and Wemos D1 Board
*/
#include <ESP8266WiFi.h>

const char* ssid     = "***yourWifiSSID***"; //Change this value for your network
const char* password = "***yourWifiPassword***"; //Change this value for your network
boolean connected = false;
boolean colorToggle = false;

void WiFiEvent(WiFiEvent_t event) {
    //Serial.printf("[WiFi-event] event: %d\n", event);

    switch(event) {
    case 3:
        Serial.println("WiFi connected");
        Serial.println("IP address: ");
        Serial.println(WiFi.localIP());
        connected = true;
        break;
    case 6:
        Serial.println("WiFi lost connection");
        connected = false;
        break;
    }

    // 0 : WL_IDLE_STATUS when Wi-Fi is in process of changing between statuses
    // 1 : WL_NO_SSID_AVAILin case configured SSID cannot be reached
    // 3 : WL_CONNECTED after successful connection is established
    // 4 : WL_CONNECT_FAILED if password is incorrect
    // 6 : WL_DISCONNECTED if module is not configured in station mode

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    Serial.begin(115200);
    WiFi.disconnect(true);
    delay(1000);
    WiFi.onEvent(WiFiEvent);
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("");
    Serial.print("Connected to ");
    Serial.println(ssid);
    Serial.print("IP address: ");
    Serial.println(WiFi.localIP());

}

// the loop function runs over and over again forever
void loop() {
    //if we are connected
    if(connected){
      digitalWrite(LED_BUILTIN, LOW); //Turn on LED on the Board
      turnLEDSOn();
    }
    else
    {
      digitalWrite(LED_BUILTIN, HIGH); //Turn off LED on the Board
      setup();
    }
}

void turnLEDSOn() {
    const uint16_t port = 5577;
    const char * host = "192.168.10.2";  //Change to whatever your LED Controller IP is

     WiFiClient client;

     if (client.connect(host, port)) //Try to connect to TCP Server
     {
        Serial.println("Connected to LED Controller... ");
        if (colorToggle)
        { //Green
          char command[] = "\x31\x00\xff\x00\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = false;
          delay(5000);
        }
        else
        { //Blue
          char command[] = "\x31\x00\x00\xff\x00\x00\xf0\x0f\x2f";
          client.write((uint8_t *)command, sizeof(command));
          colorToggle = true;
          delay(5000);
        }

        Serial.println("Command sent ... "); // command is the color or animation sent to the LED controller
     }
     else
     {
        Serial.println("connection failed ... ");
     }

      if (client.available())
      {
        //Read from LED Controller
        char c = client.read();
        Serial.print(c);
      }

      if (!client.connected())
      {
        Serial.println();
        Serial.println("disconnecting ... ");
        client.stop();
        for(;;);
      }
}


text:
Compilation Error: "cannot declare 'client' to be of abstract type 'Client'"
I know, it isn't my original code, but I'm using this for a larger project that I am currently working on. I keep getting this error message: "cannot declare 'client' to be of abstract type 'Client'".
here's the code:

// RoboSapienServer.cpp
// RobosapienServer - Web enable a RoboSapien
// Kevin N. Haw
// http://www.KevinHaw.com/RoboSapienServer.php

// This project combines the default webserver example in the IDE distribution and Karl Castleton's(http://home.mesastate.edu/~kcastlet) RoboSapienIR (http://playground.arduino.cc/Main/RoboSapienIR).
// Source code merged from those two sources.

// Include files
#include <Ethernet.h>
#include <string.h>
#include <WebServer.h>

//////////////////////////////////////////////////////////////////
// Begin Web Server specific variable deinitions
//////////////////////////////////////////////////////////////////

byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

// KNH, 02/09/2010 - Change IP address to use local subnet at home
//byte ip[] = { 10, 0, 0, 177 };
byte ip[] = { 192, 168, 1, 177 };

// Server for web requests
EthernetServer server(80);

// Define field name in the submitted form
#define SUBMIT_BUTTON_FIELDNAME "RSCmd"

// String for HTTP request variables
char pcHttpReqRsCmd[20] = {'\0'};

volatile int viRobsapienUrlCmd = -1;  // A robosapien command sent over the URL of a webpage HTTP request

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific variable deinitions
//////////////////////////////////////////////////////////////////

// Some but not all RS commands are defined
#define RSTurnRight       0x80
#define RSRightArmUp      0x81
#define RSRightArmOut     0x82
#define RSTiltBodyRight   0x83
#define RSRightArmDown    0x84
#define RSRightArmIn      0x85
#define RSWalkForward     0x86
#define RSWalkBackward    0x87
#define RSTurnLeft        0x88
#define RSLeftArmUp       0x89
#define RSLeftArmOut      0x8A
#define RSTiltBodyLeft    0x8B
#define RSLeftArmDown     0x8C
#define RSLeftArmIn       0x8D
#define RSStop            0x8E
#define RSWakeUp          0xB1
#define RSBurp            0xC2
#define RSRightHandStrike 0xC0
#define RSNoOp            0xEF

// Subset of additional codes pulled from http://www.contrib.andrew.cmu.edu/~ebuehl/robosapien-lirc/ir_codes.htm
#define RSRightHandSweep  0xC1
#define RSRightHandStrike2 0xC3
#define RSHigh5           0xC4
#define RSFart            0xC7
#define RSLeftHandStrike  0xC8
#define RSLeftHandSweep  0xC9

#define RSWhistle         0xCA
#define RSRoar            0xCE

int IRIn = 2;            // We will use an interrupt
int IROut = 3;           // Where the echoed command will be sent from

boolean RSEcho = true;    // Should Arduino Echo RS commands
boolean RSUsed = true;    // Has the last command been used
volatile int RSBit = 9;   // Total bits of data
volatile int RSCommand;   // Single byte command from IR
int bitTime = 516;        // Bit time (Theoretically 833 but 516)
// works for transmission and is faster
int last;                 // Previous command from IR

//////////////////////////////////////////////////////////////////
// Begin Robosapien specific code
//////////////////////////////////////////////////////////////////

// Receive a bit at a time.
//  NOTE: Unused in the RoboServer aplication
void RSReadCommand() {
  delayMicroseconds(833 + 208); // about 1 1/4 bit times
  int bit = digitalRead(IRIn);
  if (RSBit == 9) { // Must be start of new command
    RSCommand = 0;
    RSBit = 0;
    RSUsed = true;
  }
  if (RSBit < 8) {
    RSCommand <<= 1;
    RSCommand |= bit;
  }
  RSBit++;
  if (RSBit == 9) RSUsed = false;
}

// send the whole 8 bits
void RSSendCommand(int command) {
  digitalWrite(IROut, LOW);
  delayMicroseconds(8 * bitTime);
  for (int i = 0; i < 8; i++) {
    digitalWrite(IROut, HIGH);
    delayMicroseconds(bitTime);
    if ((command & 128) != 0) delayMicroseconds(3 * bitTime);
    digitalWrite(IROut, LOW);
    delayMicroseconds(bitTime);
    command <<= 1;
  }
  digitalWrite(IROut, HIGH);
  delay(250); // Give a 1/4 sec before next
}

// Set up RoboSpapien functionality
void RSSetup()
{
  pinMode(IRIn, INPUT);
  pinMode(IROut, OUTPUT);
  pinMode(10, OUTPUT);
  digitalWrite(IROut, HIGH);

  attachInterrupt(0, RSReadCommand, RISING);

  last = RSNoOp;

  // Make robot burp to indicate setup is complete
  RSSendCommand(RSBurp);

}

// Loop for RoboSapien functionality
// Write only functionality - send the command from the web page to the robot, ignoring any input from the remote
void RSLoop()
{
  // Has a new command come in from the server?
  if (viRobsapienUrlCmd != -1)
  {
    // New command - send it to robot
    Serial.print("Sending command to RoboSapien: ");
    Serial.println(viRobsapienUrlCmd, HEX);
    RSSendCommand(viRobsapienUrlCmd);

    // Now clear command
    viRobsapienUrlCmd = -1;
  }
}

//////////////////////////////////////////////////////////////////
// Begin Webserver Specific Code
//////////////////////////////////////////////////////////////////

// Print ourt MIME and HTML header at top of webpage
void HtmlHeader(Client client)
{
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println();
  client.println("\n");
  client.println("  <TITLE>Kevin's Arduino Webserver</TITLE>");//
  //  client.println("  <META HTTP-EQUIV=\"refresh\" CONTENT=\"5\">");
  client.println("");
}

// Print the footer at the bottom of the webpage
void HtmlFooter(Client client)
{
  client.println("");
}

// Print a submit button with the indicated label wrapped in a form for the indicated hex command
void SubmitButton(Client &client, char *pcLabel, int iCmd)
{
  client.print("<form method=post action=\"/?");
  client.print(iCmd, HEX);
  client.print("\"><input type=submit value=\"");
  client.print(pcLabel);
  client.print("\" name=\"" SUBMIT_BUTTON_FIELDNAME "\">");
  client.println("</form>");
}

// Parse an HTTP request header one character at a time, seeking string variables
void ParseHttpHeader(Client &client)
{
  char c;

  // Skip through until we hit a question mark (first one)
  while ((c = client.read()) != '?' && client.available())
  {
    // Debug - print data
    Serial.print(c);
  }

  // Are we here for a question mark or did we run out of data?
  if (client.available() > 2)
  {
    char pcUrlNum[3], *pc;

    // We have enough data for a hex number - read it
    for (int i = 0; i < 2; i++)
    {
      // Read and dump data to debug port
      Serial.print(c = pcUrlNum[i] = client.read());
    }
    // Null terminate string
    pcUrlNum[2] = '\0';

    // Get hex number
    viRobsapienUrlCmd = strtol(pcUrlNum, &pc, 0x10);
  }

  // Skip through and discard all remaining data
  while (client.available())
  {
    // Debug - print data
    Serial.print(c = client.read());
  }
}

// Set up webserver functionality
void WebServerSetup()
{
  Ethernet.begin(mac, ip);
  server.begin();
}

// Web server loop
void WebServerLoop()
{
  Client client = server.available();
  boolean bPendingHttpResponse = false; // True when we've received a whole HTTP request and need to output the webpage
  char c;  // For reading in HTTP request one character at a time

  if (client) {
    // Loop as long as there's a connection
    while (client.connected()) {
      // Do we have pending data (an HTTP request)?
      if (client.available()) {

        // Indicate we need to respond to the HTTP request as soon as we're done processing it
        bPendingHttpResponse = true;

        ParseHttpHeader(client);
      }
      else
      {
        // There's no data waiting to be read in on the client socket.  Do we have a pending HTTP request?
        if (bPendingHttpResponse)
        {
          // Yes, we have a pending request.  Clear the flag and then send the webpage to the client
          bPendingHttpResponse = false;

          // send a standard http response header and HTML header
          HtmlHeader(client);

          // Put out a text header
          client.println("
Kevin's RoboSapien Webserver
");

          client.println("

");
          client.println("");

          // Create buttons
          SubmitButton(client, "WakeUp", RSWakeUp);
          SubmitButton(client, "Roar", RSRoar);
          SubmitButton(client, "Whistle", RSWhistle);
          SubmitButton(client, "High5", RSHigh5);
          client.println("
");

          client.println("	");

          SubmitButton(client, "LeftArmUp", RSLeftArmUp);
          SubmitButton(client, "LeftArmIn", RSLeftArmIn);
          SubmitButton(client, "LeftArmOut", RSLeftArmOut);
          SubmitButton(client, "LeftArmDown", RSLeftArmDown);
          SubmitButton(client, "LeftArmSweep", RSLeftHandSweep);
          client.println("
");

          client.println("	");

          SubmitButton(client, "RightArmUp", RSRightArmUp);
          SubmitButton(client, "RightArmIn", RSRightArmIn);
          SubmitButton(client, "RightArmOut", RSRightArmOut);
          SubmitButton(client, "RightArmDown", RSRightArmDown);
          SubmitButton(client, "RightArmSweep", RSRightHandSweep);
          client.println("
");

          client.println("

");

          client.print("

URL Hex no: ");
          client.print(viRobsapienUrlCmd, HEX);
          client.println("
");

          // send HTML footer
          HtmlFooter(client);

          // give the web browser time to receive the data
          delay(1);
          client.stop();
        }
      }
    }  // End while(connected)
  }
}

//////////////////////////////////////////////////////////////////
// Begin arduino entry points
//////////////////////////////////////////////////////////////////

void setup()
{
  // open the serial port at 9600 bps:
  Serial.begin(9600);

  // Print greeting
  Serial.println("Kevin's RobSapien Server");

  RSSetup();
  WebServerSetup();
}

void loop()
{
  RSLoop();
  WebServerLoop();
}

You can't use Client directly like that.  It's just an abstract class.  You have to use one of the classes like EthernetClient or WiFiClient that implements it.
Client is like a shell of a class.  It says that there will be classes that act as clients and will have this basic form.  But it doesn't have any code, just the outline.  The base classes that implement that abstract class like EthernetClient or WiFiClient actually have the code to actually BE a client.

I would guess the problem lies here:
void HtmlFooter(Client client) {
    client.println("");
}

(Also the HtmlHeader function)
When you call that function you make a new Client object and copy the contents of your existing object into it. Since Client is pure virtual you can't do that. Instead you should be working with a reference as in the other functions:
void HtmlFooter(Client &client) {
    client.println("");
}


text:
Servo FS5106B does not work properly
I was testing out my new Servo FS5106B. Here is the code I used:
#include <Servo.h>

Servo servo;
void setup()
{
    servo.attach(10);
}

void loop()
{
    servo.write(0);
    delay(1000);
    servo.write(180);
    delay(1000);
}

After I upload the sketch, the console says:

Sketch uses 2872 bytes (1%) of your device memory. Total available 253952 bytes. Global variables use 161 bytes (1%) of the dynamic memory, leaving 8031 bytes for local variables. Maximum 8192

The delay between the rotations wasn't 1 second (as I was expecting), but 13 seconds (when I connect only a LED and use the delay function, everything works perfectly). Why is that happening?
P.S The power source for the servo is my Arduino-Mega 2560, wich outputs 5V. The model I use for wiring is:
Edit 1:
I tried to execute the program that @ChrisStratton suggested, here an updated code
#include <Servo.h>
#define led 22

Servo servo;

void setup()
{
    Serial.begin(9600);
    while(!Serial)
        delay(10);

    Serial.println("Start!");
    pinMode(led, OUTPUT);
    servo.attach(10);
}

void loop()
{
    digitalWrite(led, HIGH);
    servo.write(0);
    delay(1000);
    digitalWrite(led, LOW);
    servo.write(180);
    delay(1000);
}

When this program loads, servo does 2 rotations in 0.4 seconds and the LED goes high and low really fast, then anything changes for another 10 seconds, then again the LED goes high and low and the Servo does 2 rotations

Please give a small but working sketch. I can not compile this. The stall current of the FS5106B is about 1A, the Arduino 5V pin can not supply that.

It is critical that your post contain the exact code tested.  Obviously the posted code cannot build, which means it could not have been tested.  You need to use the "edit" button to post the exact code you tested, and you need to include a description of your wiring and the power source for the servo.  But before you do any of that, make an experimental version which blinks an LED at 1 second intervals without any connection to a servo, and make sure that interval is approximately correct.

@Jot Changed my code

@ChrisStratton Changed my code to the one I was testing with exactly

And the rest of what is missing?

@ChrisStratton It is the hole code

Reread, it's not just code that was missing from your post.  And there was an experiment you were supposed to run.

@ChrisStratton Modified my answer, was this what you meant?

No, please reread the original two comments.

@ChrisStratton Added everything you asked for. Excuse me for not reading your full comment

In the official Arduino examples, a servo motor is powered by the 5V pin of the Arduino board. In real life, that is a bad idea.
Your FS5106B has specified about 1A stall current. The average current is less than that, but the start peak current could indeed be 1A.
Could you try to use a seperate power supply of 5V (or 6V) for the servo motor ?
To check if the Arduino resets, you could do a Serial.begin(9600); in setup, directly followed by Serial.println("the sketch has started");
Some servo motors require different timing. That would not explain the 13 seconds delay, so I assume that your servo motor has normal timing.
Do you use a breadboard ? Sending a current peak through a breadboard (with bad contacts) can cause a lot of voltage spikes.
(To the other problem solvers: I'm ignoring the 13 seconds and assume that once in a while the servo motor is able to start, just a guess, I could be wrong).
[ADDED]
@ChrisStratton is trying to tell you this:
void setup()
{
  pinMode( LED_BUILTIN, OUTPUT);
}

void loop()
{
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

The next step would be:
#include <Servo.h>

Servo servo;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);
}

[ADDED2]
Or even more fun, with a counter (as @ChrisStratton wrote):
#include <Servo.h>

Servo servo;

unsigned int counter;

void setup()
{
  Serial.begin(9600);
  Serial.println("The sketch has started");
  pinMode( LED_BUILTIN, OUTPUT);
  servo.attach(10);
}

void loop()
{
  servo.write(0);
  digitalWrite( LED_BUILTIN, HIGH);
  delay(1000);

  servo.write(180);
  digitalWrite( LED_BUILTIN, LOW);
  delay(1000);

  Serial.print("Still alive after ");
  Serial.print(counter);
  Serial.println(" seconds");
  counter += 2;   // two seconds per loop iteration
}

The serial output on start is a good idea, but if the servo motor is causing the arduino to brown out, depending on if the USB port / chip are also involved, the serial device may keep dissapearing and so subsequent output may not be obtained. It might be better to have the Arduino print out "still alive after " and a running count - that way the messages would indicate success in the case where they could be seen. This could then be run with the motor removed from the circuit, with it powered by an external supply having only a common ground, or (dubiously) with Arduino/USB power.

@ChrisStratton Tried your suggestion, modified my question.

You were supposed to try it first without the servo connected.  Also you don't seem to be monitoring the serial output Jot suggested, but it would be even better if you generated output in between each operation in the loop.

@ChrisStratton I tried it without the servo connected and it worked. I actually wrote it in my question > (when I connect a LED and use the delay function, everything works perfectly)

Sounds like you have a power problem. As we've been saying, you shouldn't try to power a servo through an Arduino.

@ChrisStratton I tried another power supply (6V), and it did not work either. Do you think the servo is broken?


text:
Interrupt problem...?
I am working on a code including interrupts. They, however, refuse to work, even in this simple code that could be the most basic example of interrupts.
In this simplified extract I have a momentary push button attached to an Arduino Pro Mini's PIN 2, with the other side grounded. I have this code uploaded:
#include <Encoder.h>   // is this library the cause??...

#define PIN_1 4
#define PIN_2 3 //interrupt pin    //using these for a rotary encoder, not in this extract
#define PIN_B 2 //interrupt pin    // the rotary encoder also works as a push-button

void setup() {
  pinMode(PIN_B, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(PIN_B, ButtonPressISR, FALLING);
  attachInterrupt(PIN_B, ButtonReleaseISR, RISING);
}

void loop() {
  Serial.println("Don't interrupt me");
  delay(10);
}

void ButtonPressISR() {
  Serial.println("Yay, I'm pressed!");
  delay(1000);
}

void ButtonReleaseISR() {
  Serial.println("Yay, I'm released!");
  delay(1000);
}

One would expect that without action, the Arduino floods the serial console with "Don't interrupt me". And that's correct.
When I press the button, however, nothing on Earth happens, neither of the interrupt service routines starts. No matter how hard I try, "Yay, I'm pressed" and "Yay, I'm released" never appears on the console output, and the 1 s delay never happens.
The circuit, shown below, is tested with a multimeter, and is error-free. Pin 2 does get pulled down, and back, upon button press/release.

simulate this circuit – Schematic created using CircuitLab

Generally, Serial.println() does not work correctly from within an ISR, as println() uses interrupts itself

I believe adding the 2nd interrupt disables the first. Use a single interrupt with CHANGE. Also, digitalPinToInterrupt() might help.

@JamesWaldby-jwpat7 thanks. But does this explain the lack of the 1 sec delay as well? i.e. does the ISR fails completely as is because of println()?

Neinstein, you missed what @JohnnyMopp is saying. Number '2' or '3' are not valid interrupts for the Pro Mini. The function digitalPinToInterrupt is preferred. https://www.arduino.cc/en/Reference/AttachInterrupt (read the whole page). No one sets two interrupts for a single pin, it does not work, a CHANGE does work. Set a volatile byte in the ISR and use that byte in the loop. If you have an encoder, why not use the Encoder library that you have already downloaded ? https://www.pjrc.com/teensy/td_libs_Encoder.html

@jot the Encoder libary does not support buttons AFAIK.

For the Arduino it is often not needed to use interrupts for buttons. For an embedded system, it is normal to connect buttons to interrupts, but it is not normal for the Arduino. When interrupts are needed, the sketch might be written in a bad way. The Bounce2 library handles button bounching and has useful functions: https://github.com/thomasfredericks/Bounce2 It uses normal digital inputs with digitalRead, no interrupts, and millis for debouncing.

Neither delay or print should be used in an interrupt routine as they use interrupts themselves, instead set a flag (usually a volatile variable) and test for that in the loop. Also be aware that due to contact bounce the interrupt will trigger multiple times for each button press.

They, however, refuse to work,

more accurately, you are unable to make them work.

don't delay large amount of time;
be careful with calling routines that are also called outside of the isr;
one isr for one pin.


text:
Why is the T2 transistor used in Arduino Micro?
I was about to design a small custom board using ATmega32U4, replicating the Arduino Micro. I know that T1 is used to block VUSB when VIN is connected.
But why T2? The gate is 5V, so it will be always OFF! Or does it act as a diode?
Schemtic https://www.arduino.cc/en/uploads/Main/arduino-micro-schematic.pdf

T1 and T2 implement a power supply ORing of the VUSB and VIN voltages. Read this for extended information.
The body diode of each MOSFET performs the basic ORing function. When the MOSFET is turned OFF it just behaves as a diode. But when the MOSFET is turned ON, the diode is shorted by the conduction channel, thus avoiding its voltage drop (and achieving a behaviour closer to an ideal diode).
So:

When VUSB is present and VIN is not connected (but pulled down to ground by R9), T1 turns ON and the +5V rail is connected to VUSB. Also, T2 turns OFF and the regulator input is isolated from VIN and the regulator simply doesn't operate (thus, avoiding a potential conflict because its output +5V is being forced to VUSB).
When VUSB is not connected and VIN is present, T1 turns OFF and VUSB is isolated from the +5V rail. Also T2 turns ON and VIN is connected to the regulator input, which then regulates the voltage down into the +5V rail.
When both VUSB and VIN are connected, the behaviour is the same as in case 2 above. Because VIN is supposed to be >7V and VUSB approx 5V, T1 will isolate VUSB and avoid a conflict with the regulator output. Also, a VIN >7V will allow T2 to turn on hard enough to bypass the body diode and avoid its voltage drop.

i got it. Could you please tell why "7V" in 3rd case?

The input voltage VIN for the Arduino Micro is specified in the 7-12 V range.

So it could be any volt that can be handled by voltage regulator?

The input capacitor probably can't withstand as much voltage as the regulator itself. I wouldn't operate the Micro outside its recommended voltage range.

It's known as a "zero drop-out diode". When the power is first applied the body diode of the MOSFET conducts and powers the system. That imposes a (roughly) 0.7V drop on the input voltage.
Once the power gets through the regulator and is regulated to 5V that is then fed back into the gate of the MOSFET, which turns it on (as long as -5V is above the source voltage less the diode drop, so -5.7V minimum [it's a P channel so thresholds etc are negative]). That then bypasses the internal body diode getting rid of the 0.7V drop.
If the input voltage is too low the 5V gate no longer turns the MOSFET on and the body diode blocks any reverse current.


text:
Arduino RS232 Shield with SD Card conflict
I have an Arduino Mega with a Ethernet2 Shield + RS232 Shield
SD Card works well with Ethernet2 Shield, but it get a conflict when I add the RS232 Shield.
Both hardware use the same PIN:
#define RS232_DIR_PIN     4 // RS232 Shield
#define AMS_SS_SD         4 // Ethernet Shield

 pinMode(RS232_DIR_PIN, OUTPUT);             //Set RS232 direction pin as output
    digitalWrite(RS232_DIR_PIN, LOW);           //Set RS232 chip as receiver

    //Set SPI to Read SD Card
    pinMode(AMS_SS_HARDWARE, OUTPUT);
    digitalWrite(AMS_SS_HARDWARE, HIGH);

I dont need both running at same time, but I dont know how to make only one work at a time.

You will need to physically modify one of these to use different pins.

@ChrisStratton, do you know wich pin I could use for them? for Arduino Mega

Probably any available I/O, it's more a mechanical issue of what you can access.

@ChrisStratton, it worked, just moved the RS232 Pin to 5 physically. Set this as an answer. thanks


text:
Can I power my shift register with a 12V external power supply and connect only the data, strobe and clear pins to the Arduino digital pins?
I'm using a CD4094 shift register to power my LEDs along with a ULN2003A darlington transistor array. I want to hook up the LEDs to an external power supply of 12V (common anode).
The cathodes of little groups of LEDs will be connected to the ULN2003A which is connected to the shift register which will get its data from the arduino (the digital pins which i assume work at 5V).
My question is, if I connect the Vdd pin of the shift register to the 12V external power supply, will it still function as intended through the Arduino?

No. CD4k devices reference their high and low voltages to a (mostly) fixed ratio of Vdd, so there will be no way for the Arduino to operate the device.
Consider using a TPIC6C595 instead, which combines the shift register and the high-voltage driver into a single device.

Is that TPIC drop-in compatible for a HEF4094?  Basically I'm trying to repair a display that uses these chips. My first goal is use the chip (acquired an extra from ebay) to drive ~8 LEDs off 1.  I realize this isn't the best way to learn (I'm trying to fix something, by first replicating parts of the circuit) and the biggest impediment is finding good examples to mimic and learn from.

@Crossfit_and_Beer: It's drop-in compatible with a 74HC595 (except for the whole OD bit), but I'm not sure it would substitute for something in the 4k series.

@Crossfit_and_Beer: Having looked at the datasheets now, you'd have to put it on an adapter to use it, and it still expects a 5Vish supply.

Good to know. I'll add (since there's a dearth of examples for this chip) that the "BP" chip version accepts a VDD (VCC) of up to 15V. Sadly while I have good reputation on other SE sites, I don't have rep "here" and cannot post questions yet, so a good definition of my problem will have to wait...


text:
GPS Logger Error
I have created a GPS logger code using DFRobot SIM808 library. The tcp code and getGPS codes are working fine. but when integrating the both the code, it failed to upload GPS data to thingspeak. It gets the IP connect to the server, but the get command is not working; and also the GPS data shown as a string. Can anyone please tell me where the problem is?
/*
### Connect TCP and send GET request.
1. This example is used to test DFRobot_SIM808 GPS/GPRS/GSM Shield's connect TCP and send GET request.
2. Open the SIM808_TCPConnection example or copy these code to your project
3. Download and dial the function switch to Arduino
4. Open serial helper
5. Waiting for a few minutes, until serial has sent "Connect mbed.org success"
6. Serial will send "Hello world!"

create on 2016/09/23, version: 1.0
by jason
*/
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    10
#define PIN_RX    11
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

//make sure that the baud rate of SIM900 is 9600!
//you can use the AT Command(AT+IPR=9600) to set it through SerialDebug

//DFRobot_SIM808 sim808(&Serial);

char buffer[512];

void setup(){
  mySerial.begin(2400);
  Serial.begin(2400);

  //******** Initialize sim808 module *************
  while(!sim808.init()) {
      delay(1000);
      Serial.print("Sim808 init error\r\n");
  }
  delay(3000);

  //*********** Attempt DHCP *******************
  while(!sim808.join(F("hutch3g"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //************* Turn on the GPS power************
  if( sim808.attachGPS())
      Serial.println("Open the GPS power success");
  else
      Serial.println("Open the GPS power failure");
  delay(2000);
}

void loop(){
//  gps();
  delay(2000);
  tcp();
  delay(2000);
}

void tcp(){
    //*********** Establish a TCP connection ************
  if(!sim808.connect(TCP,"api.thingspeak.com", 80)) {
      Serial.println("Connect error");
  }else{
      Serial.println("Connect mbed.org success");
  }

  //*********** Send a GET request *****************
    float lati=sim808.GPSdata.lat;
    float longi=sim808.GPSdata.lon;

    char http_cmd[100];
    sprintf(http_cmd, "GET https://api.thingspeak.com/update?api_key=FF19NVWMPZEWX0XK&field2=%s&field3=%s HTTP/1.0\r\n\r\n\0", lati, longi);

    boolean retValue = true;
    sim808.send(http_cmd, strlen(http_cmd));
    int ret = sim808.recv(buffer, sizeof(buffer)-1);
    if (ret <= 0){
        Serial.println("error receiving");
        retValue = false;
    }
    buffer[ret] = '\0';
    Serial.print(buffer);

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
}

//void gps() {
//   //************** Get GPS data *******************
//   if (sim808.getGPS()) {
//    Serial.print(sim808.GPSdata.year);
//    Serial.print("/");
//    Serial.print(sim808.GPSdata.month);
//    Serial.print("/");
//    Serial.print(sim808.GPSdata.day);
//    Serial.print(" ");
//    Serial.print(sim808.GPSdata.hour);
//    Serial.print(":");
//    Serial.print(sim808.GPSdata.minute);
//    Serial.print(":");
//    Serial.print(sim808.GPSdata.second);
//    Serial.print(":");
//    Serial.println(sim808.GPSdata.centisecond);
//    Serial.print("latitude :");
//    Serial.println(sim808.GPSdata.lat, 6);
//    Serial.print("longitude :");
//    Serial.println(sim808.GPSdata.lon, 6);
//    Serial.print("speed_kph :");
//    Serial.println(sim808.GPSdata.speed_kph);
//    Serial.print("heading :");
//    Serial.println(sim808.GPSdata.heading);
//    Serial.println();
//
//    //************* Turn off the GPS power ************
//    sim808.detachGPS();
//  }
//}

First, I would assume you need to call sim808.getGPS() to update the GPS data. Not sure why you commented that out.
Normally, when building a GET command, you don't include the url (unless going through a proxy).
Last, you need to use %f with sprintf to format a floating point value.
Something like this might work:
void tcp()
{
    // Update the GPS data
    float lati, longi;
    if (sim808.getGPS()) {
        lati = sim808.GPSdata.lat;
        longi = sim808.GPSdata.lon;
        sim808.detachGPS();
    }
    else {
        // No gps, abort
        return;
    }

    //*********** Establish a TCP connection ************

    if (!sim808.connect(TCP,"api.thingspeak.com", 80)) {
       Serial.println("Connect error");
       return;
    }
    else {
       Serial.println("Connect mbed.org success");
    }

   //*********** Send a GET request *****************

    char http_cmd[100];
    sprintf(http_cmd, "GET /update?api_key=FF19NVWMPZEWX0XK&field2=%f&field3=%f HTTP/1.0\r\n\r\n\0", lati, longi);
    sim808.send(http_cmd, strlen(http_cmd));
    int ret = sim808.recv(buffer, sizeof(buffer) - 1);
    if (ret <= 0){
        Serial.println("error receiving");
    }
    else {
        buffer[ret] = '\0';
        Serial.print(buffer);
    }

    //************* Close TCP or UDP connections **********
    sim808.close();

    //*** Disconnect wireless connection, Close Moving Scene *******
    sim808.disconnect();
}

Thanks a lot, man! I 'll check this and let you know! Thanks again!


text:
'Class SdFat' error message with Adafruit wave shield
I'm using Arduino Uno and Adafruit Wave Shield, with the WaveRP library.
I was able to run the example programs of the waveRP library, but I try to connect a mic to the shield, didn't go well, so I returned to one of the examples to verify if the shield was working well and now is showing me this error message. I damaged the shield?
> Arduino:1.8.2 (Mac OS X), Tarjeta:"Arduino/Genuino Uno"
>
> Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:
> In function 'void setup()': dapRP:31: error: 'class SdFat' has no
> member named 'init'    if (!sd.init(SPI_FULL_SPEED))
> sd.initErrorHalt();
>
>            ^ Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:
> In function 'void play(SdBaseFile*)': dapRP:67: error: no matching
> function for call to 'SdBaseFile::readDir(dir_t&)'    while
> (dir->readDir(dirBuf) > 0) {    // Read every file in the directory
> one at a time
>
>                              ^ Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:67:29:
> note: candidate is: In file included from
> Documents/Arduino/libraries/SdFat/SdFile.h:24:0,
>                  from  Documents/Arduino/libraries/SdFat/SdFat.h:38,
>                  from Documents/Arduino/libraries/Adafruit_waverp/WaveRP.h:22,
>                  from Documents/Arduino/libraries/Adafruit_waverp/examples/dapRP/dapRP.pde:4:
> Documents/Arduino/libraries/SdFat/SdBaseFile.h:325:10: note: int8_t
> SdBaseFile::readDir(dir_t*)    int8_t readDir(dir_t* dir);
>
>           ^ Documents/Arduino/libraries/SdFat/SdBaseFile.h:325:10: note:   no known conversion for argument 1 from 'dir_t {aka
> directoryEntry}' to 'dir_t* {aka directoryEntry*}' exit status 1
> 'class SdFat' has no member named 'init'
>

No, you didn't break the shield. That is a software error - a problem in your sketch. If it's an unmodified example maybe you need to reinstall the library.

@Majenko I reinstalled both libraries the SdFat one and the WaveRP, but it keeps saying the same


text:
Arduino UNO two SoftwareSerial ports communication
I am working on a project involving bluetooth and wifi communications. Both of them are wired up to the Arduino and communicate to it using two software serial port.
The scenario is the one in the picture attached.
What I am doing is:

retrieve the sensor value
send it from the BT slave module to the master one (wired up to Arduino)
take it and send it, using AT commands, through the WIFI channel (the WIFI module is a ESP8266-01) to a web server.

The problem is that if I start listening to the BT serial port (BTSerial.listen()) I am not able to properly send the sensor values through the WIFI connection. But if I comment out the lines related to the BT sotware serial, and try to send fixed value to the web server, the sending terminates succesfully.
In my opinion there are some problems with the BTSerial.listen() and WIFISerial.listen() calls, since they are not able to switch from one the the other correctly.
I saw the TwoSerialPort example provided into the Arduino IDE and I tried to apply it into my code but it still not works to me.
Does anyone have a idea which would be the problem? Does anyone already faced with this problem or a similar one?
Hoping to be as much clear as possible, thanks in advance to anyone would help me.
Filippo
[EDIT] Added two code snippets
// This method prepares the AT commands will be send to the ESP8266-01 module in order to upload the values on the web server
void send2server(String ip, int port, String file, int t, int h, int p) {

  String queryString = "temp=";
  queryString.concat(t);
  queryString.concat("&hum=");
  queryString.concat(h);
  queryString.concat("&press=");
  queryString.concat(p);
  Serial.println(queryString);

  // Prepare and exec the AT+CIPSTART command provideing the TCP connection init
  String CIPSTART_cmd = "AT+CIPSTART=\"TCP\",\"" + ip + "\"," + port + "";
  exec_cmd(CIPSTART_cmd, 1000);

  // Prepare the POST request
  String httpPOST_cmd = "POST /";
  httpPOST_cmd.concat(file);
  httpPOST_cmd.concat(" HTTP/1.1\r\n");
  httpPOST_cmd.concat("Host: ");
  httpPOST_cmd.concat(ip);
  httpPOST_cmd.concat("\r\n");
  //httpPOST_cmd.concat("Accept: */*\r\n");
  httpPOST_cmd.concat("Content-Length: ");
  httpPOST_cmd.concat(queryString.length());
  httpPOST_cmd.concat("\r\n\r\n");
  //httpPOST_cmd.concat("Content-Type: text/html\r\n\r\n");
  httpPOST_cmd.concat(queryString);

  // Calculate the POST request length
  unsigned int len = httpPOST_cmd.length();

  // Prepare and exec the AT+CIPSEND statement with the POST request length just calculated
  String CIPSEND_cmd = "AT+CIPSEND=";
  CIPSEND_cmd.concat(len);
  exec_cmd(CIPSEND_cmd, 1000);

  // Exec the HTTP POST request
  exec_cmd(httpPOST_cmd, 1000);

  // Close the connection
  exec_cmd("AT+CIPCLOSE", 1000);
}

// This method execute each AT command in the previuous method
void exec_cmd(String cmd, int delayTime) {
   byte i = 0;

   while(1) {
      Serial.println("invio comando");
      WIFISerial.println(cmd);
      while(WIFISerial.available()) {
         if(WIFISerial.find("OK")) {
            i = 8;
         }
      }
      delay(delayTime);

      if(i > 5)
         break;

      i++;
   }

   if(i == 8) {
      Serial.println("OK");
      //return true;
   } else {
      Serial.println("ERRORE");
      //return false;
   }
}

The problem is the code goes properly till the AT+CIPSEND command, then the POST request is sent but no good feedback arrives, ending with the "ERRORE" error message.

[EDIT 2] Attached serial monitor output
This is the serial monitor output when I execute the skecth. It seems to work properly but it does not upload any value.

SoftwareSerial is poor at best. With two it's poor squared.

You can't use two instances of the normal software serial.  Probably you best bet is to drop the Arduino and instead run your sketch on the ESP8266, with that talking to the BT.  Or use nRF24L01's to link the sensors instead of BT.

Arduinos now come in so many configurations and use so many different processors you now need to specify exactly what you are using.  If a processor has only 1 hardware serial port you will have to implement the 2nd serial port in software.  There are different libraries to use for this.  Needless to say, a software implemented serial port is not as good (fast) as a hardware serial port.  As you can see, there is more to programming serial ports on Arduinos then simply instantiating another instance of the standard serial port library. Goodby software. Welcome to firmware.

This answer provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

Use the HardwareSerial port (i.e., Serial) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.
Use AltSoftSerial for the other device.  It is the most efficient software serial port, and it can be used at the same time as Serial.  It only works on two specific pins.
NeoSWSerial is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on NeoSWSerial prevents them from receiving.
SoftwareSerial is the worst choice.  Receiving or transmitting on SoftwareSerial prevents all of the above from receiving anything.  It disables interrupts for long periods of time.

UPDATE - Here is the most reliable configuration:

Your code will have something like this:
#include <AltSoftSerial.h>
AltSoftSerial BT; // 8 is RX, 9 is TX

#define WIFI Serial  // 0 is RX, 1 is TX (disconnect 0 to upload new sketch)

void setup()
{
  WIFI.begin( 115200 );
  BT.begin( 9600 );
}

void loop()
{
  if (BT.available) {
    char c = BT.read();
    // do something with the character
       ... save them until '\n' arrives?
         ... then parse some values?

    if (values all received) {
      Serial.print( F("Sending values") ); // this is the WIFI port, but
          //  the ESP8266 ignores this debug print because it doesn't
          //  start with "AT".

      WIFI.println( F("AT+ ...") ); // all the AT commands
          ...
      WIFI.print( btValue1 );    // and the BT values
          ...
    }
  }
}

Thanks for the replies @slash-dev. If I understand correctly, using NeoSWSerial I would be able to receive data on the BT serial and transmit it towards the WIFI module over the WIFI serial simultaneously. Am I right or not?

And if so, is there a guide or a tutorial on NeoSWSerial? Thanks again!!

@Filippo, so you're ignoring the two best choices?    You would have to create a NeoSWSerial instance with a RX pin for the BT TX, and a TX pin for the WIFI RX.  Right now, you can only transmit and receive simultaneously with the one NeoSWSerial that is "listening".  You could make another instance for the WIFI TX/BT RX.  Just like SoftwareSerial, NeoSWSerial can only listen to one pin at a time.  Srsly, use AltSoftSerial (pins 8 & 9) with Serial (pins 0 & 1) to avoid all these issues.

@Filippo, there is no "tutorial" for NeoSWSerial, because it is a drop-in replacement for Serial or SoftwareSerial.  Some extra info at the NeoSWSerial github page.  All these libraries are available from the Arduino IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries....

Already found either github page or library into the Arduino IDE, thanks @slash-dev.
I am trying to understand the test sketch in to the NeoSWSerial library in order to apply it into my project. But, since I am nquite new to Arduino, could you explain ti tom  me a little bit, please?
I have an Arduino UNO, so I got no Serial1, Serial2, ecc. ports. How can I apply your library to the scenario in the picture below?

@Filippo, the test sketch is for verifying the library, not an example for you.  Look at any example for Serial, AltSoftSerial or SoftwareSerial and it will work with NeoSWSerial.  I will add an update in my answer to show the best connections/libraries.

Huge thanks @slash-dev!!! My picture was just to give you an idea about the communication scenario, but I have the exactly same wirings than the ones in your schema.
Now I have a better idea about I have to do! Thanks again so much!!

Just a curiosity regarding the example in the code you posted above: what if I would use a software serial (e.g. AltSoftSerial or NeoSWSerial) instead of hardware serial (Serial) for the WIFI connection? Should it be possible?

@Filippo, you can only have one AltSoftSerial port, and it must be on two specific pins (8 & 9 for an UNO).  And as I said, "[NeoSWSerial] can be used with the above choices [i.e. AltSoftSerial], but transmitting on NeoSWSerial prevents them from receiving."  If you never transmit to the BT and the BT can run at 9600, 19200 or 38400, you could use NeoSWSerial for the BT.  Then you could use AltSoftSerial for the WIFI.  It won't be as reliable as the above configuration, because AltSoftSerial can affect NeoSWSerial reception, especially if AltSoftSerial is running above 38400.

Thanks @slash-dev! I wired up all the stuff as in the circuit you posted and used AltSoftSerial for the BT and the hardware serial (pin 0 and pin 1) for the WiFi. Despite all this I am not able to send the sensor value to the web server. I edit my initial question and added two snippets.
Any yours feedback would be strongly appreciated!!

Sorry, I don't know how to help with the AT commands, but I would suggest that you eliminate the String variables.  There's no reason to build up a big  String and call WIFI.println once.  Just print the pieces to WIFI, individually.  This will save a huge amount of RAM, which could be the problem.  The one exception is the Content-length.  I believe there is a mode where you can send the content and terminate it with ^Z (char 26), instead of sending the length first.  Maybe.

Thank you so much again @slash-dev. Your help was very very appreciated!
Just one more question: using the hardware serial port as a serial one for WIFI (#define WIFISerial Serial;), would not be the possibility the that the command for the ESP8266-01 module would be interpreted as simple prints on the serial monitor instead of the instruction for the module, leading to not actually producing the WIFI command

Yes, the ESP8266 commands would be visible in the Serial Monitor window, but they are only interpreted by the ESP8266.  It is the debug prints that must be ignored (not interpreted) by the ESP8266.  As long as they don't start with "AT", the ESP8266 should ignore them.  Or comment out all the debug prints to see if it starts working.  (I doubt it changes the behavior).  So you will see both debug prints and AT commands in the Serial Monitor window, but it doesn't matter.

Still it does not works fine for me, since the WIFISerial.println("AT+...") statements are only printed out onto the serial monitor window and they DO NOT produce any effective results about uploading values to the web server.
In my previuos connections (in which I used two SoftwareSerial ports, but commenting out the BT.begin(9600) statement), I used the exactly same code for the AT commands and it worked properly since the upload works fine (althought with fixed values).
I edited the intial post to attach to you the serial monitor output for a better comprehension.
Thanks again!!

Well, that doesn't make any sense to me... it seems to be replying "OK", but it doesn't actually send to the server?  A poor level-shifting circuit could affect the ESP8266.  Using [tt]Serial[/tt] means that there is extra loading on the TX and RX pins (0 & 1) from the on-board FTDI chip (for the USB).  You could try the alternative I suggested in the comment above:  "you could use NeoSWSerial for the BT. Then you could use AltSoftSerial for the WIFI."  This assumes you never send to the BT.


text:
ATtiny85 soft-latching, and sensor-waking: Are multiple switches differentiable by pin change interrupt?
I am using a vibration switch with a pin change interrupt on an ATTiny85 to wake the processor and run some code when the vibration switch grounds an input pin. The circuit is battery-powered, so sleep mode is important. I would now like to add another input switch (momentary pushbutton) between an internal pullup on the ATtiny and ground to use as a soft latching switch to accomplish on/mode/off (power-on/case-selection/power-off). I'd like the vibration-wake-sleep code to be one of the cases selectable by the pushbutton. The ATtiny85 has one hardware interrupt (pin2 aka INT0), and the rest are pin change interrupts available on the other I/O pins.
After reading around, my understanding is that the pin change interrupts cannot be separated to run pin-specific code, as they all trigger the same pin change interrupt effect. Is that correct?
To put it another way, do I need to put my pushbutton on the hardware interrupt pin, or can I put it on any old I/O pin and still be able to use the vibration switch on another I/O pin only when I select that mode, without it triggering the same effect as the pushbutton every time there's a vibration? Or is there a better way? I'm trying to minimize the number of components, as this is a space-constrained project. Thanks!

What does the vibration signal look like? Is it a one-shot pulse? If so, what is the minimum width?

The vibe switch physically consists of a helical coil of thin, springy wire that bounces against another piece of wire. So presumably its signal is a big bouncy mess that varies with the force and frequency of the vibration impact.

If you have one dedicated interrupt signal, and enable the shared pin change interupt for only one pin, then you have no ambiguity - the hardware ISR is caused by the dedicated pin, and the shared pin change ISR is caused by the only enabled pin change pin.
Where things get more complicated is if you enable more than one pin to trigger the pin-change interrupt.  In this case, either the ISR or whatever follows in cause from it will need to figure out which pin caused the interrupt.
Unless I'm overlooking it in the data sheet, the ATtiny pin change interrupts don't have a register which latches the causing condition, so you may have to look at the actual pin input register.   The catch is that things like contact bounce might make the causing signal no longer present at the exact instant you check it.  However, contact bounce is typically a more serious problem when releasing a contact than closing it.
Some things you can do:

In the ISR, don't actually do anything, but set an "interrupt happened" flag.  Then in the main program, poll the inputs for a while until you see one actually asserted, and act on that.  You should only need to stay awake for a small fraction of a second before you catch the responsible contacts closed when you are looking.
You could try to use a small capacitor to slow the rate at which the pullup resistor responds to the switch bouncing back open, in the hopes of  making sure that the causing condition is seen when the ISR itself looks.

In either case you will probably want to stay awake and keep the pin change interrupt disabled until the switch has been released, and for maybe a hundred milliseconds thereafter to let release bounces die out.  Then you can re-enable the interrupt and go back to sleep.
Do keep in mind that regardless if the MCU is awake or not, if someone wedges the product into packing material or something which holds the switch closed in opposition to the pullup resistor, then that pullup resistor itself may drain your battery over a few weeks/months.

Ah. Thanks. So I'm reading that as 'yes, use the hardware interrupt for your pooshbutton'

and b) barring that, here are some very interesting techniques that are tantalizingly just beyond your newb level which you will now probably spend countless hours nerding out on. I guess for now I will try to restrict myself to mucking up my beautiful PCB layout to put the button on a different pin. Much appreciated. And good point about the risk of errant button pushing.

Or is there a better way?

Read the data sheet to see if it has individual flags for those pins.
Short of that, read and keep track of the pin states in the use to see which pins may have changed.

Read the manual, you are right.


text:
Maximum Delay time
I am designing a driver for a Bipolar stepper motor using Arduino Mega 2560 and DRV8825 Stepper driver.
In my application, a stepper motor (Nema 24) will run for 5 minutes and stop for 2 minutes. I have doubts about is what is the maximum time an Arduino Mega can delay the process, or how much a maximum time delay() function will last, or work in programming?

Note: there's an existing question here this should be closed as a duplicate of, but that is proving hard to find.  So until someone does find it...
The arduino delay() function creates a blocking delay of the provided number of milliseconds.   The argument is an unsigned long which on a 16-bit Arduino is a 32-bit unsigned integer type, having a maximum value of 4,294,967,295.  Since these are milliseconds, the maximum delay() would be 4,294,967.295 seconds, or about 49 days.
However, you can easily achieve longer delays by using counting variables to count up instances of shorter delays.  At an extreme, by using up available memory for keeping track of such counting, you can readily achieve theoretical delays exceeding the age of the universe.
Note that the Arduino delay() function is blocking, which is to say that nothing else (except interrupts and on-chip hardware peripherals) runs during it.  This is often undesirable.  A more useful solution might be to make a loop taking say 20 milliseconds to run, as the result of a delay() and a few housekeeping operations, and then run this over and over again while counting.  Or you could make a 1 second loop, or whatever you choose.


text:
How to get Arduino to talk to two seperate motors wirelessly?
I have an Arduino Uno and I also have two Servo Motors. Say I have a room that is 15 feet wide, and I want to be able to place the Arduino in the center of the room and control two servo motors placed at each end of the room using a button on the Arduino. Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers? Or will I have to use three Arduinos, one for the center with the button and one for each servo. If so, will I be able to substitute the two servo Arduinos with an ATtiny chip?

Place the motors in two separate rooms.  Walk into room A and say "Hello motor, how are you today?", then go into room B and repeat.  Oh and do it while holding an Arduino Uno and you have done what you asked about.

You'll probably need 3 "controllers", of which the one in the middle of the room might need to be a full-featured Arduino. Depending on the the needed libraries of your bluetooth receivers at the remote servos, it seems likely that you could use ATTinys in place of more feature-filled Arduino, but you would still have to think of the ATTinys as Arduinos or at least the glue controller to translate commands from Bluetooth to servo signals (PWM).
You could provide us with more details, such what particular bluetooth modules or transceivers you plan to use; some might provide an asynchronous serial interface, others might present an I2C or SPI interface, and given the small flash and RAM size in the ATTiny line, you would need to evaluate the code and associated libraries needed to operate it on such a processor.
The answer to your question is, "Maybe", given the small amount of detail you have provided.

Is it possible to wirelessly communicate with these two servo motors using just one Arduino and bluetooth transmitters/receivers?

Yes. The process goes like this:

Can you get your Arduino to talk?
Can you get your Arduino to talk to one servo via wires?
Can you get your Arduino to talk to one servo wirelessly?
R. Can you get your Arduino to talk to two servos wirelessly?

Or will I have to use three Arduinos, one for the center with the button and one for each servo.

That's certainly one aporoach.

If so, will I be able to substitute the two servo Arduinos with an ATtiny chip

It certainly can be done. Whether you can do it is unknown to anyone but you.


text:
SPI MOSI receive error
I have a master and a slave (both are arduino UNO) connected through SPI connected. I want to transmit a character to the slave and receive true or false to the master. The transmission is working perfectly. If I send '2', slave is receiving '2'. When I try to transmit an integer from slave to master, the master is always receiving some arbitrary number like 128 or 255.
Master Code:
void setup() {
  Serial.begin(9600);
  Serial.println("Master");
  digitalWrite(SS,HIGH);
  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}
void loop() {
  digitalWrite(SS,LOW);  //  Slave select to low
  received1 = SPI.transfer(test);  // test is a variable which is '2'. The data received by master is stored in received1 variable which is char.
  Serial.println(received1);
  digitalWrite(SS,HIGH);
}

Slave code:
void setup() {
  Serial.begin(9600);
  Serial.println("Slave");
  pinMode(MISO,OUTPUT);
  SPCR |= _BV(SPE);
  process = false;
  SPI.attachInterrupt();
}
ISR(SPI_STC_vect){
  received = SPDR;  // the data received by slave is slored in **received** variable(the variable is char type)
  Serial.println(received);
  process = true;
}
void loop() {
  if(process){
    SPDR = jj;  // Updating SPDR to send data from slave. jj is char type
    process = false;
  }
}

The most important part, declaration of variable process, is not here. Is it volatile? Also do you realize that SPDR on slave must be set before the master starts transmission?

Sorry for not mentioning about process. It's a boolean variable which will be true when something is received by slave.

I have found a solution for this problem in a blog.
Link: http://www.gammon.com.au/forum/?id=10892
I modified my master code and got my desired result.
Master code:
byte transferAndWait (const byte what)
{
  byte a = SPI.transfer (what);
  delayMicroseconds (2000);
  return a;
} // end of transferAndWait

void loop() {
  digitalWrite(SS,LOW);
  transferAndWait (10);
  received1 = transferAndWait (11);
  digitalWrite(SS,HIGH);
  Serial.println(received1);
}

The response will be "collected" next time through the loop. That's why we need to keep a dummy transferAndWait() function first and then the result of that transfer will be stored in received1 variable.

Please accept your own answer if it solved your problem, otherwise Stack Exchange throws it up from time to time as an unsolved question.