text:
Garbage stored in SD card
I am an electronics graduate and an embedded design engineer, working in this field for about two years apart from the hobby time during my graduation. I am currently working on a system that has an Atmega2560 as the core controller with an arduino bootloader, we are using an 8GB memory card to save the log data from our system and send it to our server at regular intervals of time. The system worked fine however some of them are facing issues with the writing of data, some garbage value are getting stored in the SD card. I have attached the schematic and code snippet for the same, please let me know if there is any problem with the system and how can i resolve it, please let me know if any other things are required for understanding the problem correctly.
Thank you in advance.
     SD_Initialize();
  if(!SD.exists(SDTransactionDirectory))
  {
    if(SD.mkdir(SDTransactionDirectory))
    {

    }
  }
  RTC_Date_Time();
  String FileName = SDTransactionDirectory + "/" + RTCSDDate + RTCSDTime + ".txt";
  SD_File = SD.open(FileName, FILE_WRITE);
  if(SD_File)
  {
    delay(100);
    digitalWrite(LED_SD, HIGH);
    SD_File.println(GSMData);
    SD_File.close();
  }

The SD_Initialize() is a user function:-
void SD_Initialize()          //initialise SD card
{
  digitalWrite(SD_EN, HIGH);
  digitalWrite(SD_CS, LOW);

  delay(500);

  if(SD.begin(SD_CS))
  {
    digitalWrite(LED_SD, HIGH);
  }
  else
  {
    digitalWrite(LED_SD, LOW);
  }
}

The data stored in the filename is as follows:-
CLEnT|T|M008|\00Ÿûmï°]ŸëÜ£·zoòTÏæ{Œü[ŸýUô~ÛcCWY®ÞgÙë×<;wBÄgnìÇFÿÉ=XoÎ.êžÄf·®ö¯³ç~åeÝ]1_ÏÀyÿÌÍ?ô"zBõ¬ñ
As you can see the initial values till "M008" is fine but its garbage after that, and the CLEnt|T|M008 is the start of the string after that a lot of other parameter information is to be stored which turns out to be garbage.

Are the filenames garbage as well or only the content of the files? Is the garbage only on certain sd cards of a certain brand or type? What does the garbadge look like?

Is GSMData a String? You should avoid String and all String-based concatenation operations. Even on a Mega2560 with that little extra bit of SRAM it's still "iffy".

Are all files being written?  Does RTCSDDate and RTCSDTime contain illegal Filename characters?

@Jot The filenames are correctly stored however the data written is garbage, i have added an edit to let you know about the data stored in the card. Its not dependent on brand and type since we are using the SD card for all the systems.

@Majenko yes it is a string variable, can you please suggest any other way to store the data to that particular card, the data is about 200 characters.

@CodeGorilla yes the files are being made with correct names however only the data is out of the desired format.

You said: "Its not dependent on brand and type since we are using the SD card for all the systems.".  Did you mean to say you are using "different SD cards for each system"?  Also, check your power supply current capabilities and dependability.  Consider the possibility of voltage fluctuations causing corruption in the processor, communications between the processor and the SDCard and in the SDCard.

@st2000 we are using the same SD card brand and type in all the systems, we are using an MPTT based regulated supply which is further converted to 5volts for proper operation. It has sufficient power rating for upto 2A output rating.

The example data starts CLEnT|T|M008|\0; is the \0 an actual sequence of the two characters "" and "0"? It may be coincidence, but it looks suspicious to see the escaped null char just before the "corrupt" data. Makes one think String termination problems.

Can you confirm exactly what should be saved? Should the M008| be the last value saved? In other words, what do you expect to see?

@shwetankvishnu https://majenko.co.uk/blog/evils-arduino-strings

Likely, SDCards are not alike between OEMs.  Further, there are counterfeit SDCards on the market.  It would have been more ideal if you had used different SDCards and identified any correlation between SDCards and observed unexpected behavior.

There are many comments, but no answer yet. This answer has only a few basic rules.
The first thing to do is to see if the problem can be replicated with a small sketch and to check the voltages.
The arduino mega 2560 works best at 5.0V, or maybe a little less. It is not reliable at 4V. When powering it with a 5V power supply, the usb connecter is the best option to power the arduino board. Powering the arduino board via the 5v pin is not advised. When a strong power supply is connected to the 5v pin, the voltage regulator can be blown.
When something is not working, fall back to something that is reliable. For example a SD module with a HC4050 to shift the voltage levels. The resistors make the signal weaker.
Make a small test sketch without the use of the String object. The more experienced someone is with arduino, the more he or she tells to avoid the String object with avr microcontrollers.
There are counterfeit SD cards. One of those might turn up in your hands someday. Beside that, not every SD card is compatible with the arduino SD library.
In your situation it is suspicious that the file system is okay, the filenames are okay, the first text is okay, but when data is written it suddenly goes wrong. That is a strong indication for a memory problem.
When data to a display or SD card is wrong, then send it also to the serial monitor. You have to know what is actually written to the SD card.

hi @jot thank you for concluding the comments and pointing out the possible issues,

The power supply is well regulated and filtered using a DC-DC buck convertor which is getting an input from an 18-36Volt SMPS with upto 5A current rating. And I am using the Atmega2560 chip with an arduino bootloader, not the arduino board itself.
I am looking forward for making change in the hardware to use the HC4050 to check the response
Checked the sample sketch and worked fine like most the systems. Note this problem is with few systems not alll
I formatted all the cards with a FAT b4 using

I have asked to ship the system from site and once i get it will check the serial monitor to see whats going around.


text:
QRPrint library characters limit
I am trying to use this library to print QR codes using Arduino. There is a limit on the number of characters allowed in the string to be printed.
printQR("This is the string to be QR encoded !!! Tralalala. Some other random characters !!!");

When I scan the generated QR code, the string seems to be truncated. Did anyone run into this before? Or is there any way to get around this issue by raising the number of characters allowed in the string?
Thank you.

What is the limit, exactly? 47?

The code in the library truncates to 47 characters for some reason:
void printQR(String message) {

...

  // create QR code
  message.toCharArray((char *)strinbuf,47);
  qrencode();

The buffer is actually 116 bytes, oddly.
unsigned char strinbuf[116];

It's a little unclear why the limit of 47, or 116, was chosen.
You could try changing that line in qrprint.cpp to increase the number from 47 to at least 115.

Edit
After reading some of the comments, I doubt that will help. The QR code looks like it is generated into an internal array, which would have to have some size limits due to the amount of RAM available. The current array size is:
unsigned char qrframe[600];

That is already 1/3 of the available memory on a Uno.

Does the library actually support version 10 or larger QR codes though?

Also, the 116 limit is for pure numeric codes (115/3*8=48).

I think I've identified why the string is truncated. The reason (for 47) is a bit more obscure. I couldn't find any documentation about which version they library produces, and therefore whether that is in fact the upper limit. See Information about QR codes. Version 2, ECC level L, alphanumeric, has a limit of 47 characters.

This is also a reason why I dislike "magic numbers" in the middle of code. Why 47? Why not 46 or 48? A comment on that line explaining why the number 47 is there would be very useful.

Thank you @NickGammon for the clarification. The thing is that I am using this library in order to convert larger strings into printed QR codes. I tried increasing the numbers in the source code but that generated odd QR figures that are neither scannable nor compliant to QR standards. I would like to know if anyone ran into this before and what is the correct way to generate version 7 QR codes or higher. If it could be of help the library is build on top of https://github.com/tz1/qrduino . Thank you

Judging by what I read about higher version QR codes, they are more complex. For one thing they have more "locator" boxes in them. A version 7 code would be 45 x 45 modules (2025) which could hardly be stored in the RAM, unless you stored a bit at a time, in which case they might fit. The library might need complete reworking - try asking the author. The alternative would be to print something short (like a web page link) and have that link provide more information.

source: Stack Exchange

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

sort: votes


text:
Temperature sensor and LCD
I have a project which uses a DS18B20 temperature sensor and an LCD with an I2C interface on it. I have connected the sensor to my micro-controller (the DS18B20 has a 12-bit digital output) to the ATmega16 PD17, but as I try to print my values on the terminal the sensor output a really high value in decimal. Here is part of the code (and yes everything is working fine, this is a home-made Arduino):
DDRD &= 0x00;
PORTD |=  0x00;
ds18b20_init(&PORTD, 20, 30, DS18B20_12BIT_RES);
int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);
printf("Temperature: %d  ", temperature_sensor_output);
delay_ms(500);

ds18b20_init is the Dallas function for initializing the module. ds18b20_temperature returns a float value of the temperature
From this code it just prints:

Temperature: 51603

If I change %d to %f it prints:

Temperature: without any value

I do not understand where I may have missed some things.

Should it be float temperature_sensor_output =?

"printf"?  Are you including the standard I/O C library?  I would have thought that a bit much on a small embedded processor.  But if it works, great! Still, floating point math too?

The home arduino works, though the way I am using the sensor does not.I think I am using these functions wrong but I cannot see the mistake.

@Gerben Yes you are right, but if I put a float into an int it should truncate it?like float 27.89 to int 27?

@DianaLc, you are doing normal C programming on an embedded processor.  A float is usually made up of a integer mantissa and an integer exponent.  I am not sure how much supporting software is available (has been written) for this platform to support casting like you are doing.  I am thinking, not sticking to integer arithmetic is probably causing your problems.  Most professional embedded programs would stick to integer math.  Most software only people just assume all hardware is abstracted to the same level.  That's the different between software and firmware.

Without more detail about the system, I won't understand what printf() does; in non-embedded systems,  printf() writes to stdout by default, but Arduino systems typically don't use such a device.
That aside, %d is the proper format code for printing an integer value, and %f is proper for a float or double.  If you attempt to print an integer value like temperature_sensor_output under a %f format code, either the compiler will complain or the integer pattern of bits (plus perhaps two additional random bytes) will be interpreted as if it is a float or double pattern of bits.  No type cast occurs within printf().  If you want to use a %f format code, pair it up with a float-type variable.
If, as you say, ds18b20_temperature() returns a float, then the type cast  (float)ds18b20_temperature(&PORTD) will have no effect.  Generally, casts convert data from one form to another, or in some cases declare that data has a given form.  Going from float to float doesn't change anything.
In a C statement like a=b, if b has a type that's different from that of a, the b value will be cast to the type of a.  Thus, the float value on the right hand side of
int temperature_sensor_output =  (float)ds18b20_temperature(&PORTD);

will be converted to an integer value and stored into the integer variable temperature_sensor_output.

You can use printf(), if you define a FILE descriptor for stdout as: "static FILE uartout = { 0 };   // dbprintf file descriptor" and a declare and write a char-output function, e.g.: "static int uart_putchar (char c, FILE *stream);", where uart_putchar() Serial.write()s 'c' to the terminal (and ignores the "stream" arg). Note, however, the arduino library's printf() does not implement "%f", even if floating-point is loaded.

Have you looked at the raw return value from ds18b20_temperature(), without casting it to float and then to int, perhaps in hex? It may not be your printing code that's causing trouble but the value returned from the function. If the function is returning something equivalent to 51603, it is already bogus. DS18b20s temperature values are in 16-ths of a degree (Celsius, assuming the routine didn't convert it). 51603/16 is still an unreasonable value, not to mention that viewed as as a 16-bit int, the sign bit is set. Is it truly negative? Did something overlow?
I think you need to look at what that function is doing.

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


