text:
Turn on/off low current device (LED) with Arduino
I am just starting with Arduino and my first project consists in switching a LED light with Arduino.
I know a relay must be use to control AC high voltage device (i.e. 240V), however, as my LED seems to be powered by DC 7V voltage (7V - 0.43A written on the power supply which is integrated within the outlet, so I can only access the low voltage wire), I am wondering how to control such a device.
Do I still need a relay or the Arduino can handle this on its own?

Do you have the LED datasheet?

It's the Jansjo lamp from Ikea. I copy below what's written on the outlet: MODEL: KMV-070-030-GS-3, PRI: 220-240V~50/60Hz 0.05A, SEC: 7V_-- 0.43A 3W    SELV

Look into MOSFET as a switch

You could probably run the Arduino from that same 7V supply. Negating the need for a separate adapter.

@chrisl: would you have a mosfet reference in mind which could do the job?

I have just found a relay (SRD-05VDC-SL-C) which can handle 10A/30V DC devices so I will start with this.

Use a power MOSFET transistor. This one from Sparkfun is an example: https://www.sparkfun.com/products/10213
If you use a relay you will probably need transistor and a separate power supply to drive the relay coils anyway, and will also need a flyback diode to protect the control circuit of the relay from the "back EMF" of the relay coils.
DO NOT try to drive relay coils directly from an Arduino digital pin. It will almost certainly fry the Arduino pin, and might destroy the entire Arduino.
A MOSFET transistor like the one I linked can be controlled directly from an Arduino GPIO line, and can switch DC loads of up to 60V and 30A.

Why would I need an extra power supply while the SRD-05VDC-SL-C relay can be driven with 5V, as output by the Arduino?

You can drive the control line of a relay like that with 5V, but it needs a 5V supply to drive the relay coils. It may be within the current limits of the Arudino's 5V line, but it might also cause the 5V line to bounce around as the relay energizes and de-energizes.

No You can easily achieve this by using a NPN Transistor....

simulate this circuit – Schematic created using CircuitLab
You can use BC548 NPN transistor for this is..
But make sure that ground of both emitter and arduino should be same....

This transistor is a poor recommendation because the Collector Current — Continuous for the BC548 is only 100mA, yet the LED load could be up to 430mA.


text:
pin change interrupt on arduino Due
Greeting! I am finding it difficult setting up a pin change interrupt on an arm board ( I am using Arduino due). I found a sample online which I have used but I discovered that when ever an interrupt occurs on a particular pin, it tends to pick up noise from other pins (i.e it prints the state of other pins which didn't get an interrupt) even after appropriate de-bouncing of the signal. For that reason it is quite difficult to carry out appropriate decision with the result am getting. Please I need a code example on how to set of pin change interrupt on Arduino Due for me to continue with my final year project. its very urgent, thanks in anticipation.
Code as Follows:
#include <ArduinoJson.h>
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

#define DEBOUNCE_TIME 50L

#define interruptPin3 3
//#define interruptPin4 4

byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(172, 168, 1, XXX);
IPAddress server(172, 168, 1, XXX);

EthernetClient ethClient;
PubSubClient mqttClient(ethClient);

char data2[700];
void reconnect() {
  // Loop until we're reconnected
    while (!mqttClient.connected())
    {
   SerialUSB.println("Attempting MQTT connection...");

    if (mqttClient.connect("arduinoClient")) {
       SerialUSB.println("Now connected!");
    } else {
      SerialUSB.println("Failed! Please wait for reconnection ...");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//ISR Flags
volatile bool ISR_DEACTIVATED = false;
volatile bool display_int_time = false;

bool debounce_started = false;
unsigned long Isr_debounce_pin_timer;

volatile bool initializationFlag = false;
volatile bool pinVoltStatus = HIGH;
volatile bool lastVoltStatus=LOW;
String pinStatusValue="HIGH";

volatile int interruptPinDigitalPin;

void PinsInitialization() {

  pinMode(interruptPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(interruptPin3), Pin3ChangeInterrupt, CHANGE);
}

void setup()
{
  SerialUSB.begin(9600);
  while (!SerialUSB) continue;
  mqttClient.setServer(server, 11883);

  Ethernet.begin(mac, ip);
  // Allow the hardware to sort itself out
  delay(1500);
  reconnect();

  ISR_DEACTIVATED = false;
  display_int_time = false;
  initializationFlag = false;

  PinsInitialization();
}

void getPinStatus()
{
   bool pinStatus;
    pinStatus = digitalRead(interruptPinDigitalPin);
    if(pinStatus == LOW)
    {
      pinStatusValue = "LOW";
      pinVoltStatus = LOW;
    }else{
      pinStatusValue = "HIGH";
      pinVoltStatus = HIGH;
    }
}

void Pin3ChangeInterrupt()
{
  if(!ISR_DEACTIVATED)
  {
    interruptPinDigitalPin = interruptPin3;
    ISR_DEACTIVATED = true;
    display_int_time = true;
  }
}

//Returns TRUE if pin is stable at desired state, FALSE if bouncing or other state
bool debounce(const int debounce_pin, const bool state, unsigned long &state_latch_start)
{
  static bool current_state;

  // Read the required pin
  current_state = digitalRead(interruptPinDigitalPin);

  if ((!debounce_started) && (current_state == state)) {

      state_latch_start = millis();
      debounce_started = true;
  }

  if (debounce_started && (current_state != state))

      debounce_started = false;

  if (debounce_started && (current_state == state) && (((unsigned long)(millis() - state_latch_start)) >= DEBOUNCE_TIME))
  {
    debounce_started = false;
    // report back that all is goood.
    return(true);
  }

  //Either the pin is at the wrong level, or is still bouncing. Try again later!
  return(false);
}

void messageToPublish(String digitalPinNumber, String voltageStatus)
{
  StaticJsonDocument<200> doc;

    doc["digitalPin"] = digitalPinNumber;
    doc["voltStatus"] = voltageStatus;

    String payload = doc.as<String>();
    payload.toCharArray(data2, (payload.length() + 1));
    mqttClient.publish("interruptTopic", data2);
    SerialUSB.println((String)digitalPinNumber+ ":"+(String) voltageStatus);
}

void loop()
{
  //This runs every time an interrupt occurs
  if (display_int_time)
  {
    detachInterrupt(interruptPinDigitalPin);
    //Done with interrupt stuff. Clear the interrupt flag
    getPinStatus();
  }

   //Debounce for the ISR routine in main loop
    if (ISR_DEACTIVATED)
    {//Wait until the pin settles LOW to reactivate the ISR
      bool debounceStatus = debounce(interruptPinDigitalPin, pinVoltStatus, Isr_debounce_pin_timer);
      if(debounceStatus)
      {
        if (initializationFlag == false)
        {
          ISR_DEACTIVATED = false;
          initializationFlag = true;
        }else
        {

           if(interruptPinDigitalPin == interruptPin3)
          {
            attachInterrupt(digitalPinToInterrupt(interruptPin3), Pin3ChangeInterrupt, CHANGE);
            messageToPublish("Pin3", pinStatusValue);
          }
          display_int_time = false;
          ISR_DEACTIVATED = false;
        }
      }

    }
}

I haven't worked with the Due yet, but on other Arduinos you can deactivate the pin change interrupt for the pins, that you don't need, by setting a mask register. Please post the code, that is showing this problem

@chrisl Thanks alot for your prompt response, am actually just a beginner with arduino and programming at large. Here is the updated question with my code attached

@chrisl can you kindly share a code example on how to achieve that on other arduino boards (AVR am guessing).

source: Stack Exchange

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

sort: votes


text:
Using an Arduino Nano to program (as ISP) a standalone 328p
I uploaded the ArduinoISP sketch to an Arduino Nano to use it as a programmer for other chips.
It worked successfully to program an ATtiny45, I did the usual wiring between them, and added a 10uF between RST and GND of the Nano. Everything worked.
Now I'd like to program a standalone ATmega328p with the Nano, I did the usual wiring as well (see this tutorial), as well as this 10uF cap.
But it does't work:

avrdude: Device signature = 0x000000
  avrdude: Yikes!  Invalid device signature.
           Double check connections and try again, or use -F to override
           this check.

The reason might be because this 328p comes from an Arduino Uno, probably configured to be ext-clocked by a crystal. Whereas I don't have any crystal here and wanted to clock the 328p with the internal clock.
Question: how can I restore the 328p to factory default / internal clock, if I don't have a crystal?
Or what other reason can this error be?
Edit: a solution is found here: Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

There is some differences (signature numbers) between similar processors, like ATMega328P-PU and ATMega328PU. Check this link

Solution: https://arduino.stackexchange.com/questions/68779/change-the-fuses-of-an-arduino-uno-can-an-arduino-uno-change-its-own-fuses

You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)
Or, you could use a high voltage programmer.
Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.
You can then reset the fuses, so it doesn't need a crystal.

Thank you for your answer. I will try to put it on a Uno temporarily just the time of setting clock to internal. How to do this from arduino IDE ? When I select Board: Uno there is no submenu to select clock internal / external. Any idea ?

@Basj sorry about that. I kind of glossed over the fact that you only use the UNO for the crystal, and still need to connect it tho the other Arduino used as ISP programmer. I edited my answer to reflect that. Looking at your edit, it seems like you already  figured it out yourself. Which it great.

That error basically says the bootloader you are trying to burn does not appear to be for that device.  This could be due to corruption or (more likely in your case) harvesting and reconfiguring the hardware.
If the error does not appear when you try to load the bootloader for the Uno (original device you harvested it from for those harvesting from other configurations), you will know it is the latter.
Either way, you can try to -f it by running avrdude to burn the bootloader via command line (as it says).  I've successfully saved  stuff with a corrupt bootloader this way although i've never found it worth the hassle to harvest and reconfigure- if you pulled it off the uno, surely you can stitch it to a clock.
If your clock is off by a bit, you may just need to get lucky over several attempts :)

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


text:
exit status 1 error compiling for board arduino/Genuino Uno when tone code is used
I am just trying to use an ultrasonic sensor with a buzzer but the buzzer doesn't respond to my code. I mean it doesn't make any sound. I tested it to check if by sending 5 volts to it, it will make a sound.. and it did... but using this code below... for some reason, it doesn't make any sound....
#include <NewPing.h>
#define TRIGGER_PIN 11
#define  ECHO_PIN 12
#define buzzer 13

NewPing sonar1 (TRIGGER_PIN, ECHO_PIN);

long inches1;
int sound = 250;

void setup (){

  Serial.begin (9600);

  pinMode (TRIGGER_PIN, OUTPUT);
  pinMode (ECHO_PIN, INPUT);
  pinMode (buzzer, OUTPUT);

}

void loop () {

  inches1 = sonar1.ping_in();
   if (inches1 <= 5 ){
 //   sound = 250;
    tone(buzzer, 1000); // Send 1KHz sound signal...
    delay(1000);        // ...for 1 sec
    noTone(buzzer);     // Stop sound...
    delay(1000);
    Serial.print (inches1);
    Serial.print ('\n');
   }
  delay (200);
}

don't use tone() if it makes sound with 5 V. only set pin HIGH

hhhmmmm.....
i see... i will try.. thanks for your answer... :)

what exit code are you talking about?

What's the whole message the Arduino IDE gives you. Exit 1 usually means you've got a missing library or a syntax error in your code.

If you have a look at the complete error message you will see that there is a collision between the libraries NewPing and Tone.
Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_7'

libraries\NewPing\NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Arduino/Genuino Uno.

yes, but the point is that they don't have to use tone()

I agree! But the question is "error" and perhaps someone take in the information that libraries can have conflicts, I have seen it to many times.


text:
How can I make my arduino start when a magnet is sensed, and stay running until the application determines it was to shut down
My thought was to use a magnetic reed switch to turn on the arduino.  But how do I keep it running if the magnet is moved?  The idea is that the application will determine when it is ok to shut off the power to the arduino.
I don't want any power usage when the system is dormant since it could be weeks between magnetic triggers.
Doug

You can connect a power MOSFET in parallel to the reed switch, that is controlled by the Arduino:

simulate this circuit – Schematic created using CircuitLab
The Arduino powers up, when the reed switch is activated. Then you can activate (drive HIGH) the pin connected to the MOSFET, so that the Arduino is still provided with the needed power through the MOSFET, if the reed switch turns off. If the correct time comes to turn the Arduino off, you can release the digital pin (drive LOW or high impedance/input), so that it get's pulled to low. That will deactivate the MOSFET, which cuts the power off the Arduino.

chrisl - I think this is exactly what I was looking for.  However, I have one question:  Since I am using 4 AA Batteries as a power source, should I connect the "Arduino 5V" connection in your diagram to the Vin pin instead?  Will there be any other issues since I am using a higher voltage? - Doug

No, the higher voltage should not be a problem (most MOSFETs have a rather high voltage limit). Only be sure, that the used MOSFET is rated for a current higher than what your total circuit needs. And it has to drive into saturation for 5V gate voltage

Put your Arduino into deep sleep and attach an interrupt to a pin that is monitoring your reed switch. Once triggered it can run your code before deep sleeping again

The LowPower library will help you to minimize the amount of power used by putting the Arduino to sleep. The Arduino will awaken once the magnetic reed switch triggers it, then you can execute some code before it goes back to sleep again.
There is an example sketch that may work for you:

// **** INCLUDES *****
#include "LowPower.h"

// Use pin 2 as wake up pin
const int wakeUpPin = 2;

void wakeUp()
{
    // Just a handler for the pin interrupt.
}

void setup()
{
    // Configure wake up pin as input.
    // This will consumes few uA of current.
    pinMode(wakeUpPin, INPUT);
}

void loop()
{
    // Allow wake up pin to trigger interrupt on low.
    attachInterrupt(0, wakeUp, LOW);

    // Enter power down state with ADC and BOD module disabled.
    // Wake up when wake up pin is low.
    LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

    // Disable external pin interrupt on wake up pin.
    detachInterrupt(0);

    // Do something here
    // Example: Read sensor, data logging, data transmission.
}

Thanks for this solution.  It's not exactly what I was looking for because of the power consumption (although it is very low!), but I plan on using this for other projects.


text:
Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)
For now, I'm using an Arduino Uno alone including its 328p (no other external chip to program).
I would like to change its fuses to internal 8 Mhz clock (because then I'll move the 328p out of the Arduino Uno), and for simplicity I'd like to do it from Arduino IDE.
Here is what I tried:

I created a new entry in boards.txt copy-pasted from Uno, fuses modified, like this:
atmega328p.name=Atmega328p
atmega328p.upload.tool=avrdude
atmega328p.upload.protocol=arduino
atmega328p.upload.maximum_size=32256
atmega328p.upload.maximum_data_size=2048
atmega328p.upload.speed=115200

atmega328p.bootloader.tool=avrdude
atmega328p.bootloader.low_fuses=0x62
atmega328p.bootloader.high_fuses=0xD9
atmega328p.bootloader.extended_fuses=0xFF
atmega328p.bootloader.unlock_bits=0x3F
atmega328p.bootloader.lock_bits=0x0F
atmega328p.bootloader.file=optiboot/optiboot_atmega328.hex

atmega328p.build.mcu=atmega328p
atmega328p.build.f_cpu=8000000L
atmega328p.build.board=AVR_UNO
atmega328p.build.core=arduino
atmega328p.build.variant=standard

I selected this board in Tools > Board: Atmega328p
I tried to Upload any sketch (and not Upload with programmer since I have no other chip connected to the Arduino Uno), hoping it would modify the fuses during the (successful) Upload process.

I think it didn't work (when I move the 328p outside of the Uno it doesn't work).
How can I change the fuses for an Arduino Uno directly from Arduino IDE, to enable internal 8 Mhz clock?

