text:
How to connect the INT pin of a MPU 6050?
I am using an Arduino Leonardo together with a GY-521 breakout board (like this one, schematic) for an MPU 6050.
I am currently trying to get the DMP Version of the examples from Mr Rowberg to work.
For all my tests, I use these connections:

GY-521 ->  Leonardo
VCC -> 5V (3.3V has the same behaviour)
SDA -> SDA
SCL -> SCL
GND -> GND

The "raw" sketch works fine, I can read out the sensor data. For the DMP version I think I need to connect the INT pin to pin 3 on the leonardo, to allow the MPU6050 to trigger an interrupt.
But as soon as I connect INT to anything (pins 0 through 3), the sketches do not find the MPU6050 any more. (They report ""MPU6050 connection failed").
Is my wiring off, or is my chip defective, and even more important, how could I figure that out on my own in the future? =)
Edit:
The example source code says
/* =========================================================================
   NOTE: In addition to connection 3.3v, GND, SDA, and SCL, this sketch
   depends on the MPU-6050's INT pin being connected to the Arduino's
   external interrupt #0 pin. On the Arduino Uno and Mega 2560, this is
   digital I/O pin 2.
 * ========================================================================= */

The example does nothing (that I can see) to configure this pin.
Edit again:
I've borrowed an oscilloscope. SDA and SCL sit on 3.3V during normal communication, and I can see packets being exchanged. As soon as I connect the INT pin to any input pin on my Leonardo, both SDA and SCL go to ground. This means nothing to me, but maybe to someone else.

Possible problem: pin interference

But as soon as I connect INT to anything (pins 0 through 3), the
  sketches do not find the MPU6050 any more. (They report ""MPU6050
  connection failed").
Is my wiring off, or is my chip defective, and even more important,
  how could I figure that out on my own in the future? =)

If I'm reading the Arduino Leonardo schematic correctly,
Arduino D0 is Rx, Arduino D1 is Tx,
Arduino D2 is the I2C_SDA, and Arduino D3 is the I2C_SCL.
You're already using the I2C_SDA and I2C_SCL as bidirectional I2C communication;
connecting some other output pin (such as the MPU6050 INT pin) to either of those pins is going to disrupt that communication and then things won't work.
On most Arduinos, Serial.println() and Serial.read() and the reprogramming process use the Rx and Tx pins.
Perhaps connecting the MPU6050 INT pin to either of those pins also causes some sort of problem leading to things that don't work.
(Although the Arduino Leonardo actually uses its USB_D- and USB_D+ pins for both Serial.println() and reprogramming, so maybe it isn't really a problem for the Leonardo?).
I would avoid using those pins for anything other than serial communication, even though I'm not at all sure that would actually cause a problem on the Arduino Leonardo.

The example source code says
  ... this sketch depends on the MPU-6050's INT pin being connected to
  the Arduino's external interrupt #0 pin. ...
  The example does nothing (that I can see) to configure this pin.

I assume you're using https://github.com/jrowberg/i2cdevlib/blob/master/Arduino/MPU6050/Examples/MPU6050_DMP6/MPU6050_DMP6.ino , right?
Interrupts are configured a little differently than I/O.
(In particular, "volatile" is critical to getting interrupts working right).
The part that configures that interrupt is in the setup() function:
void setup() {
    // ...

        // enable Arduino interrupt detection
        Serial.println(F("Enabling interrupt detection (Arduino external interrupt 0)..."));
        attachInterrupt(0, dmpDataReady, RISING);
    // ...
}

The "attachInterrupt(0, dmpDataReady, RISING)" line
configures the interrupt vector table and the configuration bits so that when something drives Arduino pin D2 (i.e., external interrupt source 0) from a low to a high, no matter what the Arduino is in the middle of doing, the Arduino puts that on hold, executes the dmpDataReady() function, and then the Arduino resumes where it left off.
I don't see how that ever worked, since "external interrupt 0" comes from pin D2, which on the Arduino Leonardo is connected to I2C_SDA, which we're using for I2C communication, so we can't use it for watching the gyro interrupt pin.
However, since the "attachInterrupt()" gets run long after the "MPU6050 connection failed" message gets printed out on your screen, a software bug in how the example code uses attachInterrupt() doesn't explain why you get that "fail" message printed on your screen.
what to do about pin interference
I would try either using some other pin, or try getting it to work without hooking that pin to the Arduino at all.
Using some other pin
I would try to assign a dedicated pin on the Arduino to the MPU6050 INT pin.
Maybe D9 would work?
I'm guessing on the Arduino Leonardo, the interrupt should be set up something more like:
// warning: untested code.
#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

// connect MPU6050 interrupt to Arduino D9
#define MPU6050_INT D9

void setup(){
    // ...
    // pin change interrupt
    pinMode(MPU6050_INT, INPUT);
    PCintPort::attachInterrupt(MPU6050_INT, dmpDataReady, RISING);
    // ...
}

Getting it to work without hooking INT to the Arduino
It's not at all clear that the Arduino really needs to be connected to the MPU6050 INT pin.
It appears that another option is for the Arduino to occasionally use the I2C communication to read the status of the MPU6050, which includes the current state of that pin.
That simplifies the hardware -- simply leave the MPU6050 INT pin unconnected.

possible problem: level mismatch
I speculate that maybe some output on this Arduino is trying to push close to 5.0 V into your gyro, which is well outside the specifications of your gyro.
You are lucky that anything worked at all.
According to page 12 of the MPU-6050 gyroscope datasheet,
the gyroscope is designed to operate from a power supply of VDD = 2.375V to 3.46V.
You might think that is already taken care of by the 3.3V regulator on your breakout board.
However, a VDD of 3.3 also implies that the gyro expects all of its inputs to be in the range 0 V to 3.3 V, and the gyro will drive its outputs in the range 0 V to 3.3 V.
Page 358 of the ATmega32u4 datasheet says that the ATmega32u4 is designed work with any power supply in the range 2.7V to 5.5V.
There is a 3.3V regulator on the Arduino Leonardo and another one on the GY-521 breakout board.
So the GY-521 breakout board should have its VCC connected to 5V and its GND connected to the Arduino GND so that regulator can power the gyro chip with 3.3.
Unfortunately for you, the Arduino Leonardo is designed to power the ATmega32u4 with VCC = 5.0 V.
What to do about level mismatch
Perhaps it would work better if we connect things the way they were designed to be used.
If I were you, I would try to keep signal levels within specifications by any one of:

Use a level converter, perhaps a I2C-compatible level converter for each data connection between the 3.3V I/O pins of the gyro and the 5.0V I/O pins of the Arduino Leonardo. (a) (b) (c) Or,
Somehow tweak the Arduino Leonardo to connect 3.3 V to the VCC pin of the ATmega32u4. (Does this require cutting traces on the PCB?). Or,
Use some other Arduino configured to run the processor at 3.3V (LilyPad Arduino USB; Arduino Fio; Arduino Zero; Arduino Due; Arduino TRE; some versions of Arduino Pro Mini; some versions of Arduino Pro; etc.) or easily connected to 3.3V (LilyPad Arduino SimpleSnap;  LilyPad Arduino Simple; LilyPad Arduino; etc.)

To use external interrupt 4 (INT6), pin D7 on Leonardo board. we need change interrupt register as follows
   EICRB |= (1<<ISC60)|(1<<ISC61); // sets the interrupt type
   EIMSK |= (1<<INT6); // activates the interrupt

that write in WInterrupts.c
Follow this link
http://forum.arduino.cc/index.php?topic=124057.0

Is it possible that the INT pin on the MPU 6050 in an input, not an output?
The symptoms you describe make it sound like you're locking the gyro chip into an interrupt state so it's not responding any more.
I wasn't able to figure out the use of the INT pin from a quick scan of the data sheet however. It would take more careful study.
Do you have your Arduino pin set up as an input or an output? And if it's an input, does it have a pull-up or pull-down resistor, either internal or external, set up?

Thanks for your input. I'll need to check how the pins are configured; I only use the example code linked in the question and have nothing configured myself. The INT on the MPU should be an output. This setup works for others (at least with a Uno).

the interrupt pin in the attachInterrupt command should be kept to #4 which is pin D7 as stated here "http://arduino.cc/en/Reference/AttachInterrupt" since we can't use pins D0-D3 the only left out option is D7 but the problem still persists. Somebody please solve this !!


text:
Where to connect an external power source for an Arduino motor driver shield to?
I have a BYJ48 stepper motor and an ULN2003A motor driver shield shield.
In many tutorials I read:

do not to draw current from the 5V on the Arduino rail, but use an
  external power source, since the motor can draw quite some current

Which of these options to they mean by this?

Connect an external power adapter to the Arduino and connect the
  ULN2003A board to the Vin pin and GND on the Arduino

or

Connect the motor shield itself to an external power adapter and connect it to the + and - pin on the motor shield

or perhaps both are valid solutions?
The board I use is this one.

https://www.ebay.nl/itm/5V-4-Phase-Geared-Stepper-Motor-with-ULN2003A-Driver-Board-28BYJ-48-Arduino/121433812858 I added it to the my question as well

You are missing a connection from the green wire to the Arduino GND.

@BasvanDijk where did you get your "external 5V power supply"? did you make it?

@alcor bought it from https://arduino-tutorials.net/r/ZsECKh
I also made a tutorial about this motor with the power from an external power supply https://arduino-tutorials.net/tutorial/control-28byj-48-stepper-with-uln2003-driver-with-arduino

thanks, @BasvanDijk! I didn't know you had that great site. I was looking for something prettier than an external 5v source like that, but maybe I'm too spoiled :P thanks again!

There are two things you need to do:

Prevent the motor drawing its power from the micro-controller board.
Make sure that all the grounds are connected but avoiding motor current return through the micro-controller board.

simulate this circuit – Schematic created using CircuitLab
Figure 1. A good wiring configuration. The heavy wires carry the motor current.
Note that there is one ground connection between the micro-controller and the motor system. The return current for the 12 V supply does not pass through the micro-controller board.

Ok, what I have now is that the Arduino powered via the USB connection. The motor shield is complete independent powered with a 5V adapter. As shown on the eBay picture, there is a + and - pin on the driver board. This is where I connected the external power supply to. I did not connect the ground of the Arduino with the - pin in any way as shown in the picture.

And? Does it work or not? You need to connect the GND/- as I have shown for correct operation, otherwise there is no return path from the micro outputs 0 to 4.

Yeah it does work, but I still have my question. Since another option is to connect the external power supply directly in my Arduino and connect the motordriver + and - pin to the Vin and GND on the Arduino

Read my answer again. I explained why not to do that twice.

Perhaps I misunderstood "Prevent the motor drawing its power from the micro-controller board." I thought you referred to the USB provided 5V. For 12V I understand, but my motor is powered by 5V which the Arduino should be able to handle. This made me think I could power the Arduino as well as the motor on the external power supply.

That will be OK if the Arduino GND/- and stepper '-' are connected only at the power supply.

source: Stack Exchange

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

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

sort: votes


text:
What is the meaning of the term FQBN?
So I'm reading the Platform specification and doing some programming and I'm getting the error:
Error missing FQBN

So what does FQBN mean?

My guess: Fully Qualified Board Name
I.e., a descriptor that uniquely identifies a board and its configuration.

That sounds about right. Just couldn't think of the right words for these letters and the net is quite silent about the meaning of it. But thanks and I'll be accepting when the site lets me

I guess it's a modification of "FQDN" - Fully Qualified Domain Name used in networking. If you know FQDN that only leaves the B to interpret, and there's not many things it can be in relation to Arduinos...

@TarickWelling, Arduino started to use this acronym recently with the new Arduino CLI.

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


text:
Garage door button with delay feature
I am working on an art project that involves a garage door opener.  I am very new to Arduino, and electronics.  I have a starter kit with a ton of accessories.
The garage door opener has 2 screws (terminals?) designed to connect a button.  If I touch a wire between them, the opener will start.  I connected a button to my bread board, and ran wires to those terminals on the opener to see if a simple switch would work, and it does.
I want to:

press a button, and the Arduino connects the terminals on the opener, and then it starts
button is then ignored (delayed) for a set amount of time (5 seconds for this example)
after the set amount of time, the button works as normal (like in step 1)

I ran through some tutorials on buttons, and I think I got ahead of myself.

I can turn on an LED from a switch on the bread board, and use a delay(5000) to ignore any other button presses.  I tried to connect the wires that were going to LED to the 2 terminals on the garage door opener, and it did not work
In code, I setup pin 5 as OUTPUT, and pin 6 as INPUT.  I used the button to send a HIGH on pin 5, to see if that signal would work when connected to the 2 terminals on the opener.  I tested this a bit in code by reading the state of pin 6, and it appears to have worked.  However, it did not work when I connected both pin 5 to one terminal, and pin 6 to the other.

I tried looking for a simple example, but searching for garage door openers and Arduino results in too many tutorials on how to do super fancy wireless stuff.  I just want to ignore a button press for 5 seconds after it has been pressed once.
I'm looking for a simple example that allows my button to tell the Arduino to make that connection on the garage door opener.  I guess I'm looking for my Arduino to act like a switch instead of my (physical) switch?
My Arduino kit comes with a bread board, wires, switches, Uno R3 and tons of other stuff I haven't gotten to yet.  I apologize in advance if I'm not thinking of something super-simple that would solve my problem.  I'm very new to this.
Thanks for your time!
Edited for spelling.  Elaborated on my attempts.  I'm going to read about what a relay is.

why do you need to debounce the button? ... i am sure that the button on the garage door opener is not debounced

if you want the opener to only run between two limits, just put additional limit switches at the two limits, wire them in parallel. and wire the push-button in series with the switches.

Just a detail: check the voltage and if it's high you must use a relay.

Please share some details like what are the connection diagrams (schematic), the kind of switch or a block diagram and the expected behavior of the door opener (like for what is the minimum time you want it to operate, switch behavior during its operation, how switch should turn it ON, etc.)

I figure out a solution - I just needed to use a relay.
I didn't know what a relay was, and had a hard time figuring it out.  I've included some notes for anyone who finds this post in the future.

I can't determine if it took reading 3-4 articles on relays for it to sink in, or if one article was the best.  Anyway, for me this one helped the most: https://www.instructables.com/id/How-Electronic-Switches-Work-For-Noobs-Relays-and/
My relay looked different from most of the tutorials.  I figured it out by connecting a couple alligator clips to a 9v battery and listening for the click of the magnetic switch.  Then I used my volt meter to determine which leads were working with the relay.

Relay Setup:

I connected my ~5 to one lead on the relay, and 5v to the other
The Common (middle) lead connects to one terminal on the garage door opener
The N/C (Normally Closed) lead connects to the other terminal on the garage door opener

Button Setup:

The button setup was just like all the other button tutorials
When the button is pressed (LOW), I start and stop the relay to trigger a "button press" for the garage door opener (it starts)
I then run a delay for the set amount of time I want
All button presses are ignored until after the delay has finished

Now I can move on to the actual project.  Thanks!


text:
Programming a switching AC current?
I tried using this code to output AC power from one H-bridge and then another, switching every second, but when I connected a motor to it, it just seemed to output direct current. This is the code I was using (by the way, the motor controller I'm using has a max frequency of 20 kHz, so that's not the problem as far as I know):
int EnablePin = 8;
int duty;
int PWMPinA;
int PWMPinB;

const byte CPin = 0;  // analog input channel
int CRaw;      // raw A/D value
float CVal;    // adjusted Amps value

void setup() {
  pinMode(EnablePin, OUTPUT);
  pinMode(PWMPinA, OUTPUT);
  pinMode(PWMPinB, OUTPUT);
}

void loop() {

  digitalWrite(EnablePin, HIGH);

  for(duty = 0; duty <= 20000; duty += 1){

    PWMPinA=11;  // Timer2
    PWMPinB=3;
    analogWrite(PWMPinA, 255);
    analogWrite(PWMPinB, 0);
    delayMicroseconds(50);

    if(PWMPinA == 11) {
      PWMPinA = 3;
      PWMPinB = 11;
    } else {
      PWMPinA = 11;
      PWMPinB = 3;
    }

  }
  for(duty = 20000; duty>=0; duty -= 1){

    PWMPinA=6;  // Timer2
    PWMPinB=5;
    analogWrite(PWMPinA, 255);
    analogWrite(PWMPinB, 0);
    delayMicroseconds(50);

    if(PWMPinA == 6) {
      PWMPinA = 5;
      PWMPinB = 6;
    } else {
      PWMPinA = 6;
      PWMPinB = 5;
    }
  }
}

..... Your outputing PWM signals to 4 difference pins? its very confusing to be changing the pin assigned to a variable rather then having them all defined and changing which one you are using.    Need to post a schematic of what you have done if you want any help

I tried that and it seems to work.  Don't know why I didn't think of that considering it's simpler, but thank you!

Sounds like you have it sorted already but the first major problem with your original code is that you use PwmPinA and PwmPinB in setup(), before they are assigned any values.
I'd be surprised if the compiler didn't warn about that. Never ignore compiler warnings! :-)


