text:
arduino mega buzzer output
I have project by Arduino mega which have 22 inputs and 22 outputs and buzzer reset and output reset pushbuttons , it have two status

if the input is high(not continuous ) the output will on and the buzzer will be on, if  output reset pushbutton is pressed  the output will off , if buzzer reset pushbutton  is pressed the buzzer will off.
if the input is always high (continuous high signal on input ) the output will on and the buzzer will be on, in this case we will not reset the output even if the output  reset pushbutton is pressed , and we will be able to reset the(turn off) buzzer by the  buzzer reset pushbutton, and wait until  input state to change to high again to repeat procedure

help me with editing my code

    //int input[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,23,24}; //input pins (23 for reset ,24 for buzzer reset)
//int output[] = {26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 24, 34, 44, 45, 46, 47, 48,49}; //output pins (49 for buzzer)

int in1 =     2;

int in25 =   26;// for output reset
int in26 =   27;// for buzzer reset

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

int out1 = 28   ;

int out24= 51   ;
int out25= 52   ; // output for buzzer

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

int buttonState1 =  0;

int buttonState24 =  0;
int buttonState25 =  0; //for  reset
int buttonState26 =  0; //for buzzer reset

//unsigned long previousMillis = 0;        // will store last time buzzer was updated
//const long interval = 10000;           // interval at which to buzzer (milliseconds)
//int buzzerState = LOW;             // buzzerState used to set the buzzer

void setup() {

  pinMode(in1 , INPUT);

  pinMode(in24 , INPUT);
  pinMode(in25 , INPUT);
  pinMode(in26 , INPUT);

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

pinMode(out1, OUTPUT);
pinMode(out2, OUTPUT);

pinMode(out24, OUTPUT);
pinMode(out25, OUTPUT);

digitalWrite(out25, LOW); // buzzer LOW

}

void loop() {
  buttonState1 = digitalRead(in1);
  if (buttonState1 == HIGH) {
    digitalWrite(out1, LOW);
    //digitalWrite(out25, LOW);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState25 = digitalRead(in25); //read reset button state from input (25) pin 26
  if (buttonState25 == HIGH )

  {
    digitalWrite(out1, HIGH); //reset out1
    //digitalWrite(buzzer, LOW);
  }

  //else {
   // buttonState26 = digitalRead(in26); //read the buzzer reset button state from input (26)pin 27
   // if (buttonState26 == HIGH) {
    //  digitalWrite(out25, HIGH);

   // }
  //}

    //   while (digitalRead(input1) == HIGH);
    //digitalWrite(buzzerrelay, LOW);

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

 buttonState2 = digitalRead(in2);
  if (buttonState2 == HIGH) {
    digitalWrite(out2, LOW);
   // digitalWrite(out25, LOW);
    //delay(10000);
    //digitalWrite(buzzer, LOW);
  }

  buttonState25 = digitalRead(in25); //read reset button state
  if (buttonState25 == HIGH )

  {
    digitalWrite(out2, HIGH); //reset the output
    //digitalWrite(buzzer, LOW);
  }

 // else {
  //  buttonState26 = digitalRead(in26); //read the buzzer reset button state
    //if (buttonState26 == HIGH) {
    //  digitalWrite(out25, HIGH);

    //}
 // }

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

  //  }
 // }

  }

your code is definitely overly repetitive ... why did you opt to not use arrays, such as the first two lines of your code, which you commented out? .... it is definitely simpler to use in[1], in[2], etc. because you can use a for loop to access the variables... you cannot use a loop for in1, in2, etc. so you are forced to repeat the same code multiple times

What is the problem with your code? Is it not working? If yes, please explain, what you expected and what it actually does

i have  tried to use arrays put they do not worked properly because i am new to Arduino and arrays , and now I'm focusing on solving buzzer problem

it is working put the buzzer part is not working ,,the problem that if the input is contentious the buzzer could not be reset and still ON until the input goes low after that i can reset the buzzer

You posted over 850 lines of code. It's unrealistic to expect your readers to review and post suggestions on that much code. You need to simplify and narrow your question, and provide a smaller example project that illustrates what you are struggling with.

i simplified the code ;)

couple of questions ... what is the difference between continuous high input and non-continuous high input ................... re. #2 if the input is continuously high, then how can you wait until input state to change to high again?

Any time you have the same sequence of code repeated over and over with slight variations, that is a "code smell" (an indication that you may be using the wrong approach.)
You should use arrays of pin numbers as you have in the first couple of commented-out lines, and write code that loops through those arrays, as well as functions that take parameters and can do the same thing using different values that are passed in.
Don't try to tackle a problem like this without learning the skills and concepts you need. You said "...I am new to Arduino and arrays , and now I'm focusing on solving buzzer problem." That is a mistake. Code like you have posted is hard to write, hard to read, and much harder to maintain.

Here is your code simplified. (untested)
Since the pins are sequential, you could calculate pin numbers, instead of using an array for pin number lookup.
For example, you could use a loop for (int i = 1; i < 25; i++) and first input pin would be referenced as i + 1 and first output pin would be referenced as i + 27.
// https://arduino.stackexchange.com/questions/80972/arduino-mega-buzzer-output

//  int in25 = 26;                           // for output reset
//  int in26 = 27;                           // for buzzer reset

//  int out25 = 52   ;                       // output for buzzer

//  int buttonState25 =  0;                  // for  reset
//  int buttonState26 =  0;                  // for buzzer reset

//  arrays are zero indexed (first element is at index zero)
//  array index      0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26

    int in [27] = {255,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27};   // input  pin numbers (26 for reset, 27 for buzzer reset)
    int out[26] = {255, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 24, 34, 44, 45, 46, 47, 48, 49, 50, 51, 52    };   // output pin numbers (52 for buzzer)

    int buttonState[27];

//  unsigned long previousMillis = 0;        // will store last time buzzer was updated
//  const long interval          = 10000;    // interval at which to buzzer (milliseconds)
//  int buzzerState              = LOW;      // buzzerState used to set the buzzer

    void setup() {

      for (int i = 1; i < 27; i++) { buttonState[i] = 0;      }       // clear states of buttons 1 to 26
      for (int i = 1; i < 26; i++) { pinMode(out[i], OUTPUT); }       // configure outputs 1 to 25

      digitalWrite(out[25], LOW);                                     // buzzer LOW

    }

    void loop() {

      for (int i = 1; i < 25; i++) {                                  // loop buttons 1 to 24

        buttonState[i] = digitalRead(in[i]);

        if (buttonState[i] == HIGH) {
          digitalWrite(out[i], LOW);
//        digitalWrite(out[25], LOW);
//        delay(10000);
//        digitalWrite(buzzer, LOW);
        }

        buttonState[25] = digitalRead(in[25]);       // read reset button state

        if (buttonState[25] == HIGH ) {
          digitalWrite(out[i], HIGH);                // reset the output
//        digitalWrite(buzzer, LOW);
        }

//      else {
//        buttonState[26] = digitalRead(in[26]);     // read the buzzer reset button state
//        if (buttonState[26] == HIGH) {
//          digitalWrite(out[25], HIGH);
//        }
//      }
      }
    }


text:
Decreasing Arduino pro micro power consumption
I'm working on a project that involves sending GPS coordinates wirelessly from an arduino board to another one. I was thinking of using an arduino micro for this task. The problem is that I want it to last as long as possible on a lithium battery. I searched and found too many tutorials on how to decrease arduino pro mini power consumption, but I didn't find anything related to the arduino pro micro. So I was thinking, does the same procedure used to decrease the arduino pro mini consumption apply for the arduino pri micro?
Also, what microcontroller do you suggest for this project? (PIC, Arduino mini, micro, nano...)

how are you obtaining the GPS coordinates?

Most techniques apply to all Arduino boards. Remove the power led. Put the microcontroller in sleep-mode. Possibly remove/exchange the voltage regulator. Put attached devices to sleep, or remove power to them entirely.

Bringing Down power consumption by taking the LED out and lowering the
  clock ?

Yes, you can do that! And you are okay with Arduino unless you want to complicate things more...If you want to check out other methods then you can check out the Microcontrollers Schematics and also the datasheets of their Components...

source: Stack Exchange

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

sort: votes


text:
Arduino TimerOne breaks the program when calling "digitalRead"
I'm trying to make this project.
But i have a problem running this code. It appears to be val = digitalRead(inPin); breaks entire program. just because i call this from the callback function which attached as an interrupt function Timer1.attachInterrupt(callback);
Here is the more simplified problem simulation program,
#include "TimerOne.h"

int inPin = 7;   // sensing digital pin 7

int val;

void setup() {
  pinMode(inPin, INPUT);      // sets the digital pin 7 as input to sense receiver input signal

  Serial.begin(9600);
  Timer1.initialize(8);  // initialize timer1, and set the frequency; this drives both the LC tank as well as the pulse timing clock
  // note: modify this as needed to achieve resonance and good match with the desired tags
  // the argument value is in microseconds per RF cycle, so 8us will yield RF of 125kHz, 7us --> 143kHz, etc.

  Timer1.pwm(9, 512);

  Timer1.attachInterrupt(callback);
}

void callback()
{
  val = digitalRead(inPin);//once you comment this line, it works fine
}

void loop() {
  Serial.print("Program running \n");

}

Any help is much appreciated.