text:
Convert string to array
I have a project and i need to convert string (contain numbers and letters) to array
String name = "s111, s222, bbbb,cccc ";

and i want
array[0] = s111;
array[1] = s222;
array[2] = bbbb;
array[3] = cccc;

here is the code :
 String name = "s111, s222, bbbb,cccc ";
 int array[50];
 int r=0,t=0;

 for(int i=0;i<name.length();i++){
      if(name.charAt(i) == ','){
          array[t] = name.substring(r,i);
          r = (i+1);
          t++;
         }
 for(int k=0 ;k<=t ;k++){
   Serial.println(array[k]);
  }

When I compile I get just zeros like :
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;

What exactly does not work? What did you expect and what actually happened? Please provide a full compilable code (this one does not have the declaration of the other variables in it, including the array). Also my answer to this question might also be helpful.

why are you asking us to guess what your code actually does? ... we can't even test your code because you provided code that does not compile ... your description of the problem, it wont work, it useless

I think the description is clear

Re “i want array[0] = s111;”: this doesn't make sense. array is an array of ints, and “s111” is not an int.

thanks but do you have another way to split the character of that variable

Do you need an array of strings or an array of int? If int, how should the last 2 parts be interpreted? ASCII hex?

array of strings

"I think the description is clear." You are wrong. Your question is a muddy mess. You haven't provided enough code for us to test your program. You haven't told us what goes wrong with your current code. You haven't told us what format your output is supposed to be in (you finally said "array of strings" in the comments, but you need to edit your question to provide a full description of the problem in the question itself. Don't expect somebody trying to help you to read through an endless question-and-answer session to figure out what you are really asking.

When you declare int array[50]; you declare an array of numbers so only numbers can be stored inside it. If you really want an array of strings then declare an array of strings like String array[50]; There was also a a problem that sometime you split the name by comma, sometime by space, and sometime by comma+space. Also your code was missing closing bracket.
The algorithm has to split both by comma and my space and then take only values that have length more than one to avoid inserting empty strings.
String name = "s111, s222, bbbb,cccc ";
String array[50];
int r=0,t=0;

for(int i=0;i<name.length();i++)
{
  if(name[i] == ' ' || name[i] == ',')
  {
    if (i-r > 1)
    {
      array[t] = name.substring(r,i);
      t++;
    }
    r = (i+1);
  }
}

for(int k=0 ;k<=t ;k++)
{
  Serial.println(array[k]);
}

thanks you it works

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


text:
How can I copy and compare a string?
I have the following code (I realise String isn't very efficient, but this sketch doesn't have to be)
debugOutput gets called every loop, but I only want to spam the serial bus (to debug) if the status changes.
However, it runs once, despite changes to the pins being made.
String prevState = "";
void debugOutput() {
  String s = "";
  //s = s + digitalRead(6) ? "1" : "0";
  //s = s + digitalRead(5) ? "1" : "0";
  s = s + digitalRead(4) ? "1" : "0";
  s = s + digitalRead(3) ? "1" : "0";
  s = s + digitalRead(2) ? "1" : "0";
  if(!prevState.equals(s)) {
    Serial.println("State Change: "+s);
    //strcpy(s, prevState);
    prevState = s;
  }
}

My suspicion is it was because of the pointers being the same, but I declare a new string every time this function runs. Just in case, I tried to swap this to strcpy, which isn't valid since I'm using String instead of character arrays.
What can I do, I'm really confused.
This is the Serial output, btw
State Change: 1 So it's clear to me that my string appending isn't even working as expected.

Why are you using a String for this?  Just save the pin states and compare them and if any have changed send a message.  Take out the intermediate step of creating a String from that data and compare the data directly.

Why using a String? Anyway making a copy si as simple as prevState = s; And check for inequality is simply prevState != s.

This was intended to be quick and dirty debug code that wouldn't be in the final thing, I was attempting to do what I thought was easy and quick for me at the time, but when you need to start debugging your debugging code, you start to get frustrated.

I've added an edit as I realized I missed including what my serial output was.

Yeah, operator priority is kinda need to know (or you have to use paretheses). Even  +=  operator would let you avoid stuff like adding result of digital with s and then use it as bool value for ?:  :D

Operator Priority? God damn it, I assumed that the types disambiguate it (coming from Java, C#) would prevent that from happening, now I feel really foolish.

The string class can handle  String+int, and obviously it can be also implicitly casted to the bool value (which is really surprising and quite dangerous operator in this case)

There is this thing called "operator precedence" that defines the hierarchy of operators.
The ?: will be calculated after the +. That's why
s = s + digitalRead(2) ? "1" : "0";

actually means
s = (s + digitalRead(2)) ? "1" : "0";

But you want
s = s + (digitalRead(2) ? "1" : "0");

To make this a more useful answer, you should really mention how the types are ignored / coerced. I've awarded you the answer regardless though. I was aware of operator precedence, but not how it interacted with the types under C.

I'm not sure why string appending using + was failing, but changing it from
s = s + digitalRead(2) ? "1" : "0";
to
s += digitalRead(2) ? "1" : "0";
fixed my issue.

I won't be accepting this as the answer, even though that it is AN answer, in order to award the answer points to someone that explains what was wrong.

first of all you shouldn't use String for this. you can store numbers, compare numbers, print numbers. digitalRead returns a number

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


text:
Testing of voltage level converter with arduino
I am having a problem I am testing logic level shifter https://ewall.com.pk/product_view/IIC-I2C-Logic-Level-Converter-Bi-Directional-Module-5V-to-3.3V/910. I have followed the procedure as given in this post Test level shifter with Arduino and some data. But I am getting opposite result when I connect LV1 to LV2 arduino stop uploading and give error and nothing displays on serail monitor. Kindly help me.

Please post your circuit schematic.  It's not at all clear what you are doing.

Apparently you did not completely follow the description at Test level shifter with Arduino as that states that you need to upload a blank sketch before connecting the Arduino serial port to the level shifter, not after (that will not work but that's as expected). Did you also add pullups as described in the answer? Also, a schematic would really help.

i have not added pullups. Sorry but i don't know how to add pull ups and their purpose. I just followed the edited solution of post.

In electronic logic circuits, a pull-up resistor or pull-down resistor is a resistor used to ensure a known state of a signal. They are a very fundamental building block in electronics. I would recommend reading this article on pull-up resistors: https://www.electronics-tutorials.ws/logic/pull-up-resistor.html This will help you understand some of the above comments.

so that means without adding pullups my circuit is incomplete

Someone please guide me .


text:
Coding of arduino and ZEDF9P GNSS module
I have ZEDF9P AND ARDUINO and connected them Via UART.
I have written program which is showing that NMEA strings are coming in arduino and arduino is filtering out if GPS jamming is taking place. Now once GPS signals are coming LCD show GPS:ok. oNCE GPS is jammed it is giving output as GPS:INVALID
.During this time it converts to GLONASS. I want to write GLONASS ENABLED on LCD once I get signals. But my problem is that I am unable to write code for the time once GLONASS is enabled. I want that once I switch on another system The system name should come on LCD automatically but I don't know where the code is wrong. Kindly help me with the code. (I am doing it with NEO6M as well so kindly ignore baudrate)
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

// Choose two Arduino pins to use for software serial
 int RXPin = 6;
 int TXPin = 7;

//Default baud of NEO-6M is 9600
int GPSBaud = 9600;

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

#define GPSENABLE 2
byte GPSBuffer[82];
byte GPSIndex=0;
#define MAX_NMEA 200 // Max characters in NMEA Sentence to accumulate

float gpsSpeed;
void processGGA(char *nmea)
{
// TODO
}
void processGLL(char *nmea)
{
// TODO
}
void processRMC(char *nmea)
{
char *token = strtok(nmea, ",");  // Split NMEA string with ',' delimiter
if (token) // Is Token NULL?
{
int i;
for(i=0; i<7; i++) // Process Fields, truncated
{
 token = strtok(NULL, (i < 11) ? "," : "*"); // delimit based on expected termination
  if (!token) break; // NULL Token
  if (i == 1) // Field 1 Fix
  {
  lcd.clear();
    lcd.setCursor(0,0);
    if (token[0] == 'A')
     { lcd.print("GPS:OK");
    digitalWrite(9, HIGH);
    digitalWrite(8, LOW);}
    else if (token[0] == 'V')
      {delay(100);
        lcd.print("GPS:INVALID");
    for (int i = 0; i <= 100; i++) {
  digitalWrite(8, HIGH);
  delay(100);
  digitalWrite(8, LOW);
  delay(100);
  };
  uint8_t ubx_cfg_gnss[] = {
0xB5,0x62,0x06,0x3E,0x2C,0x00, // UBX-CFG-GNSS
0x00,0x00,0x10,0x05, // 16-Channels, 5-Constellations in list
0x00,0x08,0x10,0x00,0x01,0x00,0x01,0x01, // GPS
0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x01, // SBAS
0x03,0x08,0x10,0x00,0x00,0x00,0x01,0x01, // GALILEO
0x05,0x00,0x03,0x00,0x00,0x00,0x01,0x01, // BEIDOU
0x06,0x08,0x0E,0x00,0x00,0x00,0x01,0x01, // GLONASS
0xE8,0xFE }; // compute checksum
 Serial.write(ubx_cfg_gnss,sizeof(ubx_cfg_gnss));

      }
    else
      lcd.print("GPS:UNKNOWN");
  }
  if (i == 6) // Field 6 Speed Knots (Basically a Nautical Mile, or One Arc Minute)
   { gpsSpeed = atof(token) / (3600.0 / 1852.0); // Pull as a floating point (in knots, convert to
  m/s)
  }
  }

  }
  }
  void ProcessGPSLine()
  {
     if ((GPSBuffer[1] == 'G') && (GPSBuffer[2] == 'L') && (GPSBuffer[3] == 'G') && (GPSBuffer[4] ==
        'G') && (GPSBuffer[5] == 'A'))
   {
     lcd.print("GLGGA Detected!");
      }

    }
    void readSerialGPS()
   {
     static char receivedGPSChars[MAX_NMEA]; // buffer for received GPS data
   static int ndx = 0; // buffer index
    static boolean newGPSData = false;

    while((gpsSerial.available() > 0) && (newGPSData == false)) // Drop out at each complete line
  {
   char rc = gpsSerial.read();

Serial.write(rc); // Feed byte from GPS to the console

if (rc != '\r') { // Terminate line, CR,LF pair
  if (rc == '$') // Resync on leading '$'
    ndx = 0;
  if (rc != '\n') // Don't copy LF
    receivedGPSChars[ndx++] = rc;
  if (ndx >= MAX_NMEA) // Constrain length
    ndx = MAX_NMEA - 1;
  }
   else { // '\r'
  receivedGPSChars[ndx] = '\0'; // Terminate the string
  ndx = 0;
  newGPSData = true;
   }
 } // while
 if (newGPSData) // One new line available
 {
   static boolean gpsAlert = false;

if (gpsAlert == false)
{
  lcd.setCursor(0,0);
  lcd.print("GPS:ENABLED");

  gpsAlert = true;
}
 if (strncmp(receivedGPSChars, "$GPGGA", 6) == 0)
  processGGA(receivedGPSChars);
else if (strncmp(receivedGPSChars, "$GPGLL", 6) == 0)
  processGLL(receivedGPSChars);
else if (strncmp(receivedGPSChars, "$GPRMC", 6) == 0)
  processRMC(receivedGPSChars);

newGPSData = false;
 }
 }
  void setup()
 {
 // Start the Arduino hardware serial port at 9600 baud
 Serial.begin(9600);
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);

  pinMode(9, OUTPUT);
  // Start the software serial port at the GPS's default baud
  gpsSerial.begin(GPSBaud);
  }
  void loop()
  {
     readSerialGPS(); // Consume data, process sentences
  }

Your question is very unclear.  Please edit the question and clearly state what you are attempting to do, what is happening, what you expect, what you are getting.  As it is, there is little anyone can do to help you.

I have edited it.


text:
Code for 2 ultrasonic sensors
This is my code:
int trigPin=13; //Sensor Trig pin connected to Arduino pin 13
int echoPin=11;  //Sensor Echo pin connected to Arduino pin 11
float pingTime;  //time for ping to travel from sensor to target and return
float targetDistance; //Distance to Target in inches
float speedOfSound=776.5; //Speed of sound in miles per hour when temp is 77 degrees.
int trigPin1=2;
int echoPin1=3;
float pingTime1;  //time for ping to travel from sensor to target and return 1
float targetDistance1; //Distance to Target in inches 1
void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(trigPin1, OUTPUT);
  pinMode(echoPin1, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:

  digitalWrite(trigPin, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state
  digitalWrite(trigPin1, LOW); //Set trigger pin low
  delayMicroseconds(2000); //Let signal settle
  digitalWrite(trigPin1, HIGH); //Set trigPin high
  delayMicroseconds(15); //Delay in high state
  digitalWrite(trigPin1, LOW); //ping has now been sent
  delayMicroseconds(10); //Delay in low state

  pingTime1 = pulseIn(echoPin1, HIGH);  //pingTime is presented in microceconds
  pingTime1=pingTime1/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime1=pingTime1/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance1= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance1=targetDistance1/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance1= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)
  pingTime = pulseIn(echoPin, HIGH);  //pingTime is presented in microceconds
  pingTime=pingTime/1000000; //convert pingTime to seconds by dividing by 1000000 (microseconds in a second)
  pingTime=pingTime/3600; //convert pingtime to hourse by dividing by 3600 (seconds in an hour)
  targetDistance= speedOfSound * pingTime;  //This will be in miles, since speed of sound was miles per hour
  targetDistance=targetDistance/2; //Remember ping travels to target and back from target, so you must divide by 2 for actual target distance.
  targetDistance= targetDistance*63360;    //Convert miles to inches by multipling by 63360 (inches per mile)

  Serial.println(targetDistance);

  Serial.println(targetDistance1);

  delay(100); //delay tenth of a  second to slow things down a little.
}

Python code:
import serial #Import Serial Library

arduinoSerialData = serial.Serial('com3',9600) #Create Serial port object called arduinoSerialData

while (1==1):
    if (arduinoSerialData.inWaiting()>0):
        myData = arduinoSerialData.readline()
        myData=str(myData)
        myData= myData.replace("b'",'')
        myData=myData.replace("\\r\\n'",'')
        if myData<"3":

            print( myData)

When I compile the sketch, it shows no error.But when I run the file in python, output=0.However, when they are run individually, python gives me a valid input.so is this code correct?Also, is there a way to call for the exact c++file in python?Thanks for the help!

What file you are you running in python? You didn't show your python sketch. 2. How do you distinguish between the data from the first sensor and from the second sensor? Or doesn't that matter for you?

Edit:outputs are distinguished by targetDistance1 and targetDistance(one variable has a'1' and one doesn't)

I meant it your python program. But as you are just printing every line, that doesn't really apply here. Have you checked, that the Serial output of your Arduino sketch is as you expect it to be? You could check that simply in the Serial monitor. And why are you doing if myDATA<"3" in your python program? Why do you only want to display lines, which are lexically at a lower order as "3"?

I was testing if my idea was gonna work..Cus the program that i am building,triggers a series of actions if distance is lesser than 3

You are not checking for the distance being lesser than 3. You first need to convert the data to a number, before you can compare it that way. Currently you are comparing two strings lexically, not 3 numbers.

Please confirm, that the Serial output is as you expected. In that case it is purely a python problem. I think you should do some basic tutorials for python and read a bit about variable types in python. That will give you enough knowledge, to write your python script correctly

Alright ill look into it from a python perspective,thanks!

I just check my python code,it just prints the data outputted by the c++ code......so is the c++ code correct?
edit:The serial output is not exactally as expected.When I run the code for each ultrasonic sensor,it gives the correct output, but when i combine them (to form the code above) the output I get is 0.00.So there is a error when i combine the 2 codes.(What i mean by individual code is the above code without the echoPin1,triggerPin1,pingTime1 ect)

You are trying to measure with 2 ultrasonic sensors at once. You cannot do that so easily. You need to measure sequentially for 2 reasons:

The ultrasonic sensors might get confused by the others signal
You will miss the pulse of the one sensor, while you are reading the pulse of the other via pulseIn().

So the order of actions is like this:

Trigger sensor 1
Read sensor 1 with pulseIn()
Trigger sensor 2
Read sensor 2 with pulseIn()

Thanks so much!It works perfectly!

Is there a way i can differentiate the 2 inputs?

You can print an identifier before it, for example 1:100 for the value 100 of the first sensor. Then you can split the string in python at the colon to get the sensor number and the value individually

ah okok got it thanks!!

Is it possible to add for eg "a" and "b" to differentiate the 2 values?

Sure, just Serial.print them before each corresponding value


text:
I cannot get my code to play music in a or manner. I have to open one switch then the other. Music should play with either door open
Problem is if I open the necklaceDoor first, nothing happens. I have to open the ringDoor first. That turns everything on. Then with the necklaceDoor open, the stepper motor will turn off and the lights and music will continue to play. But I want to be able to open the necklaceDoor first and play the music with the lights. I do not want it to matter which one is opened first. I also realized that if I can get an or statement to work within an and statement I could do away with the fourth if statement completely. Both ringDoor open and necklaceDoor open, as well as ringDoor closed and necklaceDoor open have the same outcome. Now if I switch the door states in the third if statement, I get necklaceDoor only plays audio after closed(original problem) but if both doors are open and then ringDoor is closed, the music will shut off after the stepper timer is done and then start again after necklaceDoor is closed?!?!?!?
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;   //Number of pulses per revolution
const int ringDoor=2;                  //Ring door
const int necklaceDoor=7;              //Necklace door
const int relayPower=22;               //Turn relay on

Stepper myStepper = Stepper(stepsPerRevolution, 8, 10, 9, 11);

void setup() {
  Serial.begin(9600);                         //Start connection with computer

  if (!SD.begin(53))                         //Chip pin on card
  {
    Serial.println("failed!");                //SD card did not read
    return;
  }

  tmrpcm.speakerPin = 46;                      //Speaker output pin
  myStepper.setSpeed(5);                       //Stepper speed
  pinMode(ringDoor,INPUT);                     //Check state of ring door magnetic switch, NO
  pinMode(necklaceDoor,INPUT);                 //Check state of necklace door magnetic switch, NO
  pinMode(relayPower,OUTPUT);                  //Relay enable for 12V LED
  digitalWrite(ringDoor,HIGH);                 //Make door closed read high on start up
  digitalWrite(necklaceDoor,HIGH);             //Make door closed read high on start up
  digitalWrite(relayPower,LOW);                //Make relay off on start up
}

void loop() {

  if ((digitalRead(ringDoor)==HIGH)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door and necklace door is closed, everything is off
    digitalWrite(relayPower,LOW);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door is open and necklace door is closed, lights on, stepper motor spinning, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
    myStepper.step(stepsPerRevolution);
    delay(500);
    myStepper.step(-stepsPerRevolution);
    delay(500);
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==HIGH))
  {                                                                                //ring door closed and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }

  if ((digitalRead(ringDoor)==LOW)&&(digitalRead(necklaceDoor)==LOW))
  {                                                                                //ring door and necklace door open, lights on, stepper motor off, music playing
    digitalWrite(relayPower,HIGH);
    tmrpcm.play("music.wav");
  }
}

Please and thank you to any and all who help. It is greatly appreciated.
Yes, I asked the the original question and the answer I received not only did not work, somehow neither latch worked anymore.

The code you've presented should not even compile. Some of what looks like code is in comments, line endings are apparently missing, and lines extend far out across the page. Is this what you tried to run or did it get mangled when you posted it? If it's the latter, please repost the code you actually compiled.

I don't know what happened to your code when you copy-pasted it, but please reformat it entirely and paste it in here again. It's entirely unreadable, and definitely should not compile as it is. Once you paste it, highlight it all and click the "Code Sample" button in the editor to get the editor to treat it as a code block (as it is now already).

Updated. Thank you, I had not realized it messed up.

Did you intend for the two middle if statements to have the exact same condition?  Or should one have been for the other door?

all you need is two if statements to cover the open doors ... if either door is open then lights on and play music .... if ring door is open then run motor ... run them one after the other

I have tried two if statements.I have tried else if statements. I have tried just about everything imaginable to me. No matter what, what I cannot get the lights to turn on with just the necklace door open. And, I need the motor to stop if the necklace door is opened at any point. Thanks for the help but I think I am going to have to pay someone to look at it.

First of all, you have to find out how your magnetic switches work. Are they opened or closed if you attach a magnet to them? Do they behave the same or is one closed and the other opened if you attach a magnet?
Your code above is written for active LOW switches i.e. if the respective door is closed the switch is opened and therefore the logic level of the pin is HIGH. The level is LOW if the door is opened (activated; hence active LOW).
In order your code had a chance to work, the switches must be connect the right way: on one side connect them to GND and on the other side to the respective Arduino pin. If this is not the case, the code must be changed or the switches must be conneted the right way. You did not show us your schematic, so I can not check it for you.
Here is some code to try: But first find out if the switches you use are LOW or HIGH active. I also have no access to an IDE at the moment, so I can not try out the code. Take it as a hint on how to do it.
And one tip from a guy that does the job for 30 years now: Don't comment variables if their names say it all:
//  this sort of comments makes the code unreadable --V
const int ringDoor=2;                          //Ring door

I know it is a common behavior in the Arduino community, but don't write comments after a statement. In your code above I did realize that there are comment for the if statements only when I copied the code in my answer. Comments are only usefull if they say something new and can be read without problems.
#include <SD.h>
#include <TMRpcm.h>
#include <Stepper.h>
TMRpcm tmrpcm;

const int stepsPerRevolution = 2048;
const int ringDoor = 2;
const int necklaceDoor = 7;
const int relayPower = 22;

Stepper myStepper = Stepper( stepsPerRevolution, 8, 10, 9, 11 );

void setup()
{
  Serial.begin( 9600 );
  if ( ! SD.begin( 53 ) )
  {
    Serial.println( "failed!" );
    return;
  }

  tmrpcm.speakerPin = 46;
  myStepper.setSpeed( 5 );
  pinMode( ringDoor, INPUT );
  pinMode( necklaceDoor, INPUT );
  pinMode( relayPower, OUTPUT );

  digitalWrite( ringDoor, HIGH );
  digitalWrite( necklaceDoor, HIGH );

  digitalWrite( relayPower, LOW );
}

void loop() {

  // the following code works if both switches are LOW active
  // (i.e. LOW if the door is open)
  // if the "ringDoor-switch is HIGH active change
  // digitalRead( ringDoor ) == LOW to
  // digitalRead( ringDoor ) == HIGH
  // if the "necklaceDoor-switch is HIGH active change
  // digitalRead( necklaceDoor ) == LOW to
  // digitalRead( necklaceDoor ) == HIGH
  // and
  // digitalRead( necklaceDoor ) == HIGH to
  // digitalRead( necklaceDoor ) == LOW

  if ( ( digitalRead( ringDoor )     == LOW ) ||
       ( digitalRead( necklaceDoor ) == LOW ) )
  {
    // one of the doors is open
    digitalWrite( relayPower, HIGH );
    tmrpcm.play( "music.wav" );
    if ( digitalRead( necklaceDoor ) == HIGH )
    {
      // only the ring door is opend
      myStepper.step( stepsPerRevolution );
      delay( 500 );
      myStepper.step( -stepsPerRevolution );
      delay( 500 );
    }
  }
  else
  {
    digitalWrite( relayPower, LOW );
  }
}

So your code works almost perfect. Thank you very much! I do apologize for the notes. The arduino page forum asked for them as did my first post here. The only issue I am having now is that if I open necklace door first no music will play until I close that switch? Then music will play? I am trying to figure out how to add picture of my schematic. Be gentle with me, I don't have CAD so I drew it in MultiSim. ( A program I still have from college). I just edited original post with the schematic.

@VincentLedbetter You're welcome. There is no reason to apollogize. The schematic is fine. The switches connect GND to the sensor pins so the first part of the program (e.g. activating the pull up resistors) seems to be correct. Theres one thing I can not check, and that's: Are the switches close if the doors are close or are they open? See the comment in the code above. If you can not find out, make the HIGH/LOW changes I suggest in the comment and find out if that works better. There could also be an issue with the needed power. The Mega might not be able to drive all the current you need.

So the 12v Power supply has a splitter. One side goes to the arduino and I am only running the sd card reader, the relay enable and the audio pin. Then the other side of the 12v power supply is ran through the relay. The LED's plug in before the voltage regulator and the stepper motor is powered after the voltage regulator. So my high amperage draw is coming straight from the power source and not through the board.

@VincentLedbetter The 3.3V Pin has a maximum current of 50mA. How much current draws the SD Card Module? The IO Pins can deliver 40mA. How much draws the Buzzer? The 5V can deliver the minimum of the possible Power Supply current and 500mA (controlled by a thermofuse). From that you have to subtract the current that's drawn from the other pins: 3.3V, IO Pins, the pullups on the switches draw current ...  It was just an idea if nothing else makes sense. The other idea, that the switches might not behave as expected, is more important to me.


text:
For Arduino, is there a meaningful difference between carriage returns?
Serial.write(0x0d); // hex
Serial.write(13);   // ASCII
Serial.write('\r');  // char
Is one more efficient? I read how it depends on the terminal program. So does that mean the IDE? (This is my first time working with serial comm.)

It’s \r not /r.

All of them are identical. But the last one is the most readable to us humans. So I’d prefer the last one.

it depends on the terminal program ... no it does not. .... the terminal program will receive ASCII CR for each of the lines

As mentioned before they are all the same. The thing you have to rememeber is that the compiler takes the human readable code you write and turns it into the instructions the processor can understand. If you want to explore ways the compiler does thing you can compile the program into the hex file and then compare. Or for even less detail, but much easier, look at the size of the file created when you compile in the IDE
using just the one line in question inside the setup function
write(0x0d)  ----> 1334 bytes
write(13)    ----> 1334 bytes
write('\r')  ----> 1334 bytes

For this simple example we can assume that all three of these are producing the exact same hex file.   There are many more complicated example of different ways to do the same task that may produce more or less efficient code, but in this case the compiler is going to produce the same instruction set to the processor.
As pointed out in the comments, I am not saying that because they are the same size they must be the same hex code. As any single byte being written would produce the same size code, but not the same result. But when comparing two methods that we know are the same functionality ( 0x0d and '\r') and they produce the same size binary, then we can assume the compiler reduced them to the same code.

write('\t') would result in same size

yes, as would any other single byte. and without having the ability to analyze the hex file, or other ways of getting a gaining a detailed idea of how efficient the code is, you could deduce that they were equally efficient. Although there are many cases this idea would not hold. It does give a new programmer an Idea of whats going on under the hood.

There is no difference between all the lines of code in your question. All representations stand for one value, containing one byte. There is only one implementation of Serial::write(), which has a uint8_t as parameter. So all the different representations result in a uint8_t anyway.

Is one more efficient?

after compilation it is same for all notations. the function and the value are the same for all 3 notations.


text:
"Serial does not name a type error"
I m getting serial does not name a type error, expected declaration before '}' token line 69
const int trigPin = 9;
const int echoPin = 10;
const int buzzer = 11;
const int ledPin = 13;

// defines variables
long duration;
int distance;
int safetyDistance;

void setup() {
  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  pinMode(buzzer, OUTPUT);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
// Clears the trigPin
  digitalWrite(trigPin, LOW);
  delayMicroseconds(2);

// Sets the trigPin on HIGH state for 10 micro seconds
  digitalWrite(trigPin, HIGH);
  delayMicroseconds(10);
  digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in microseconds
  duration = pulseIn(echoPin, HIGH);

// Calculating the distance
  distance = duration * 0.034 / 2;

  safetyDistance = distance;
  if (safetyDistance <= 5) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 1000);
    delay(100);
    noTone(buzzer);
    delay(100);
  }

  else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }
  Serial.print("Distance: ");
  Serial.println(distance);

}