PS: "Tools > Burn Bootloader" does not succeed, but I think this is normal, since there is just the Arduino Uno, and no other chip / nothing to use as a "Programmer":

avrdude: stk500_recv(): programmer is not responding
  avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

You need a programmer to burn fuses.  If you have another arduino then you can use the Arduino as ISP example sketch in the IDE.  You can't burn fuses just using the USB cable like you upload code with.  The only reason that can talk to the chip at all is because there is another chip to convert it to serial and a bootloader on the 328P to allow it to upload code via serial.

Thank you for your answer. Just be sure: 1) is it really impossible for an Arduino Uno to change its own fuses ?

if I use a Nano as programmer (Arduino as ISP) to program the Uno, during which process will the fuses be modified? During "Burn bootloader" or during "Upload with programmer"?

As mentioned in the other answer, it seems that it's not possible for an Arduino Uno to change its own fuses.
So here is how I did:

I used a Nano (loaded with "Arduino as ISP") as programmer for the Uno with this classical wiring (except that in my case, the left board, the programmer, is a Nano):

I added this to boards.txt (source here):
##############################################################
atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)
atmega328bb.upload.protocol=arduino
atmega328bb.upload.maximum_size=30720
atmega328bb.upload.maximum_data_size=2048
atmega328bb.upload.speed=57600
atmega328bb.upload.tool=avrdude
atmega328bb.bootloader.tool=arduino:avrdude
atmega328bb.bootloader.low_fuses=0xE2
atmega328bb.bootloader.high_fuses=0xDA
atmega328bb.bootloader.extended_fuses=0x05
atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
atmega328bb.bootloader.unlock_bits=0x3F
atmega328bb.bootloader.lock_bits=0x0F
atmega328bb.build.mcu=atmega328p
atmega328bb.build.f_cpu=8000000L
atmega328bb.build.core=arduino
atmega328bb.build.variant=standard
atmega328bb.build.board=AVR_BARE

I used "Programmer: Arduino as ISP", then "Burn bootloader" then "Upload with programmer" with any sketch.
Then the fuses are programmed to Internal 8 Mhz, and we can take the ATmega328p out of the Uno and move it on a breadboard! Working now :)