text:
Set PWM frequency to 25 kHz
I currently can set four PWM pins to around 31 kHz with the following code:
void setup()
{
    TCCR1B = TCCR1B & B11111000 | B00000001; // Set PWM frequency for D9 & D10:
    pinMode(pwmPin9, OUTPUT); // Sets the pin as output
    pinMode(pwmPin10, OUTPUT); // Sets the pin as output

    TCCR2B = TCCR2B & B11111000 | B00000001; // Set PWM for D3 & D11
    pinMode(pwmPin3, OUTPUT); // Sets the pin as output
    pinMode(pwmPin11, OUTPUT); // Sets the pin as output
}

I found this setup somewhere, but I don't know how I can set these four PWM pins to around 25 kHz instead. How is that possible?

Do you understand how the AVR timers work?

See my page about timers.

@IgnacioVazquez-Abrams Im not familiar and I need to set those four pins to around 25kHz at the beginning . I have hurry to finish a project and I would be glad any help. The code I have sets to 31kHz. Can I modify it to 25kHz? DC motors require that freq.

@NickGammon Thanks but I really dont have enough time to study these at the moment. Could you provide me the code part to setup 25kHz. Im lost

Why four pins? Are they all going to have different duty cycles? Why not one pin and send it to four different places?

I currently can set four pwm pins to around 31kHz with the following code - I just tried your code and it did not output anything.

I need to tune their exact rpm so their duty cycles will be slightly different. How about is it possible to set 2 pins only to 25kHz?

This code can be easily adapted to set the frequency to 31400, 3920, 490, 123 or 30.6 Hz. Other frequencies would not be so simple, and will most likely involve a change in the resolution of the PWM output. Can you live with a resolution of only 41 steps? Or 80 steps but loosing the “phase correct” feature? Or 321 steps but only on pins 9 and 10?

I think the last option would be great then I use two Ard. boards. Can you help me with that part? Im not familiar

While discussing with Gerben, I just thought about a fourth possibility: You could slow down the main system clock to 8 MHz and use the three timers. You would then have 4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. The cost would be loosing the timing functions (millis(), delay() and co.), having to adjust the serial baud rates, and having the whole program run half as fast. Would that be an interesting option?

@EdgarBonet Thanks for your detailed great answers. In my current code I can control 31kHz four pwm pins. At the same same time I can use LCD screen(I use delay() here to prevent flickering) and baud-rate is 9600. So if I use your 8MHz suggestion, which baudrate should I use?

With the CPU @ 8 MHz, if you Serial.begin(19200), the actual baud rate will be 9600 bps. delay() may kind of work, but in units of 39.0625 µs.

The best material explaining PWM with the AVR timers I have found so far is the YouTube video "8. Arduino Timers and Counters" (1 h 00 m 08 s).

searched this out, it's right what I need.
How can modify it to output about 14 KHz? in fact between 11 - 19 khz OK.
Thanks

I am posting this second answer since I realized it is possible to have
4 PWM channels at 25 kHz with 161 steps on a single Arduino Uno. This
involves changing the main clock frequency to 8 MHz, which
has some side effects since the whole program will run half as fast. It
also involves reconfiguring the three timers, which means loosing the
Arduino timing functions (millis(), micros(), delay() and
delayMicroseconds()). If these trade-offs are acceptable, here is how
it goes:
void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}

Unlike the other answer, this does not need a modified version of
analogWrite(): the standard one will work fine. Only care should be
taken that:

The value written should be between 0 (meaning always LOW) and 160
(always HIGH), inclusive.
Only pins 3, 5, 9 and 10 are available. Attempting to analogWrite()
to pins 6 or 11 will not only fail to deliver a PWM output, it will
also change the frequency on pin 5 or 3 respectively.