I formatted your code and now you can see that you have a redundant } before the line with error report

  if (safetyDistance > 5 && safetyDistance <= 10) {
    digitalWrite(buzzer, HIGH);
    digitalWrite(ledPin, HIGH);

    tone(buzzer, 3000);
    delay(3000);
    noTone(buzzer);
    delay(3000);
  } else {
    digitalWrite(buzzer, LOW);
    digitalWrite(ledPin, LOW);
  }
  }                           //<--
  Serial.print("Distance: ");
  Serial.println(distance);

}

There is a duplicate } after the else clause is closed. Remove it and your code will compile.

is this worth an Answer?

@Juraj Because it answers the question, yes. Even beginner questions deserve to be answered. We have to be more inclusive, as I read in https://stackoverflow.blog/2018/04/26/stack-overflow-isnt-very-welcoming-its-time-for-that-to-change/.

Maximilian, I somehow don't like that I formatted the code in question to show the problem and you write an answer equivalent to my comment

@Juraj that's true and good that you formatted the question 3 hours ago, but questions are still to be answered in answers and not in comments. And since the question does not really allow for any different answer but this, we also have identical answers


text:
Replying with a html page in HTTP Web Server using esp01 and ArduinoIDE
Now there are many ways to reply with a webpage content to a user who is accessing the web server,
But Keeping in mind to use as less space as possible,
I was trying something new, Since i didnt got compilation error, I am a little confused as to what might be the error,
in void data() I am storing the html page and saving it in ROM,
void data()
{
  if(SPIFFS.exists("/login.html"))
  {
    Serial.println();
  }
  else{
    SPIFFS.begin();
    File f=SPIFFS.open("/login.html","w");
    String s="<title>AP</title>
Welcome to AP page
\n";
    s+="<form name=\"/myform\" action=\"/login\" method=\"POST\">\n";
    s+="<input type=\"text\" name=\"username\" placeholder=\"username\">
\n";
    s+="<input type=\"password\" name=\"password\" placeholder=\"password\">
\n";
    s+="<input type=\"submit\" value=\"login\"></form>";
    f.println(s);
    f.close();
  }

}