This is technically possible, but tricky.
First you'd have to wire up the Arduino with some jumpers in such a way that the 328P can use its ICSP header to reprogram the 16U2/8U2 via that chips own header. With the right custom firmware in place you could then re-wire the board so that the 16U2 changes the fuses of the 328P upon boot and reuploads the firmware before switching into its usual function. Then it's just a matter of having the 328P reprogram the 16U2 with the original DFU firmware, and presto! An Arduino that changed its own fuses!
If you just need to change the fuses without a ICSP programmer then that can be done by just programming the 16U2 chip directly through its USB port (although technically that doesn't qualify as the Uno "programming itself").


text:
can't power up arduino from dc jack
Yesterday I was working on Arduino based bluetooth car. I was using adafruit motor shield v1. Arduino and shield were on same power supply(11v li-ion cell battery). Every thing was fine. I decided to add some leds to my car. I connected two leds with 5v on shield pins(leds were in series and were multi-colored so 5v was okay). It worked for sometime but later it stopped working. Green led on arduino was on while other were off. I disconnected shield and supplied arduino from dc jack, same result. Then I connected arduino with usb cable then everything was fine. Now it works because I supply arduino from usb and shield is working too either from usb supply or external supply. What could possibly go wrong?

it was 11.70 as measured with multi-meter

i tried but voltage on shield 9v header was okay

bad voltage regulator probably

Thanks for adding the image of your Arduino Uno R3.

It would appear that the output of the power regulator pin has been vaporized.

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator.  Here is that data sheet for that part. From that data sheet we see the physical image of the part.

It appears that pin 2 has been vaporized.  If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics.  Note the red "X" indicating the vaporized pin 2.

The schematic and the data sheet both indicate the regulator's TAB is also an output.  If true it is difficult to explain why pin 2 vaporized.  Perhaps this particular version of the regulator does not use the TAB as an output.  Or perhaps the Arduino R3 PCB and schematic do not agree.
Added later...
There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin.  Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1.  However, to be sure, you would have to check the voltage before D1 and after U1.

I'm confused. How are you posting images of the OPs Arduino? Or are you describing a failure you have seen? Your post is unclear.

@DuncanC, It appears the person asking the question has posted twice.  The second time with a picture.  I advised him in the other post that he should have edited his original post.  I was hoping he would follow through and delete his second post and move his picture to his original post.

how can i delete question asked before

Your second question has been closed so the option to delete it may no longer be available (there are a number of options following your question just left of your avatar).  Every stackexchange web site has slightly different rules tailored for that group.  There are dozens of stackexchanges sites ranging from Arduinos to Law to Physics.


text:
Why can't I control speed of the motor? (M1 and E1)
When myservo_1,myservo_2,myservo_3,myservo_4 is commented, I can't control the speed of my M1 motor. But only when I uncomment myservo_1 and so on, I can control the motor speed again.
Can someone help me? My codes are listed down below:
#include <Servo.h>
Servo myservo_1;
Servo myservo_2;
Servo myservo_3;
Servo myservo_4;

int SensorL = 0;
int SensorR = 0;
int SensorM = 0;

#define E1 10
#define M1 12
#define E2 11
#define M2 13
int pos = 0;
int incomingByte = 0;

void setup()
{
  Serial.begin(9600);
  myservo_1.attach(9);
  myservo_2.attach(8);
  myservo_3.attach(7);
  myservo_4.attach(6);
  pinMode(SensorL, INPUT);
  pinMode(SensorR, INPUT);
  pinMode(SensorM, INPUT);
  pinMode(M1, OUTPUT);
  pinMode(M2, OUTPUT);
//  pinMode(E1, OUTPUT);
//  pinMode(E2, OUTPUT);
}

void loop()
{
  SensorR = digitalRead(2);
  SensorL = digitalRead(3);
  SensorM = digitalRead(5);

  if (SensorL == LOW && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" FORWARD ");
    //delay(1);
  }
  if (SensorL == HIGH && SensorR == LOW && SensorM == HIGH)
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" LEFT ");
    //delay(1);
  }
  if (SensorL == LOW && SensorR == HIGH && SensorM == HIGH) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 255);
    analogWrite(E2, 255);
    Serial.println(" RIGHT ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == HIGH && SensorM == HIGH) //stop
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 0);
    analogWrite(E2, 0);
    Serial.println(" STOP ");
    //delay(1);
  }

  if (SensorL == HIGH && SensorR == LOW && SensorM == LOW) //move left
  {
    digitalWrite(M1, HIGH);
    digitalWrite(M2, LOW);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" LEFT ");
    //delay(1);
  }

  if (SensorL == LOW && SensorR == HIGH && SensorM == LOW) //move right
  {
    digitalWrite(M1, LOW);
    digitalWrite(M2, HIGH);
    analogWrite(E1, 125);
    analogWrite(E2, 125);
    Serial.println(" MoVE Right ");
    //delay(1);
  }

  if (Serial.available() > 0)
  {
    incomingByte = Serial.read();
    {
      {
        if (incomingByte == 'J')//ARM OPEN
        {
          myservo_1.write(0);
          Serial.println(" ARM OPEN ");
        }
        if (incomingByte == 'L')//ARM CLOSE
        {
          myservo_1.write(180);
          Serial.println(" ARM CLOSE ");
        }
        if (incomingByte == 'I')//ARM UP
        {
          myservo_2.write(0);
          myservo_3.write(180);
          Serial.println(" ARM UP ");
        }
        if (incomingByte == 'K')//ARM DOWN
        {
          myservo_2.write(180);
          myservo_3.write(0);
          Serial.println(" ARM DOWN ");
        }
        if (incomingByte == 'U')//ROTATE LEFT
        {
          myservo_4.write(0);
          Serial.println(" ROTATE LEFT ");
        }
        if (incomingByte == 'O')//ROTATE RIGHT
        {
          myservo_4.write(180);
          Serial.println(" ROATE RIGHT ");
        }
        if (incomingByte == 'M')
        {
          myservo_1.write(90);
          myservo_2.write(90);
          myservo_3.write(90);
          myservo_4.write(90);
          Serial.println(" ALL STOP ");
        }
        if (incomingByte == 'N')//ARM STOP
        {
          myservo_1.write(90);
          Serial.println(" ARM STOP ");
        }
        if (incomingByte == 'B')//UP DOWN STOP
        {
          myservo_2.write(90);
          myservo_3.write(90);
          Serial.println(" UP DOWN STOP ");
        }
        if (incomingByte == 'V')//ROTATION STOP
        {
          myservo_4.write(90);
          Serial.println(" ROTATION STOP ");
        }
        if (incomingByte == 'W')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 200);
          analogWrite(E2, 0);
          Serial.println(" FORWARD ");
        }
        if (incomingByte == 'Z')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" FORWARD ");
          delay(100);
        }
        if (incomingByte == 'S')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" REVERSE ");
        }
        if (incomingByte == 'A')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" LEFT ");
        }
        if (incomingByte == 'D')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 255);
          analogWrite(E2, 255);
          Serial.println(" TURNING RIGHT ");
        }
        if (incomingByte == 'X')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 0);
          analogWrite(E2, 0);
          Serial.println(" STOP MANAUAL ");
        }
        if (incomingByte == 'w')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW FORWARD ");
        }
        if (incomingByte == 's')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW REVERSE ");
        }
        if (incomingByte == 'a')
        {
          digitalWrite(M1, HIGH);
          digitalWrite(M2, LOW);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW LEFT ");
        }
        if (incomingByte == 'd')
        {
          digitalWrite(M1, LOW);
          digitalWrite(M2, HIGH);
          analogWrite(E1, 125);
          analogWrite(E2, 125);
          Serial.println(" SLOW RIGHT ");
        }
      }
    }
  }
}

The Servo library uses timer 1 to send the signals to the servos. But timer 1 is also used to run PWM on pins 9 and 10. It can't however do both.
So since Motor E1 uses pin 10, and timer 1 is already used by the Servo library, PWM, and by extension, analogWrite doesn't work.
E2 uses pin 11, which uses timer 2 for it's PWM, so is therefor no affected.
So move E1 to one of the PWM pins, other than 9 and 10, and thing should start working again.
I however don't know why M1 doesn't work.

I had change the pin for my servo 2 3 5 6 so it will not affect pin 9 and 10 but whoever it still doesnt work properly but my E2 M2 still works fine. Is there any other method to troubleshot it? By the way Thx alot!

That's not what I said. You can use both the servo library (it doesn't matter which pins you use for servos), and PWM on pins 9 and 10. Since you need the servo library, you can't use pins 9 and 10 for PWM. So you need to change the pin for that motor that's currently connected to pin 10. Changing servo pins does not help here.

Please correct your code there are several mistakes, such as

the lines at beginning of loop SensorR = digitalRead(2); SensorL = digitalRead(3); SensorM = digitalRead(5); doesn't make any sense.. as
you not defined 2,3,5 pin as input. And for taking analog input
please change pins 2,3,5 and analog pins..
Motor Pin M1 and M2 are connected 12,13 which are not pwm pins so you can't use to change the speed of your Motor.. Please make this
code sensible....

E1 E2 are used by pwm pins to control the speed and the ir sensor is define as input above


text:
FatalError('Invalid head of packet (0x%s)' % hexify(b)) while uploading on ESP8266
I have this error while uploading my code to ESP8266 despite the fact that the code runs without errors. I have the git version of installation for the board.
ERROR:
File"C:/../../AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.5.2/tools/esptool\esptool.py", line 1889, in slip_reader
raise FatalError('Invalid head of packet (0x%s)' % hexify(b))
esptool.FatalError: Invalid head of packet (0x46)
esptool.FatalError: Invalid head of packet (0x46)

Any help with this? Thanks.

is the esp8266 in flashing mode?

How do I know If its in flashing mode?

io 0 must be pulled down at boot to start in flashing mode. how did you wire the esp8266 module? how is it connected to PC?

why do you say that the code runs without errors? ... how can the code run if you are unable to load it into the ESP8266?

I press the "verify" button and is running without errors.
My esp8266 module is connected via usb cable.
I didn't understand what you are saying about "io 0 must be pulled down..."


text:
how to switch more 230v with arduino?
i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

I'm quite surprised that you need to build a project with so high current/voltage/purpose around a coarse Arduino, are you sure of that ? Regarding the loads to switch, a relay is the simplest solution, but according the load type it could possibly have a huge current peak at turn on which will damage very quickly the relay if it's not intended to handle it, think carefully about it !

What is the current per light? Say it's 5 amps per light. For 40 lights you'd need a >415V (430V would be better) relay rated for >200A. (It would be a good idea to get a relay that can handle a little more than your peak power. So if your load is 200A, get a relay that can handle 20% more, or 240A.) That would be a heavy duty industrial relay, and not something you're going to find from a consumer electronics outlet.