Been very long time and now I'm stuck with the same thing with Arduino Due which uses another processor. I would be glad if you hae any input here https://arduino.stackexchange.com/questions/67053/trouble-with-setting-the-pwm-frequency-for-arduino-due

You can configure Timer 1 to cycle at 25 kHz in phase correct PWM mode, and use it's two outputs on pins 9 and 10 like so:
// PWM output @ 25 kHz, only on pins 9 and 10.
// Output value should be between 0 and 320, inclusive.
void analogWrite25k(int pin, int value)
{
    switch (pin) {
        case 9:
            OCR1A = value;
            break;
        case 10:
            OCR1B = value;
            break;
        default:
            // no other pin will work
            break;
    }
}

void setup()
{
    // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;           // undo the configuration done by...
    TCCR1B = 0;           // ...the Arduino core library
    TCNT1  = 0;           // reset timer
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
           | _BV(COM1B1)  // same on ch; B
           | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
           | _BV(CS10);   // prescaler = 1
    ICR1   = 320;         // TOP = 320

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT);
    pinMode(10, OUTPUT);
}

void loop()
{
    // Just an example:
    analogWrite25k( 9, 110);
    analogWrite25k(10, 210);
    for (;;) ;  // infinite loop
}

Writing a value of 0 with analogWrite25k() means the pin will be
always LOW, whereas 320 means always HIGH. The regular analogWrite()
should almost work, but it will interpret 255 the same as 320 (i.e.
always HIGH).
This code assumes an Arduino Uno or similar board (ATmega168 or 328 @
16 MHz). The method used here requires a 16-bit timer, and thus it
uses Timer 1 as it's the only one available on the Uno; that's why only
two outputs are available. The method could be adapted to other
AVR-based boards with a 16-bit timer. As Gerben noted, that timer should
have a corresponding ICRx register. There are 4 such timers on the
Arduino Mega, each with 3 outputs.

It might be useful to explain that this method only works for timer1, as the other timers don't have a ICRx register. At most, you can only have one PWM pin per timer, for timers 0 and 2.

@Gerben: Don't all the 16-bit timers have that register? At least on the Mega they do.

Yes, but only timer1 is 16-bit  on the ATMega328. The rest are 8-bit. And  the OP wants 4 PWM output, and your solution only provides 2. Or am I mistaken?

@Gerben: No, you are right. I just say that requiring ICRx seems to be redundant with requiring the timer to be 16-bits. For the Uno and Mega at least, not sure about other AVR-based Arduinos. The OP understand this only provides 2 PWM channels: see my comment on his question and his answer.

On the ATMega328 (which the OP is using) only timer1 has the ICRx register. For the others you'd have to use OCRxA as TOP, which will make it impossible to use PWM on the OCxA pin. The OP said he/she was okay with only two PWM pins, but then says he/she would be using 2 Arduinos. It should still be possible to do with only 1 Uno, if the OP's willing to loose millis and delay.

@Gerben: Only one Uno? Are you talking about the other two options I proposed (i.e. setting the prescalers to 8)? Oh, one could also change the frequency of the main clock and have 161 steps, I hadn't though about that one. Is that what you have in mind?

I wasn't really following the main comment thread. I was indeed talking about your 41 step alternative. (I'm not sure if the OP really needs more thatn 41 steps for RPM control.)

@Edgar Bonet
I am trying to follow this and generate the same 25khz on pin 8 of arduino mega which is controlled by TIMER 4; I dont see any success; could you please help?

@techniche: 1. Works for me. Maybe you forgot to set COM4C1 in TCCR4A? 2. If that's not the problem, then read How do I ask a good question?, then update your question by including your full source code and clearly stating what you expect the program to do and what it does instead (“I dont see any success” is not considered a valid problem statement).

@EdgarBonet - thanks a lot for the response and help; I am able to generate the pwm signal and someone else verified it with an alpine 64 gt fan and it seems to work; its not working with the fan I have https://www.amazon.in/StorinTM-CPU-Cooler-Cooling-Connector/dp/B06XJV1SH8/ It is a standard CPU fan with 4 wires and its infact used a lot; could it be an issue with the fan and the pwm wire is just for show off?

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


text:
C3 not declared in this scope when running MIDI example code
I'm trying to run the MIDI example from Arduino.CC in Arduino Studio.
I am using an Arduino Leonardo, which has USB HID capabilities. I have installed the library as mentioned:

When I press the compile or upload button, it says:
'D3' was not declared in this scope

What's wrong? How do I fix this?

the error happens when the source code is being compiled .... the upload is not attempted ... upload only happens when the code compiles without errors

The pitches for the notes are taken from pitchToNote.h. In there you can see definitions for the notes like:
#define pitchC3  48

It seems that the names were changed from C3 to pitchC3.
I am not 100% sure, but my guess is that this was done to avoid conflicts between the note A3 and the analog input A3 (and silimar).
So, in line 25 of the example code, add pitch for all notes:
const byte notePitches[NUM_BUTTONS] = {pitchC3, pitchD3, pitchE3, pitchF3, pitchG3, pitchA3, pitchB3};


text:
How to change SIM908 GPS location coordinates format?
I am using the SIM908 module to get GPS position.
The SIM908 sends the latitude and longitude in the ddmm.mmmm format, but major online services for GPS location (for example, Google Earth) use the dd.dddd format.
So, how can I modify my code to convert coordinates from the SIM908 to dd.dddd format?
This is the SIM908 GSM Library Code that I am using:
#include "gps.h"
char GPSGSM::getBattInf(char *str_perc, char *str_vol)
{
     char ret_val=0;
     char *p_char;
     char *p_char1;

     gsm.SimpleWriteln("AT+CBC");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBC"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_perc, (char *)(p_char1));

     //Voltage
     p_char++;
     p_char1 = strchr((char *)(p_char), '\r');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_vol, (char *)(p_char));
     return ret_val;
}

char GPSGSM::getBattTVol(char *str_vol)
{
     char *p_char;
     char *p_char1;
     char ret_val=0;

     gsm.SimpleWriteln("AT+CBTE?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("+CBTE"))
          ret_val=1;

     //BCL
     p_char = strchr((char *)(gsm.comm_buf),':');
     p_char1 = p_char+2;  //we are on the first char of BCS
     p_char = strchr((char *)(p_char1), '\r');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_vol, (char *)(p_char1));
     return ret_val;
}

char GPSGSM::attachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=1", 500, 100, "OK", 5))
          return 0;
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSRST=1", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::deattachGPS()
{
     if(AT_RESP_ERR_DIF_RESP == gsm.SendATCmdWaitResp("AT+CGPSPWR=0", 500, 100, "OK", 5))
          return 0;
     return 1;
}

char GPSGSM::getStat()
{
     char ret_val=-1;
     gsm.SimpleWriteln("AT+CGPSSTATUS?");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("Unknown")||gsm.IsStringReceived("unknown"))
          ret_val=0;
     else if(gsm.IsStringReceived("Not"))
          ret_val=1;
     else if(gsm.IsStringReceived("2D")||gsm.IsStringReceived("2d"))
          ret_val=2;
     else if(gsm.IsStringReceived("3D")||gsm.IsStringReceived("3d"))
          ret_val=3;
     return ret_val;
}

char GPSGSM::getPar(char *str_long, char *str_lat, char *str_alt, char *str_time, char *str_speed )
{
     char ret_val=0;
     char *p_char;
     char *p_char1;
     gsm.SimpleWriteln("AT+CGPSINF=0");
     gsm.WaitResp(5000, 100, "OK");
     if(gsm.IsStringReceived("OK"))
          ret_val=1;

     //longitude
     p_char = strchr((char *)(gsm.comm_buf),',');
     p_char1 = p_char+1;  //we are on the first char of longitude
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_long, (char *)(p_char1));

     // latitude
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_lat, (char *)(p_char));

     // altitude
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_alt, (char *)(p_char1));

     // UTC time
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }
     strcpy(str_time, (char *)(p_char));

     // TTFF
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }

     // num
     p_char++;
     p_char1 = strchr((char *)(p_char), ',');
     if (p_char1 != NULL) {
          *p_char1 = 0;
     }

     // speed
     p_char1++;
     p_char = strchr((char *)(p_char1), ',');
     if (p_char != NULL) {
          *p_char = 0;
     }
     strcpy(str_speed, (char *)(p_char1));

     return ret_val;
}

void parseTime(char *field, int *time)
{
     ////////////////Time////////////
     char tmp[4];
     tmp[2]=0; // Init tmp and null terminate
     tmp[0] = field[8];
     tmp[1] = field[9];
     time[0] = atoi(tmp); // Hours
     tmp[0] = field[10];
     tmp[1] = field[11];
     time[1] = atoi(tmp); // Minutes
     tmp[0] = field[12];
     tmp[1] = field[13];
     time[2] = atoi(tmp); // Seconds
     /////////////Date///////////////
     tmp[0] = field[0];
     tmp[1] = field[1];
     tmp[2] = field[2];
     tmp[3] = field[3];
     tmp[4]=0; // Init tmp and null terminate
     time[3] = atoi(tmp); // year
     tmp[0] = field[4];
     tmp[1] = field[5];
     tmp[2]=0; // Init tmp and null terminate
     time[4] = atoi(tmp); // month
     tmp[0] = field[6];
     tmp[1] = field[7];
     tmp[2]=0; // Init tmp and null terminate
     time[5] = atoi(tmp); // day
}

// Read the latitude in decimal format from a GGA string
double convertLat(char* latString)
{
     double latitude = atof(latString);                                    // convert to a double (precise)
     int deg = (int) latitude / 100;                               // extract the number of degrees
     double min = latitude - (100 * deg);                  // work out the number of minutes
     latitude = deg + (double) min/60.0;                   // convert to decimal format
     return latitude;
}

// Read the longitude in decimal format from a GGA string
double convertLong(char* longString)
{
     double longitude = atof(longString);                                  // convert to a double
     int deg = (int) longitude / 100;                              // extract the number of degrees
     double min = longitude - (100 * deg);                 // work out the number of minutes
     longitude = deg + (double) min/60.00;                 // convert to decimal format
     return longitude;
}

You can convert between formats, as explained here