The time between 2 interrupt triggers is only 8us. Also digitalRead() is a quite big function, that needs some time to execute (I don't know how much). That way it is to short for the Serial print command to execute in the leftover time. Make the following change and you will see, that it works.
void loop(){
  noInterrupts();
  Serial.print("Program running \n");
  interrupts();
  delay(1000);
}

Now the interrupts are disabled during the execution of the Serial.print(), so that it can finish. After this the interrupts are enabled again and we wait for 1 second to give the interrupts some time before we are disabling them again.
The speed of the Arduino is limited, so you cannot do much, when constantly triggering interrupts in the pace of 8us. If you only want to check this digital input you can get the value directly with using the PINB registers (refer to this side), which works much faster.
Also you should consider making the variable val volatile, since it will can change everytime through your interrupt service routine.

Thanks mate, It all makes sense. And i'll try this out and let you know how it went. Still i wonder how the tutorial worked for them at some point, Perhaps it was an older Arduino core?

I'm not sure about how the tutorial worked for them. On a quick look I see, that they are not sending serial in every loop cycle, but only when special conditions arrive. Not sure about how this changes the problem. To be sure you would have to measure the length of the interrupt routine with an oszilloscope

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


text:
5V Pressure sensor module with 3.3V ADC
I'm using ESP32 to read analogue pressure readings from this pressure transducer. My Problem is this sensor outputs 0.5V – 4.5V linear voltage output based on the pressure but ESP32 can only handle 0 - 3.3V in the ADC inputs. Can anyone advice me to how to accomplish this in 0 - 3.3V range?

voltage divider is what you need ... approx values for R1 and R2 are R2 = 2 * R1 ... that will produce 3v on 4.5v input

@JaromandaX That could work if the output is low impedance. It may not be though, in which case it would need to be buffered first, since the voltage divider would mess things up royally.

LOL... Gotta love Chinese specifications... Insulation Resistance: >100mΩ 500VDC... milli ohms?!?!

@Majenko you can't challenge that statement.. In fact it should be greater than 100 milliohms... Hopefully ;)

@frarugi87 You right that it's not "wrong" ;) It's just like saying that "The temperature today is greater than 3 Kelvin"...

@JaromandaX, Thanks for the comment and thats what exactly i wanted. I can accept it as the correct answer if you could just put it as an answer.


text:
Arduino UNO stuck in Setup function when interfacing UNO with ESP8266 module
Following is my code that i am trying to use it with Arduino Uno with ESP8266 module but my code stucked in setup function why is that.
#include "ESP8266.h"
#include <SoftwareSerial.h>
SoftwareSerial mySerial(12,13);
#define SSID        "abcd"
#define PASSWORD    "87654321"
#define HOST_NAME   "www.baidu.com"
#define HOST_PORT   (80)

ESP8266 wifi(mySerial);

void setup(void)
{
    Serial.begin(9600);
    Serial.print("setup begin\r\n");

    Serial.print("FW Version:");
    Serial.println(wifi.getVersion().c_str());

    if (wifi.setOprToStationSoftAP()) {
        Serial.print("to station + softap ok\r\n");
    } else {
        Serial.print("to station + softap err\r\n");
    }

//    if (wifi.joinAP(SSID, PASSWORD)) {
//        Serial.print("Join AP success\r\n");
//
//        Serial.print("IP:");
//        Serial.println( wifi.getLocalIP().c_str());
//    } else {
//        Serial.print("Join AP failure\r\n");
//    }
    delay(500);
    if (wifi.disableMUX()) {
        Serial.print("single ok\r\n");
    } else {
        Serial.print("single err\r\n");
    }

    Serial.print("setup end\r\n");

}

void loop(void)
{
    uint8_t buffer[1024] = {0};

    if (wifi.createTCP(HOST_NAME, HOST_PORT)) {
        Serial.print("create tcp ok\r\n");
    } else {
        Serial.print("create tcp err\r\n");
    }

    char *hello = "GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n";
    wifi.send((const uint8_t*)hello, strlen(hello));

    uint32_t len = wifi.recv(buffer, sizeof(buffer), 10000);
    if (len > 0) {
        Serial.print("Received:[");
        for(uint32_t i = 0; i < len; i++) {
            Serial.print((char)buffer[i]);
        }
        Serial.print("]\r\n");
    }

    if (wifi.releaseTCP()) {
        Serial.print("release tcp ok\r\n");
    } else {
        Serial.print("release tcp err\r\n");
    }

    while(1);

}

On Serial Monitor i get the following continuously
setup begin
FW Version:0018000902
to station + softap ok
singl

setup begin
    FW Version:0018000902
    to station + softap ok
    singl

It's always a good idea to put a serial output in the setup of your code.

It seems that your Arduino resets itself.
But why?
I believe the problem would be with too little power for your ESP8266 and Arduino. When the ESP8266 wants to create a network connection, it takes a little more current, possibly leaving your Arduino without enough current to run on itself.
So your Arduino would shut down since the ESP8266 takes up all the current. Creating some kind of bootloop on your Arduino.
Please tell us how you powered the devices and how you connected them.
You might try using a separate power supply or a big capacitor on the Arduino's 5V+GND.

yes i am using separate voltage regulators for both and my other code which is different a little bit works fine thats why i am curious about this code

and i need to run above code

I think you're running out of RAM memory, try using a buffer of only 256 bytes and put the printed text in statments with F() like: Serial.print(F("Write something on the Serial Monitor that is stored in FLASH"));

yes its the buffer issue thanks but i need more memory because esp module send too much data to arduino when get request has been made it means i need to move towards mega board or due

Teensy3.2 might be a good choice. That thing has got some serious bang for buck (but is a little more difficult to use). BUT there are other options, you don't have to receive the whole message at once! You can check it in a per-byte fashion. You should ONLY save the information that you actually need!

If your question is answered with this, you should press the ✔ at the side of this answer. But keep in mind that it's probably still possible with the UNO, but will require some "lower level programming", if you really want to get into that, you should post a new question on how to perform that. But there is indeed nothing wrong with scaling up hardware.


text:
ESP32 not detecting PN532 module running in SPI mode
I am trying to get the Pn532 module working on the esp32, first I tried to get it working with i2c and had some "success"(it worked, but as soon as I had another i2c device, in my case a display, 90% of the time it refused to work) and after some research, it's mentioned in the github repo the module doesnt work with multiple devices attached on the i2c bus. Now I am trying to get it working trough spi, but it doesn't get detected.
Code: readMirafe example from the Adafruit Pn532 Library, but I modified the pins from line 42-45
/**************************************************************************/
/*!
    @file     readMifare.pde
    @author   Adafruit Industries
    @license  BSD (see license.txt)
    This example will wait for any ISO14443A card or tag, and
    depending on the size of the UID will attempt to read from it.

    If the card has a 4-byte UID it is probably a Mifare
    Classic card, and the following steps are taken:

    - Authenticate block 4 (the first block of Sector 1) using
      the default KEYA of 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF
    - If authentication succeeds, we can then read any of the
      4 blocks in that sector (though only block 4 is read here)

    If the card has a 7-byte UID it is probably a Mifare
    Ultralight card, and the 4 byte pages can be read directly.
    Page 4 is read by default since this is the first 'general-
    purpose' page on the tags.
This is an example sketch for the Adafruit PN532 NFC/RFID breakout boards
This library works with the Adafruit NFC breakout
  ----> https://www.adafruit.com/products/364

Check out the links above for our tutorials and wiring diagrams
These chips use SPI or I2C to communicate.
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
*/
/**************************************************************************/
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_PN532.h>

// If using the breakout with SPI, define the pins for SPI communication.
#define PN532_SCK  (18)
#define PN532_MISO (19)
#define PN532_MOSI (23)
#define PN532_SS   (27)

// If using the breakout or shield with I2C, define just the pins connected
// to the IRQ and reset lines.  Use the values below (2, 3) for the shield!
#define PN532_IRQ   (2)
#define PN532_RESET (3)  // Not connected by default on the NFC Shield

// Uncomment just _one_ line below depending on how your breakout or shield
// is connected to the Arduino:

// Use this line for a breakout with a software SPI connection (recommended):
Adafruit_PN532 nfc(PN532_SCK, PN532_MISO, PN532_MOSI, PN532_SS);

// Use this line for a breakout with a hardware SPI connection.  Note that
// the PN532 SCK, MOSI, and MISO pins need to be connected to the Arduino's
// hardware SPI SCK, MOSI, and MISO pins.  On an Arduino Uno these are
// SCK = 13, MOSI = 11, MISO = 12.  The SS line can be any digital IO pin.
//Adafruit_PN532 nfc(PN532_SS);

// Or use this line for a breakout or shield with an I2C connection:
//Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

void setup(void) {
  Serial.begin(115200);
  while (!Serial) delay(10); // for Leonardo/Micro/Zero

  Serial.println("Hello!");

  nfc.begin();

  uint32_t versiondata = nfc.getFirmwareVersion();
  if (! versiondata) {
    Serial.print("Didn't find PN53x board");
    while (1); // halt
  }
  // Got ok data, print it out!
  Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
  Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
  Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

  // configure board to read RFID tags
  nfc.SAMConfig();

  Serial.println("Waiting for an ISO14443A Card ...");
}

void loop(void) {
  uint8_t success;
  uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
  uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

  // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
  // 'uid' will be populated with the UID, and uidLength will indicate
  // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
  success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);

  if (success) {
    // Display some basic information about the card
    Serial.println("Found an ISO14443A card");
    Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
    Serial.print("  UID Value: ");
    nfc.PrintHex(uid, uidLength);
    Serial.println("");

    if (uidLength == 4)
    {
      // We probably have a Mifare Classic card ...
      Serial.println("Seems to be a Mifare Classic card (4 byte UID)");

      // Now we need to try to authenticate it for read/write access
      // Try with the factory default KeyA: 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF
      Serial.println("Trying to authenticate block 4 with default KEYA value");
      uint8_t keya[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };

      // Start with block 4 (the first block of sector 1) since sector 0
      // contains the manufacturer data and it's probably better just
      // to leave it alone unless you know what you're doing
      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 4, 0, keya);

      if (success)
      {
        Serial.println("Sector 1 (Blocks 4..7) has been authenticated");
        uint8_t data[16];

        // If you want to write something to block 4 to test with, uncomment
        // the following line and this text should be read back in a minute
        //memcpy(data, (const uint8_t[]){ 'a', 'd', 'a', 'f', 'r', 'u', 'i', 't', '.', 'c', 'o', 'm', 0, 0, 0, 0 }, sizeof data);
        // success = nfc.mifareclassic_WriteDataBlock (4, data);

        // Try to read the contents of block 4
        success = nfc.mifareclassic_ReadDataBlock(4, data);

        if (success)
        {
          // Data seems to have been read ... spit it out
          Serial.println("Reading Block 4:");
          nfc.PrintHexChar(data, 16);
          Serial.println("");

          // Wait a bit before reading the card again
          delay(1000);
        }
        else
        {
          Serial.println("Ooops ... unable to read the requested block.  Try another key?");
        }
      }
      else
      {
        Serial.println("Ooops ... authentication failed: Try another key?");
      }
    }

    if (uidLength == 7)
    {
      // We probably have a Mifare Ultralight card ...
      Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");

      // Try to read the first general-purpose user page (#4)
      Serial.println("Reading page 4");
      uint8_t data[32];
      success = nfc.mifareultralight_ReadPage (4, data);
      if (success)
      {
        // Data seems to have been read ... spit it out
        nfc.PrintHexChar(data, 4);
        Serial.println("");

        // Wait a bit before reading the card again
        delay(1000);
      }
      else
      {
        Serial.println("Ooops ... unable to read the requested page!?");
      }
    }
  }
}

My wiring is the following
(PN523 Module->esp32):
SCK  -> D18;
MSO  -> D19;
MOSI -> D23;
SS   -> D27

And yes, the board is in SPI mode(the dip switch). Thank you!

try hw SPI. now you use the library in software SPI mode

Same issues here, same setup, any news?

The project has just been sitting here, collecting dust. Didn't have the time to look into it

@AllanAlmeida found the solution! https://github.com/adafruit/Adafruit-PN532/issues/80#issuecomment-649915457