You have to use a relay that can handle minimum 415 volts (and keep some reserve).
Also take the current/amperage into account (possibly use multiple relays).

I thaught that but I was unable to get 415v relay!

See e.g. https://nl.mouser.com/Electromechanical/Relays/General-Purpose-Relays/_/N-5g36 ... the list goes to 480 VAC. Tip: I wouldn't buy such high voltage items from ebay or aliexpress.

Thanks.actually I am computer science student I don't know which one to buy exactly so could help me with that! please

Also make sure the relay can handle the current used by 40 lights.

@prajwalmegalamani I also studied software engineering / computer science ... There are mostly two important properties: voltage (make sure it's at least 415V, preferably more, like 480 VAC. And either use multiple relays, one per light, or one per several light or sum up the current used by all of them and see if there is a relay that can have that amperage. E.g. 40 lights * 1 A / light = 40 A. Use a relay that is e.g. minum 45 of 50 A to be sure.

To add some backround to help you choose: The voltage spec of a relay's contacts (not its coil!) is the maximum voltage that it can open (i.e., interrupt) without arcing across the contacts and damaging them. The current spec - again, of the contacts - is the maximum current the contacts can carry while closed, without overheating. (When they're open, of course, they won't be carrying any current).

I took a training course just to be certified to flip an ~ 415 V breaker and strongly recommend that you do not work with those voltages at the current draw of street lights without proper EE training and certification or at least working with someone who knows what they are doing. We are talking dangerous stuff, here.


text:
When I verify the sketch I get several errors
I am extremely new to Arduino coding and have downloaded a sketch for the PCA9685 to use with model railroading and turnout control.  When I verify the sketch I get several errors ... I don't even know how to resolve and could use some assistance.  There are two sketches:
1:
    /***************************************************
  This sketch can be used to operate any number of turnouts on a
  Model Railroad. Code blocks can be added to accomodate any number
  of servos. This sketch uses only two servos for this demonstration.

  The pushbutton can be replaced with a SPST switch
  commonly used on a control panel. Three pin Bicolor LED can be used
  in place of two seperate LEDs in each circuit.

  10K Ohm pulldown resistor used on switch
  330 Ohm resistor used on LEDs. One per pair of LEDs

  Created 03/02/2019 by Tom Kvichak
  https://tomstrainsandthings.com/
  Additional Arduino Projects can be found at the above web address

 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

int buttonPin0 = 2;   // Can add as many buttons as needed
int ledPin0C = 3;     // C designates Closed position of turnout
int ledPin0T = 4;     // T designates Thrown position of turnout
int buttonState0 = 0;

int buttonPin1 = 5;
int ledPin1C = 6;
int ledPin1T = 7;
int buttonState1 = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutFinal!");
  pwm.begin();
  pwm.setPWMFreq(60);
  delay(30);

  pinMode(ledPin0C, OUTPUT);
  pinMode(ledPin0T, OUTPUT);
  pinMode(buttonPin0, INPUT);
  pinMode(ledPin1C, OUTPUT);
  pinMode(ledPin1T, OUTPUT);
  pinMode(buttonPin1, INPUT);
}

void loop() {
  ///////////
  buttonState0 = digitalRead(buttonPin0);
  if (buttonState0 == HIGH) {
    pwm.setPWM(0, 0, 370);
    digitalWrite(ledPin0T, LOW);
    digitalWrite(ledPin0C, HIGH);
  }
  else  {
    pwm.setPWM(0, 0, 285);
    digitalWrite(ledPin0C, LOW);
    digitalWrite(ledPin0T, HIGH);
  }
  //////////
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH) {
    pwm.setPWM(1, 0, 370);
    digitalWrite(ledPin1T, LOW);
    digitalWrite(ledPin1C, HIGH);
  }
  else  {
    pwm.setPWM(1, 0, 285);
    digitalWrite(ledPin1C, LOW);
    digitalWrite(ledPin1T, HIGH);
  }
  //////////
}

2:
    /***************************************************
  This is an example for our Adafruit 16-channel PWM & Servo driver
  Servo test - this will drive 8 servos, one after the other on the
  first 8 pins of the PCA9685

  Pick one up today in the adafruit shop!
  ------> http://www.adafruit.com/products/815

  These drivers use I2C to communicate, 2 pins are required to
  interface.

  Adafruit invests time and resources providing this open source code,
  please support Adafruit and open-source hardware by purchasing
  products from Adafruit!

  Written by Limor Fried/Ladyada for Adafruit Industries.
  BSD license, all text above must be included in any redistribution
 ****************************************************/

#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
//Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

#define SERVOMIN  110 // this is the 'minimum' pulse length count (out of 4096)
#define SERVOMAX  510 // this is the 'maximum' pulse length count (out of 4096)

// May have to adjust values to match your servos
// Test your servo with the procedures below

// our servo # counter
uint8_t servonum = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("pca9685_TurnoutTest!");
  pwm.begin();
  pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
  delay(50);
}
///////////////////Functions//////////////////////

void driveMin() {
  pwm.setPWM(servonum, 0, SERVOMIN);    //Use to test low range
}
void driveMax() {
  pwm.setPWM(servonum, 0, SERVOMAX);    //Use to test high range
}
///////////////End Of Functions//////////////////