This could be a general programming question. The only thing specific to
Arduino here is that you may want a solution that minimizes the use of
memory and avoids floating point operations.
Here is a memory-friendly solution that reformats the string in place,
i.e. it overwrites the original string. In many cases this is
appropriate, as it is unlikely that you need the original string later,
but you have to make sure it fits your application. It works by first
moving a few characters around in order to have the format "dd.mmmmm",
then parsing the minutes and converting to fractional degrees, then
writing that in ASCII.
It should be noted that the only reason for dropping the last digit in
the minutes field is to avoid 32-bit operations. I compiled for an Uno
and checked the generated assembly: it uses only four bytes of RAM, in
the stack.
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point
    s[8] = '\0';  // drop last digit

    // Compute fractional degrees.
    uint16_t fraction = atoi(s + 3);  // unit = 1e-3 arcmin
    fraction /= 6;                    // unit = 1e-4 deg

    // Write in ASCII, right to left.
    s[7] = '\0';
    for (int i = 6; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

You can use this same function to convert a longitude from "dddmm.mmmm"
to "ddd.dddd" by just skipping the first character:
static inline void convertLon(char* s)
{
    convertLat(s + 1);
}

Addendum: To answer Lipsyor comment, it is possible to have the
latitude in units of 1e-6 deg by using 32-bit arithmetic:
// Convert the format of a latitude from "ddmm.mmmm" to "dd.dddddd".
// The string is converted in place.
void convertLat(char* s)
{
    // Convert ddmm.mmmm to dd.mmmmmm
    s[4] = s[3];  // move minutes
    s[3] = s[2];  // move tens of minutes
    s[2] = '.';   // put decimal point

    // Compute fractional degrees.
    uint32_t fraction = atol(s + 3);     // unit = 1e-4 arcmin
    fraction = (fraction * 10 + 3) / 6;  // unit = 1e-6 deg

    // Write in ASCII, right to left.
    for (int i = 8; i > 2; i--) {
        s[i] = fraction % 10 + '0';
        fraction /= 10;
    }
}

The + 3 in the computation is only to round to nearest. Dropping this
term should not make any significant difference.

There is a way to increase accuracy?

@Lipsyor: Sure. Do not drop the last digit, uint32_t fraction = atol(s+3) * 10 / 6;, and now fraction is in units of 1e-6 deg.

Thank you Edgar. I'm sorry but don't understand the operation in the code.
I removed the line that drop the last digit (s[8] = '\0';) and used uint32_t fraction = atol(s+3) * 10 / 6; instead of  uint16_t fraction = atoi(s + 3); fraction /= 6; but I have a great translation on the map. May you explain me?

@Lipsyor: You probably failed to properly write the number as ASCII. Since it's now in units of 1e-6 deg, you have to write six digits instead of four. C.f. the amended answer.


text:
How to change a code for an I2C 16x2 to a 20x4?
I have found a sketch that someone wrote for a rotary encoder controlled LCD menu.
The code is for an I2C that is 16x2 and I have an I2C that is 20x4. With the code that I found, the layers are all 3 lines, so when they appear on the LCD, it is on 2 "pages".  Since my LCD is 20x4, I don't need to scroll to a second page.
How do I get that third line on the same page as the first two?  I am also still looking at other sketches people have posted for LCD menus, but most of them seem to have outdated libraries or are for 16x2 screens.
#include <OneButton.h>
#include <Encoder.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>

LiquidCrystal_I2C  lcd(0x27, 2,1,0,4,5,6,7);

// ROTARY ENCODER
long oldPosition  = 0;
int encoderDTpin = 34;
int encoderCLKpin = 30;
Encoder myEnc(encoderDTpin, encoderCLKpin);

int buttonPin = 26;
OneButton button0(buttonPin, true);

// MENU ARRAY
// First number in array = amount of menu items in root layer. Same goes for next layer.
//(Example: first value in array is 4. This means Layer 0 has 4 menu items. Layer 1 has only 2 menu items.)
// First number infront of menu text is the layer number that item points to. (Example: 1_Rotation points to Layer 1)
// Second number infront of menu text is the number of the value connected to that menu item in the values array.
//(Example: 15Direction points to position 5 in the values array)

String menu[] = {"4","1__Rotation","056Active","3__Watches","4__Item4",       // Layer 0
                 "3","100Rotations","105Direction","109Speed",                // Layer 1
                 "3","256Active","2__Item2.2","2__Item2.3",                    // Layer 2
                 "4","4__Watch 1","3__Watch 2","3__Watch 3","3__Watch 4",     // Layer 3
                 "2","4__Item3.1.1","4__Item3.1.2"};                          // Layer 4

// VALUES ARRAY
// TYPES, 1 numeric / 2 character value range
// 1 - type,value,increments,min,max
// 2 - type,starting value in options array,lowest value options array,max value options array
int values[] = {1,11,25,50,1450, //0-4 WATCH1
                2,2,0,2,         //5-8
                1,600,25,75,600, //9-13

                1,11,25,50,1450, //14-18 WATCH2
                2,2,0,2,         //19-22
                1,600,25,75,600, //23-27

                1,11,25,50,1450, //28-32 WATCH3
                2,2,0,2,         //33-36
                1,600,25,75,600, //37-41

                1,11,25,50,1450, //42-46 WATCH4
                2,2,0,2,         //47-50
                1,600,25,75,600, //51-55

                2,4,3,4,         //56-59 WATCH1 ACTIVE
                2,4,3,4,         //60-63 WATCH2 ACTIVE
                2,4,3,4,         //64-67 WATCH3 ACTIVE
                2,4,3,4};        //68-71 WATCH4 ACTIVE

String options[] = {"CW","CCW","MIX",
                    "No","Yes"};

// Custom character for LCD.
byte cursor[8] = {
  0b10000,
  0b10000,
  0b01000,
  0b00110,
  0b01000,
  0b10000,
  0b10000,
  0b00000
};

byte watch[8] = {
  0b01110,
  0b01110,
  0b11011,
  0b10001,
  0b10001,
  0b11011,
  0b01110,
  0b01110
};

int currentType = 0;
int value = 0;
int numIncr = 0;
int Min = 0;
int Max = 0;

int currentLayer = 0;
int lastLayer = 99;
int currentLength = menu[0].toInt();
int currentPosition = 0;
int currentSelect = 1;
int currentChange = 0;
String currentPress = "";
float currentlcdLayerFloat = 0;
int currentlcdLayer = 0;
int lastlcdLayer = 0;
int lcdUpdated = 0;
int currentLine = 0;
int cursorLayer = 0;
int cursorPosition = 0;
int valueLength = 0;

/*
int homeScreen = 1;

String currentTime = "00:00:00";
String lastTime = "00:00:00";
String temptime = "00";
String currentDate = "";

int watch1active = values[56] - 3;
int watch2active = values[60] - 3;
int watch3active = values[64] - 3;
int watch4active = values[68] - 3;
int watch1rotations = 0;
int watch2rotations = 0;
int watch3rotations = 0;
int watch4rotations = 0;
int watch1left = values[1];
int watch2left = values[15];
int watch3left = values[29];
int watch4left = values[43];
String temprotationsleft = "";
*/

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

  // Map rotary button to actions single and doubleclick.
  button0.attachClick(singleClick);
  button0.attachDoubleClick(doubleClick);

  lcd.begin (16,2);
  lcd.setBacklightPin(3,POSITIVE);
  lcd.setBacklight(HIGH);
  lcd.home();

  // Create the custom character.
  lcd.createChar(0, cursor);
  lcd.createChar(1, watch);

  lcd.setCursor (2,0);
  lcd.print("Watch Winder");
  delay(1000);
  clearLine(0);

  // Set the select cursor on the first line.
  cursorLayer = 0;
  lcd.setCursor (0,cursorLayer);
  writeCursor();

}

void loop() {

    // Listen to button presses.
    button0.tick();

    // Listen if the rotary encoder moves.
    rotary_check();

    // Print the LCD menu.
    lcdMenu();

}

void singleClick() {

  // IF current layer number is the same as redirect layer number, we stay on the same layer
  // AND no item is selected in the menu
  // AND the selected item has a redirect to another layer
  if(currentLayer == menu[currentPosition + currentSelect].substring(0,1).toInt()
      && menu[currentPosition + currentSelect].substring(1,3) != "__" && currentPress == ""){

    currentPress = menu[currentPosition + currentSelect].substring(3);
    currentChange = menu[currentPosition + currentSelect].substring(1,3).toInt();

    Serial.println("Currentpress: " + currentPress);

    currentType = values[currentChange];
    value = values[currentChange + 1];

    // Type select change is numeric
    if(currentType == 1){
      Min = values[currentChange + 3];
      Max = values[currentChange + 4];
      numIncr = values[currentChange + 2];

      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

      valueLength = String(value).length();

    // Type select change is character range
    } else if(currentType == 2){
      Min = values[currentChange + 2];
      Max = values[currentChange + 3];

      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }

      valueLength = options[value].length();

    }

    clearSelect();
    cursorPosition = 15 - valueLength;
    lcd.setCursor(cursorPosition,cursorLayer);
    writeCursor();

  // ELSE IF something is selected in the menu, and the button is pressed again. We deselect the item.
  } else if(currentPress != ""){

    currentValues();
    currentPress = "";
    currentChange = 0;

    clearChar(cursorPosition,cursorLayer);
    lcd.setCursor(0,cursorLayer);
    writeCursor();

  // IF nothing is selected and nothing will be deselected, move to the redirect layer listed in the first position of the array.
  } else {

    currentLayer = menu[currentPosition + currentSelect].substring(0,1).toInt();
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();

  }

}

// Reset to layer 0.
void doubleClick() {
  if(currentLayer == 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;

    lcd.clear();
    lcdUpdated = 0;
  }
  if(currentLayer != 0){
    currentLayer = 0;
    currentSelect = 1;
    currentlcdLayerFloat = 0;
    currentlcdLayer = 0;
    lastlcdLayer = 0;

    clearSelect();
    cursorLayer = 0;
    lcd.setCursor (0,cursorLayer);
    writeCursor();
  }
}