Please correct the above lines if I wrote it wrong,
After that,
I wrote some lines in void setup()
WiFi.mode(WIFI_AP_STA);//Only Access point
  WiFi.softAP(ssid, password);  //Start HOTspot removing password will disable security

  IPAddress myIP = WiFi.softAPIP(); //Get IP address
  Serial.print("HotSpt IP:");
  Serial.println(myIP);

  server.on("/", HTTP_GET, handleRoot);      //Which routine to handle at root location
  server.on("/",HTTP_POST,handlelogin);
  server.onNotFound(handleerror);

  server.begin();

Now  I am calling void handleRoot()
I want to send the page that I wrote and saved in the /login.html file.
so for that,
void handleRoot()
  {
    SPIFFS.begin();
    File f=SPIFFS.open("/login.html","r");
    server.send(200, "text/html",f.readStringUntil('EOF'));
  }

Now once I do this and execute and load the program in ESP01, it shows me nothing,
I have also tried sending (String)f, anything else I write is giving me an error,
This is compiling fine, but when I connect to the AP and open 192.168.4.1 in the browser i am not seeing anything,
But when I wrote server.send(200,"text/html",(String)f)
I was getting 0, Any idea on what mistake I am making.

What do you hope to achieve by having one bit of your program save a file of static data to SPIFFS and then another bit read that file and send it?