Got it working by running the module in VSPI and modifying the library a bit: https://github.com/adafruit/Adafruit-PN532/issues/80#issuecomment-649915457

There is a switch on your PN5322 by default it is set to 0, 0. Switch to the mode of communication you are using.

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


text:
Newbe needing help with fixed string length
im trying to build a bit of test equipment that will talk to some software and it needs to send a fix string. when the voltage changes the string length does as well. i need to cap the results to 4 in length. (sorry for not knowing the correct terminology. this is the output i need -

Where,
X = Flag CP Value
_ = Space
P = Polarity
C = CP Received value
Y = Flag Field Gradient
F = Field Gradient Received value
Z = Flag Contact CP
T = Contact CP Received value

There is also a line feed and carriage return present at the end of each string.
The polarity indicator will only display a minus sign ‘-‘ if the received value is
negative otherwise no assignation will be transmitted. Although the overall string
length is constant the values for each measurement are right justified and hence a
space will be present should the value of the measurement not necessitate the
utilisation of all allocated character spaces.
Sample Outputs
< X -89 Y -1989 Z -1096 >
< X 1039 Y 8 Z 78 >

this is my code so far
#include <Wire.h>
#include <Adafruit_ADS1015.h>

Adafruit_ADS1115 ads1(0x48);     // Use this for the 16-bit version
Adafruit_ADS1115 ads2(0x49);

void setup(void) {

  Serial.begin(9600);

  ads1.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV
  ads2.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV

  ads1.begin();
  ads2.begin();
}

void loop(void) {

  int16_t results01,results02,results03;

  results01 = ads1.readADC_Differential_0_1();
  results02 = ads1.readADC_Differential_2_3();
  results03 = ads2.readADC_Differential_0_1();

  Serial.print("X ");
  Serial.print(round(results01 * multiplier));

  Serial.print(" Y ");
  Serial.print(round(results02 * multiplier));

  Serial.print(" Z ");
  Serial.print(round(results03 * multiplier));

  Serial.println();              // send a cr/lf
  delay(500);
}

Any help pointing me in the right direction would be Amazing.
Thanks in advance
Joe

What is it that your trying to "cap to 4 in length"? I'm assuming you have no control over how the device sends its string, and that you want to format the device's results for the terminal? Can you show a sample of what you want the end-result to look like?

< X      -89 Y -1989 Z -1096 >

each of the reading im getting need to be 4 in length . im reading -2000 to +2000 but say when the voltage is -89 it shortens the string.

So you want to print, e.g. "15" as "0015"? How about "-1500"? How can that take fewer than 5 printing characters?

sorry i mean 5 characters.  "___15" or " __-15"  or "-1500" or "_1500"  like i said im very new to this and im amazed i have got this far without asking for help . :)

The printf() family of functions comes handy when you need
this kind of control over the formatted output:
/*
 * Format a number as 5 characters.
 * Returns the string in a statically allocated buffer.
 */
char * format5(int x)
{
    static char buffer[6];  // 5 chars + terminating NUL
    snprintf(buffer, sizeof buffer, "%5d", x);
    return buffer;
}

void setup() {
    Serial.begin(9600);
    Serial.println(format5(15));
    Serial.println(format5(-15));
    Serial.println(format5(-1500));
    Serial.println(format5(1500));
}

void loop(){}

output:
   15
  -15
-1500
 1500

thanks for this. as been very new to this I have tried and cant  get this working...

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


text:
Command through Serial monitor does not properly work in Arduino
I am executing a function in Arduino by giving String input to the serial monitor.
The issue here is when I enter SHOW$, the function showData() works but when I enter the same SHOW$, it doesn't gets called.
I want to call the function showData() every time i enter the SHOW$ text into the serial console.
My question here is to what mistake I am doing here, and what is the solution for this.
String strReq = "";
char inChar = 0;

void setup() {

  Serial.begin(9600);

}

void loop() {

  while (Serial.available())
  {
    inChar = Serial.read();

    if (inChar == '$') {

     Serial.println(" Received String :");
     Serial.print(strReq);

     if (strReq.equalsIgnoreCase("SHOW"))
       showData();

     Serial.flush();
     strReq = "";

    } else {

      strReq = strReq + inChar;
    }
  }
}

void showData() {
  Serial.print("Showing Information");
}

how is line ending set in Serial Monitor? it is possible that the second time you add line end characters from previous input to strReq

both NL & CR is set

then the second input is "\r\nSHOW" and this is not equal to SHOW

right because next time it is printing with new line.. how to solve this.?

one option is to ignore control caracters when reading. else if (inChar >= 32) {

what other option is there. because there are too many strings i am comparing in original code.
actually serial data output doesn't matter to me. I am turning LED on and off on this command , it is not executing in the second time as explained in the question.

Do you know what Serial.flush() does?

@Majenko, flush waits until tx buffer is empty

@Juraj I'm not asking you. I know you know. Looking at the code I am thinking the java bee thinks it works how it did in pre-Arduino 1.0.0.

you could turn off the line ends in Serial Monitor

You could also use a real terminal emulator instead of the POS Serial "monitor".

@Majenko, sorry. I overlooked the flush() in OP's code

@Juraj If the OP assumed it worked how it used to (clears the RX buffer contents) then the code would work as expected.

The solution was to use String.trim() function.
Thanks guys for giving a quick reply on the question.

The root of your problem seems to be not knowing what Serial.flush() does.
It pre-Arduino 1.0.0 times Serial.flush() used to clear any data in the serial's RX buffer. It would throw it away.  In your code that would throw away the line ending \r\n that is sent along with the command.
However in Arduino 1.0.0 it was changed to instead block execution until all bytes had been sent out of the Serial TX buffer.  This was deemed more useful, and a replacement to the original functionality is very easy to implement if needed.
This change was not widely documented, but it is mentioned in the manual:

Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

So with Serial.flush() acting like it does in current versions, you would get a different string the second time around.  You would see:
SHOW$
\r\nSHOW$
\r\nSHOW$

and so on.
You have come up with a "fix", which uses String::trim() to discard any leading and trailing non-printable characters, which removes the line-endings from your subsequent strings.  However it would be far better to ignore them in the first place and not need to do the trimming.
The simplest way would be to only add characters to your string if they are printable:
if (inChar == '$') {
 Serial.println(" Received String :");
 Serial.print(strReq);
 if (strReq.equalsIgnoreCase("SHOW"))
   showData();
 Serial.flush();
 strReq = "";
} else if (inChar >= ' ') { // << Only add if a space or above
  strReq = strReq + inChar;
}

A simple change, but one which then means you're not having to add the extra processing of trimming unwanted characters from the string.


text:
Motor does not rotate smoothly ( Even in High speed )
I am bhanuka and i am new to Stepper motors and to this library.
I am trying to control 4 NEMA 17 motors ( Different speeds in same time ) using 4 (four)  DM320t stepper driver. Actually i want to move the robot ( Robot has omni wheels) to coordinates according to the Gcode.
It seem like code is ok, but when i enter a G-code, motors start to rotate to correct direction but they don't give smooth rotation ( I can hear  clicking sound , motor seems jumping from step to step and motor get hot too much ).
I think the problem for this case is motor miss some steps.
here i have attach the code. Can someone help me to overcome this problem.
Thank you.
#include <AccelStepper.h>
#include <math.h>

int Gval;
int Xval, Yval, Zval;
int Fval;
int Ival, Jval;
String Gvalstr, Xvalstr, Yvalstr, Zvalstr, Fvalstr, Ivalstr, Jvalstr;
char Key;
String code; // parameters of G code Translator, It will execute the code
String ab; // Para of G code translator, For come to Gcode function

AccelStepper w1(1, 2, 3); // pin 3 = step, pin 6 = direction
AccelStepper w2(1, 49, 51); // pin 4 = step, pin 7 = direction
AccelStepper w3(1, 5, 6); // pin 3 = step, pin 6 = direction
AccelStepper w4(1, 8, 9); // pin 4 = step, pin 7 = direction

int w1_enb = 4;
int w2_enb = 53;
int w3_enb = 7;
int w4_enb = 10;
char x ; // x cordinate
char y ; // x cordinate
char command; // case vari.
char com;

String inString = "";

void setup() {
  digitalWrite(w1_enb, HIGH);
  digitalWrite(w2_enb, HIGH);
  digitalWrite(w3_enb, HIGH);
  digitalWrite(w4_enb, HIGH);

  Serial.begin(9600);
  Serial.println("G code");

}

void loop() {
  Gvalstr = "";
  Xvalstr = "";
  Yvalstr = "";
  Zvalstr = "";
  Fvalstr = "";
  Ivalstr = "";
  Jvalstr = "";

  String code;
  if (Serial.available() > 0 ) {
    ab = Serial.readString();
    Gcode();
  }
  else {}

}

void Gcode () {
  code = ab;
  Serial.println("code is " + ab);
  //Serial.println(code);
  //String code = "G01 X1 Y1 F200 T01 M03 S500";
  int len = code.length();
  for (int i = 0; i < len; i++) {

    if (code[i] == 'G')Key = 'G';
    else if (code[i] == 'X')Key = 'X';
    else if (code[i] == 'Y')Key = 'Y';
    else if (code[i] == 'Z')Key = 'Z';
    else if (code[i] == 'F')Key = 'F';
    else if (code[i] == 'i')Key = 'i';
    else if (code[i] == 'j')Key = 'j';
    else if (isdigit(code[i]) || code[i] == '-') {
      if (Key == 'G') {
        Gvalstr += code[i];
      }
      else if (Key == 'X') {
        Xvalstr += code[i];
      }
      else if (Key == 'Y') {
        Yvalstr += code[i];
      }
      else if (Key == 'Z') {
        Zvalstr += code[i];
      }
      else if (Key == 'F') {
        Fvalstr += code[i];
      }
      else if (Key == 'i') {
        Ivalstr += code[i];
      }
      else if (Key == 'j') {
        Jvalstr += code[i];
      }

    }
    else
    {
      Key = '-1';
    }

  }

  Gval = Gvalstr.toInt();
  Xval = Xvalstr.toInt();
  Yval = Yvalstr.toInt();
  Fval = Fvalstr.toInt();

  Serial.println( Gval);
  Serial.println (Xval);
  Serial.println (Yval);
  Serial.println (Fval);

  switch (Gval) {

    case 0:
      motor_setup(Xval, Yval);
      //Serial.println("**********");
      break;
    case 1:
      motor_setup(Xval, Yval);
      //Serial.println("**-------");
      break;

    case 2:
      motor_setup(Xval, Yval);
      break;

    case 3:
      motor_setup(Xval, Yval);
      break;

    case 90:
      motor_setup(Xval, Yval);
      break;

    case 91:
      motor_setup(Xval, Yval);
      break;

    case 92:
      motor_setup(Xval, Yval);
      break;

  }
}

void motor_setup (int Xval , int Yval) {

  double Xprojection;
  double Yprojection;

  if (Yval == 0 ) {

    if (Xval > 0) {
      Xprojection = '1';
    }

    else if (Xval == 0) {
      Xprojection = 0;

    }

    else {

      Xprojection = -1;
    }
    Serial.println("Xprojection in if ");
    Serial.println(Xprojection);

    Yprojection = 0;

  }
  else {
    float alpha = Yval / Xval;
    Serial.println("CALCULATING");
    Serial.println(alpha);

    double atanval = atan(alpha);
    Xprojection = cos(atanval);
    Yprojection = sin(atanval);

    Serial.println("X_projection : ");
    Serial.println(Xprojection);

    Serial.println("Y_projection : ");
    Serial.println(Yprojection);
  }

  float W1, W2, W3, W4;  // Radial Velocity required to move to Position

  W1 = float ( -0.35 * Xprojection + 0.35 * Yprojection) ;
  W2 = float (-0.35 * Xprojection - 0.35 * Yprojection );
  W3 = float ( 0.35 * Xprojection - 0.35 * Yprojection );
  W4 = float (0.35 * Xprojection + 0.35 * Yprojection );

  Serial.println ("Velocity components ");
  Serial.println (W1);
  Serial.println (W2);
  Serial.println (W3);
  Serial.println (W4);
  Serial.println('\n');

  long c = 20;    // these values for testing
  long d = 20;
  long e = 20;
  long f = 20;

  w1.setMaxSpeed(2);
  w1.setAcceleration(12);
  w1.moveTo( Xval );

  w2.setMaxSpeed(2);
  w2.setAcceleration(12);
  w2.moveTo( Yval);

  w3.setMaxSpeed(2);
  w3.setAcceleration(12);
  w3.moveTo( -Xval);

  w4.setMaxSpeed(2);
  w4.setAcceleration(12);
  w4.moveTo( -Yval );

  while (w1.distanceToGo() != 0 || w2.distanceToGo() != 0 || w3.distanceToGo() != 0 || w4.distanceToGo() != 0) {
    w1.run();
    w2.run();
    w3.run();
    w4.run();

  }

  Serial.println("Executed");
  Serial.println("Next GCODE");
  Serial.flush();

}

reduce your code to control only one motor ... remove all other code ... run motor for 2 seconds and stop ... update your post with the results

The problem was the Supply Voltage. I have connected it to 24DC V. when i connect it to 12V problem was solved.

It seems that you see too high current at the driver. You should always use minimum current, that smoothly moves your device. Try decreasing the current, it then will work at lower voltages

It's OK to accept you're own answer as the solution to the problem.


text:
When i upload the code to nodeMCU this error comes I have checked libraries ,ports made enviroment for nodemcu but error always come to screen
Arduino: 1.8.7 (Windows 10), Board: "NodeMCU 1.0 (ESP-12E Module), 80 MHz, Flash, Disabled (new aborts on oom), Disabled, All SSL ciphers (most compatible), 32KB cache + 32KB IRAM (balanced), Use pgm_read macros for IRAM/PROGMEM, 4MB (FS:2MB OTA:~1019KB), 2, v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

ICACHE : 32768           - flash instruction cache

IROM   : 425200          - code in flash         (default or ICACHE_FLASH_ATTR)

IRAM   : 29829   / 32768 - code in IRAM          (IRAM_ATTR, ISRs...)

DATA   : 1664  )         - initialized variables (global, static) in RAM/HEAP