void loop() {

  for( int angle =0; angle<181; angle +=15){  // testing only right now
    delay(500);
    pwm.setPWM(1, 0, convert2angle(angle) );   // May only need this for sweeping the servo
  }

}
int convert2angle(int myang){
   int pulse = map(myang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
   Serial.print("Angle/Pulse: ");Serial.print(myang);
   Serial.print(" / "); Serial.println(pulse);
   return pulse;
}

ERROR MESSAGES:
pca9685_TurnoutTest:23:25: error: redefinition of 'Adafruit_PWMServoDriver pwm'

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:21:25: note: 'Adafruit_PWMServoDriver pwm' previously declared here

 Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                         ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void setup()':

pca9685_TurnoutTest:35:6: error: redefinition of 'void setup()'

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:33:6: note: 'void setup()' previously defined here

 void setup() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void loop()':

pca9685_TurnoutTest:52:6: error: redefinition of 'void loop()'

 void loop() {

      ^

C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:48:6: note: 'void loop()' previously defined here

 void loop() {

      ^

Using library Wire at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\Wire
Using library Adafruit-PWM-Servo-Driver-Library-master at version 2.0.0 in folder: C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master
exit status 1
redefinition of 'Adafruit_PWMServoDriver pwm'

The errors are shown in the Arduino IDE under the sketch. Mark the corresponding text, press Control+C, click "edit" on this site, click at the end of the text in the appearing text editor. Press Control+V to paste the text into the question. Then select the whole text of the error message and click on the {} button, that you can see above the text in the text editor.

You seem to compile a sketch from a folder, where more than 1 .ino file is placed. I guess this from the paths, that are mentioned in the error messages.
The Arduino IDE supports you to organize your code into multiple .ino files, so that big code can be read way easier. For this it put's together all .ino files in the folder of the main sketch, so that they get compiled together.
Since you have at least 2 full sketches in the same folder, this leads to a redefinition error, since these resources (the variable pwm and the functions setup() and loop()) are already defined by the first sketch, when the compiler gets the second sketch.
You have to put all your individual sketches into own folders. Then the error will not appear. I tried to compile your two sketches individually and that worked fine.

Thanks so much ... I will work on creating individual sketches!

Great! Every sketch in an individual file in an individual folder

@WayneHensley If this answer solved your question, you can accept it as correct :)


text:
Why Arduino pins don't output 0 volt?
void setup() {
  pinMode(5, OUTPUT);
}

void loop() {
  analogWrite(5, 0);
  // or
  //digitalWrite(5, LOW);
}

Output is 0.003V and the tiny voltage causes the circuit to draw 20uA.
Is there anyway to get absolute 0V from Arduino PWM pin?

That is a quite tiny voltage. This is not a code issue, since you cannot do more that driving the pin to LOW (which is what happens, when you use analogWrite(pin,0). Please show us your circuit.

@chrisl I'm converting arduino PWM to analog with RC and OA and then use that voltage as a reference voltage for another OA...

To be clear, setting a voltage this precise can be very hard (also because this is in the range of noise). I'm not sure, if this even comes from the Arduino. It might as well come from the opamp circuit itself, since they are not build perfectly either. Depending on your exact circuit it might be better to use an extra circuit part for turning the opamp circuit really off, instead of letting it amplify noise.

@chrisl the 0.003V is from Arduino, of that i'm sure (tested it). it's just gonna count from 0V to 0.5V and then stay at 0.5V. can you please provide a link or anything related to that "extra circuit" you mentioned?

Where get's anything counted? I don't see something like this in your code. About the extra circuit: That was just a thought about cutting the power of the opamps (maybe through a MOSFET) or pulling the output of the opamp over a current limiting resistor to low (also with a MOSFET). Just a thought, not a full fletched circuit, that I could provide a link for

@chrisl i didn't add that counting to the code because it was unrelated to the question. using a mosfet/transistor is a good idea, i'll try that. thanks.

You probably won't get below 3mV even with a transistor (that's what the arduino already does). Do you really need to get below that tiny voltage, I mean, it's 4 times less than the pwm's (ideally filtered) resolution when running at 3V3. If so, the only chance I see is to use external circuitry

Inside the Arduino, a FET is turning on, shorting the output pin to the internal ground on the chip. If the ground of your external circuit is not at the same potential as the ground Inside the chip, your external circuit will see some voltage.  Now.... how could the two grounds be at different potentials?. Perhaps there is some current traveling through the wire connecting the two grounds! Make sure there is NO current in the wire that connects the grounds.

@Sim Son I suggested using a MOSFET after the amplification, because the problem seems, that the opamp amplifies the 3mV to an unwanted greater signal. Pulling the output of the amplification to a low voltage might be sufficient, so that the amplification itself doesn't matter at that point.

@newbie how did you actually test that those 3mV are comming from the arduino? Have any external circuitry been removed when you did so? Otherwise I would suspect those 3mV to be the opamp's input offset voltage.

@SimSon I disconnected everything form Arduino and then measured the voltage on pin 5.

https://majenko.co.uk/blog/what-exactly-gpio-pin

It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.
LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".


text:
Interface a mobile phone's finger print scanner with arduino
Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

any direction you could point me to where i can start digging. Did some basic googling but didnt had any luck.

@Anmol it will be easier if you first identify the finger print sensor (manufacturer, part number etc...).

Long-shot, but if the phone is still functional enough to unlock with a fingerprint, try sensing the overall screen brightness when locked and when unlocked, and use that as the "Fingerprint matched" signal. Obviously this won't work with a truly dead phone.
A lot of processing goes into reading and storing or matching a finger-print. The magic is in the software, not (only in) the sensor. An Arduino (Uno class or similar) is way under-powered for the task. Perhaps one of the Arm- or other high-end Arduinos would have the capability if you had or could write the necessary software.
Short answer: No.

Possible but not directly as the arduino compatible fingerprint sensor contains image formation and saving mechanism which means that those sensors scan a fingerprint form image and send the scan status not the finger print image....
As in case of fingerprint sensor of phones, the sensor directly send the whole image...
so you have to use FPGA (Field Programming Gate Arrays) to make communication between that...
But this is a very expensive way... As FPGA are very expensive but have huge functionality means you can design any circuit any sensor any controller you want using FPGA

In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)
All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.


text:
Requesting help with CNC Project using Arduino
I have made a setup with Arduino Uno, Nema 17, T8 lead screw, IR Sensor and a DC motor.
I am trying to establish a code which:

Resets Home position of the Machining Head on the lead screw
Has an action button, which operates only when the position of the Head is on the lead screw, goes down the specified depth
Takes input from user to run the DC Motor (to rotate the tool on the machine head)
Takes second input to stop rotating and return to the reset position.

I am facing one major problem and two minor problems:
Major Problem:
To remove an error which was later resolved, I added the line: action_permit=0
Now due to some reason (I have pulled a lot of hairs trying to understand this), when I remove this action_permit line, the DC Motor rotation is stopped. I  have to include this line to rotate my DC Motor.
Minor Problem:
To get input from the user as to control when the DC motor starts and stops, I included the code which accepts 'y' for yes (start rotating the DC motor) and 'n' as no (stop rotation and return to home position)
Minor Problem:
I am not sure how to control the PWM, I have copied the code from a video, but do not know how to reach maximum and minimum rpm; also I understand the variation between PWM value and RPM is not linear. Any feedback on how to precisely control the rpm of the motor would be great

int IR_signal=2;
int DC_ENB=11;
int DC_IN3=4;
int DC_IN4=5;
int STE_dir=6;
int STE_step=7;
int STE_ena=10;
int button_reset=8;
int button_action=9;
//define arduino pin
int action_permit;//0-action part is not allowed to run. 1-action part is allowed to run
int IRon;
int COUNT;//the amount of steps that the machine head should go
int HEIGHT;//total height that the machine head should go
int i;
int reset_on;
int action_on;
String Switch_DC;

//parameter
void setup() {
  // put your setup code here, to run once:
  pinMode(IR_signal,INPUT);
  pinMode(button_reset,INPUT);
  pinMode(button_action,INPUT);
  //input part
  pinMode(DC_ENB,OUTPUT);
  pinMode(DC_IN3,OUTPUT);
  pinMode(DC_IN4,OUTPUT);
  pinMode(STE_dir,OUTPUT);
  pinMode(STE_step,OUTPUT);
  pinMode(STE_ena,OUTPUT);
  //output part
  action_permit=0;// ban the action part at the beginning
  COUNT=0;
  HEIGHT=0;

  //original value of parameters
  //digitalWrite(DC_ENB,HIGH);
  analogWrite(DC_ENB,200);
  digitalWrite(STE_ena,LOW);
  digitalWrite(DC_IN3,HIGH);
  digitalWrite(DC_IN4,HIGH);
  //original pin output
  Serial.begin(9600);
  // start the monitor
}

void loop() {
  // put your main code here, to run repeatedly:
  reset_on=digitalRead(button_reset);
  action_on=digitalRead(button_action);
  //read the signal from the button
  if(reset_on==0)//reset button is pressed
  {
    delay(10);
    // preventing manual error
    if(reset_on==0)
    {
      RES();
    }
  }
  if(action_on==0)//action button is pressed
  {
    delay(10);
    // preventing manual error
    if(action_on==0)
    {
      ACT();
    }
  }
}
void RES()//reset part
{
  while(action_permit==0)//when 0, this "while" loop will keep running
  {
    IRon=digitalRead(IR_signal);// read the signal from IR sensor
    if(IRon==1)// machine head is not in original position
    {
      delay(1);
      //ensure the signal is not happened by a BUG
      IRon=digitalRead(IR_signal);
      if(IRon==1)
      {
        digitalWrite(STE_dir,LOW);
        digitalWrite(STE_step,HIGH);
        delay(1);
        digitalWrite(STE_step,LOW);
        delay(1);
        //if machine head is not in original position, it will go up for one step
      }
    }//if HIGH, go up
    else if(IRon==0)
    {
      action_permit=1;
      COUNT=0;

    }//once machine head reaches the original position, controller will get out this loop and allow action part to run
  }
}
void ACT()//action part
{
  if(action_permit==1)
  {

   for(i=0;i<3523;i+=1)
   {
     digitalWrite(STE_dir,HIGH);
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   delay(100);
   for(i=0;i<100;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(10);
     digitalWrite(STE_step,LOW);
     delay(10);
   }
   action_permit=0;

   Serial.println("Please press y to start tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if (Switch_DC == "y")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,HIGH);
    digitalWrite(DC_IN4,LOW);
    delay(2000);
   }

   Serial.println("Please press n to stop tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if(Switch_DC == "n")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,LOW);
    digitalWrite(DC_IN4,LOW);
   }
   digitalWrite(STE_dir,LOW);
   for(i=0;i<4523;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   action_permit=0;
  }
}

for precise control of motor RPM, you need to use a sensor that generates a pulse, or multiple pulses for one revolution of the motor

You have some obvious problems in your code, though I don't know, if the logic will be correct (doing what you want it to do) if you fix them. But either way it is a good start.

You check for action_on and reset_on to be LOW, so I guess the button will pull the pin to LOW, if you press it. You didn't activate the internal pullup resistors, so I guess you already have them externally (if not: You definitely need them). So action_on==0 actually is the case for action is permitted to run, not forbidden. You seem to think, that it is the other way round.
Then you are doing this (and the same with reset_on):
if(action_on==0)//action button is pressed
  {
  delay(10);
  // preventing manual error
  if(action_on==0)

You check, if action_on is zero. If yes, you wait a bit and check the same again. The value of action_on cannot change during the delay, so this will always be true and thus is superfluous. If you meant to read the button again, to check if the button was really pressed (for debouncing), you have to actually read the button state again with digitalRead() and save it to action_on, like you have done before. This is not done automatically for you.
for(i=0;i<3523;i+=1)  Using a global variable to count in a for loop is not a good idea. Instead you should always use a local variable to do this: for(int i=0;i<3523;i+=1)
Switch_DC=Serial.readString();  Using readString() is not good coding, because this function just reads all data, that comes until the timeout hits (default 1s). This is not a reliable way to read data from Serial. Instead you should read each character individually from the Serial interface, put it into a buffer, and only stop and process the output, if a delimiting character was send. Often a newline character \n is used for this. So one message/command, that should be processed as a whole should be ended with a newline character. That will prevent, that the input from serial is processed incorrectly, only because the timing was different. If you only have commands, that consist of only 1 character, you can instead use a single Serial.read(), which reads exactly one character from the Serial interface (or returns -1 if there is no character to read).
Then you wrote this:
if (Switch_DC == "y")
action_permit=0;
{

I guess, here you have inserted the action_permit=0. This cannot be, want you meant. As you wrote it, the action_permit=0 line will only be executed, if Switch_DC is equal to "y", since this statement is inside the if statement. The ; at the end of the statement also closes the if statement. So the code inside the following brackets will always be executed and the brackets are superflous. I don't know, where you intended to insert the action_permit=0, but since it is never used in the rest of the function, it is sufficient to just use it at the end of the function, like you already did. Remove all other of these lines from that function.

If you want to control the RPM of the motor, not just some relative PWM value, you first need to measure the RPM. PWM just controls the electrical energy going into the motor in a relative way (relative to fully powered on). To set a RPM value for the motor, you need to measure the current RPM (for example with a light barrier or a rotary encoder) and use that as input for a PID controller (Proportional Integral Differential). The output of the PID controller then must be fed into the analogWrite() function. The PID controller will raise or lower the PWM value, until the RPM setpoint is reached. There is a PID library for Arduino, that will help you with the calculation.

A big thank you for your help! I will implement your suggestions one by one and see how the code improves. Your help has enabled me to start thinking like a programer and I can't thank you enough for this. As to respond to the action_permit. Yes its a normally closed button, also when I remove action_permit from any place in the code (I have tried removing it one by one at all places), the lines of code near that statement start misbehaving. In regards to your comment about the reading the input from the user, can you suggest a better alternative as to how to read 'y' and 'n'?  Thankyou again!

hi Chrisl, as for the PWM function. Yes I do have a tachometer. I am not sure if I want to use a PID, can you suggest as to how I can calibrate it manually?

About Serial: As I already wrote in the answer, if you just have commands consisting of 1 byte/character, you can just use Serial.read(), which reads exactly 1 character. About PWM: This is a a typical situation for a control cycle. Using PID is the best here. It get's you the desired output fastest and without oscillation. If you only calibrate the PWM values (mapping PWM values to RPMs by testing), that disregards the load on the motor and will not be accurate. Ultimately it is your decision, what you need. PID with the linked library is not difficult.


text:
a code to implement a simple traffic signal and also display on LCD which color is ON?
I have tried code given below for simple traffic signal and also display on LCD which color is ON, but it didn't work. Please me to make it work.

int red = 10;
int yellow = 9;
int green = 8;
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup(){
    pinMode(red, OUTPUT);
    pinMode(yellow, OUTPUT);
    pinMode(green, OUTPUT);
}

void loop(){
    changeLights();
    delay(1500);
}

void changeLights(){
    lcd.print("red");
    digitalWrite(yellow,LOW );
    digitalWrite(red, HIGH);
    digitalWrite(green,LOW );
    delay(3000);
    lcd.print("yellow");
    digitalWrite(yellow,HIGH );
    digitalWrite(red,LOW );
    digitalWrite(green,LOW );
    delay(3000);
    lcd.print("green");
    digitalWrite(yellow,LOW );
    digitalWrite(red,LOW );
    digitalWrite(green,HIGH );
    delay(3000);
    //if(
}

What is not working? What should it be doing?

The LCD won't work unless you begin it...

You need to provide more information. What doesn't work? Have you tried a simple sketch that just turns on one of your lights, then edit it to turn on the next, and then the last? (You need to use the simplest possible code to rule out hardware problems)

Write a sketch to test your LCD.
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 4, 2);
void setup(){
    lcd.begin();
    lcd.print("Hello World!");
}
void loop() {
    lcd.setCursor(0, 1);
    lcd.print(millis() / 1000);
}

Make sure the R/W pin is connected to GND on your breadboard. You may need to connect the contrast pin to 5V. Ideally it should be connected to the wiper of a 10KOhm trimpot with either end connected to GND & 5V (so you can vary the contrast).
Once that set-up works change your code
 void setup(){
     lcd.begin();
     lcd.print("Traffic signals");
     delay(500);
     pinMode(red, OUTPUT);
     pinMode(yellow, OUTPUT);
     pinMode(green, OUTPUT);
 }

 void loop(){
     changeLights();
     lcd.setCursor(0,0);
 }

A small update to your code

Added lcd.begin(); function
added lcd.clear(); function so that old characters will be removed before adding new display

Here is the complete code
int red = 10;
int yellow = 9;
int green = 8;
#include <LiquidCrystal.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
void setup() {
  lcd.begin(16, 2);
  pinMode(red, OUTPUT);
  pinMode(yellow, OUTPUT);
  pinMode(green, OUTPUT);
}

void loop() {
  changeLights();
  delay(1500);
}

void changeLights() {
  lcd.clear();
  lcd.print("red");
  digitalWrite(yellow, LOW );
  digitalWrite(red, HIGH);
  digitalWrite(green, LOW );
  delay(3000);
  lcd.clear();
  lcd.print("yellow");
  digitalWrite(yellow, HIGH );
  digitalWrite(red, LOW );
  digitalWrite(green, LOW );
  delay(3000);
  lcd.clear();
  lcd.print("green");
  digitalWrite(yellow, LOW );
  digitalWrite(red, LOW );
  digitalWrite(green, HIGH );
  delay(3000);
  //if(
}

The output would look like this:

Here is the link to the Arduino simulator example


text:
Expected unqualified-id before 'public'
I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say expected unqualified-id before 'public'.
Does anybody know how to fix this?
void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}

static public int recordings[99999999] = {NULL}

This is not valid C code. Remove the word public.
Also you cannot create such a big array. The Arduino has only 2 KB (SRAM) memory and also since it is static you have to fill it with values directly, like:
static int recordings[5] = { 0, 1, 2, 3, 4 };

How many values you want to store?
In case you need quite a lot (like hundreds), I would use a different solution for the state array as it only stores values 0 or 1. For example, you can use arrays of uint8_t which cost only 1 byte per element, but even better would be to store 8 0 or 1 (boolean) values in one byte each, but that means you have to get/set the values in the correct indices yourself.

Thanks. Yeah, the arrays used up way to much memory. I appreciate the help.

You're welcome.


text:
NodeMCU MQTT getting topic but not calling IF loop
I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. My connection is successful and I am able to receive message/topic printed out on serial console. Here is my code:
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "SSID"
#define wifi_password "PASSWORD"
#define mqtt_server "192.168.1.1"
#define mqtt_user "mqtt_username"
#define mqtt_password "mqtt_password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;
WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>

Security Door

<button class="button">Open</button>

<button class="button">Close</button>

)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();
  Serial.print(messageTemp);

 if(topic=="livingroom/securitydoor"){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       doorClosing();
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function -----------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

Issue is: message from below is not printing in serial
       Serial.print("On");
       Serial.print("On from opening");

In fact code is displaying topic and message in serial console.
My actual user case is to display status on OLED display as well as control relay.

That's not how you compare C strings.  You're comparing two addresses there, and they will never match.  Read up on strcmp.

thanks for suggestions,
When i am doing it in below way, it got worked
if (strcmp(topic, "livingroom/securitydoor") == 0)
  {
    Serial.print(topic);
  }


text:
MKR GPS Shield Sampling Frequency
I have the MKR 1010 and am working on a circuit that needs realtime GPS positioning.  I bought the MKR GPS Shield, and am using it on the I2C bus (attached via cable to the 1010 board), and am using the Arduino_MKRGPS library in my sketch.
I am attempting VERY basic interaction with the board at the moment, and basically just want to print out the GPS coordinates to the serial.
I am using the GPSLocation sample from the Arduino_MKRGPS library (see here):
  /*
  GPS Location

  This sketch uses the GPS to determine the location of the board
  and prints it to the Serial monitor.

  Circuit:
   - MKR board
   - MKR GPS attached via I2C cable

  This example code is in the public domain.
*/

#include <Arduino_MKRGPS.h>

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

  // If you are using the MKR GPS as shield, change the next line to pass
  // the GPS_MODE_SHIELD parameter to the GPS.begin(...)
  if (!GPS.begin()) {
    Serial.println("Failed to initialize GPS!");
    while (1);
  }
}

void loop() {
  // check if there is new GPS data available
  if (GPS.available()) {
    // read GPS values
    float latitude   = GPS.latitude();
    float longitude  = GPS.longitude();
    float altitude   = GPS.altitude();
    float speed      = GPS.speed();
    int   satellites = GPS.satellites();

    // print GPS values
    Serial.print("Location: ");
    Serial.print(latitude, 7);
    Serial.print(", ");
    Serial.println(longitude, 7);

    Serial.print("Altitude: ");
    Serial.print(altitude);
    Serial.println("m");

    Serial.print("Ground speed: ");
    Serial.print(speed);
    Serial.println(" km/h");

    Serial.print("Number of satellites: ");
    Serial.println(satellites);

    Serial.println();
  }

  delay(100);
}

What I'm seeing is that the GPS takes on the order of 30-90 secs to initialize, and then only provides new updated coords every 20-30 secs.  This is all with a clear view of the sky.
Is that really what to expect from this module?  I was under the impression that it could provide several samples per second.  Documentation seems to be very lacking for the Arduino_MKRGPS library.  Anyone else have insights or experience with this module?
Thanks!

It seems that the problem with the GPS was caused by my usage of the arduino delay(...) method in my loop.
I'm assuming that by using delay, the connection to the GPS module was being severed, and in effect, every loop was forcing a reconnect and a new download of satellite details.
In summary, when needing high sample frequency interaction with the GPS, using delay in the sketch won't work.
EDIT:
I've done a lot of digging since originally posting this question/answer and wanted to add my findings for others that are struggling to make the MKR GPS module work for higher than 1Hz sample rate use cases.
I had to make the following two changes to the Arduino_MKRGPS library:

increase baud rate of the GPS connection.  In the very last line of GPS.cpp...

GPSClass GPS(Serial1, 460800, serialDDC, 400000, 7);

In GPS.h, make the sendUbx method a public member of the GPS class.  This allows me to send low-level commands to the SAM-M8Q from my sketch.

After this, I can construct low-level messages in my sketch and configure the GPS to my liking.  Here's what I did to increase the sample rate to 3Hz in my sketch's setup method:
  Serial.println("Configuring GPS refresh rate...");

  //  UBX-CFG-RATE (0x06 0x08) Navigation/Measurement Rate Settings
  //  See UBX-13003221 section 32.10.23.1
  byte payload[6];

  memset(payload, 0x00, sizeof(payload));

  uint16_t measRate = 333;    // ms between gps data publish  (min of 100)
  uint16_t navRate  =   1;    // ratio between measurements and nav solution calculations
  uint16_t timeRef  =   1;    // The time system to which measurements are aligned (0: UTC, 1:GPS, ...)

  // write out the unsigned shorts in little-endian form
  payload[0] = measRate & 0xff;
  payload[1] = (measRate >> 8) & 0xff;
  payload[2] = navRate & 0xff;
  payload[3] = (navRate >> 8) & 0xff;
  payload[4] = timeRef & 0xff;
  payload[5] = (timeRef >>8) && 0xff;

  GPS.sendUbx(0x06, 0x08, payload, sizeof(payload));

  Serial.println("  > done");

Hope this helps someone else struggling with higher data rate use cases.  There's still room for improvement, I think, in particular by reducing the number of sentences returned by the GPS.  I haven't been able to get the sample rate higher than 5Hz, while technically the GPS is supposed to be capable of doing 10Hz.  I'm not sure where the bottleneck is.

Can you post your entire code. The delay can cause some problems mainly because the data is streaming into a buffer and it is supposed to be either read or processed almost immediately depending on the buffer size. I checked the library and the I2C example is built over the UART library and it might be acting up. With UART it is usually pretty straightforward and you should be able to see streaming data coming from the GPS multiple times a second

I edited my original post to include the entire sketch.  It's the sample called "GPSLocation" included in the Arduino_MKRGPS library, with the simple addition of the delay statement at the end of the loop.


text:
Blew my Arduino. Did I wire this correctly?

Hi,
I am currently doing a project and it seems that I may have blown my Arduino Nano (or maybe not). The power LED of the Nano was still on and I believe the L pin blinks once every time I press the reset button.
I wanted to use 4AA alkaline batteries to power my project. The servo is a continuous servo rated for 4-6V and 15-200mA from Parallax. Given that the Nano runs optimally when powered at 7-12V, I decided to buy a step-up converter (adjustable output voltage). It looks like this although I bought it elsewhere:
https://www.ebay.com.au/i/283603471149?chn=ps&norover=1&mkevt=1&mkrid=705-139619-5960-0&mkcid=2&itemid=283603471149&targetid=752505019384&device=c&mktype=pla&googleloc=9071392&poi=&campaignid=1979582348&mkgroupid=72745766764&rlsatarget=pla-752505019384&abcId=1139426&merchantid=7364522&gclid=Cj0KCQjwt5zsBRD8ARIsAJfI4Bh8cSOKugFrugHz-gA-s8nXclnO7H8iQ-WX46FRdhDLchwbl6UyWLgaAr4oEALw_wcB
When I tried to test it with the servo running, my Nano stopped working after several seconds later. Did I wire them up wrongly? I also measured the output of the step-up converter when it was running with a voltmeter between the two terminals of the step-up's output. Would it be possible to short it that way?
Appreciate any help I can get. Thanks

It would be best if everything ran at the same voltage. (And it is necessary that everything uses the same ground.)  Which is possible as there are 5V Arduino boards.  Interestingly, the Arduino nano, according to this schematic, runs at 5V.
In order to use the Arduino Nano at 5V, instead of using VIN / Pin 1, you should be able to skip the Arduino's 5V regulator and use +5V / Pin 4.  But this must be a regulated 5V power source.
Now, why are you having problems controlling the servo?
It is difficult to tell, but your boost switching power supply negative input may not be directly connected to the negative output.  With out a common ground, it may be difficult to create the proper signal to control the servo.
To be specific, if the ground or negative side of the servo power supply is not at the same potential as the ground or negative side of the Arduino power supply, controlling the servo may be difficult at best and at worst you could burn something out on the servo or Arduino.
To check, measure with a volt meter to see if there is any difference between the boost switcher negative input and negative output.
To solve this problem consider using a USB power supply plugged into the Arduino Nano and powering the servo off the 5V at pin 4 of the Nano.  Or, keep using your 6V battery and 6V to 9V boost switching power supply.  Connect this as you are to VIN Pin 1.  The Arduino Nano's 5V power regulator should kick in and provide 5V at pin 4.

Hey thanks for answering!
I used the step-up converter in hopes that it could regulate a constant voltage around 7-12V and also avoid the Nano from resetting when the servo is powered. I didn't want to set the Vin at the lowest possible level to keep it from happening.
I don't have much problem with using the servo if the Arduino didn't blow up. Also, I recalled that the Arduino cant supply enough current to the servo.
The device will need to be portable as well. I think your explanation with the step-up converter may help. I will check on it when I can. Thanks a lot for the help!

I think your servo is small enough such that it can be powered through the Arduino's voltage regulator.  But you are correct to concern your self with the possibility of the servo pulling too much current and resetting the processor or, worse, burning out the Arduino's voltage regulator.  The most common problem I have seen in questions here is not having a common ground between the servo and the Arduino power supplies. If the above answer eventually works for you mark it as correct. If not, add to your question so that others may be able to provide better answers.

I had a friend to check it for me and he said that the grounds are connected appropriately. Still was not too sure why it blew up but appreciate the help. Got the arduino working now as well! cheers!


text:
How to decrease delay for String concatenation + Arduino Due
In my project I need to add a delimiter between integer numbers. In the following code. I add a "," between integer numbers obtained from inputsig matrix. The problem is that concatenation of these numbers with concat() command for a Matrix with 100 rows and 9 columns takes 10 ms.  Is there any efficient way to decrease this delay?
#include <CStringBuilder.h>

int Max_pack_size = 100;

void setup() {
  SerialUSB.begin(115200);

  while (!SerialUSB) ;

}

void loop() {

  String  datas1;
  String  inputsig[Max_pack_size][9];
  char buff[((8+1)*Max_pack_size+1)*9];
  CStringBuilder sb(buff, ((8+1)*Max_pack_size+1)*9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;

    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      //datas1.concat(inputsig[i][j]);
      //datas1.concat(",");
  sb.print(inputsig[i][j]);
  sb.print(F(","));
    }
  }

 SerialUSB.println(float(micros() - t0));
 delay(1000);

 SerialUSB.println(buff);

}

Comments are not for extended discussion; this conversation has been moved to chat.

I don't have Arduino Due but I have an Arduino Uno so I had to adjust the code to run with much smaller RAM and use the standard Serial.
This is the original code as you can see i can use only Max_pack_size of 5
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];
  CStringBuilder sb(buff, ((8 + 1)*Max_pack_size + 1) * 9);

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      sb.print(inputsig[i][j]);
      sb.print(',');
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