void rotary_check(){

  // Constantly read the position of the rotary encoder
  long newPosition = myEnc.read() / 4;

  // IF the new position of the encoder is different then the old position
  if (newPosition != oldPosition) {

    // IF nothing has been selected in the menu
    if(currentPress == ""){

      if(newPosition > oldPosition && currentSelect < currentLength){
        clearSelect();
        currentSelect++;
        currentlcdLayerFloat = currentlcdLayerFloat + 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      } else if (newPosition < oldPosition && currentSelect != 1){
        clearSelect();
        currentSelect--;
        currentlcdLayerFloat = currentlcdLayerFloat - 0.5;
        currentlcdLayer = currentlcdLayerFloat;

        cursorSelect();

        lcd.setCursor (0,cursorLayer);
        writeCursor();
        Serial.println("> " + menu[currentPosition + currentSelect].substring(3));

      }

      if(lastlcdLayer != currentlcdLayer){
        lcdUpdated = 0;
      }

      lastlcdLayer = currentlcdLayer;
      oldPosition = newPosition;

    // IF something has been selected in the menu, we are going to change the value of a menu item.
    } else if(currentPress != ""){

      lcd.setCursor(cursorPosition + 1,cursorLayer);
      // IF the new position is HIGHER then the old position
      if(newPosition > oldPosition){
        clearChar(cursorPosition,cursorLayer);

        // IF the selected item has a change type that is NUMERIC.
        // AND the MAXIMUM of the selected item has not been reached.
        // We change the value UPWARDS with the icrements listed in the array.
        // SAME applies for next ELSE IF, just for the change type character. And the next ELSE IF we just go down.
        if(currentType == 1 && value < Max){
            value = value + numIncr;
            values[currentChange + 1] = value;
            Serial.println(value);

            clearValue();
            valueLength = String(value).length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(value);
          }

        if(currentType == 2 && value < Max){
            value++;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      } else {
        clearChar(cursorPosition,cursorLayer);

        if(currentType == 1 && value > Min){
          value = value - numIncr;
          values[currentChange + 1] = value;
          Serial.println(value);

          clearValue();
          valueLength = String(value).length();
          cursorPosition = 15 - valueLength;
          lcd.setCursor(cursorPosition + 1,cursorLayer);
          lcd.print(value);
        }

        if(currentType == 2 && value > Min){
            value--;
            values[currentChange + 1] = value;
            Serial.println(options[value]);

            clearValue();
            valueLength = options[value].length();
            cursorPosition = 15 - valueLength;
            lcd.setCursor(cursorPosition + 1,cursorLayer);
            lcd.print(options[value]);
          }
          lcd.setCursor(cursorPosition,cursorLayer);
          writeCursor();

      }

      oldPosition = newPosition;
    } else {
      oldPosition = newPosition;
    }

  }
}

void lcdMenu(){
  if (lastLayer != currentLayer || lcdUpdated == 0){

    currentLength = menu[0].toInt();
    currentPosition = 0;

    for (int i=0; i < currentLayer; i++){
      currentPosition = (menu[currentPosition].toInt() + 1) + currentPosition;
      currentLength = menu[currentPosition].toInt();
    }

    clearMenu();
    int tempPosition = currentPosition;

    if(currentlcdLayer != 0){

      currentPosition = currentPosition + (currentlcdLayer * 2);
    }

    Serial.println("LCD-------------");

    for (int i=1; i <= 2; i++){
      lcd.setCursor (1,i - 1);
      lcd.print(menu[currentPosition + i].substring(3));

      currentType = 0;
      value = values[menu[currentPosition + i].substring(1,3).toInt() + 1];
      String tempvalue = "";

      if(menu[currentPosition + i].substring(1,3) != "__" && menu[currentPosition + i].substring(1,3) != ""){
        currentType = values[menu[currentPosition + i].substring(1,3).toInt()];
        if(currentType == 1){
          lcd.setCursor (16 - String(value).length(),i - 1);
          lcd.print(value);
          tempvalue = " "+ String(value);
        }else if(currentType == 2){
          lcd.setCursor (16 - options[value].length(),i - 1);
          lcd.print(options[value]);
          tempvalue = " "+ options[value];
        }

      }

      Serial.println(menu[currentPosition + i].substring(3) + tempvalue);
    }
    Serial.println("----------------");

    currentPosition = tempPosition;
    lastLayer = currentLayer;
    lcdUpdated = 1;

    /**
    Serial.println("Layer " + String(currentLayer + 1));
    Serial.println("Layer length " + String(currentLength));
    Serial.println("Layer position " + String(currentPosition));
    **/

  }
}

void currentValues(){

  Serial.println("Currentpress: " + currentPress);

  if(currentType == 1){
      Serial.println("Currentvalue: " + String(value));
      Serial.println("Increments: " + String(numIncr));
      Serial.println("Min: " + String(Min));
      Serial.println("Max: " + String(Max));

    } else if(currentType == 2){
      Serial.println("Currentvalue: " + options[value]);
      Serial.println("Options: ");

      for (int i=Min; i <= Max; i++){
        Serial.println(options[i]);
      }
    }
}

void clearChar(int charPosition, int line){
  lcd.setCursor (charPosition,line);
  lcd.print(" ");
}

void clearLine(int line){
  lcd.setCursor (0,line);
  lcd.print("                ");
}

void clearMenu(){
  lcd.setCursor (1,0);
  lcd.print("               ");
  lcd.setCursor (1,1);
  lcd.print("               ");
}

void clearSelect(){
  lcd.setCursor (0,0);
  lcd.print(" ");
  lcd.setCursor (0,1);
  lcd.print(" ");
}

void cursorSelect(){
  switch (currentSelect){
          case 1:
            cursorLayer = 0;
            break;
          case 2:
            cursorLayer = 1;
            break;
          case 3:
            cursorLayer = 0;
            break;
          case 4:
            cursorLayer = 1;
            break;
          case 5:
            cursorLayer = 0;
            break;
          case 6:
            cursorLayer = 1;
            break;
        }
}

void writeCursor(){
  lcd.write(byte(0));
}

void clearValue(){
  for (int i = 16 - valueLength; i <= 16; i++){
        lcd.setCursor (i,cursorLayer);
        lcd.print(" ");
      }

}

or use and existing menu library https://github.com/search?utf8=%E2%9C%93&q=arduino+menu&type=

Change line
lcd.begin (16,2);

to
lcd.begin (20,4);

then position cursor as you did for lines 0 & 1.


text:
Button and switch to turn on and off LED and changing after time
I have system connected to an Arduino Uno where I want to read whether the switch is open or closed.
Based on if the switch is open/closed, I want an LED light to turn on/off.  When the switch is open, the LED turns on and pushing the button turns it off and stays off for 24 hours then turns back on if the switch is still open and I can again turn off the light with one push of the button.  However, if the switch is closed within the 24 hours, the light doesn't turn on and pushing the button does not do anything.
I don't know how to change the state of the LED back on after the 24 hours.  Should I use a button counter, if statements, or while statements?  I'm really new to coding and took on a large project I'm not sure how to complete. This is obviously a very small portion of the project.  Any help is much appreciated.
This is as far as I've gotten.  When the switch is open the LED turns on, but when I push the button, the light just dims.  I also have to hold the button down to keep the light "off" and it turns right back on when I release the button.
if (digitalRead(switch) == LOW) {
digitalWrite(Light, HIGH );

if (digitalRead(Button) == LOW) {
    digitalWrite(Light, LOW);
}

else if (digitalRead(switch) == HIGH) {
  digitalWrite(Light, LOW );

}
}

Please edit your question (click "edit") and make clear whether you are describing what you want to happen or what does happen.  For example, you say  “However, if the switch is closed within the 24 hours, the light doesn't turn on and pushing the button does not do anything”; is that what your code does now, and it is erroneous or undesired behavior?  Try to write a clear specification of what should happen, couched in sentences that begin with phrases like “The system shall ...”

Please edit your question to include a Minimal, Complete, and Verifiable example of code, not just snippets.  Minimal means you've stripped away irrelevant stuff, just leaving what's needed to show the problem.  Complete means all the library names are shown, all the variable declarations, and all the function definitions – so people don't have to waste time guessing what you did or what you meant.  Verifiable means it can be compiled and tested, allowing other people to test their theories about the problem.

Do not name a constant switch.

I have to make an answer, since I cannot use items/links easily in a comment.
Instead of creating the application for you, I suggest you do the following:

Read/try and experiment with the default Arduino examples for a switch (see Switch
In the above example also is shown how to debounce the signal, this is needed since you want to use it as a 'toggle'.
Use a timer for millis() and check for 24 hrs (which is 1,440,000) millis, so it should fit in a long.
Small thing: Always align brackets to make it easier for yourself and others.

A few things will need to be done.

You have to figure out to detect a button press. This needs to be transition based. Ie. Detect a button press when it was not pressed the previous time.

Once a button is pressed, you take a snap shot of the time. And then turn on the led.

Then you test current time at each pass and see if the desired time has passed.

This can be done by configuring one of the timers to record sufficiently long period.
If you have to use mill is(), you have to figure out how long it overflows and how to detect its overflow.
Both can be done, fairly easily.

Your problem is, that you do not keep the status and acts only on actual state of switch+button each pass of loop() (that is many thosand each second).
So you Light On is switch is turned, then Light off if button is pressed and next split of second you repaet it again - led looks dim, as your eye cannot see how fast is blinking.
You need to keep the status (OFF,ON,TEMP_OFF) and act upon that. Also if it is temporary off, you need know, when it happend, to undo it after 24 hours. (google for state automat arduino)
the code would be like this (not tested, I wrote it from head, so try to understand the principle and fix all small errors and play with the idea on your own)
// statuses - just some different values
#define ST_OFF 1
#define ST_ON 2
#define ST_TEMP_OFF 3

// pin assignment - change by tour projects need
#define pin_switch 2
#define pin_button 3
#define pin_led 13

unsigned long temp_time; // temporarry off from this time
byte status=ST_OFF; // start with dark

loop() {
  switch (status) {

    case ST_OFF:
      if ( digitalRead(pin_switch) == LOW ) {
          status = ST_ON;
          // light it on if switch turns/is LOW
          };
       break;

    case ST_ON:
      if ( digitalRead(pin_button) == LOW ) {
         status = ST_TEMP_OFF;
         temp_time=millis();
         // light it off temporary if button pressed, remeber when
         };
       if ( digitalRead(pin_switch) == HIGH ) {
          status = ST_OFF;
          // light it off permanently if switch released - override TEMP, if both happens
          };
       break;

    case ST_OFF:
       if ( millis()-temp_time > 24L*60L*60L ) {
          status = ST_ON;
          // light it on, if timeouted
          };
       if ( digitalRead(pin_switch) == HIGH ) {
          status = ST_OFF;
          // light it off permanently if switch released - overrides TEMP/ON
          };
       break;
    };

  digitalWrite(pin_led,(status == ST_ON) );
  // light the led if ST_ON, turn it off otherwise
  // we can keep old value or look for actual and write only if it differs, but it is the simplest way

}


text:
The LCD doesn't display the words typed
I've tried this code on an LCD, and instead of displaying "Hello World!" it displays what is shown on the picture.
Code:
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

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

void loop() {
  lcd.print("Hello World!");
  delay(500);
  lcd.clear();
  delay(500);
}

You probably listed the wrong pin numbers in  LiquidCrystal lcd(12, 11, 5, 4, 3, 2); but haven't supplied a wiring diagram so who can say.

I've doublechecked the wiring

Sure, the wiring may be fine ... but you might have the wrong numbers within lcd(12, 11, 5, 4, 3, 2), or have them in the wrong order

From the attached I can see that you are connecting D7 to digital 2 of arduino. And I assume the pins D6 D5 D4 are also connected to 3, 4, 5 pins respectively, which is correct for your code.
But make sure the R/W pin is connected to proper ground. Verify that by measuring voltage if possible.
Also serial print whatever you are giving the lcd  to make sure it is not an encoding issue.

Try the following

Double-check the LCD soldering
Double-check your wiring
Ensure that the pins you are using for your LCD are not assigned to some other function. This caused jumbled, random characters here.

Don't take this the wrong way but some of those solder joints looks a little rough. I'm not sure this is your issue but you need some soldering practice. Solder joints should be bright and shiny and should completely cover the pad.
I can tell by the joint on pin 16 you didn't get it hot enough or the solder would have flowed to cover the entire pad. Some of the other joints look like they were overheated. Does your soldering iron have a temperature control? Experience will help you know when to turn it up and when you can get by with a lower temperature. Is your tip too large or needs replacing?
There's lot's of soldering how-to videos out there but no substitute for practice, practice, practice and then practice some more. :)


text:
Wiring Feather Huzzah ESP8266 to Monochrome 1.3" 128x64 LCD
I'm new to Arduino and the pinouts for the Adafruit 938 LCD doesn't seem to match the pinouts that I looked up for the Huzzah ESP8266.
Does anyone know the proper pinout for this display and the Huzzah?

At the Adafruit site it says: (for the 938) The driver chip, SSD1306 can communicate in two ways: I2C or SPI.  And (for the Huzzah) 9 x GPIO (3.3V logic), which can also be used for I2C or SPI.  I think the problem you are faced with is that the Huzzah has programmable pins that can be configured for many things.  Two of which are, evidently, I2C or SPI.  BTW, this isn't necessarily an easy 1st Arduino project.

Shouldn't it be just as easy as connecting certain wires to certain pins? I just am confused with the pinout, thats all..

You may need pull up resistors for the I2C bus.  I2C was designed so all devices are open collector drivers so the bus needs at least 1 pull up resistor on the data line and 1 on the clock line.  That said, sometimes the pull up resistors have been added by the people who designed the PCB.  For SPI I believe you don't need pull up resistors.  However the labeling can get confusing (MISO connects to MOSI & the other MOSI connects to the other MISO).  As for the pin-outs, the same pins might be used for more than 1 feature.  You need to sift through the data sheets and figure this out.


text:
A1 was not declared in the scope
I'm trying to put all my settings in a config.h file and then #include it in the Arduino sketch.
Here's what my config.h looks like:
RobotConfig.h
#ifdef BOT
    //hardware pins
    int motor1Pin = 9; //s0
    int motor2Pin = 10; //s1

    //pins for light
    int light2 = A4;
    int light3 = A2; //right
    int light1 = A1; //left

And here's what .ino sketch looks like:
#define BOT
#include "RobotConfig.h"

void setup() {
  //Light INIT
  pinMode(light1, OUTPUT); //left light with motor1/s1 in front
  pinMode(light2, OUTPUT); //middle light with motor1/s1 in front
  pinMode(light3, OUTPUT); //right light with motor1/s1 in front
  ...
}

This compiles fine on my Mac but I'm trying to compile this on Raspberry Pi (Pi3 with new Jessie install with sudo apt-get install arduino) and get an error while doing so. The error says:

A1 was not declared in the scope etc.

What am I missing?

Do you have an #endif in RobotConfig.h ?  If so, please edit your question to show it

RobotConfig.h needs to include Arduino.h in order to have those constants.


text:
Arduino resets itself
If I connect more power consuming components to Arduino, it gets reset. What is the cause of this observation?

Look up "brownout".  For example https://forum.arduino.cc/index.php?topic=246359.0

What is the solution for this?

When powered through USB there is a resettable polymeric ("poly") fuse. If you draw more than about 500mA this fuse will cut out and isolate the power.  When you remove the load the fuse will reset and allow power back to the board.
"Poly" fuses are in fact "Positive Temperature Coefficient" (PTC) thermistors. As they get hot their resistance increases (as opposed to the NTC thermistors you use for temperature sensing where the resistance decreases as they get hotter).  The current flowing through the PTC causes it to warm up. Too much current and it gets too hot, and the resistance gets too high (it's non-linear, so the resistance suddenly increases a lot).

Very good information!

It depends on what is shorted. As stated by Duncan C, shorting the 5V pin to ground will probably not harm the arduino due to the mentioned protection mechanisms.
On the other hand an output port should not be shorted, chances are that the port gets destroyed.
In case of a short circuit the arduino "resets" itself because the voltage drops below the mcu's operating conditions, because the voltage regulator either shuts down completely or is not able to provide enough current.

Branded Arduino boards have overload protection on their voltage regulators. If the voltage regulator overheats it shuts down, and then attempts to restart when the temperature returns to normal. I believe there is also short-circuit protection, although I'm not positive.
When power returns the processor will do a power-on reset.

Consider this: An Arduino was not designed as a power supply. Connect your loads to an external power supply things will get a lot better.


text:
Serial monitor read value depending on delay
I am working on a small piece of code as shown:

When I enter character 'a' in the Serial Monitor and use a delay in between successive reads then the monitor gives out acceptable results(i.e 97 for character 'a' and 10 for new line) as shown:

Whereas if I do not include the delay, it seems like the microcontroller is not able to read the next value(i.e 10 for new line) immediately and just gives out a -1. And it is only after the loop is run again that we get to see the value 10 for new line(again with -1).

Is my observation correct? If yes, what causes this to occur?
EDIT: I am sorry for the improper format of displaying the code. I am adding the code as below:
#include <Wire.h>

void setup() {

  // Initialize I2C communications as Master
  Wire.begin();
  // Setup serial monitor
  Serial.begin(9600);
  Serial.println("I2C Master Demonstration");
}

void loop() {

  if(Serial.available()>0)
  {
    char c = Serial.read();
    Serial.print((int)c);
    delay(10);
    char d=Serial.read();
    Serial.print((int)d);
    Serial.println("Writing data to slave...");
}
}

please post the code text, not pictures of code ... you have been asked the same thing on your previous post

Ok i will consider it next time.... I thought that showing it graphically would make it easier to interpret!

it makes it very difficult to test your code to see if it even compiles

Are the downvotes just because of improper way of displaying the code? Or because of  the question itself?

possibly, you still show the pictures of the code ... if you remove the pictures and the downvotes get reversed, then you will have your answer

Yes, UART is much slower then the CPU and you run it on extremely slow baud rate. The CPU runs many loops before Serial.available() is again more then 0.
From reference of read() function:

Returns the first byte of incoming serial data available (or -1 if no data is available).

But why is  '-1' here? What does it indicate?

I enhanced the answer

the -1 works 100% correctly only for int data type ... int c = Serial.read(); ... the reason is that -1 is binary 11111111 as a byte (255 decimal) ... it is 1111111111111111 as an integer ... if you receive a valid byte of 255,  your code will see it as meaning no data ... if you receive it as an integer then your code will see it as data ... int 255 = binary 0000000011111111 .... your code receives bytes (char), so you could get into trouble with char(255)


text:
Problem with Input from Serial Monitor
I have a piece of code as shown, and I wish to print the value I send using serial monitor along with a message: "Writing data to slave...".

But everytime I enter a character/number in the serial monitor(like 'a' as shown), the loop runs two times instead of just once. It seems like an extra character(somewhat invisible or null) is being sent along with the typed character.

If I use the condition (Serial.available()>1)  then the loop runs just once on sending one character.
Why is this so?

Please copy the code as text instead of bad screen dumps.

I suspect an end of line character is send (probably \n or \r, see comment of Edgar Bonet), or an end of string (0 character).
You can easily find it out by printing the integer value of the character:
char c = serial.read();
Serial.print((int) c);

Actually '\n' = 10 (a.k.a. LF, line feed, new line), not to be confused with '\r' = 13 (CR, carriage return). And yes, it's a '\n', as attested by the selection “Newline” on the drop-down menu at the bottom. The other options of this menu are “No line ending”, “Carriage return” and “Both NL and CR”. Note that the last options sends CR before LF.

@EdgarBonet Thanks for your clarification, I put a forward to your comment. It's always better to check the exact character(s) which ends a line.


text:
Reproducing a Fiber Optic Shape Sensor with Arduino?
I want to be able to track the curvature of a human arm as it straightens out and retracts (ex: like live tracking a bicep curl). I don't want to use resistive flex sensors.
I've been trying to find suppliers for this technology demoed here: https://www.youtube.com/watch?v=iAeXp-TpFLU&t=38s
But I cant seem to find anyone who sells directly to consumers. I was thinking about creating a hobbyist level version my own using fiber optic wire, a led, and a light wavelength sensor, using a more powerful Arduino such as the Intel Edison. I have a basic understanding of how this technology works, but I want to learn by attempting to create it.
Is this practical or possible with an Arduino?
if so:

Are these the correct materials I would need?

if not:

Why not?
What kind of equipment would I need to achieve this?
Is there anywhere to buy this sensor directly?
Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

how does the technology work? .... it is unclear from the video how much computing power is needed to calculate the position of the fiber optic cable ..... btw: there is no such thing as a fiber optic wire ... wire is metal

it is also unclear what kind of a sensor is used on the end of the optic fibre ..... it is most likely some sort of a multi cell sensor

Cable* is what I meant. Here is a video that explains the technology (0:50 start), https://www.youtube.com/watch?v=Kc3foeu2-50, from what I read, but again I have a limited understanding of this technology in depth, it measures the wavelength that is reflected back from the bragg gratings, in the video an oscilloscope is scene used, so I assume maybe an Intel Edison Arduino, since having a 500 MHz clock speed, maybe this is enough?

Likely you need to measure the time it takes for light to travel over a distance of fractions of a meter.  And light in a vacuum travels at about 3x10^8m/s.  This is the type of measurement a LIDAR based car navigation system only starts to approach.  Further, it is inferred the color of the light is important to measure.  The only test equipment I know of that might be capable of measuring the speed of light and the color of light are used in high speed fiber optics communication.  We're talking anywhere from the price of an expensive car to the price of a house.

I think nobody here can really give you an answer, if this is possible with an Arduino, since we don't know enough about the technology and the nitty gritty things, that make this a difficult task. So making a hobbyist version won't be easy and maybe really expensive.
In the fiber each bragg grating reflects a bit of the light back. The wave length of this reflected light is dependend on the angle between light and grating. So you get a specific wave length back from each grating, that corresponds to the bending at that particular part of the cable. The task is to measure the many wave lengths, that are being reflected in the fiber, and match them to a particular part of the cable. Since they don't say, how they are solving this, I will mention some ideas here:

Spectral Measurement (Wave length):

From the video I guess, that they use white light to shine into the cable. The gratings will only reflect the wave lengths from this spectrum, that satisfy Bragg's law due to bending angle. You have to measure the wave length directly with a spectrometer. Mostly this is another grating, that will seperate the wave lengths spatially, so that you can measure the spectral structure by using a spatial sensor, for example a camera or a line sensor. You would have to correct for different wave length sensitivities of the camera.
Maybe they are only using a laser with 1 wave length. Then the bending would result in a change in intensity reflected from that grating. If you can seperate the signals from the different gratings good enough, you would be able to measure just the change in intensity, which would be easier, since you basically need just a photo transistor or similar for that wave length. (In this case you would need to calibrate the sensor each time as a straight cable and ensure, that the measurement is fast enough for the expected movement).

Matching of signals to each part of the cable: Here I guess, that they use a time-of-flight sensor, because I cannot think of anything else without further information. This is a really difficult problem, because most available sensors are not sensible enough for measuring quarter inches without being cheap in the first place. You will likely spend a lot of money for a sensor like this. And you building an own time-of-flight sensor with the wanted sensitivity may be as difficult as building the whole device in the first place.
Needed Parts: Also you will need the fiber itself, which is - as stated - not a normal glas fiber, which you can by everywhere. It is most likely a custom build and you will pay a lot of money, to get one of these. The light source is dependend on the spectral measurement above. For a white light it is important, that all wavelength should have as equal intensity as possible. You would also have to account for the spectral absorption and the overall absorption in the fiber, which restricts the sensitivity and possible lengths.

Is there anywhere to buy this sensor directly?

Most likely not. In the videos it seems like a device, that was developed by the NASA for a specific application. The video is a proposal for other companies to learn from the NASAs development, so the device is not consumer ready. But you might be able to get a paper about this device by searching the internet for it or by asking the NASA directly. This paper would contain way more information about the device as the videos.
All in all this would be an extremely difficult task. Since you came here (a simple Q&A site) with this difficult question, I think, that you are not really ready for this big of a task. Most likely even the developers at the NASA needed long and much money for this.

Are they any alternatives for 3D shape/position sensing besides 3D magnetic sensing?

I would propose to build a string of bending strips, which change their resistance according to the bending angle. You can use multiple strips for getting multiple readings for different parts of the human arm. With each strip you build a voltage divider and do an analog measurement. With a bit of calibration you should be able to measure the curls.

Thank you for all of this information, this will help me a great deal. About the bending strips specifically, is there a way to make a 3D bending strip? If we put two together in a fashion where one measures the strain forward and backwards and the other from left to right? And using the change in light intensity as you previously said, would an optical bend sensor be better/more precise? Also a problem with a flex sensor, it doesn't give you a different value if you bend it forward or backwards to be able to tell bend direction or am I wrong?

your arm does not really bend two ways, except for your wrist ..... on the wrist, place one sensor on each side .... one will extend and one will contract .... that will indicate the direction of bend

Well. is not impossible and the accepted answer is quite dark.
To use a FBG with an Arduino (I advise a ESP32) one needs to have a light* emitter and also a light receiver for the same end of the fiber. To achieve this, is used an unidirectional optical circulator coupled with both emitter, receiver and the FBG.
The difficulty is in finding those components suitable or sensing and at the same time inexpensive. That said, here https://europepmc.org/article/pmc/6651577 is an article depicting a portable FBG interrogator using a raspberry pi. The Pi uses a 120Mhz MCU , so a ESP32 MCU is also a suitable option.

in sum, it can be done quite easily.

(FWIW, Pi3 uses a 1.2GHz CPU, not 120MHz)

correct. howeverthe MCU in a Pi clocks at 120Mhz

I guess I don't understand what you mean by "the MCU in a Pi" here; can you be specific?

@Dave Newton,  since you know so much, why not answer this question by yourself or better, edit this one ?

Not sure why you're upset--I just don't understand what you're talking about; I don't know what part of an RPi would be called an MCU or what part of an RPi runs at 120MHz. Geez.


text:
Communication with socketserver fails after specific number of packets
I'm trying to implement a full-duplex communication between my ESP8266 and a socketserver running on my laptop. In concrete I need each of the devices to initiate communication whenever it needs to. The ESP is measuring temperature all the time and when the temperature changes, I want the ESP to transmit the new temperature to my laptop.
On the other side I want to transmit a command from my laptop whenever I want to know the actual temperature (even if the temperature has not changed).
Therefore I have a python server-script and a python client-script both running on my laptop (see scipts below).
In the loop function on my ESP I'm also running a server and a client (script below).
Sending commands from laptop-client to ESP-server works perfectly. Even at high rates and for days without any problem.
Communicating the other way around (that is sending from ESP-client to laptop-server) seems to work in general, but after numerous packages (usually a few hundreds) have been sent from ESP-client to laptop-server the communication fails and the laptop-server only receives empty byte-strings. After that has happened, also sending commands from laptop-client to ESP-server does not work any more temporarily.
When I shutdown the laptop-server, the ESP needs some time to "calm down" and will then continue working as usual.
Can anyone imagine what causes this behaviour? To me it looks like a buffer overflow or something like that.
I appreciate any help and hints about how to implement the desired functionality (do I actually need to run a server on both my laptop and the ESP?).
Laptop-Server:
import socket
import time

# create a socket object
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)

host = "0.0.0.0"
port=1992

# bind to the port
serversocket.bind((host, port))

# queue up to 5 requests
serversocket.listen(5)

try:
  while True:
    # establish a connection
    clientsocket,addr = serversocket.accept()
    try:
        data = clientsocket.recv(1024)
        print(str(addr),":  ",data)
        clientsocket.send("hi there, "+str(addr)+"\n")
        clientsocket.close()
    except:
        pass
except:
  print(" !!! an exception occured !!!")
  serversocket.shutdown(socket.SHUT_RDWR)
  serversocket.close()

Laptop-Client:
import os,sys,re,time,socket,threading,readline

timeout=2

HOST, PORT = "ESP-IP", 1991

response=""
def s_client(data):
    global response
    try:
        response='Error: received no response'

        # Connect to server and send data
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(timeout)
        sock.connect((HOST, PORT))
        sock.sendall(bytes(data + "\n", "utf-8"))

        # Receive data from the server and shut down
        response=str(sock.recv(1024), "utf-8")
    except ConnectionRefusedError:
        response='Error: connection refused by remote host'
    except socket.timeout:
        response='Error: connection timed out'
    finally:
        sock.close()
    return 1

while True:
    try:
        print('  -->  '+s_client(input('_$ ')))
    except KeyboardInterrupt:
        break

ESP-script (containing server and client):
#include <WiFiClient.h>
#include <ESP8266WiFi.h>

IPAddress laptop_ip=(0,0,0,0);
uint16_t TCP_port=1991;
uint16_t TCP_remote_port=1992;
WiFiServer TCPserver(TCP_port);
WiFiClient client;

void ESP_server(void){
  if (!client.connected()) {
    client=TCPserver.available();
  }
  else {
    laptop_ip=client.remoteIP();
    Serial.println("received request");
    int query_l=client.available();
    if(query_l>0){
      String query="";
      for (int nb = 0; nb < query_l-1; nb++){
        query+=(char) client.read();
      }client.read();
      Serial.print("received from laptop: ");Serial.println(query);
      //  Do something with query and return the result
      //  For simplicity I'm just returning a constant value
      client.write("command transmitted");
    }
  }
}

void ESP_client(String message){
  WiFiClient TCPclient;
  if (TCPclient.connect(laptop_ip, TCP_remote_port)){
    TCPclient.print(message);
  }
}

void setup() {
  Serial.begin(115200);
  WiFi.begin("MYSSID","MYPASS");
  Serial.print("connecting with WiFi  ");
  while(WiFi.status()!=WL_CONNECTED){
    Serial.print(".");
    delay(500);
  }Serial.println();
  TCPserver.begin();

  // wait until a command has been received from the laptop
  // ESP_server stores the remote (laptop) ip in laptop_ip
  while(laptop_ip==(0,0,0,0)){
    ESP_server();
  }
}

int temp=0;
void loop() {
  // handle commands sent from my laptop
  ESP_server();

  //  here is a temperature meaurement returning the current temperature
  //  I've replaced it with a temperature generator
  if(temp<30){temp++;}
  else{temp=0;}

  // temperature has changed and needs to be transmitted by this function
  ESP_client((String) temp);
}

The above code differes from the code I'm actually running but it reproduces my problem. I hope that somebody can figure out a misstake or give my some advice about how I could implement things in a better way.
Actually I'm not sure whether the misstake is on laptop- or ESP-side but as the ESP crashes sometimes I think it's the ESP...
I'm using the arduino IDE for flashing, btw.

I found my stupid mistake:
By using try without catching specific exceptions (I know one shouln't do that) in my Laptop-Server script I didn't recognize that I was trying to send unencoded strings.
So,
clientsocket.send("hi there, "+str(addr)+"\n")
has to be
clientsocket.send(bytes(("hi there, "+str(addr)+"\n").encode('utf-8')))
instead.

close the disconnected socket before reconnecting
if (!client.connected()) {
  client.stop();
  client=TCPserver.available();
}

Please excuse my belated response. Unfortunately, that doesn't do the trick...


text:
Arduino Uno - How to write personal data in NTAG213 using RFID-RC522
I am trying to write some data in NTAG213 sticker with this code:
#include <SPI.h>
#include <MFRC522.h>

constexpr uint8_t RST_PIN = 9;     // Configurable, see typical pin layout above
constexpr uint8_t SS_PIN = 10;     // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

// Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
   return;
}

// Select one of the cards
if ( ! mfrc522.PICC_ReadCardSerial()) {
  return;
}

Serial.print(F("Card UID:"));    //Dump UID
for (byte i = 0; i < mfrc522.uid.size; i++) {
   Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
   Serial.print(mfrc522.uid.uidByte[i], HEX);
}
Serial.print(F(" PICC type: "));   // Dump PICC type
MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
Serial.println(mfrc522.PICC_GetTypeName(piccType));

byte buffer[34];
byte block;
MFRC522::StatusCode status;
byte len;

 Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
 // Ask personal data: Family name
 Serial.println(F("Type Family name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
 for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

 block = 1;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("PCD_Authenticate() success: "));

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 block = 2;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }
 else Serial.println(F("MIFARE_Write() success: "));

 // Ask personal data: First name
 Serial.println(F("Type First name, ending with #"));
 len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
 for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

 block = 4;
 //Serial.println(F("Authenticating using key A..."));
 status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("PCD_Authenticate() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
 }

 // Write block
 status = mfrc522.MIFARE_Write(block, buffer, 16);
 if (status != MFRC522::STATUS_OK) {
   Serial.print(F("MIFARE_Write() failed: "));
   Serial.println(mfrc522.GetStatusCodeName(status));
   return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
   }

   // Write block
   status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
   if (status != MFRC522::STATUS_OK) {
     Serial.print(F("MIFARE_Write() failed: "));
     Serial.println(mfrc522.GetStatusCodeName(status));
     return;
   }
   else Serial.println(F("MIFARE_Write() success: "));

   Serial.println(" ");
   mfrc522.PICC_HaltA(); // Halt PICC
   mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD
}