RODATA : 7200  ) / 81920 - constants             (global, static) in RAM/HEAP

BSS    : 28472 )         - zeroed variables      (global, static) in RAM/HEAP

Sketch uses 463893 bytes (44%) of program storage space. Maximum is 1044464 bytes.
Global variables use 37336 bytes (45%) of dynamic memory, leaving 44584 bytes for local variables. Maximum is 81920 bytes.
esptool.py v3.0
Serial port COM6
Connecting....
Chip is ESP8266EX
Features: WiFi
WARNING: Detected crystal freq 255.46MHz is quite different to normalized freq 40MHz. Unsupported crystal in use?
Crystal is 40MHz
MAC: 44:17:93:11:8c:e4
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Compressed 468048 bytes to 339496...
Writing at 0x00000000... (4 %)
Writing at 0x00004000... (9 %)
Writing at 0x00008000... (14 %)
Writing at 0x0000c000... (19 %)
Writing at 0x00010000... (23 %)
Writing at 0x00014000... (28 %)
Writing at 0x00018000... (33 %)
Writing at 0x0001c000... (38 %)
Writing at 0x00020000... (42 %)
Writing at 0x00024000... (47 %)
Writing at 0x00028000... (52 %)
Writing at 0x0002c000... (57 %)
Writing at 0x00030000... (61 %)
Writing at 0x00034000... (66 %)
Writing at 0x00038000... (71 %)
Writing at 0x0003c000... (76 %)
Writing at 0x00040000... (80 %)
Writing at 0x00044000... (85 %)
Writing at 0x00048000... (90 %)
Writing at 0x0004c000... (95 %)
Writing at 0x00050000... (100 %)
An error occurred while uploading the sketch

This report would have more information with
"Show verbose output during compilation"
option enabled in File -> Preferences.

Are you sure you selected the correct board and partition scheme?

Welcome! I am not familiar with nodeMCU but your error sounds similar to what happens in Linux, the errors are sent to the error out which in your case may be the console. Sorry I do not have the time to get into this further but you have the manuals etc this should give you an idea of what to look for,

You might want to try to upload with verbose compilation on and then post the output, it might give us a better idea of your problem (Look at the preferences in the Arduino environment).


text:
Why am I reading only zeroes from PORTB?
I am using a custom Arduino Nano compatible board with an Atmel 328P.  I am externally changing the values applied to several pins on PORTB.  I expect to be able to read the values of these pins (low or high) but I always read zeroes.  However, the pin change interrupt is called.  What do I need to do to read values from PORTB?
Supply voltage is 5 volts.  Pin applied high voltage is 3.3 volts.
With the below code, when I change the voltage applied to a pin, LED1 flashes but LED2 does not.
#include <avr/interrupt.h>

#define LED1_PORT                           (PORTD)
#define LED1_PIN_bm                         (_BV(4))         //D1, white

#define LED2_PORT                           (PORTD)
#define LED2_PIN_bm                         (_BV(3))         //D2, red

volatile bool g_bValueChanged = 0;

void setup()
{
  DDRB = 0;                     //set all as inputs
  PCMSK0 = 0xfb;                //exclude 1 pin because of noise
  PCICR |= (1 << PCIE0);        //enable pin change interrupt 0 (for pins PB0..7)

  sei();
}

uint8_t g_valuePrevious = 0;

void loop()
{
  if (g_bValueChanged)
  {
    g_bValueChanged = false;

    LED1_PORT |= LED1_PIN_bm;
    delay(40);
    LED1_PORT &= ~LED1_PIN_bm;
    delay(40);
  }

  uint8_t value = PORTB;
  if (value != g_valuePrevious)
  {
    g_valuePrevious = value;

    LED2_PORT |= LED2_PIN_bm;
    delay(40);
    LED2_PORT &= ~LED2_PIN_bm;
    delay(40);
  }
}

ISR(PCINT0_vect)
{
    g_bValueChanged = true;
}

The PORTB register is initialized by the hardware to zero. You never
write to this register, so it always stays zero.
Maybe you are mixing up PORTB and PINB:

PORTB is the port output register, controlled by you
PINB is the port input register, for which the bits
corresponding to input pins are controlled by whatever drives those
pins from the outside.

I am applying a signal to those pins externally.  I have been programming XMega which uses the same PORTB for input and output.  Now I see PINB in the datasheet, you are probably correct, I will try it.

@Joe: Yes, that is what I understood from reading your question.

Thank you, that was the answer, I was not aware that the processor I am using had different registers for input and output.

Different registers, indeed. And there is even a free goodie: if you attempt to write to the port input registers, you get toggle functionality: for every bit you write to one, the corresponding output pin is toggled.


text:
Trouble connecting barcode scanner to ESP32 devkit using UART - fails to connect over serial
I'm having trouble connecting a SparkFun 2D Barcode Scanner Breakout (effectively a DE2120) to a 30-pin ESP32 dev kit v1 (marked ESP-WROOM-32) and running the SerialScan sample application for this sensor successfully.
I believe I have the two devices connected as per the instructions:

ESP32 -> DE2120
3V3 -> 3.3v
GND -> GND
RX2 -> RX
TX2 -> TX

In the sample code I have pins configured as follows:
SoftwareSerial softSerial(25,27);

(according to the mapping here these are the TX2/DX2 and the right pin numbers)
But something is not right: the sample code never reports a connection being made. Tracing this back, it looks like isConnected() here is always returning false, which means sendCommand() is either timing out or getting a DE2120_COMMAND_NACK.
I'm stumped. I've tried 2 different scanner units, replaced all the cables, tried swapping pin numbers around, and done a load of trials using HardwareSerial too with no success. The scanner unit itself responds to commands when I connect it to a laptop and talk to it over USB serial.
Any ideas? I am assuming there is something deeply trivial I'm getting wrong (e.g. in the physical connection or in the specifics of serial connections on ESP32). Generally I've found example code from Arduino libraries runs first time, but I am relatively new to Arduino.
Update 7/20: I have tried with pins 16 and 17, and also with RX2->TX and TX -> RX2. I have scanned the setup barcode as per the instructions.

For Serial Communication, you usually connect RX - TX, and TX - RX. 2) For ESP32, the naming convention is based on GPIO pin numbers, So Serial2 (HardwareSerial) is on 16 GPIO16-RX2), and 17 (GPIO17-TX2). 3) ESP32 has 3 hardware serial ports, there is no need for SoftwareSerial.

maybe the scanner module has to be programmed to use the serial port ... it may be programmed by scanning programming barcodes