The timer displays values around 2.08 milliseconds for the code above.
First optimization attempts is to stop using StringBuilder. Everything that's written to be universal and easy to use is usually slow.
Note that when we generate String from long the implicit cast allocates char buf[2 + 3 * sizeof(long)]; so the max length of such string is 14 characters. String is of course terminated by null character '\0'
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  String inputsig[Max_pack_size][9];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      inputsig[i][j] = 16777215;
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}
}

Now the timer displays 0.86 milliseconds. Much better, but we can improve even more!
Let's drop the String. It's just an over complicated wrapper for a char array anyway.
#include <CStringBuilder.h>

int Max_pack_size = 5;

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

void loop() {

  char inputsig[Max_pack_size][9][14];
  char buff[((8 + 1)*Max_pack_size + 1) * 9];

  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      ltoa(16777215, inputsig[i][j], 10);
    }
  }

  int t0 = micros();

  int p = 0;
  for (int i = 0; i < Max_pack_size; i++)
  {
    for (int j = 0; j < 9; j++)
    {
      for (int k = 0 ; k < 14; k++)
      {
        char c = inputsig[i][j][k];

        if (c == 0)
          break;
        else
          buff[p++] = c;
      }

      buff[p++] = ',';
    }
  }

  int t1 = micros();

  Serial.println(float(t1 - t0) / 1000.0);
  delay(1000);

  Serial.println(buff);
}