With the tag and card included in the module (RC522) this code works fine:

With the NTAG213 sticker the code doesn't work:

I need to write data in this stickers, how can I do that?

I also tried to use this code, thank you for your answer but I would like to write data to NTAG213 NFC tags from serial monitor. First code (example code from libary) works with serial monitor. How we can write data from serial monitor?

The one that comes with RC552 is MiFare Classic 1K
And the programming running is for the same.
Ntag213 is MiFare Ultralight C, which requires different type of programming..
Try this one
/* mifare ultralight example (25-02-2018)
 *
 *   RFID-RC522 (SPI connexion)
 *
 *   CARD RC522      Arduino (UNO)
 *     SDA  -----------  10 (Configurable, see SS_PIN constant)
 *     SCK  -----------  13
 *     MOSI -----------  11
 *     MISO -----------  12
 *     IRQ  -----------
 *     GND  -----------  GND
 *     RST  -----------  9 (onfigurable, see RST_PIN constant)
 *     3.3V ----------- 3.3V
 *
 */

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

  #define SS_PIN          10
  #define RST_PIN         6

  MFRC522 mfrc522(SS_PIN, RST_PIN);  // Create MFRC522 instance
  MFRC522::StatusCode status; //variable to get card status

  byte buffer[18];  //data transfer buffer (16+2 bytes data+CRC)
  byte size = sizeof(buffer);

  uint8_t pageAddr = 0x06;  //In this example we will write/read 16 bytes (page 6,7,8 and 9).
                            //Ultraligth mem = 16 pages. 4 bytes per page.
                            //Pages 0 to 4 are for special functions.