Thank you both. I have tried the connection pattern you suggested, hcheung (though wouldn't reversing the pin numbers in the source code have the same effect? I tried that too), and have tried with 16 and 17 as the pin numbers. SoftwareSerial is what the example source code uses, in my own program I tried using HardwareSerial too.
jsotola: yes, I had already done that step - updated original question with details.

Answering my own question: this is about the scanner not getting enough power from the ESP32 devkit board, I think.
When I power both the barcode scanner and the ESP32 from separate power supplies (both USB) I can connect from the ESP32 to the scanner and read codes just fine.
However when I power the scanner from the ESP32, following the instructions in the hookup guide, the scanner is unresponsive.

HI, you are allowed to tick your own answer.


text:
About UART one transmitter multiple receivers
I have vector nav vn100 IMU that sends data serially rs232...I want to drive 4 servo motors using atmega32 upon roll angel from vector nav vn100..atmega32 can only drive 2 servos using hardware fast pwm mode 14...so I should to use two atmega32...so I should receive the vn100 message to the two atmega32...my question is ..does UART rs323 support one transmitter multiple receivers?

If you do not need the control lines, and the communication is only one
way, then yes, you can connect the TX (transmit) of the IMU to the RX
(receive) of both microcontrollers. On the other hand, connecting one RX
to multiple TX is likely to burn something.
Note however that the ATmega MCUs do not support RS-232 communication.
If you want to go this way, you will then have to attach an RS-232
transceiver to each MCU. If the distances are short (say, a few
centimeters), I would recommend using “serial TTL” instead.

Thank you very much...I am so thankful for your help...


text:
ESP32 not seen by a network analyzer application in server mode
I have used the scan wifi and blink examples provided by Espressif,
they are both working on the ESP32 using arduino ide.
However, I can not see my ESP( the SSID and signal strength) in the list of detected wifi when searching for it using a network analyzer app  ( Net analyzer on android)
This was solved when I used the ESP as Access point.
In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?
why is the ESP32 Lolin getting hot only when it is in AP mode?
Thanks in advance

What do you mean by "see" it? And what NA app? Are you assuming it should be an AP by default? Have you programmed it to be an AP and broadcast an SSID?

Can't a client be seen by all? So the problem is that I need to make it as an AP? My point is to use the ESP as client on assets and make the access point know the position using its signal strength.

Only access points can be seen by stations. When connected you use other protocols (mDNS) to advertise services.

In Client mode the ESP is using the WIFI capability. But why it can
  not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.


text:
Liquid Crystal LCD and serial monitor not playing well together
On my Arduino Uno, when I'm not using the serial everything seems in order:
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");
}

void loop()
{
    delay(1000);
}

However the moment I open the serial port with:
Serial.begin(9600);

The problem starts.
Clearing the LCD does not clear it but prints a character with 4 horizontal lines. Trying to move the cursor will print a different  unrecognisable character. Sending things to the Arduino via the Serial port prints gibberish on the LCD.

Any idea why? Is there a way to work with the LCD and the serial port simultaneously? I require the serial port in order to control the Arduino from NodeJS.
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");

    Serial.begin(9600);

    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Native USB only
    }
}

void loop()
{
    lcd.clear(); // This will print 4 horizontal lines character instead of clearing
    delay(500);
}

What type of Arduino?  On some pin 1 is one of the hardware serial pins. You can’t use that pin for other things like LCDs if you are using serial.

@Delta_G The board is Arduino Uno and you are right. Changing the pin from 1 to 3 solved the issue. Tnx! I wonder how many of 846,000 viewers of this youtube had the same issue? https://www.youtube.com/watch?v=dZZynJLmTn8&pbjreload=101 :-)

I will make it an answer.  Please accept

@jsotola the question was downvoted so I thought perhaps I misrepresented the issue. I restored the previous title to your suggestion. tnx.

somebody probably downvoted the post because you did not check which pins are used by the serial port

On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.
Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


text:
Problem in receieving message
I'm working on a project in which when I press reset button the arduino should send longitudes and latitudes to my phone. I'm a beginner and tried to join two codes, first code can send the message and the second code can get the lon and lat printed on the serial monitor.
First code--
int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void setup()
{
  Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
    while(Serial.read()!='>');
    {
      Serial.print("Hii If this message is sent then its a huge sucess for me");
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
    }
    count++;
  }
}

Second code--
#include <SoftwareSerial.h>
#include <TinyGPS.h>

long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup(){
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
}

void loop(){
  while(gpsSerial.available()){ // check for gps data
   if(gps.encode(gpsSerial.read())){ // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    // display position
    Serial.print("Position: ");
    Serial.print("lat: ");Serial.print(lat);Serial.print(" ");// print latitude
    Serial.print("lon: ");Serial.println(lon); // print longitude
   }
  }
}

My code which is not working--
#include <SoftwareSerial.h>
#include <TinyGPS.h>
long lat,lon; // create variable for latitude and longitude object

SoftwareSerial gpsSerial(4, 3); // create gps sensor connection
TinyGPS gps; // create gps object

void setup()
{
  Serial.begin(9600); // connect serial
  gpsSerial.begin(9600); // connect gps sensor
    Serial.begin(9600);
  delay(2000);
  Serial.println("AT+CMGF=1");
  delay(200);
}

int timesTosend=1;
int count=0;
char phone_no[]="+917771914436";
void loop()
{
  while (count<timesTosend)
  {
    delay(1500);
    Serial.print("AT+CMGS=\"");
    Serial.print(phone_no);
    Serial.println("\"");
     while(Serial.read()!='>');
    {
      while(gpsSerial.available())
      {
        if(gps.encode(gpsSerial.read()))
        { // encode gps data
    gps.get_position(&lat,&lon); // get latitude and longitude
    Serial.print(lat,lon);
      delay(500);
      Serial.write(0x1A);
      Serial.write(0x0D);
      Serial.write(0x0A);
      delay(5000);
        }
      }
    }
    count++;
  }
}

Please help me out by correcting my mistake in the code.

Serial.print(lat,lon);

That doesn't do what you think it does.  That is trying to print the latitude encoded in base "lon", which just isn't going to work.
Instead you need to send it as separate operations:
Serial.print(lat);
Serial.print(",");
Serial.print(lon);

Also you should separate out the GPS and GSM routines.  Create a function that gets the latitude and longitude, and another function that sends the two values as a text message.  Then you can keep things as discrete obvious steps and not get confused with what is happening when.

Then please tell me what can I do to send it as text message?


text:
Debouncing results in no reaction at all
Update:
I changed the code to this, but it does not work either.
`if ((millis() - lastDebounceTime) > debounceDelay) {
   if (button) {
 //DEBOUNCING

     if (!button_prev && button) {

      int e = input[j];`

I am trying to debounce a button and integrated this code http://arduino.cc/en/Tutorial/Debounce into my sketch.
The result is, that there is no reaction to the button at all.
I can't figure out the mistake, but maybe someone else sees what I overlook.
Circuit

Parts marked with //DEBOUNCING are only for the purpose of it, parts marked //DEBOUNCE relevant are necessary for the code to run as well when there is no debouncing.
void setup() {

  Serial.begin(9600);

  //setting button pin as input and LOW

  pinMode(8, INPUT);
  digitalWrite(8, LOW); //DEBOUNCE relevant

  //setting input pins as output

  int act_pin[6] = {A0, A1, A2, A3, A4};

  int k = 0;

  for (k = 0; k < 5; k++) {

      pinMode(act_pin[k], OUTPUT);

    }

  //setting state pins as output

  int z_pin[5] = {2, 3, 4, 5};

  int a = 0;

  for (a = 0; a < 4; a++) {

      pinMode(z_pin[a], OUTPUT);

   }

  //setting output pins as output

  int out_pin[6] = {9, 10, 11};

  int b = 0;

  for (b = 0; b < 3; b++) {

      pinMode(out_pin[b], OUTPUT);

   }

  //setting input

  for(k = 0; k < 5; k++) {

      randomSeed(analogRead(5));

      int i = random(2);

      if(i == 1){

         digitalWrite(act_pin[k], HIGH);

         input[k] = 1;

         Serial.print(input[k]);

      }

       else{

         digitalWrite(act_pin[k], LOW);

         input[k] = 0;

         Serial.print(input[k]);

      }

    }

   //setting initial situation

   digitalWrite(2, LOW);
   digitalWrite(3, HIGH);
   digitalWrite(4, LOW);
   digitalWrite(5, LOW);

   }

//DEBOUNCING

long lastDebounceTime = 0;  // the last time the button pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers
int buttonState;

//DEBOUNCING

boolean button_prev = 0;

boolean button = 0;

int j = 0; //value shows current lamp being processed

//setting initial state

char z[4] = "z_0";

void loop() {

    button_prev = button;

    button = digitalRead(8); //DEBOUNCE relevant

    // DEBOUNCING
    if (button != button_prev) {

    lastDebounceTime = millis();

    }

    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button != button_prev) {
     //DEBOUNCING

         if (!button_prev && button) {

          int e = input[j];

           //provides a nice output
            Serial.println(" ");
            Serial.print("Current lamp being processed:");
            Serial.println(j);
            Serial.println(" ");
            Serial.print("Current input:");
            Serial.println(e);

             delta(e, z);

            Serial.print("State outside function:");
            Serial.println(z);

            lamda(e, z);

             j = (j+1) % 5;

      }

    }

   }
}

It's difficult to tell without seeing your circuit, but it looks like there could be a mix up between pin 12 and pin 8.  Can see that you initialize the pinMode for pin 12 in setup, but it isn't used in the loop.  You didn't initialize pin 8 (not completely necessary) in setup, but it is used in the loop.  If you don't feel this is relevant, please provide some more detail.

That was indeed a mistake, thank you. It is not the cause of the error though. I fixed it and included the circuit.

If the button has stopped bouncing then (button_prev == button) and the inner if (button != button_prev)  will fail. Basically you're trying to ensure the button is steady but then you're checking that it changed.
Try this:
    if ((millis() - lastDebounceTime) > debounceDelay) {

       if (button) {     // Check the button is still pressed
       ... code...
}

I tried that, so it looks like in the edit, but it doesn't work, I'll try your suggestion from the other question(a rhyme).

@Merlin I mean that you should remove 'if (!button_prev && button)'

Don't I need the if (!button_prev && button) to determine if the button has changed its state? At least that's the solution for checking if the state changed which you procided in your answer from the other question. And I actually like your debounce solution from there way more when my initial approach.

You've probably fixed this already but pin 8 is always grounded, regardless of the button state.  Pin 8 should be connected between the button and the pull-down resistor.

It took me a bit, but now I get what you mean. I had it right all the time in my actual circuit, only the picture is wrong. But thank you a lot, I didn't mind that it is not indifferent where the pull down resistor sits as I made the picture.


text:
How to display tilt sensor data on an LCD?
I'd like for a 16x2 LCD monitor from Sparkfun to display sensor data from a 4-directional tilt sensor from Parallax. The Arduino board is a Duemillanove. The board will run and power both programs and modules, but the serial monitor displaying the tilt sensor data will not relay the info to the LCD display. Any suggestions?
Here are the two pieces of code I am trying to get to work together—they are both from Arduino:
For the tilt:
void setup() {
   Serial.begin(9600);
}
void loop() {
   Serial.print("Photo 1: ");
   Serial.print(digitalRead(6), DEC); // Display Out 1 value
   Serial.print("; ");
   Serial.print("Photo 2: ");
   Serial.println(digitalRead(7), DEC); // Display Out 2 value
   delay(250); // Wiat 1/4 second
}

For the LCD:
#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)
void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}
void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");
  while(1); //
  wait forever
}