Now the timer shows 0.50 milliseconds. So we optimized the code to the point it runs 4 times as fast.

Deat Filip. Thanks for your help. I tested this and could decrease the delay to 2ms.


text:
How to use the pushbutton without using if, else
I want to let the led blink for 3 seconds then 2 seconds then one second using the button one time and without using if/else
void setup() {
    // put your setup code here, to run once:
    pinMode(5, INPUT);
    pinMode(6, OUTPUT);
}

void loop() {
    // put your main code here, to run repeatedly:
    digitalRead(5, HIGH);
    digitalWrite(6, HIGH);
    delay(3000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(2000);
    digitalWrite(6, LOW);
    digitalWrite(6, HIGH);
    delay(1000);
}

Why don't you want to use if/else? Or is this a school assignment?

it is a school assignment actually

switch case is your friend ;)

Switch is an alternative to if --- unless are you at the "interrupts" section of your class...

digitalRead() returns either LOW (which is a macro equivalent to 0) or HIGH (which is 1).

I can think of a dozen ways to write what you want.  None of them are very good, the best method would use an if statement.  The problem is that the teacher probably wants you to use some skill that you just learned and we don't know what that is.  I could write you a great program that doesn't use an if statement, but if it isn't what your teacher is looking for then you probably still wont' get credit for the assignment and you'll make it readily apparent that you have people on the internet doing your homework for you, which if your teacher is any good at all get you kicked out of class.

@GMc delay doesn't work when put inside interrupt method, because itself it uses interrupts to increase the millis timer counter. The only way of writing this logic with interrupts is to set a flag in global scope and then use if to test for that flag in loop method. So interrupts are not the good solution to this homework. Unless maybe make button press interrupt to setup timer interrupt? That seems really awful..

@FilipFranik I agree and did not advocate that. You definitely don't want to include any lengthy operations in an interrupt service routine. My comment was more of a suggestion that switch is an obvious alternative to using an if - but it is also possible that the OP was at the "interrupts" section of their class and thus would require a completely different approach to the serial code as posted in the question - and as you suggest, definitely should not be using delay. Hopefully that was also taught in the class... I should perhaps in hindsight been more clear in my original comment.

was that a 'cut-and-pasto' with 'digitalRead(5, HIGH);'?  The digitalRead() function only takes one argument, not 2.