Unless I format the device, I can remove the bit where I add those lines to save the HTML file. Like remove the block of that code later.

Why not use the IDE's SPIFFS tools to create the SPIFFS image with the file already on it?

What I am doing wrong? Can I send a response like this? Or do I have to write the full html code again

I suspect it's the 'EOF' that you're reading until. That's looking for the letter E not the end of the file.

You should use server.streamFile("text/html", f);

Ok, but the problem is , it's  'end of office' today. Thanks for the info, I have to update tomorrow. Sorry

@WanStreet, did you see this example https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/examples/FSBrowser/FSBrowser.ino?

I will now.. I y

I commented further as an answer post, I needed to post an image, I still havent yet tried with server.streamFile() ... will work on that in a minute.

It looks like you never called data().

hmmm.. ok.. seems like it.. can you please tell me where to call the data(), sorry I am unable to follow..

Small update, I used the same code for ESP8266 NodeMCU.
Sorry If I am posting this with wrong device number. But I tried that same code and uploaded it to ESP8266, it worked, and I am getting the AP webpage, that I am storing and sending the file. I will post it as an answer as I need to post an image.
The is the page that I get when using the HTML that I wrote:

So, this happened. I am confused as to why it didn't work with ESP01, plus I have to load the code every time I plug in the ESP01.

wrong spiffs size or spiffs not initialized on the first device?

initialization of spiffs meaning? like spiffs.begin() ?

upload or format() http://esp8266.github.io/Arduino/versions/2.0.0/doc/filesystem.html

ah ok.. I will have to check tomorrow..


text:
ESP32 Access Point using ESPAsyncWebServer, how to send multiple parameters between submenu and main (index) menu while still retaining page layout?
I am trying to figure out how to get requests (or whatever they are called) to display in the serial monitor, yet not change the HTML page bodies.
The user selects their choices in the submenu (selection). Once clicking the submit button there, they return to the original main index menu and simultaneously the query parameters are sent to the ESP32 of the user's selections.
Based off another very similar question I asked, it works so that the query parameters (in the URL) can be seen in the serial monitor. Although, then the main menu is cleared out and left with "message sent".
Alternatively, the main menu can remain the same, but the query parameters are not sent. So one works but not the other, and vise versa.
The files are below and here: https://github.com/adamelli/MinimalExamples/tree/main/22-1-25_query_parameters_submitButton
File structure
sketch (folder)

sketch.ino
data (folder)

index.html
selection.html

sketch.ino
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
#include <painlessMesh.h>

const char* ssid = "Wireless Controller";
const char* password = "12345678";

// User stub
void sendMessage() ; // Prototype so PlatformIO doesn't complain

Task taskSendMessage( TASK_SECOND * 1 , TASK_FOREVER, &sendMessage );

void sendMessage() {
  taskSendMessage.setInterval( random( TASK_SECOND * 1, TASK_SECOND * 5 ));
}

AsyncWebServer server(80);

void notFound(AsyncWebServerRequest *request) {
    request->send(404, "text/plain", "Not found");
}
IPAddress IP(192, 168, 1, 1);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

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

  // Initialize SPIFFS
  if (!SPIFFS.begin(true))
  {
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  WiFi.softAP(ssid, password);
  delay(500);
  WiFi.softAPConfig(IP, gateway, subnet);
  IPAddress IP = WiFi.softAPIP();
  Serial.print("AP IP address: ");
  Serial.println(IP);

  server.on("/selection.html", HTTP_GET, [](AsyncWebServerRequest * request) {
    request->send(SPIFFS, "/selection.html", String(), false );
  });

// Main menu index page works
//  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request) {
//    request->send(SPIFFS, "/index.html", String(), false );
//  });

// Query parameters works
  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)
  {

    int paramsNr = request->params();
    Serial.println(paramsNr);

    for (int i = 0; i < paramsNr; i++)
    {
      AsyncWebParameter* p = request->getParam(i);
      Serial.print("Param name: ");
      Serial.println(p->name());

      Serial.print("Param value: ");
      Serial.println(p->value());

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

    request->send(200, "text/plain", "message received");
  });

  server.begin();
}

void loop() {}

index.html
<!DOCTYPE html>

Main Menu

<button class="button">Selection</button>

<button class="button">Oblivion</button>

selection.html
<!DOCTYPE html>

<form action="/" method="get">

    Shape Size:

    <select name="size" id="size" style="font-size: 22px;">
      <option value="1"> 1   </option>
      <option value="2"> 1/2 </option>
        </select>

Speed:

    <select name="speed" id="speed" style="font-size: 24px">
      <option value="1">          Slowest </option>
      <option value="2" selected> Regular </option>
    </select>

<button class="submit" name="circle" value="3">Circle</button>

<button class="submit" name="square" value="4">Square</button>

</form>