Update:
I'm still tinkering with the suggested program from @Ariser shown below, but keep getting a compile error:
tilt_lcd_ase.cpp: In function ‘void loop()’:
tilt_lcd_ase.cpp:24:43: error: expected ‘)’ before ‘;’ token
tilt_lcd_ase.cpp:25:43: error: expected ‘)’ before ‘;’ token
I've done some research and one person had a similar problem, but it was within #include not void loop. The search continues, but if anyone has a suggestion please chime in. The liquid crystal library is also turning up similar errors but it needs a closer look.

Please give us your code, so we can work on it.

Try using the liquidcrystal library.

The serial monitor cannot relay data from different peripheral unit in an arduino system.
I think you have certain misconception of the hard and software. Your USB connection to the microcontroller on the arduino is just a trunk for a asynchronous serial transmission. In the past this was done via a RS-232 interface.
So, what is it, that you see in your serial monitor? That's just a bunch of characters sent by the microcontroller on your arduino. This data is sent from the microcontroller, because some piece of software fills the fifo of its serial interface. In fact, such commands are executed, when you call the method "Serial.print()". Data gets then sent to your PC, Mac or whatever you are running your IDE on.
Now on the very same microcontroller the software for your tilt sensor is being executed. How could the serial monitor (which resides on your PC) route data from your tilt sensor to your LCD display? I'll tell you: It can't.
(In fact you could write a terminal script on your PC which reads data from serial and writes it back to the same interface, but it may cross your mind, that this might be a very big indirection)
So what do you wanna accomplish? You want to put data read from a device connected to your Arduino to another device connected to your Arduino. So you better tell it the Arduino. The serial monitor will not be involved, hence you won't need any calls of Serial.print() to accomplish that.
To help you with that task, we need to see the code you have written so far.
Ok. first thing you need to know: You can't have two arduino sketches running simultaneously on your arduino. This is, because there is nothing like an operating system on your arduino which might provide a scheduler to run both programs. (If you want, look up scheduler on wiki, as it is very useful to know what you can't have)
So you need two pieces of code to run on the same microcontroller (the big black thing on your arduino) one doing the tilt sensor readings and the other printing data on your display. Hence you have to make one program out of two. To accomplish this, you have two problems to solve.

you have to execute both code fragments alterantely, which, because the controller is fast enough, boils down to do both task nearly simultaneously
you have to bring the data which is acquired by code part 1 from the tilt sensor to code part 2 writing to the display. This is (for people into programming) rather simple as it simply has to be stored in a variable.

I recommend you to look up some programming basics at the arduino home page concerning the "setup" function and the "loop" function. But for now: You can have only one of each running on your arduino. Everything which is inside "setup" is executed only once after powerup. Everything which is inside "loop" is going to be executed over and over again consecutively (if nothing breaks).
Your program might look like this:
#include <SoftwareSerial.h> // Attach the serial display's RX line to digital pin 2
SoftwareSerial mySerial(3,2); // pin 2 = TX, pin 3 = RX (unused)

char gl_senstr1[15];
char gl_senstr2[15];

void setup() {
  mySerial.begin(9600); // set up serial port for 9600 baud
  delay(500); // wait for display to boot up
}