And, while I'm on the subject, some comments about good coding style.  Try to avoid using 'magic numbers' in your code.  Statements like 'digitalWrite(6,HIGH)' should be replaced by something like 'digitalWrite(LED_PIN, HIGH), where LED_PIN is defined before setup() with something like '#define LED_PIN 6' or 'const int LED_PIN = 6;' (which one you use here is more a matter of style than anything else).  Also explanatory comments should be used liberally; they will tend to make you think about what it is you are trying to do and will help reviewers like us to understand your intent.

As the required operation is finite and short, you can just hard code the sequence.

You could you simple inversion of boolean variable to set state of LED.
const int LedPin = 5;
bool ledState = true;

// in your loop

// bool will be transformed from true to 1 (HIGH)
digitalWrite(LedPin, (int)ledState);
// invert LED state to be false
ledState = !ledState;
// false -> 0 (LOW)
digitalWrite(LedPin, (int)ledState);

Ternary operator maybe helpful. [Reference]

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes.


text:
Interrupt is activated as soon as I insert a jumper wire into the port
I have written a very simple code to test the interrupt functionality of my Arduino Uno expansion board:
const byte buttonPin3 = 3;

void setup() {
  pinMode(buttonPin3, INPUT);
  attachInterrupt(digitalPinToInterrupt(buttonPin3), trigger, CHANGE);

  Serial.begin(9600);
}

void loop() {
}

void trigger(){
  Serial.println("trigger");
}

However, the Serial.println("trigger"); is activated as soon as I insert a jumper wire into pins 2 or 3. It seems like I have broken the microcontroller. I would appreciate if you could help me know if there is something wrong with my code or I need to change the microcontroller? if I have to replace the MCU can I just use any identical AVR and just place it on the DIP IC socket adaptor?
P.S. Filip Franik asked me to draw the schematics:

simulate this circuit – Schematic created using CircuitLab
P.S. I used the official Button's tutorial and now everything works just fine. I can't reproduce the issue anymore for no obvious reason!.

In the circuit that you posted there is not button or jumper wire to somewhere else. In the current state, both pins will only show 0 as their state. Please explain what jumper cable you actually mean, where you are connecting it and where it goes from there.

Connect both Pin2 and Pin3 with two 1K resistors to ground.
When a pin that's set as INPUT is "floating" (it's not connected to anything) the value on it is "undetermined" and interrupt can trigger when a neighboring pin status changes, or even just magically by itself. The 1K resistors (called pulldown resistors) will make sure that pin is set to LOW when it's not connected using the jumper.
This circuit should put a stable 0V on Pin3 when switch is unpressed and 5V when it's pressed. You should be able to verify that using any voltage meter.

If the issue persists then swapping the microcontroller on the Arduino is just one of the steps you need to perform. You would also need to burn a bootloader on the chip. It's not a hard procedure but it requires a second Arduino.

Doing this there are no continuous interrupts. However, as soon as I remove the wire to connect it to another place where it should be it starts triggering again!

Can you draw your connections? I have problems picturing your design. Also use a voltage meter and check if there is a 5V after you put the jumper and resistor on the pin.

added to the post

"...as soon as I remove the wire to connect it to another place where it should be it starts triggering again!" That makes sense. When the pin is not connected to anything, it begins floating again.

CMOS inputs "float" when not connected to anything, and will give semi-random values. You can either connect the pin to ground via a medium value resistor (1kΩ-10kΩ), or set the pin to INPUT_PULLUP mode.
You shouldn't move the interrupt pin connections around while the Arduino is running. As soon as you disconnect the wire from the input, it begins floating again, and can detect semi-random HIGH/LOW values.
If you use an external pull-down resistor, put a connector after the ground connection and move that connection, so the pull-down resistor is always connected to the pin.
If you use INPUT_PULLUP mode, you should not use a pull down or pull up resistor. This mode connects the pin weakly to +5V, which will hold it at a HIGH value when not connected to anything. You would then ground it to trigger an interrupt. In INPUT_PULLUP mode you can probably disconnect the wire from the interrupt pin without triggering interrupts.


text:
How to Sort a String with Number by Ascending
I have trouble figuring out how to sort a String that has a Number in it.
The String im sending looks like 112:AAAA and 111:EEEE, how would I sort it so that the 111 will be the first in an array but (and here is what I cant figure out) the sorted array should contain the letters again so it would be a String Array that is sorted by the numbers and look like 111:EEEE, 112:AAAA.
I wanted to use what I have seen on C#, having a key and value, but that does not seem to exist in arduino code. So I improvised by writing everything in 1 char array.
edit: I see I'm mixing up char array and string, im very flexible and its no trouble to change to 1 or the other, currently I use char arrays.
I guess it would also be enough to just sort the strings, but i cant find a function for that also.

Are the numbers always 3-digit long? If so, you can just lexicographically sort the strings.

They can be 2-3 digit long

As Michel Keijzers points out, qsort is the standard sorting function
from the libc. Now, since your numbers can start with either two or
three digits, you can not sort them lexicographically, because if you
did so 111 would sort before 82. Instead I suggest to:

parse the start of the strings as integers
compare the integers
if the integers are equal, then sort the strings lexicographically.

The simplest way to parse the strings into integers is atoi(). Unlike
functions like strtol(), atoi() does no error checking, but it is
good enough if you know for sure that the strings have the right format.
Here is the comparison function:
int compare(const void *a, const void *b)
{
    // Get the strings.
    const char *sa = *(const char * const *) a;
    const char *sb = *(const char * const *) b;

    // First, compare the numeric prefixes.
    int ia = atoi(sa);
    int ib = atoi(sb);
    if (ia < ib) return -1;
    if (ia > ib) return +1;

    // If equal, compare the strings lexicographically.
    return strcmp(sa, sb);
}

And here is an example on how to use it:
#define STR_COUNT 3
const char *strings[STR_COUNT] = { "112:AAAA", "82:FFFF", "111:EEEE" };
qsort(strings, STR_COUNT, sizeof strings[0], compare);

Now the array of strings is sorted as ("82:FFFF", "111:EEEE",
"112:AAAA").

You can use the qsort function (see c-library-function-to-do-sort).
With the user definable comp function you can get the first two or three characters, convert it to in integer and compare it against the converted integer from another element.
I would not advise to use strings, because of the limited SRAM storage of an Arduino, you might run out of memory too fast.


text:
Esp8266 fatal timeout error
I recently got my esp8266-01 and for interfacing with Arduino I completed all the steps need for right form pins to board allotting from esp8266 community after everything I still get error of "connection failed fatal error : timeout ", so anyone just help out for
 soln ?
I am interfacing with empty code of loops only to check it's response at connectivity at first .

how did you wire it? is it the esp-01S version? did you put it in flashing mode for upload?

Rx to Rx and tx to tx , vcc 3.3, channel 5 , esp8266 - 01, no I had put it for blink mode for basic checking of module


text:
How to get current Date
How to get Current date, month and year. I have used RTC, NTPClient, but it didn't work. This gives default output of 1970. What can I do for fixing it.

time_t now = time(nullptr);
struct tm* newtime = localtime(&now);
String tmpNow = "";
tmpNow += String(newtime->tm_year + 1900);
tmpNow += "-";
tmpNow += String(newtime->tm_mon + 1);
tmpNow += "-";
tmpNow += String(newtime->tm_mday);
tmpNow += " ";

I don't think that the Arduino knows what date it is. To use NTPClient you need to connect Arduino to internet somehow so the date can be downloaded from NTPServer.

It is already connected to internet

Then you probably have a bug somewhere. Post your code here so we can check what's wrong. Use "code" button to format it in readable way.

From what library you get the "localtime" function? I can't find it in any of the libraries you referenced above.

An example how to use NTPClient is available at the projects github
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "<SSID>";
const char *password = "<PASSWORD>";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

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

  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

Form what I found TimeRTC requires an external device called DS1307RTC to keep track of the time as shown in video here and with it we should be able to get the real time as seen in github example
#include <TimeLib.h>
#include <Wire.h>
#include <DS1307RTC.h>  // a basic DS1307 library that returns time as a time_t

void setup()  {
  Serial.begin(9600);
  while (!Serial) ; // wait until Arduino Serial Monitor opens
  setSyncProvider(RTC.get);   // the function to get the time from the RTC
  if(timeStatus()!= timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");
}

void loop()
{
  if (timeStatus() == timeSet) {
    digitalClockDisplay();
  } else {
    Serial.println("The time has not been set.  Please run the Time");
    Serial.println("TimeRTCSet example, or DS1307RTC SetTime example.");
    Serial.println();
    delay(4000);
  }
  delay(1000);
}

void digitalClockDisplay(){
  // digital clock display of the time
  Serial.print(hour());
  printDigits(minute());
  printDigits(second());
  Serial.print(" ");
  Serial.print(day());
  Serial.print(" ");
  Serial.print(month());
  Serial.print(" ");
  Serial.print(year());
  Serial.println();
}

void printDigits(int digits){
  // utility function for digital clock display: prints preceding colon and leading 0
  Serial.print(":");
  if(digits < 10)
    Serial.print('0');
  Serial.print(digits);
}

If what I understand from your code you are actually not using any RTP or NTP. You are only creating a Time object with no values and you read it default values.
Check some more examples here

using RTC it gives output like -jan 8 2013 . How to get current date and year

@ShivaniDongre Are you 100% sure that the DS1307RTC has correct date setup? It depends on it's battery to keep date updated. If at any point the battery was removed date is reset to default value, and then inserting a new battery makes it count time from January first.