void setup() {
  Serial.begin(9600); // Initialize serial communications with the PC
  SPI.begin(); // Init SPI bus
  mfrc522.PCD_Init(); // Init MFRC522 card
  Serial.println(F("Sketch has been started!"));
  memcpy(buffer,"HELLO WORLD! ;-)",16);
}

void loop() {
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
    return;

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
    return;

  // Write data ***********************************************

  for (int i=0; i < 4; i++) {
    //data is writen in blocks of 4 bytes (4 bytes per page)
    status = (MFRC522::StatusCode) mfrc522.MIFARE_Ultralight_Write(pageAddr+i, &buffer[i*4], 4);
    if (status != MFRC522::STATUS_OK) {
      Serial.print(F("MIFARE_Read() failed: "));
      Serial.println(mfrc522.GetStatusCodeName(status));
      return;
    }
  }
  Serial.println(F("MIFARE_Ultralight_Write() OK "));
  Serial.println();

  // Read data ***************************************************
  Serial.println(F("Reading data ... "));
  //data in 4 block is readed at once.
  status = (MFRC522::StatusCode) mfrc522.MIFARE_Read(pageAddr, buffer, &size);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Read() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  Serial.print(F("Readed data: "));
  //Dump a byte array to Serial
  for (byte i = 0; i < 16; i++) {
    Serial.write(buffer[i]);
  }
  Serial.println();

  mfrc522.PICC_HaltA();

}