The data files must be uploaded via "Tools" → "ESP32 Sketch Data Upload".
How can the definitions, server.on("/" be combined so the data (size/speed/shape) is viewable in the serial monitor AND where the main and submenu remain the same (with their buttons)?
I have tried...

putting request->send(SPIFFS, "/selection.html", String(), false); and    request->send(200, "text/plain", "message received"); together inside  server.on("/", HTTP_GET, [](AsyncWebServerRequest * request)

sending different stuff for request->send(200, "text/plain", "message received"); even though I still do not understand how to get it to submit data, and return to the main menu, without clearing it out with a new message (various trial and error combinations either did not allow it to compile or just made one of the pages "Not found")

messing with HTML stuff (nothing changed)

So - if I understand you correctly - you want to just normally serve your index.html, until parameters are provided with the request. Then you want to output them to serial and serve the "message received" text. Is that correct?

Nope. The user selects their choices in the submenu (selection). Once clicking the submit button there, they return to the original main index menu and simultaneously (in the background) the query parameters are sent to the ESP32 of their selections. (When I replace "message received" with "" it just shows a blank main index menu.)

This is nothing to do with Arduino. This is all about Javascript and XMLHttpRequest calls.

Please don't repost, does this answer your question?

According to your original post https://arduino.stackexchange.com/questions/88538/esp32-access-point-and-http-web-server-how-to-send-multiple-parameters, you had a duplicate route handler for /, what you need to do is to change your param handling route to something else , say,  server.on("/submit" and also change your form submission action on selection.html to <form action="/submit" method="get">. It will shows it on Serial Monitor as what you are asking.

This is not an answer per se.
Posted as an answer because of attached images.
It is unclear what you are actually asking.
I ran a python minimal web server in the same folder as index.html.
Here is the trace from the server.
C:\Users\qwerty\Desktop2\MinimalExamples-main\22-1-25_query_parameters_submitButton\data>py3 -m http.server 80
Serving HTTP on :: port 80 (http://[::]:80/) ...
::1 - - [27/Jan/2022 15:43:23] "GET / HTTP/1.1" 200 -
::1 - - [27/Jan/2022 15:43:24] code 404, message File not found
::1 - - [27/Jan/2022 15:43:24] "GET /favicon.ico HTTP/1.1" 404 -
::1 - - [27/Jan/2022 15:43:25] "GET /selection.html HTTP/1.1" 200 -
::1 - - [27/Jan/2022 15:43:32] "GET /?size=2&speed=1&circle=3 HTTP/1.1" 200 -
::1 - - [27/Jan/2022 15:43:34] code 404, message File not found
::1 - - [27/Jan/2022 15:43:34] "GET /notMinimal.html HTTP/1.1" 404 -
::1 - - [27/Jan/2022 15:43:39] "GET /?size=1&speed=2&circle=3 HTTP/1.1" 200 -
::1 - - [27/Jan/2022 15:45:07] "GET /?size=1&speed=2&square=4 HTTP/1.1" 200 -
::1 - - [27/Jan/2022 15:52:46] code 404, message File not found
::1 - - [27/Jan/2022 15:52:46] "GET /notMinimal.html HTTP/1.1" 404 -
::1 - - [27/Jan/2022 15:53:02] "GET /?size=2&speed=1&square=4 HTTP/1.1" 200 -

This is what index.html is called with.
The data is available to index.html. You only have to parse it from the URL.


text:
Native USB port on custom ATSAM3x8e board not recognised in windows
I have been designing my own PCB using the atsam3x8e chip, the same as the Arduino due which I used to prototype with. So far I've managed to get my boards up and running by programming them via the serial TX & RX pins using a USB to serial converter, but I can't seem to get the "Native" USB port to work in windows.
When the boards are plugged in, they show up in the windows device manager as "Unknown USB Device (Device Descriptor Request Failed)" but do not show up in BOSSA or Atmel Studio 7.0. My understanding was that when the chip is reset and erased, it should just show up as a "BOSSA programming port" the same as the Arduino DUE does when it is put through the same procedure.
I'm not sure whether this is an issue with the hardware design of the board or not. I have used a USB C connector instead of a Micro USB so have not connected the UOTGID pin and instead added two pulldown resistors to the CC pins on the new connector.
If anyone has any suggestions on this please let me know.

"do not show up in BOSSA or Atmel Studio 7.0" is a consequence of "Unknown USB Device (Device Descriptor Request Failed)", not so much additional information.  Your understanding about it showing up as USB when erased is correct.  Show the hardware design.

added @timemage

I'm not terribly familiar with USB-C pinout, and it's hard to read just the PCB layout, but if I take it for granted that your two parallel traces are the D+ and D-, they go to only the high speed pins and not the full speed pins.  The due design does both.

@timemage this USB port is fairly simple, its 2.0 spec with VBUS, GND, DATA +, DATA- and CC pins instead of the ID pins. You're correct about the parallel traces being the data lines but they're connected to the high-speed pins directly and the full speed pins with 30k ohm resistors R22and R23.

Trying a different USB C cable and programming the boards over serial with an Arduino sketch makes the boards appear as Arduino DUE, but when reset and erased after this, the boards are still coming up as Unknown USB Device, is this normal behaviour since the vendor ID and Product ID are different?

Due has 39 ohms there.  Wild guess, USB interface fails or succeeds depending on the speed configured in the due/sam3x8e because of how you have it (not really) connected.

Sorry, that was just a typo... meant 39ohm, thanks for your help though


text:
Wiring Multiple MPU 6050 to Micro/Lenardo
disclaimer I am new at hardware/circuits
I am currently trying to connect two MPU-6050 to a single Micro board.
In addition, there are 5 additional buttons to be connected.
I am under the impression to connect multiple devices to the I2C bus, there must be unique addresses. I read there was a way to make unique addresses (https://playground.arduino.cc/Main/MPU-6050/#multiple).
However I am not sure of the wiring or if the voltage/resistors/anything is supposed to be located.
I have a sketch of what it may look like.

Can anyone help me verify that this is the proper configuration? Or what a proper configuration would look like?

Buttons are just buttons. You can have them "active high" with pulldown resistors as you have there (10K is fine. The actual value doesn't really matter, just don't have it too low or excess current will be drawn), or "active low" without resistors and connecting to ground when pushed instead of VCC and use INPUT_PULLUP. The choice is yours. There's no real benefit in this situation to either way of doing it.
The critical part is your AD0 connection. Whether you connect one to ground and leave the other unconnected, or connect one to VCC and leave the other unconnected, depends entirely on the design of the breakout board. It should have a resistor on the AD0 pin internally that either connects it to GND or to VCC. If it connects to GND then you need to link that pin to VCC to override it. If it connects it to VCC (or more likely 3.3V) internally then you need to connect it to GND to override it.
To find out which you will have to either consult the documentation or schematic for the board or measure the voltage at the AD0 pin. If it measures 0V (within a few mV) then it connects to ground and you will have to connect it to VCC to override it. If it measures more (probably nearer 3.3V) then connect it to ground to override it.
Because those chips are 3.3V and the board contains a 3.3V regulator (if your boards are the same as you picture in your wiring diagram) the chances are that the AD0 is pulled up to 3.3V so you just need to connect one to ground.
So it looks to me like your wiring diagram is most likely suitable and correct, pending confirmation of the pullup/pulldown in the AD0 pin.


text:
Why does controlling power with a transistor interfere with MHZ19B's serial communication?
I've been trying to turn off an MHZ19B (datasheet and teardown photos: revspace.nl/MH-Z19B). I've used an Arduino, NPN, PNP transistors and mosfets as well as the diagram below for connecting the sensor to an ESP32. In all cases, PWM communication works great! I can power off the sensor, turn it back on, and values derived from PWM communication are as expected. However when I connect the Rx and Tx lines (to software serial Tx and Rx pins respectively on Uno pins A0 A1 or ESP32 pins 32 33) they spit out gibberish and the PWM signal also suffers hiccups.
Otherwise, without any kind of logic power control, the MHZ19B works great and can communicate with anything via UART, even my PC usb port via FTDI.
I added resistors to the Rx and Tx lines so the voltage on them doesn't exceed Vcc. I tried 1n4007 diodes (they're the only ones I have; no Schottky diodes either). I tried an NPN equivalent optocoupler. I also tried powering the sensor from my breadboard. I don't own an oscilloscope :(
My High School teacher said to just use PWM, but as I searched for a solution to this error, I noticed hundreds of others have this exact same problem with all sorts of different sensors and loads with ICs; no one has come up with a general solution.
I've been obsessing with this for weeks and if anyone can help or can recommend a book about sensor schematics I would really appreciate it. Thanks!

You need to disconnect the serial, before turn of the power of the module. What I think happens is that the TX pin on MCU (RX on the MHZ19b) is HIGH when it isn't sending it anything. So you get 3.3-5V going into the MHZ19b that's powered down (which is bad). A lot of chips have clamping diodes on there input pins. So you are essentially powering the chip via the TX pin. The TX pin can supply enough power to the chip, with cause weird things to happen. For example gibberish UART data.

PS R2 looks weird to me. I think you need to move it the the horizontal section. Otherwise you only get 2.5V at the base of Q1, when Q2 is turned on.

It seems software serial doesn't have a function to "disconnect". A workaround is to set the TX pin to an INPUT, and to LOW (pinmode(txPin, INPUT); digitalWrite(txPin, LOW);). Then make sure you don't call any mySerial.print commands while power is off. Then when powering on the chip, do the reverse (pinmode(txPin, OUTPUT); digitalWrite(txPin, HIGH);

@Gerben R2 is okay. The base of Q1 will not go more than one diode drop below 5V regardless of R2 value.

Just guessing but I suggest you use a level translator. Also when you power off the sensor the serial output should go to ground disabling that channel.  Check your voltages and put a bypass cap on the transistor for the sensor. You can use a simple P channel Logic Level fet,only a 50 ohm resistor in the gate to prevent oscillation.  Your output will now be active low instead of active high. If you stay with transistors make R2 & R3 510 ohm so you have enough drive for the transistor and be sure it is NOT a darlington device, if it is you will not have enough voltage for the sensor.

I think the sensor has a built in level translator since the datasheet says it can use 3.3V or 5V logic. I tried to add a 100uF capacitor between +5V and VIN, but I don't know if it did anything. The sensor itself has 12 internal capacitors (or maybe 16 cause there is a silkscreen labeled C16) connected to ground. Is there an alternative to using transistors? How do some sensors just go to sleep and use virtually no power?

That capacitor will only decrease your noise immunity and make it more susceptible to line noise. That is not enough information, those are operating voltages, not input voltages. 3.3V and 5V logic are not compatible with each other even though both can operate on both voltages. If you look at the input structure you will see the threshold changes with the supply voltage. Thresholds are roughly 40% and 60% of VCC. That is only really valid if the sun comes up on the east side of the moon on February 33d. As far as something to read I would suggest you start with something in basic electronics.

When troubleshooting a problem like this, try 'cutting the world in half' before doing anything else.  In this case, replace the entire circuit with a manual switch (or a wire) and manually power and de-power the sensor.  If you still have the problem, then the circuit is irrelevant to the solution.  If the problem goes away, then the circuit IS the problem.
Once this experiment has been performed, then 'cut the world in half' again, working on the 'half' that is the problem. Repeat until only one component is left.

Thanks! Yeah I did that from the start. I didn't even use a microcontroller to power on and off the sensor. I just had the Rx and Tx ports connected to my computer to monitor values, and powered the sensor from a breadboard power supply connected to a wall outlet. I managed to get 4.6V @50 milliamps, using NPN or PNP based circuits, which is within spec. But the sensor never wanted to work. I suspect the internal capacitors are doing something. I would try to add a capacitor inline with the circuit but I don't know how. I think the sensor needs to draw 150 mA at the start to turn on its logic.

Glad you tried the simple route first, but it sounds like your setup still had problems.  You can get 5V power supplies from MeanWell power supplies that are cheap and reliable.

The sensor works. I ran it 24/7 for 3 months with a read every 60 seconds. If it didn't work I never would have made a post about transistors. Also why would I need a 100W power supply for a project designed to use an ordinary 5V 1A cell phone charger?

No no - not 100W or even close. For instance,https://www.meanwell.com/webapp/product/search.aspx?prod=GS05U-USB is a 5W (1.0A at 5V) wall plug with a USB connector - perfect for supplying reliable power to a range of projects.  Cut off the end of a USB cable, and wire the +/- wires to a barrel plug that fits the Arduino, and 'Bob's your Uncle' (saying from "The world's fastest Indian" movie).


text:
How to post data to database using nodeMCU?
We created a website hosted by 000webhost and we're trying to post data from our nodeMCU to the database using the sketch below, but the database doesn't seem to show any received data. How do you fix this?

and below is the php code to rtecieve the data:

#include <ESP8266WiFi.h>

const char* ssid = "Jino";
const char* pass = "myinternet";
char server[] = "cdgresearch.000webhostapp.com";

WiFiClient client;

int led = 2;

void setup() {
  Serial.begin(115200);
  WiFi.begin(ssid,pass);
  pinMode(led,OUTPUT);
  digitalWrite(led, HIGH);

  Serial.println("Connecting to: ");
  Serial.println(ssid);
  Serial.print("Connecting");

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

  delay(300);
  digitalWrite(led, LOW);
  Serial.println();
  Serial.println("Successfully connected to the network");
  Serial.print("NodeMCU IP Address: ");
  Serial.println(WiFi.localIP());

  if (client.connect(server, 80)){
    String data = "incoming=fromDuino&incoming2=FROMDUINO2";
    client.println("POST /tag.php? HTTP/1.1");
    client.println("Host: cdgresearch.000webhostapp.com");
    client.println("User-Agent: 8266/1.0");
    client.println("Connection: close");
    client.println("Content-Type: application/x-www-form-urlencoded");
    client.print("Content-Length: ");
    client.print("\n\n");
    client.println(data);
    client.stop();

    Serial.println("Connected to server");
    }
    else{
    Serial.println("Failed to Connect to server...");
    }

  client.stop();
  Serial.println("Disconnected from Server");
}

void loop() {
 // put your main code here, to run repeatedly:
}

post the code as text

did you see my answer?

im sorry, going to post the codes soon hopefully

HTTP requires \r\n as line ending. println adds \r\n. So to print the host name to client use println and remove \n from the string. And replace client.print("\n\n") with client.println(); client.println(); (or println the length and then use one println)

1st I would check each part i.e.
First check your PHP script can insert by setting some values in the script i.e. incomming = "somejunk";
I assume the PHP include file connects to your DB and changes into the corresponding DB?
I assume you have setup a user for the DB in say cPanel and set privileges
Your method of sending data is different to my working format...
You are sending the data at the end rather than the beginning...
Also if you look at your server log you can see if the values get sent
if (client.connect(server, httpPort)) {
  // connected to resource
  // send data
  client.print("POST /dir/file.php?field1=");
  client.print(data1&field2=data2); // must be url encoded
  client.println(" HTTP/1.1");
  client.println("Host: www.domainname.com");
  // client.println("Content-Length: " + String(data.length())); // you dont need
  client.println("User-Agent: ESP8266");
  client.println("Connection: close");
  client.println();

what is this? POST with url parameters. do you know what is "Content-Type: application/x-www-form-urlencoded"?

You are using POST method in the php script ($_POST['var']) and trying to pass parameters to the script by adding them in the URL. This addition of the parameters would work only if it were a GET method in place of a POST method.
Change wherever you have written POST to GET (Both in the php script and the node mcu code) and your data will be inserted into the database.
1) Change both the $_POST['var'] to $_GET['var'] in the php file.
2) Change client.println("POST /tag.php HTTP/1.1") to client.println("GET /tag.php?incoming=fromDuino&incoming2=fromDuino2 HTTP/1.1")
Also, you can go through this link to learn more about how to make a
POST request. And can you show me the whole code or the classes that you have instantiated?

what do I do if I want to use POST though? I know GET can also work that way but I need the sending of data to be more discrete, and POST method seems to be more discrete than GET

Can you please post your whole code (Including the libraries and all the declarations)? I might help you with POST method then :D

@Manav, the POST request is of type form-urlencoded. and the parameters are in body as it should be


text:
Send file from ESP to server via FTP
I've a code which records sound to SD, then starts an FTP connection for a limited time. I want to make an automatic system which records then sends the sound file continuously. Now I'm recording sound for 3s, then opening a FTP connection for 3s. In that 3s interval, my python code (PC) is trying to download the data in ESP (it also runs continuously. However, sometimes if ftp time is not enough, my connection is interrupting and ESP is resetting itself. So, I dont want to fetch this file via my computer, ESP32 should send this file after the recording, then it should start recording after the successful connection. I couldn't configured the code in the Arduino Playground
I pasted my code below, waiting for suggestions for valid examples.
You can find the libraries here
#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32FtpServer.h"
#include <FS.h>
#include <SD.h>
#include "Wav.h"
#include "I2S.h"

const int record_time = 3;  // second
const char filename[] = "/sound.wav";
const int headerSize = 44;
const int waveDataSize = record_time * 88000;
const int numCommunicationData = 8000;
const int numPartWavData = numCommunicationData / 4;
byte header[headerSize];
char communicationData[numCommunicationData];
char partWavData[numPartWavData];
unsigned long starttime;
unsigned long endtime;
File file;

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

FtpServer ftpSrv;   //set #define FTP_DEBUG in ESP32FtpServer.h to see ftp verbose on serial

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

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

  /////FTP Setup, ensure SD is started before ftp;  /////////
  if (SD.begin()) {
    Serial.println("SD opened");
    ftpSrv.begin("esp32", "esp32");   //username, password for ftp.  set ports in ESP32FtpServer.h  (default 21, 50009 for PASV)
  }
  CreateWavHeader(header, waveDataSize);

}

void loop(void) {

  SD.remove(filename);
  file = SD.open(filename, FILE_WRITE);
  if (!file) return;
  Serial.println("recording");
  file.write(header, headerSize);
  I2S_Init(I2S_MODE_RX, I2S_BITS_PER_SAMPLE_32BIT);
  for (int j = 0; j < waveDataSize / numPartWavData; ++j) {
    I2S_Read(communicationData, numCommunicationData);
    for (int i = 0; i < numCommunicationData / 8; ++i) {
      partWavData[2 * i] = communicationData[8 * i + 2];
      partWavData[2 * i + 1] = communicationData[8 * i + 3];
    }
    file.write((const byte*)partWavData, numPartWavData);
  }
  file.close();

  Serial.println("recording finished, ftp starting");

  starttime = millis();
  endtime = starttime;
  while ((endtime - starttime) <= 3000) // do this loop for up to 1000mS
  {
    ftpSrv.handleFTP();        //make sure in loop you call handleFTP()!!
    endtime = millis();
  }
  Serial.println("ftp finished");

}

Your code does not compile. Please edit your question and ensure all of the relevant includes are in the sketch.

@VE7JRO edited the question

you need to wait on the FTP to finish before moving on

@dandavis ftp transfer is handling by pc and its time changes in every connection, if connection is slow, it could take 15s or more, however esp opens tunnel without knowing this time. how can I adjust it? best option is sending file from esp with a code

What protocols are available to you on the server? Only FTP? is there HTTP for example? any others? Seems FTP isn't suited to the solution

@JaromandaX HTTP is also ok, but I always worked on FTP. How FTP is not suitable for file transfer anyway? In the code ftpSrv.handleFTP();  line starts FTP. However, it should not only start FTP, it should also transfer the file itself in the loop, then everything will be okay. Arduino Playground example is capable to do it I guess, but I couldn't configure it for ESP.

I said it SEEMS it isn't, according to your question


text:
Programming Other Atmel chips using Arduino
Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

This is either unclear, or too broad.  Of course many things are possible, if someone builds the electrical interface and writes the program.  To have an answerable question you would have to ask about something specific: which target, and if you mean you want to load some random hex/binary/elf file, or if you mean you want to build an Arduino sketch using a port of the Arduino core to that target, and then load it using a classic ATmega Arduino as the programmer.

Build an sketch using port of Arduino core to that target and then use Arduino nano as an ISP.

What 3rd party Atmel products do you have in mind in particular? If you don't provide a list, then your question is already too broad. By the way, what is a "third-party Atmel" product, if it's Atmel, then it's not 3rd party, if it's 3rd party then it's not Atmel...

Please go the new link !

Is it possible to burn Arduino code on any other third party Atmel products using an another Arduino ? And if its possible then how ?

Do you mean if the "Arduino as ISP" sketch and an Arduino would work to flash another Atmel AVR MCU? If so the answer is yes but I guess that you also want to generate code for the new MCU. In that case there is some work to be done before that is possible.
Start by reading about how to install additional cores and the guideline for a custom core. Then select an custom core to study. Here you will find the files you need to provide to support a new AVR based MCU.
Cheers!

There is some potential for confusion here. The ArduinoISP programmer is a dedicated programmer sold by Arduino, which is used by selecting Tools > Programmer > ArduinoISP. "Arduino as ISP" is the name of the programmer made by uploading the File > Examples > 11.ArduinoISP sketch to an Arduino and is selected via Tools > Programmer > Arduino as ISP. The two programmers are not interchangeable but it's easy to mistake one for the other because of the confusing sketch name.

Let me correct that to avoid any confusion.

Yup You kind off using Arduino ISP to program any other Atmel chip .Can you explain it point to point ? Mikael

No problems, I can google that for you; https://www.arduino.cc/en/Tutorial/ArduinoISP

But if I want to program any other Microcontroller other than Atmega328 or Atmega168 Then ?

This is what happens when you ask a non-specific question and accept a response that doesn't answer what you wanted to know.  Ask better questions and you might get better answers.

Please go to this : http://arduino.stackexchange.com/questions/36238/programming-other-atmel-chipsexcluding-atmega-328-and-168 Sorry for the inconvenience faced ! Sorry !


text:
What should I use for IOT Things?
I am very much interested in using the Blynk. Well I like it because of its feature. I want to control or read my sensors or something like that remotely. So Blynk says you need something like esp8266 or BLE stuff or something similar. I came across NodeMCU and Ethernet shield. I want to buy something that is efficient for reading my sensors. Is there anything similar that is similar to NodeMCU and is Arduino IDE compatible.

NodeMCU can be programmed from the Arduino IDE. You just need to instal the board files.

Is there any thing similar to that ?

Why would you want anything else? It seems that you want something, but have no idea what? The NodeMCU is a good choice for general IO over wifi.

You know I wanted to know what are the other choices

the d1mini is like the nodemcu only smaller and no extra power pins. esp32s are under $10 now/

D1 is not compatible with Blynk

I am assuming Esp8266/NodeMCU does not have enough IO for your application? (It combines Wifi with Arduino for little cost and is compatible with the Arduino IDE development tool)
Aruino have a different solution called the Arduino Yun. The problem with the Yun might be that it doesn't have very much memory and is based on the Atmel 328 processor (which has some IO but maybe not enough for you).
An alternative I have heard good reports about is the Dragino Yun Shield. That is a shield that provides powerful networking, sits on any Arduino board and works the same as an Arduino Yun. Therefore a Yun Shield sitting on an Arduino Mega2560 would give a lot of memory and a good supply of IO.

But the price tag is quite high

Yep that's why I said the NodeMCU is cheap. The Yun has a preconfigured linux/linnino server so in theory its networking is much more powerful than the Esp8266


text:
Building Custom Bootloaders
Recently I was checking out the Atmel's AVR series and I found the Atmega328PB. I am really familiar with Arduino's environment. So I thought if somehow we could bootloader it with Arduino bootloader. My doubt is how can I make a Arduino bootloader for it.

From what I remember the 328PB is not that different from the 328P. I wouldn't be surprised is the default uno bootloader would work without modification.

Here are a couple sources of ATmega328PB bootloaders based on optiboot:

https://github.com/watterott/ATmega328PB-Testing
https://github.com/ElektorLabs/Arduino

I haven't used either.
If you are set on making your own at least they can provide you with a reference.

Is it fully compatible with Arduino

Both projects are specifically written for use with the Arduino IDE, though the bootloaders could be used for any purpose you like.

authors: Роман Демчук


text:
Auto Reset during programming Arduino
I know this that when you try to program a pro mini without a DTR pin it will give you a error as the atmega needs to be reset during programming. So I had a doubt why does the microcontroller needs to be reset and clearly at which time you know at which moment does it reset ?

A Reset is necessary to activate the Bootloader and allow programming. Without the DTR signal the Reset button has to be pressed just before starting the upload from the Arduino IDE.

Is there any serial traffic before upload or is there anything like that the compiler sends any notification to the device.

The compiler does not know about the upload. It is avrdude that does the upload. The reset is generated by pulling the DTR signal. Please see http://playground.arduino.cc/Learning/AutoResetRetrofit for more information about the auto-reset feature.

If the software is somehow unable to send the reset signal then how could I create reset signal without manually pressing the reset button.

What FTDI (USB-Serial bridge) are you using? Does it lack a DTR pin?

Actually I don't really have a DTR pin I have only TX RX and GND pin.

Is there any timeout for the bootloader to take a decision whether to go for programming or to load sketch ??? If yes then how much ?????

Yes, there is a timeout in the bootloader. After reset the bootloader will wait for a short period (second, see bootloader code) for a command. If no command is received and timeout the current sketch is called. Here is a bootloader hack tutorial https://learn.adafruit.com/arduino-tips-tricks-and-techniques/bootloader.

authors: Алексей Попов


text:
Arduino sketch for NodeMCU v1.0 (ESP8266-12E) has no error of compiling but does not run on NodeMCU v1.0 (ESP8266-12E) Board
i compiled a Arduino Sketch for NodeMCU v1.0 (ESP8266-12E) which have no error while i test with verifiy button in Arduino IDE 1.8.6 but i don't know what is the problem when i upload and test it . it [ NodeMCU v1.0 (ESP8266-12E) ] is not showing an static IP address while there is turned ON WiFi hotspot from my android phone.
I'm sharing two codes (code 1, code 2) here. Code 2 connect to the WiFi Hotspot but i make changes in code 2 to make code 1 for desired output which is not working.
Need help for making proper code.
code 1
#include <ESP8266WiFi.h>

int pin1 = 2; // GPIO 14 (D5)
int pin2 = 3; // GPIO 5 (D1)
int pin3 = 6; // GPIO 5 (D2)

  const char* ssid = "wifi";
   const char* password = "12345678";

  WiFiServer server(80);

void setup()
{

  Serial.begin(115200);
  delay(10);

  pinMode(2, OUTPUT);
  pinMode(3, OUTPUT);
  pinMode(6, OUTPUT);

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

// Start the server
  server.begin();
  Serial.println("Server started");

// Print the IP address
  Serial.print("Use this URL to connect: ");
  Serial.print("http://");
  Serial.print(WiFi.localIP());
  Serial.println("/");

}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
  return;
}

// Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
  delay(1);
}

// Read the first line of the request
  String request = client.readStringUntil('\r');
  Serial.println(request);
  client.flush();
// Match the request
  int value = LOW;
  if (request.indexOf("/pin1=ON") != -1) {
  digitalWrite(2, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin1=OFF") != -1) {
  digitalWrite(2, LOW);
  value = LOW;

}

  if (request.indexOf("/pin2=ON") != -1) {
  digitalWrite(3, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin2=OFF") != -1) {
  digitalWrite(3, LOW);
  value = LOW;

}

  if (request.indexOf("/pin3=ON") != -1) {
  digitalWrite(6, HIGH);
  value = HIGH;

}
  if (request.indexOf("/pin3=OFF") != -1) {
  digitalWrite(6, LOW);
  value = LOW;

}

// Set ledPin according to the request
//digitalWrite(ledPin, value);
// Return the response
// Return the response
  client.println("HTTP/1.1 200 OK");
  client.println("Content-Type: text/html");
  client.println(""); //  do not forget this one
  client.println("<!DOCTYPE HTML>");
  client.println("");
  client.println("");
  client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
  client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
  client.println("");
  client.println("");
  client.println("

");
  client.println("
Wifi Based Project
");
  client.println("");
  client.println("

");
  client.println("");
  client.println("<button>Data </button>
");
  client.println("");
  client.println("

");
  client.println("");
  client.println("Load 1");
  client.println("<button>Turn On </button>");
  client.println("<button>Turn Off </button>
");
  client.println("");
  client.println("

");
  client.println("");
  client.println("Load 2");
  client.println("<button>Turn On </button>");
  client.println("<button>Turn Off </button>
");
  client.println("");
  client.println("

");
  client.println("");
  client.println("Load 3");
  client.println("<button>Turn On </button>");
  client.println("<button>Turn Off </button>
");
  client.println("");
  client.println("

");
  client.println("");
  client.println("

");
  client.println("");
  client.println("
");
  client.println("

");
  client.println("
");

  if(digitalRead(pin1)){client.print("Load 1 is ON	");}
  else{client.print("Load 1 is OFF	");}

  if(digitalRead(pin2)){client.print("Load 2 is ON	");}
  else{client.print("Load 2 is OFF	");}

  if(digitalRead(pin3)){client.print("Load 3 is ON	");}
  else{client.print("Load 3 is OFF	");}

  client.println("
");
  client.println("
");
  client.println("");
  client.println("");
  delay(1);
  Serial.println("Client disonnected");
  Serial.println("");

}

if you will upload this code in your NodeMCU v1.0 (ESP8266-12E) , this will connect with your Android phone. You can consider it, code 2 and above code 1.
code 2
#include <ESP8266WiFi.h>

int pin1 = 14; // GPIO 14 (D5)
int pin2 = 5; // GPIO 5 (D1)
int pin3 = 4; // GPIO 5 (D2)

const char* ssid = "wifi";
const char* password = "12345678";

WiFiServer server(80);

void setup()
{

Serial.begin(115200);
delay(10);

pinMode(pin1, OUTPUT);
pinMode(pin2, OUTPUT);
pinMode(pin3, OUTPUT);

// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

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

// Start the server
server.begin();
Serial.println("Server started");

// Print the IP address
Serial.print("Use this URL to connect: ");
Serial.print("http://");
Serial.print(WiFi.localIP());
Serial.println("/");

}

void loop() {
// Check if a client has connected
WiFiClient client = server.available();
if (!client) {
return;
}

// Wait until the client sends some data
Serial.println("new client");
while(!client.available()){
delay(1);
}

// Read the first line of the request
String request = client.readStringUntil('\r');
Serial.println(request);
client.flush();

if (request.indexOf("/l1on") > 0)  {
digitalWrite(pin1, HIGH);

}
if (request.indexOf("/l1off") >0)  {
digitalWrite(pin1, LOW);

}

if (request.indexOf("/l2on") > 0)  {
digitalWrite(pin2, HIGH);

}
if (request.indexOf("/l2off") >0)  {
digitalWrite(pin2, LOW);

}
if (request.indexOf("/l3on") >0)  {
digitalWrite(pin3, HIGH);

}
if (request.indexOf("/l3off") > 0)  {
digitalWrite(pin3, LOW);

}

// Set ledPin according to the request
//digitalWrite(ledPin, value);

// Return the response
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println(""); //  do not forget this one
client.println("<!DOCTYPE HTML>");
client.println("");
client.println("");
client.println("<meta name='apple-mobile-web-app-capable' content='yes' />");
client.println("<meta name='apple-mobile-web-app-status-bar-style' content='black-translucent' />");
client.println("");
client.println("");
client.println("

");
client.println("
Wifi Based Project
");
client.println("");
client.println("

");
client.println("");
client.println("<button>Data </button>
");
client.println("");
client.println("

");
client.println("");
client.println("Load 1");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button>
");
client.println("");
client.println("

");
client.println("");
client.println("Load 2");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button>
");
client.println("");
client.println("

");
client.println("");
client.println("Load 3");
client.println("<button>Turn On </button>");
client.println("<button>Turn Off </button>
");
client.println("");
client.println("

");
client.println("");
client.println("

");
client.println("");
client.println("
");
client.println("

");
client.println("
");

if(digitalRead(pin1)){client.print("Load 1 is ON	");}
else{client.print("Load 1 is OFF	");}

if(digitalRead(pin2)){client.print("Load 2 is ON	");}
else{client.print("Load 2 is OFF	");}

if(digitalRead(pin3)){client.print("Load 3 is ON	");}
else{client.print("Load 3 is OFF	");}

client.println("
");
client.println("
");
client.println("");
client.println("");
delay(1);
Serial.println("Client disonnected");
Serial.println("");

}

Also asked at: https://stackoverflow.com/q/52342641 and http://forum.arduino.cc/index.php?topic=568674 If you're going to do that then please be considerate enough to add links to the other places you cross posted. This will let us avoid wasting time due to duplicate effort and also help others who have the same questions and find your post to discover all the relevant information.

You can't use io 6. IO 6 is for internal use to connect the flash memory to esp8266. IO 6 has no Dx pin on the board. And io 3 is Serial RX connected to USB.
Use Dx constants and the corresponding 'D' labeled pins of the NodeMcu. (and remove conflicting comments)
const int pin1 = D2;
const int pin2 = D3;
const int pin3 = D6;

pin D3 is io 0 used to put the board into flashing mode. do not connect there something that pulls the pin LOW at reset or power-up

Actually, I am newbie in arduino and programming . i take this code in demo form, so i have no idea of conflicting comments. But i share both codes (Demo+modified) to understand for everyone to get desired code.

and did the answer help?


text:
May mulitple sensor connect to one arduino uno board since they shared same pin?
i am a Arduino beginner here. I start knowing about Arduino since my supervisor give me this project. In my project , i need to invent a car safety system to avoid animal hurting that hide under vehicle and solve drowsy driving problem. In sensor requirement, i choose to use PIR motion sensor (HC-SR501) to sense the movement of living things under the car, for the drowsy driving i choose to use pulse sensor and eye blink sensor to detect whether the driver is sleeping or not, it the driver is sleeping then it will activate alarm and led light on. But during research, i found that these 3 sensor have sharing the same pin with is the pin 2 (picture attach). So may is ask is possible to connect these all 3 sensor in one board ?? May i ask how can i do it if i connect the pins to the breadboard ??
Last question is do i need have MEMS MPU -6050 sensor in my project since i found this is with the eye blink sensor in other person research. Thank for accepting my question.

you can use pin 3 the same way as pin 2 for interrupt.  the display can use any other pin instead of pin 2

@Juraj Ok thanks.

Your drawing seems to show plenty of pins available, with only pin 2 in common. If the pin is being used for an Interrupt, then one device can use a different pin instead and the code adapted to use PCINT for the interrupt.
I would suggest the PIR does not even need an interrupt, it is slow changing and polling it for activity would be just as effective.
Add some current limit resistors to your LEDs so you don't damage the IO pins.

@ CrossRoads Ok Thanks a lot.

You did not provide a picture, or any other information.
Given how little info you provided, the answer is "it depends".
PIR sensors tend to use digital lines that change state when they detect motion. You would not want to share an input line with such a PIR. (I couldn't find a spec-sheet on your PIR with a quick search.)
For devices that use serial communication, the I2C interface standard is designed for connecting multiple devices on the same serial bus. If you have multiple I2C devices, you should connect them all to the same pins, and it works great as long as they have different device addresses on the I2C bus.
Other types of serial interfaces are only designed for 2 devices to communicate with each other, and cannot be shared.

pin 2 is interrupt pin

@ Duncan C thanks