void loop() {
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write(" "); // clear display
  mySerial.write(" ");
  mySerial.write(254); // move cursor to beginning of first line
  mySerial.write(128);
  mySerial.write("movement recorded");

      sprintf(gl_senstr1, "%d", digitalRead(6);
      sprintf(gl_senstr2, "%d", digitalRead(7);
  sprintf(gl_senstr1, "%d", digitalRead(6));
  sprintf(gl_senstr2, "%d", digitalRead(7));

  mySerial.write("sensor1: ");
  mySerial.write(gl_senstr1);
  mySerial.write(" sensor2: ");
  mySerial.write(gl_senstr2);

   delay(250); // Wiat 1/4 second

}

I did not test it, because I neither own your display nor that sensor. But you can give it a try. You eventually have to dive into the art of programming if you want to accomlish little more than this. This is where the rubber meets the road.

I appended your code to your question, because it is much better to read there.

by the looks of it you need to close the brackets of the sprintf() statement shown below if you had copied the code from Ariser:
sprintf(gl_senstr1, "%d", digitalRead(6);
sprintf(gl_senstr2, "%d", digitalRead(7);

replace it with:
sprintf(gl_senstr1, "%d", digitalRead(6));
sprintf(gl_senstr2, "%d", digitalRead(7));

That is the error you are seeing because of sprintf() not seeing a close to its statement  ;)


text:
How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins?
When programming an ESP-01 with Arduino IDE, how can I make the Tx and Rx into a generic I/O pins reliably? I think there's a command to swap the Tx and Tx with other pins. I  tried serial.swap() but it didn't work. So how to get done with Arduino IDE or is it even possible?. I am using an ESP-01, which means there will be four GPIO pins once this question in answered.
I want to achieve same as in the video, How to add more GPIOs to ESP8266 (ESP-01), but without soldering wire.

Add this to your code at the beginning of set void setup():
//********** CHANGE PIN FUNCTION  TO GPIO **********
//GPIO 1 (TX) swap the pin to a GPIO.
pinMode(1, FUNCTION_3);
//GPIO 3 (RX) swap the pin to a GPIO.
pinMode(3, FUNCTION_3);
//**************************************************

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.
To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set void setup():
//********** CHANGE PIN FUNCTION  TO TX/RX **********
//GPIO 1 (TX) swap the pin to a TX.
pinMode(1, FUNCTION_0);
//GPIO 3 (RX) swap the pin to a RX.
pinMode(3, FUNCTION_0);
//***************************************************

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.

For more info about pin functions see https://www.esp8266.com/wiki/doku.php?id=esp8266_gpio_pin_allocations

And don’t forget ‚pinMode(1/3, OUTPUT/INPUT)‘

Tx = GPIO 1
Rx = GPIO 3
Should work but be careful cause if they burn, you won't be able to program or even talk to the ESP anymore.

Im not  sure I understood your answer- so with your arduino code in your answer will it swap the tx, rx pins with others that cant be accessed (except without soldering wire) so that the previously unaccessible pins , which you refer  to as gpio 3 and gpio 1 can be used like the gpio 0 and gpio 2 as input or output pins

I mean that if you want to use the Tx pin as a OUTPUT / INPUT, declare it and consider it as GPIO 1. Same applies for the Rx pin.

So it will work like the video I referenced in the question?-except without soldering of course. and it would mean the serial pins tx and rx cant be used for serial communication-which is ok

true, just remember to be CAREFUL to not short those 2 pins

To work TX RX as GPIO Serial.begin() must be deleted from code.

Just removing the Serial.begin() is enough, worked like a charm. Thanks!

Maybe a little late but it might helps someone else.
ESP-01 GPIO pins (1&3)

Don't just link to an external page, especially when the answer is buried in it somewhere. (External pages change and disappear.) Instead, write an answer here that directly answers the question, using information from that page (and still linking to it with a mention that that's where you got the information).

Quite lengthy and interesting article, hard to summarize here... I'm leaving a mirror in case the original disappears.

One thing I noticed is that if you're trying to use the Tx/Rx pins for the main serial comm (1 & 3) as a GPIO then you must not use any Serial commands in your code, such as Serial.begin.
I was having my GPIO digital reads randomly read high (they had their mode set as INPUT_PULLUP) while I had a source pulling them low (I verified that input was indeed pulled low while the ESP8266 digitalRead was reading high)
Removing all Serial commands (begin, print and println) fixed that for me.


text:
Using SoftwareSerial along with FastLED library to control WS2812 LEDs
I am controlling WS2812 LEDs with Arduino nano using FastLED library. I want the LED patterns to change on receiving a command from another Arduino Nano over software serial, I don't have the option to use he hardware serial.
I have read that in order to write data to LEDs, the library disables all the interrupts. However the SoftwareSerial library also uses interrupts to transmit data properly. Is there any possible way to achieve this? Presently, when I am trying to do this I am getting garbage data.

The FastLED and NeoPixel libraries turn off interrupts for the specific timing of the WS2812. The Adafruit NeoPixel has a few extra options to be able to still handle some interrupts. The FastLED has a wiki that describes the problem with interrupts: FastLED wiki interrupts
The SoftwareSerial requires interrupts. When the SoftwareSerial is busy, the Arduino is occupied.
To me it seems impossible to make both libraries work at the same time. I think you have to change something. For example use a Arduino Micro or Pro Micro and use the spare hardware serial port. Or use a ledstrip with leds that have a clock signal and don't need specific timing.
If that is not possible, you might have to use pin 0 (RX) and pin 1 (TX), which are also used by the serial monitor and to upload a sketch.
It is possible to split RX and TX. The only thing that RX and TX have in common is the baudrate, but you can use them for seperate tasks.
For example, use TX to send (debug) messages to the serial monitor, and use the RX to receive commands from another Arduino board. Disconnect that other Arduino board to upload a sketch.
[ADDED] After reading the answer by @Andrew and the FastLED wiki about interrupts, I think that my answer and @Andrew's answer are equally good answers. Perhaps the best way is to do it all: faster Arduino board, hardware serial port for commands, do one thing at a time, implement some kind of XON/XOFF in software, and if possible use other leds.

Of course the best solution is to not use arduino at all. If you use a processor that lets you run an SPI bus with 12 bit data at 2.4 MHz then the hardware can handle the timing requirements and there is no need to disable interrupts to start with. Unfortunately that's not always an option.

How fast do you need to update the LEDs? The nice thing about WS2812s is that if you don't update them they maintain the current settings which means you only need to drive them once you have received a serial message.
The best way to do this would be to use some form of flow control over the serial port. e.g. you send a special control code over the serial line requesting the master to stop sending data. You then wait long enough for that to be sent and any data currently in transmission to arrive (so a absolute minimum of 20/(baud rate) seconds). After that time you call the function to update the LEDs. Once the LED update is done you send a second control code indicating that the other end can resume transmission.
This is the basic structure of software flow control (or XON/XOFF as it is also called) that most serial ports support as an option. You can either use the standard implementation or use something a little simpler since you only need data and flow control in one direction.
The other option is to design the system around rules that ensure you don't miss data. The system sending you the LED updates knows that once you get the update you will need to apply it to the LEDs and that during that time you can't receive serial data. So after an update it waits and doesn't send more data until you've had time to do that.

Another approach is to make the commands to change the pattern very short. Like, one letter/byte.
This assumes that the patterns are stored on your Arduino, and you just choose which one to show.
In order for that to work, the Arduino has to confirm commands it received, and return an error if it receives something it does not understand (e.g. only half of the command). This allows the host to check if the Arduino received the command or if it was animating at that time, in that case re-send the command.
This approach avoids the issue that you receive partial data (because the smallest transmission unit is used). Commands can still be lost, but then they can be re-sent.


text:
Random Blink LEDs
How can I make LEDs blink randomly?
I found a piece of code, but it is not working for me. I probably need something other than setPixel(), but I don't know what.
I am using the Fast.Led library with Arduino Nano and WS2812B LEDs
void loop() {
    Twinkle(CRGB::Red, 10, 100, false);
}

void Twinkle(uint32_t color, uint16_t Count, uint16_t SpeedDelay, boolean OnlyOne)
{
    FastLED.setBrightness(MAX_BRIGHTNESS);
    fill_solid(leds, random(NUM_LEDS), CRGB::White);
    FastLED.show();
    for (int i=0; i < Count; i++) {
//        setPixel(random(NUM_LEDS),red,green,blue);  //!ORIGINAL LINE OF CODE!
        setPixel(random(NUM_LEDS), color);  //!MY LINE!
        FastLED.show();
        delay(SpeedDelay);
        if (OnlyOne) {
            fill_solid(leds, NUM_LEDS, CRGB::Black);
            FastLED.show();
        }
    }

    delay(SpeedDelay);
    return;
}

What exactly is setPixel()? Does the original code work at all? Remove the statements within exclamation marks and use proper comments for your code. A link to your library would also be nice.

it is not working for me - what is it doing? Nothing blinks? Too many things blink? It isn't random? Aliens kidnap you and do scientific experiments on you? "Not working" doesn't tell us much.

I can't tell exactly whats not working with your code,it would be really helpful if you elaborate more.
But here is some code that I wrote and I think it will get the job done:
//declare our variables:
int myPins[] = {2, 4, 8, 3, 6}; //Enter the number of the pins being used
int RNum = 0;

void loop()
{
    DigitalWrite(myPins[RNum],LOW);
    RNum = Random(0,MAX) // MAX being the number of LEDs connected minus one
    //the above generates a random number
    DigitalWrite(myPins[RNum],High);
}

This will turn on one LED at a time.


text:
Wrong code ouput, when the specific function runs more than once
If I run the following code, I get the correct output, and the path is displayed on the serial monitor. However when I run the code together with the commented out portion (in the code below) I don't get any output; even the output that is printed before this code doesn't print completely. Why is that?
I have figured it out that this happens when the dijkstra functions runs more than once. But it shouldn't happen like this.
   int *path1 = NULL;
    int no_of_nodes_1;
    dijkstra(graph, startingNode1, end1_start2, &path1, no_of_nodes_1);

    /*int *path2 = NULL;
    int no_of_nodes_2;
    dijkstra(graph, end1_start2, end2_start3, &path2, no_of_nodes_2);

    int *path3 = NULL;
    int no_of_nodes_3;
    dijkstra(graph, end2_start3, endingNode3, &path3, no_of_nodes_3);
        */
        delete graph;

    Serial.println();

    Serial.println( "PATH 1:");
    for (int k = 0; k < no_of_nodes_1; k++){
        Serial.print(path1[k]);Serial.print("..");
        }

/*
    Serial.println();
        Serial.println( "PATH 2:");
    for (int x = 0; x < no_of_nodes_2; x++){
        Serial.print(path2[x]);Serial.print("..");
    }

    Serial.println();
    Serial.println( "PATH 3:");
    for (int y = 0; y < no_of_nodes_3; y++){
        Serial.print(path3[y]);Serial.print("..");
    }

*/

::UPDATE::
/******************************************************************************/
    void getNextNode(int node, const int& src, const int predecessor[264], int temp_path[], int& i){

        i = 1;

        if (node == src)
        {
            temp_path[i] = src;
        }

        else if (predecessor[node] == -1)
        {
                Serial.println("No path exists");
        }
        else {
            getNextNode(predecessor[node], src, predecessor, temp_path, i);
            temp_path[i] = node;
            i++;
        }

        return;
    }
/********************************************************************************/
    int* savePath(int predecessor[264], const int& src, const int& targetnode, int & numofnodes){

        int temp_path[200];
        temp_path[0] = src;
        int i;

        if (targetnode == src)
        {
            temp_path[1] = src;
        }
        else
        {
            getNextNode(targetnode, src, predecessor, temp_path, i);
        }

        numofnodes = i;
        int *path = new int[i];

        for (int k = 0; k < i; k++){
            path[k] = temp_path[k];
        }

        return path;

    }
 /****************************************************************************/
    void dijkstra(struct Graph* graph, int src, int target, int **path, int& numofnodes)
    {
        // The main function that calulates distances of shortest paths from src to all
        // vertices. It is a O(ELogV) function

        int V = graph->V;// Get the number of vertices in graph
        int* dist = new int[V];      // dist values used to pick minimum weight edge in cut

        int predecessor[264]; //array to save nearest nodes

        // minHeap represents set E
        struct MinHeap* minHeap = createMinHeap(V);

        // Initialize min heap with all vertices. dist value of all vertices
        for (int v = 0; v < V; ++v)
        {
            dist[v] = INT_MAX;
            minHeap->array[v] = newMinHeapNode(v, dist[v]);
            minHeap->pos[v] = v;
            predecessor[v] = -1;
        }

        // Make dist value of src vertex as 0 so that it is extracted first
        minHeap->array[src] = newMinHeapNode(src, dist[src]);
        minHeap->pos[src] = src;
        dist[src] = 0;
        decreaseKey(minHeap, src, dist[src]);

        // Initially size of min heap is equal to V
        minHeap->size = V;

        // In the followin loop, min heap contains all nodes
        // whose shortest distance is not yet finalized.
        while (!isEmpty(minHeap))
        {
            // Extract the vertex with minimum distance value
            struct MinHeapNode* minHeapNode = extractMin(minHeap);
            int u = minHeapNode->v; // Store the extracted vertex number

            // Traverse through all adjacent vertices of u (the extracted
            // vertex) and update their distance values
            struct AdjListNode* pCrawl = graph->array[u].head;
            while (pCrawl != NULL)
            {
                int v = pCrawl->dest;

                // If shortest distance to v is not finalized yet, and distance to v
                // through u is less than its previously calculated distance
                if (isInMinHeap(minHeap, v) && dist[u] != INT_MAX &&
                    /*pCrawl->weight*/1 + dist[u] < dist[v])
                {
                    dist[v] = dist[u] + 1 /*pCrawl->weight*/; // 1 is the weight of the node
                    predecessor[v] = u;
                    // update distance value in min heap also
                    decreaseKey(minHeap, v, dist[v]);
                }
                pCrawl = pCrawl->next;
            }
        }

        delete[] dist;
        delete minHeap;
        *path = savePath(predecessor, src, target, numofnodes);
    }

Please provide the whole code, including the dijkstra function and the values for graph, startingNode1, end1_start2. Also there are two sections commented out. Which one are you referring to in your question?

@Gerben I have updated the question please see it now. And I am referring to both sections together.

I performed a rollback to revision 3, as revision 4 deleted much of the code that was pertinent to the question.

You have likely run out of RAM.
You have 200 integers in the temp_path array. That equates to 400 bytes of SRAM. You also have 3 predecessor arrays each with 264 integers, which equates to 1584 bytes. These arrays combined use 1984 bytes. This is in addition to all your other variables and function calls.
The Arduino Uno only has 2KB of SRAM.
Solution:
Use an Arduino with a greater amount of SRAM.

ARDUINO M0/Zero - 32KB of SRAM
Arduino Mega  - 8KB of SRAM
Arduino Due   - 96KB of SRAM


text:
String() vs char for simple flow control
I am newbie in Arduino and writing a program where I want to control the flow by using Serial monitor input (PI controller).
I've read that using String() although easier it is slower than using char. But to use char I would need more lines of code to convert the input into a string for comparison and more knowledge to make the program robust. For the control I will enter small strings like Ramp, Increase, Decrease, Lock, Stop and any other inputs will not be used. Generally, there are not going to be much inputs. The strings are basically going to be put into if-statements leading to functions.
if(Serial.available()){

string = Serial.readString()
or some function to read out all the bytes of the string and return a char containing it;

if(string="Ramp") {
do_this();
}
else_if(string="Increase"){
do_that()
}
//If nothing matches, continue with code.
}

Since I need to finish this project soon, I am wondering if it's going to increase the loop time significantly if I use String() or I shouldn't bother learning and using char right now (at a later stage, for sure).

Ramp, Increase, Decrease, Lock, Stop  can be represented by single byte commands r, i, d, l, s

Yes, String has a bit more overhead than plain c-strings (aka char arrays), though the additional execution time will be way too small for you to notice (especially when you type the commands in by hand).
It will be no problem to use String in your sketch, though you should do it right and use String.reserve() to allocate enough memory space in the String object to hold the longest string, that you have. Also don't just add Strings together. That way you can avoid memory fragmentation (effectively making swiss cheese out of your RAM) and still use String.
Though when you are not in a hurry anymore, learning how to use c-strings will be worthwhile.

And what happens if I use char or byte and send command longer then expected? The rest of the bytes stay in the serial buffer and then on further read I get wrong command or it empties out the buffer once it fills?

What happens then depends on your programming. A common way is to end the string and throw away the rest of the incoming data for this message. That way you can recover from that. Though you have a limited list of commands, so there is a maximal length of commands for you

Using Serial.readString() will make your program very slow. This is
because readString() does not know when to stop reading. When the
serial input buffer gets empty, it will wait just in case more
characters may come later. Only when it times out does it return the
string that it could read. The default timeout is one second, so your
program will be unresponsive for a full second after receiving a command
and before acting on it.
You can shorten the timeout using Serial.setTimeout(), but this may
make your program harder to test interactively by typing commands on a
terminal emulator.
I recommend you add a terminating character (say, '\n') to each of
your messages, then replace Serial.readString() with
Serial.readStringUntil(). This method will return immediately when it
finds the terminating character. Note that this character will not
appear on the returned string object. readStringUntil() also obeys a
timeout, but only when it cannot find the terminating character.
Or you can learn the clean way to read Serial on the Arduino.
Yes, it is a bit harder, but not a horrible thing to do.


text:
Input on the Nano RP2040 does not float
I am using the Nano RP2040 with MicroPython and run the following code:
import machine
import time

p0 = machine.Pin(0, machine.Pin.IN)
while True:
    print(p0.value())
    time.sleep(0.3)

The Nano has built-in pull-up and pull-down resistors. If I do not specify machine.Pin.PULL_xx, then these built-in resistors are not activated. If they are not activated, then shouldn't the signal received be floating, i.e., shouldn't the environment interfere with the input signal and make the code above print random series of 0s and 1s on the REPL? What actually happens is the REPL prints all 0s.
I read of how input pins are interpreted as high-impedance output and while I suspect this may be the cause, I do not not understand what that means.

is the input pin connected to anything? ... what happens if you touch the pin?

That you'll get noise on a floating input observable in the read value isn't something you can rely on. The AVR like the ATMega328P seems to readily couple house/mains frequency noise onto inputs. However, I went to demonstrate this sort of thing for someone with a NodeMCU(ESP8266) board and found it was much harder to influence.
As I understand it the RP2040 has configurable Schmitt trigger inputs with a minimum hysteresis of 0.1 * IOVDD, 330 mV minimum, I think. And that these are on by default.  So your noise has to be bouncing across this threshold to affect the read value, which it may easily not be doing. If you turn off the Schmitt trigger feature, you may see more noise. I don't know how to disable them in MicroPython. The PicoSDK has a function called gpio_set_input_hysteresis_enabled that should do it.
You can also try running something like an old vacuum cleaner next to it to throw lots of noise into the environment.
For my own curiosity I may try playing with this on an RPI Pico, though perhaps not in MicroPython (we'll see) and if I do I'll show what I found.


text:
FastLED EVERY_N_SECONDS - does it generate static code?
I realize my question is not precise, so I have a simple contrived example to illustrate better what I am asking.
I am trying to use EVERY_N_SECONDS inside a member function of a class that is invoked in the sketch's loop() method. And this works fine, but when I have two instances of the class, each has its member function called in the loop(), but one instance seems to "win" and the other instance never seems to hit the inside of the EVERY_N_SECONDS block.
For example, the following code produces this output (I expected both a2 and a1 to appear in "a2 is in the EVERY_N_SECONDS loop"):
a1 is in the loop
a1 is in the EVERY_N_SECONDS loop
a2 is in the loop
a1 is in the loop
a1 is in the EVERY_N_SECONDS loop
a2 is in the loop
a1 is in the loop
a1 is in the EVERY_N_SECONDS loop
a2 is in the loop

Here is the code, a silly little program to illustrate the question:
#include <Streaming.h>
#include <FastLED.h>

class A {
public:
 String tag;
 void loop()
 {
   Serial << tag << " is in the loop" << endl;
   EVERY_N_SECONDS(2) {
      Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
   }
 }
};

A a1, a2;

void setup() {
  Serial.begin(9600);
  a1.tag = "a1";
  a2.tag = "a2";
}

void loop() {
  a1.loop();
  a2.loop();
  FastLED.delay(5000);
}

When looking at its definition and the line below, it seems like static. Though I don't quite understand what they are doing there

Assuming that the link of chrisl points to the relevant source...
Your source code:
    EVERY_N_SECONDS(2) {
        Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
    }

expands to (line split for readability):
    static CEveryNSeconds PER__COUNTER__(2);
    if( PER__COUNTER__ ) {
        Serial << tag << " is in the EVERY_N_SECONDS loop" << endl;
    }

So, yes, the instance controlling the conditional statement is static.
This is the definition of CEveryNSeconds:
template<typename timeType,timeType (*timeGetter)()>
class CEveryNTimePeriods {
public:
    timeType mPrevTrigger;
    timeType mPeriod;
    CEveryNTimePeriods() { reset(); mPeriod = 1; };
    CEveryNTimePeriods(timeType period) { reset(); setPeriod(period); };
    void setPeriod( timeType period) { mPeriod = period; };
    timeType getTime() { return (timeType)(timeGetter()); };
    timeType getPeriod() { return mPeriod; };
    timeType getElapsed() { return getTime() - mPrevTrigger; }
    timeType getRemaining() { return mPeriod - getElapsed(); }
    timeType getLastTriggerTime() { return mPrevTrigger; }
    bool ready() {
        bool isReady = (getElapsed() >= mPeriod);
        if( isReady ) { reset(); }
        return isReady;
    }
    void reset() { mPrevTrigger = getTime(); };
    void trigger() { mPrevTrigger = getTime() - mPeriod; };
    operator bool() { return ready(); }
};
typedef CEveryNTimePeriods<uint16_t,seconds16> CEveryNSeconds;

Its operator bool() returns only once the value true, if the period is elapsed. The first instance of your A receives this true, but never the second instance.
These are the relevant methods, sorted and formatted for better understanding:
    operator bool() {
        return ready();
    }

    bool ready() {
        bool isReady = (getElapsed() >= mPeriod);
        if ( isReady ) {
            reset();
        }
        return isReady;
    }

    timeType getElapsed() {
        return getTime() - mPrevTrigger;
    }

    void reset() {
        mPrevTrigger = getTime();
    }


text:
Upload to board with no USB connection
I have a Spark Fun Pro Micro (ATmega32U4) without a USB connection (it was broken off at an earlier point) that I want to use to duplicate a prototype running on another Pro Micro.
How can I upload a sketch to an Arduino without a USB connection?

The best solution is to solder back the connector or to buy a new board.
Ways to use a board with ATmega32u4 without USB for development are:

ICSP programming
upload over a serial bootloader.

Both require additional hardware.
For ICSP upload you need a programmer device. After configuring it, select the programmer in Tools menu and you can use "Upload using programmer" from the sketch menu. It is even possible to create a custom board definition which will use "Upload using programmer" with the "Upload" button from the toolbar.
To make serial upload possible you will need and USB-to-TTL-Serial adapter and  Optiboot compiled for the 32u4. To burn the bootloader you will need an ICSP programmer or a second Arduino to use with the Arduino as ISP sketch.

Use a programmer, such as one based on CH341A that has pins broken out for CLK, CS, MOSI, MIOS [sic], GND, 3.3V, and connected those to pins on the Pro Micro as follows:

Programmer    Pro Micro
CLK-----------15 (SCK)
CS------------RST
MOSI----------16 (MOSI)
MIOS----------14 (MISO)
GND-----------GND
3.3V----------RAW

It doesn't appear that the programmer is supported in the Arduino IDE, so I grabbed chavrprog.
And ran the command $ sudo ./chavrprog -d mega32u4 -a s ~/Arduino/test/test.ino.leonardo.hex

I see. The upload program implements the protocol. This is a very nonstandard solution for the problem in the question.


text:
IR sensor not incrementing or decrementing inside the loop
My project is automatic room light controller with visitor counter using Arduino.
My project was running correct upto this, but the problem started when we connected GSM module to our project because we have given a limit to the room, so when after limit exceeded using GSM a msg must be sent to the admin.
Actual problem is when a limit exceeds,code is not coming out of loop and when we are trying to increment or decrement no. of persons using IR sensor but its not happening.
Help me which loop i sholud use to send msg automatically
#include<LiquidCrystal.h>
#include <SoftwareSerial.h>
SoftwareSerial mySerial(3, 5);
char msg;
LiquidCrystal lcd(13, 12, 11, 10, 9, 8);
#define in 14
#define out 19
#define relay 2
int count = 0;
void IN()
{
  count++;
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);
  delay(1000);
}
void OUT()
{
  count--;
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);
  delay(1000);
}
void setup()
{
  lcd.begin(16, 2);
  lcd.print("Visitor Counter");
  delay(2000);
  pinMode(in, INPUT);
  pinMode(out, INPUT);
  pinMode(relay, OUTPUT);
  lcd.clear();
  lcd.print("Person In Room:");
  lcd.setCursor(0, 1);
  lcd.print(count);

  mySerial.begin(9600);   // Setting the baud rate of GSM Module
  Serial.begin(9600);    // Setting the baud rate of Serial Monitor (Arduino)
  Serial.println("GSM SIM900A BEGIN");
  Serial.println("Enter character for control option:");
  Serial.println("s : to send message");
  Serial.println();
  delay(100);
}

void loop()
{
  if (digitalRead(in))
    IN();
  if (digitalRead(out))
    OUT();

  if (count <= 0)
  {
    lcd.clear();
    digitalWrite(relay, LOW);
    lcd.clear();
    lcd.print("Nobody In Room");
    lcd.setCursor(0, 1);
    lcd.print("Light Is Off");
    delay(200);
  }
  else
    digitalWrite(relay, HIGH);

  if (count >= 3)
  {
    SendMessage();

    digitalWrite(relay, HIGH);
    delay(100);
    lcd.clear();
    lcd.print("Limit exceeded");
    lcd.setCursor(0, 1);
    lcd.print(count);
    return;
  }
  //else
  //  digitalWrite(relay, LOW);

  if (Serial.available() > 0)
    switch (Serial.read())
    {
      case 's':
        SendMessage();
        break;
      case 'r':
        ReceiveMessage();
        break;
    }
  if (mySerial.available() > 0)
    Serial.write(mySerial.read());
}

void SendMessage()
{
  mySerial.println("AT+CMGF=1");    //Sets the GSM Module in Text Mode
  delay(1000);  // Delay of 1000 milli seconds or 1 second
  mySerial.println("AT+CMGS=\"+918419906897\"\r"); // Replace x with mobile number
  delay(1000);
  mySerial.println("GSM TEST:Limit of the room exceeded");// The SMS text you want to send
  delay(100);
  mySerial.println((char)26);// ASCII code of CTRL+Z
  delay(1000);
  //Serial.end();
}

void ReceiveMessage()
{
  mySerial.println("AT+CNMI=2,2,0,0,0"); // AT Command to recieve a live SMS
  delay(1000);
  if (mySerial.available() > 0)
  {
    msg = mySerial.read();
    Serial.print(msg);
  }
}

void Response()
{
  int count = 0;
  Serial.println();
  while (1)
  {
    if (Serial.available())
    {
      char data = Serial.read();
      if (data == 'K') {
        Serial.println("OK");
        break;
      }
      if (data == 'R') {
        Serial.println("GSM Not Working");
        break;
      }
    }
    count++;
    delay(10);
    if (count == 1000) {
      Serial.println("GSM not Found");
      break;
    }
  }
}

your description of the problem is unclear. i am unable to understand which part works and which part does not work.

Why do you use so many long delays? You wait for 1 second everytime a person comes in or out. This blocks all other code, that could be running

Actual problm is when the limit of persons exceeds a msg must b sent to admin so i gave it inside loop a if condition bt the prblm is once the limit exceeds msg is sent bt i cant increment or decrement no. Of peraons manually. It is not coming out of if condition  @jsotola

Check that the GSM module is wired correctly, is setup correctly and that you get a ringing tone when you call that number from a different number.
If that is all okay, write / copy a sketch from one of the many online tutorials that sends an SMS taking all input from the serial monitor of the Arduino IDE. When that is working, transfer that code into the sketch above.
The return statement in your code will exit the loop() function within the sketch, but the C code running your sketch will just invoke your sketch again. Also, good practise says it's best not to include a function that is not actually used in the sketch - examples being the ReceiveMessage() and Response() functions.

Can u plzz send me the right code