text:
Nema 17, Arduino Uno and stepper motor drive ~2H42B
I tried running Nema 17 stepper motor using the drive in the pic below (not the basic L298N drive, which BTW I successfully used to rotate the motor) .
Could any of you review my existing connections and guide me to complete the remaining ones?
Existing Arduino Uno, Nema 17 motor and drive setup:

Existing connections to Drive from left to right:

Thick yellow wire (0v) from power adapter along with a thin black wire (Ground) from Arduino
Thick red wire (12v +) from power adapter
Green wire (A+) from stepper motor
Black wire (A-) from stepper motor
Red wire (B+) from stepper motor
Blue wire (B-) from stepper motor

What I am missing is connections to PUL, DIR, VCC and ENA. I could put the 4 wires from Arduino D8 to D11 respectively but is that enough? Is there an Arduino sketch I could refer to after the connections are ready?

Connect:

VCC to Arduino 5 V
ENA either directly to VCC or to an Arduino pin (for optional enable driver software control - active high).

Pulse (steps) and direction to Arduino GPIO.
Have a look here Arduino forum Simple Stepper Program - I think you will find what you are looking for.

Ok... been abused by « enable signal negative » in the chart page 5...

Here is the user manual for the BH-MSD-2A Micro stepping driver.
Page 5 shows the two tables giving the connections:

You have already connected P2, and that leaves P1 remaining.
The timing diagram below shows the state of the, PUL, DIR and ENA signals required
.
So, the ENA input can either be held high, by connecting to VCC or connected to a digital output pin of the Arduino, to provide  basic ON/OFF control.
This thread, arduino uno with stepper motor, the OP is using a very similar controller to yours, except that theirs is the 6 A version (BH-MSD-6A). Their code, in the thread has a lot of unnecessary code, and apparently has a number of issues. A stripped down version, of the same code, is as follows:
//arduino code
//
#include <TimerOne.h>
#include <EEPROM.h>

int rpm;
int initial_rpm;
int dutycycle_time=0;
int stepper_Enable=5; //STEPPER MOTOR  ENABLE PIN : PUL-
int stepper_Pulse=6;  // STEPPER MOTOR PULSE PIN :  PUL-

int address_eeprom=0;

void displayNumber(int);
void lightNumber(int);

void setup()
{

  Timer1.attachInterrupt( timerIsr ); // attach the service routine here
  pinMode(stepper_Pulse,OUTPUT); // Analog pin A2 is used for ENABLING the steeper motor
  pinMode(stepper_Enable,OUTPUT); // Analog pin A2 is used for DIRECTION the steeper motor
  digitalWrite(stepper_Pulse,HIGH);
  digitalWrite(stepper_Enable,LOW);

  rpm=EEPROM.read(address_eeprom);
}

void loop()
{

  while(digitalRead(stepper_Enable)==HIGH){
     int cycle_freq=(1600/60)*rpm;
     int dutycycle_freq=2*cycle_freq;
     int dutycycle_time=1000000/dutycycle_freq;
      Timer1.initialize(dutycycle_time); // set a timer of length 100000 microseconds (or 0.1 sec - or 10Hz => the led will blink 5 times, 5 cycles of on-and-off, per second)
      if(analogRead(A3)==LOW )  // STOPPING THE STEPPER MOTOR
       {
         digitalWrite(stepper_Enable,LOW);

       }

  }

  while(digitalRead(stepper_Enable)==LOW)
  {
    int initial_rpm=rpm;
     EEPROM.write(address_eeprom,rpm);

      if(analogRead(A0)==LOW && rpm<300 ) ///increasing speed of stepper motor
    {
          rpm=rpm+1;
         // delay(100);
     }
    if(analogRead(A1)==LOW && rpm>0) ///decreasing speed of stepper motor
    {
          rpm=rpm-1;
         // delay(100);
    }
    if(analogRead(A2)==LOW ) //STARTING THE STEPPER MOTOR
    {
     digitalWrite(stepper_Enable,HIGH);
    }
  }
  if(initial_rpm!=rpm){
    address_eeprom=address_eeprom+1;
  }

}

void timerIsr()
{
  // Toggle LED
  digitalWrite( stepper_Pulse, !digitalRead( stepper_Pulse ));
}

Note that while this should get you started, as the OP states in the thread there are issues with it, that will need fixing.

(I have to go now to fix some Marlin firmware, but I'll come back to this answer later)


text:
I just bought a TFT screen is it still possible to use the serial port 1 and 0?
so I have a question regarding the TFT touch screen... I would like to use the serial ports 1 and 0 (on my UNO) to transmit data to my mega... however it take up those ports. on the back of it, it shows what each prong should occupy. However, nothing is noted to be required for those ports. is it possible to clip those prongs off and still have the screen be usable or are they important to keep?

Please edit your question, and specify the brand and model of TFT touch screen you have, when you edit the question.

Yes, need more information for any kind of definitive answer..  What kind of Touch Screen and what kind of Arduino?

Yes, you can use those pins. Just because there are physical pins on the shield doesn't mean they are actually used. If nothing is written next to them then yes you can use them.
Be warned though that those pins are used for communication with your PC - and that includes uploading sketches - so you may experience problems doing things like that while your Mega is connected to those pins.