text:
PWM Input Pins Never Receive a Value from Working Receiver?
I have a very simple sketch that's supposed to intercept the signal from an RC receiver and print the pulse duration from that channel.
Sketch
int PwmPin = 9;
unsigned long duration;

void setup() {
  pinMode(PwmPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  duration = pulseIn(PwmPin, HIGH);
  Serial.println(duration);
}

Output
0
0
0
...

My setup is the normal one that would occur without an Arduino, and only the battery is connected through the ESC to provide power to the receiver. The Arduino is connected via USB because I'm just trying to read values.

I have been trying to plug between the receiver's data pin to the Arduino's PWM pin and read the pulses from the rudder channel. (I have previously tested the channel with a servo and know that it works correctly). However, no signal (0) is being printed to the serial monitor. I have difficulty understanding why.
I checked the documentation for pulseIn(), and it seems simple enough. I tested PWM pins D3, D5, D10... none of them works. I don't understand where the problem is at this point. Update: I am now connecting from the receiver's negative pin to one of the Arduino's GNDs.
This is a simplistic scenario, so I don't see what's going wrong (my programming experience is good, but my experience with Arduino is near nil).
The goal of this experiment is to program lights to change according to throttle input, and asymmetric thrust through two motors for a boat. I know that pulseIn isn't the best function to use, but for the moment I just want to do some quick development before getting into the weeds.
Update:
I am attempting to follow this video, except that connecting the Arduino to the receiver didn't work, possibly because the ESC's BEC sends some sort of power signal that arms the receiver. (The receiver's LEDs usually make a visual signal, but they just turn on without a signal when connected through the Arduino).
According to the manual on page 6 and page 8, "receivers have an operational voltage range of 3.5 to 9 volts", with an ideal voltage being above 4.8V (because servos tend to brownout sooner). This should fall within Arduino range at 5V.

First: Never show code and serial output as an image. Copy and paste them as text into the question and format them as code. Second: You really need to connect the ground between Arduino and receiver. That is not optional. Are you sure, that there really is a signal on the receivers pin?

No ground connection?! https://majenko.co.uk/blog/importance-sharing-grounds

@chrisl Yes, I'm sure there's a signal; it's marked on the receiver as - + (signal), and I tested the pin, and it works fine with a servo. Even when I connect the ground it doesn't work with Arduino, however.

On what voltage does the receiver run? 5V as the Arduino?

@Majenko Because I'm a little confused. I'm only connected to the signal pin, not the positive pin, so both the positive pin and the signal pin of the receiver ground through the negative wire?

Everything needs a common ground in order to work.  You need a common point to reference voltages to.

You can't measure a voltage with only one connection. You have to connect the grounds.

BTW, there is no such thing as a "PWM Input Pin" - PWM is output only. You are just using the generic GPIO functionality of the pins, and as such you can use any pin.

your exact code works for me so i think th board is the problem.

What misled me is the pin numbers. I was referencing this diagram:

I thought that all the pins were numbered sequentially, so that pinMode(9, ...) would set D6 (09 in the diagram). However, this sets D9. Connecting to the correct pin works fine.

If you're still doing this without a ground connection then it may only appear to be working fine for now.  IT may simply stop working at any time it sees fit based on that voltage reference.

I read the article Majenko commented previously and understand that. IDK whether working on my unplugged laptop proves the concept. Since there are only two grounds, I'm already running out. I am running the receiver and an ESC from the Arduino, but still need to add another ESC, plus LEDs... @Delta_G


text:
Can two electronic speed controllers be connected to the same ground pin?
I have a setup to read two sets of signals from a radio control receiver using an Arduino NANO: the throttle channel and the rudder channel. With some programming knowledge (which I have) this isn't too difficult, but I need help on the electrical side of things. This is the current setup I have (it works, though I'm told there is the possibility that my computer is acting as a ground for the PWM signal wires from the receiver):

OK, great. I'm able to control the motor programmatically, mix values from the receiver, etc. See this video for what I'm doing. However, this setup leaves some gaps:
Question 1
I actually need two motors for dual thrust. Each motor is to be controlled individually by the program (for asymmetric thrust). Since there are only two grounds on the Arduino, can I plug both ESC grounds to the same pin? Currently, the receiver is getting power from the Arduino, and grounds back. The speed controller grounds to the second ground pin. Diagram below:

Question 2
All that is great, but the NANO is still powered by USB: obviously I'm not putting my laptop in the RC boat just to supply a few volts! Incidentally, both electronic speed controllers (ESCs) have battery eliminator circuits (BECs), usually used to power the receiver. Would I be able to connect one of them to the VIN pin of the Arduino?
I tried something like that, but the Arduino got very hot near the pin, and it smelled. Unfortunately, I don't have my circuit at the time. The Arduino's Amazon page states support for 5V to 12V external power supply. Each ESC can supply 5V at 3A. Maybe there's a way to plug them to make 10V?
Question 3
My idea also calls for three sets of LEDs, which will be lit also based on inputs from the receiver. Can these be grounded to the same wire, like I was suggesting above for the ESCs?

Ground is ground. Whether it's got 1 pin or 100 pins, they are all the same. You can connect as many thing to ground as you need to. Whether you connect them all to one pin or each to its own, ground is ground. Like the ground under your house is the same ground as the ground under your neighbour's house.

@Majenko that effectively sums up the answer. It did work, so great!

You can connect all the grounds together and the circuit will be safe. If the BEC outputs 5V, you can feed it directly to the Arduino's 5V pin. Any more volts and you'll need to feed the BEC output to the Arduino's VIN pin.

Can I safely connect both ESC 5V outputs to the same VIN pin?

While you probably could get away with it, I would not try - 1 BEC supply will be fine. Regardless, all grounds need to be connected.

However, I'm not only supplying current to the receiver, but also to some 6 or 7 other LEDs.

source: Stack Exchange

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

sort: votes


text:
Implementing sending from N and recieving from N with FreeRtos and RF24 radio module
I'm trying to make my first chip send data through a nrf24 radio pipe and the other listen to it. After the first data is received it should switch to transmit mode and itself transmit new data. The main goal of all of this is to implement the raft protocol with at least 3 chips participating. So the requirements would be to have each chip listening all the time and to have it stop listening at random intervals to send a broadcast message to all other chips. Basically the communication is never between just two chips but always one to many. I've come across tutorials such as http://forum.arduino.cc/index.php?topic=421081 but it always comes down to a stable Master vs Slaves state while my situation is more dynamic.
This is my current task. The listener works perfectly until the first received message when it opens a writing pipe. It then does not write and does not go back to listening.
void test_Task(void *pvParameters){

    printf("some init\n");
    bool hastoSend = false;

    radio.openReadingPipe(1, address);
    while(1){

        radio.startListening();
        if (radio.available()) {
            radio.read(&rx_data, sizeof(rx_data));

                if (rx_data[1] == 101){
                    printf("Received message: %d\n", rx_data[1]);
                    hastoSend = true;
                    printf("%d\n",rx_data[0]);
                    //int someint = *((int*)pvParameters);

                    // turn on led1
                    write_byte_pcf(led1);
                    vTaskDelay(pdMS_TO_TICKS(200));
                    write_byte_pcf(0xff);
                }

        }else{
                if (hastoSend){

                    printf("I need to send a message!\n");
                    printf("sending a message\n");
                    radio.openWritingPipe(address2);
                    radio.stopListening();
                    transmit_nrf24();
                    radio.printDetails();
                    hastoSend = false;
                    radio.openReadingPipe(1, address);

                }
        }

    }

}

This is my radio setup:
static inline void setup_nrf() {

    uart_set_baud(0, 115200);
    gpio_enable(SCL, GPIO_OUTPUT);
    gpio_enable(CS_NRF, GPIO_OUTPUT);

    // radio configuration
    radio.begin();
    radio.setChannel(channel);
    radio.setAutoAck(false);

}

For testing purposes the messages being transmitted come from my other device which is just a manual transmitter. What would solve my problem is a way to completely reset the radio when the first message is received so that the pipes do not bother each other and the device could then be re-initialised as a transmitter.
Cheers!

what is chip?

Solved it by simply repeating
gpio_enable(SCL, GPIO_OUTPUT);
gpio_enable(CS_NRF, GPIO_OUTPUT);

// radio configuration
radio.begin();
radio.setChannel(channel);
radio.setAutoAck(false);

before opening a new writing pipe.

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


text:
How do I feed NRF24L01 from Arduino Pro Mini?

I wanted to control speed of my four coreless DC motors using Arduino Nano. Then I realised my 3.7V 380mAh 25C and 720mAh (110mAh on picture is just to hold my battery's place) 25C LiPo batteries won't meet the voltage requirement of a Nano. Then I came up with the idea of using Pro Mini instead of Nano; however I couldn't find a 3.3V pin on Pro Mini to feed NRF24. On Nano, I was using a 3.3V pin and 10uF capacitors between Vin and Gnd legs of NRF24.
So my question is: can I feed NRF24 directly from Vcc pin? Or as an alternative what would happen if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via another TIP122 transistor?
Note: I am using 4 of TIP122 transistors whose gate legs are connected to Pro Mini's 5, 6, 9 and 10 pwm pins (I forgot to add base-resistors). Do you also think it is a reliable way of controlling the motors' speed?

can I feed NRF24 directly from Vcc pin?

NO: the pro mini is either 5V or not strong enough to power the RF24.
EDIT: the 3V3 pro mini "could" power the RF24 via VCC, if you use the cap and if it's not the PA&LNA model (or in full power mode). Best practise is to use an external regulator.

if I fed NRF24 directly from battery and reduce 3.7V to 3.3V via
  another TIP122 transistor?

NO: lipos are 4.2V when fully charged, and they can be used until 3V (I mean 3V sag voltage, when the load is powered, not when disconnected): External 3V3 regulators is the way to go.

Do you also think it is a reliable way of controlling the motors'
  speed?

These are PWM output, so yes, why not? Also, add flyback/freewheeling diodes (and -maybe- 100nF polyester caps should help) between the motors terminals.

Please consider that since the OP said "switch from nano to pro mini" he will be using the arduino board powered from a 3-4V source, rather than 5V. This means that connecting to the Vcc pin is ok, provided that the voltage is not greater than 3.6V (and as you explained LiPos go even higher than 4V). So if the pro mini is powered by a linerar/switching regulator to 3.3V, then Vcc can be used

@frarugi87: the pro mini only has 150mA MAX on VCC, as i said it's not a matter of voltage but current instead (assuming a 3V3 pro mini is used). The capacitor helps but stable performance can't be guaranteed with the VCC supply, especially with other devices connected to the pro mini. https://forum.mysensors.org/topic/3961/nrf24l01-pa-lna-power-consumption/23

your comment made me think that probably I misunderstood the OP intentions. For me, the best way to power the pro mini is to directly connect the Vcc to the battery input, bypassing the onboard regulator in the pro mini. But probably yes, the OP wanted to connect the battery to the RAW pin, and so the reply is "it depends". As long as a standard NRF24L01+ is used the current generated is ok, but if a high power board (NRF24L01+PA-LN) is used then the regulator is not enough

Connecting the Pro Mini straight to the power bus alongside motors can cause noise-related issues and sudden current draw due to motors being turned on can cause the MCU to reset. Some voltage stabilization is required, in addition to that, the nRF24L01+ is suspectible to noise, I can't imagine it working in such a setup without at least one mF of capacitance (half electrolytic and half ceramic to get rid of HF as well) attached to it.


text:
Java + JSSC + Arduino + Windows
I want to know the basics of Arduino serial communications and connection with a Java application in Windows.
Can anybody provide me with a sample Java program that upon running just makes an Arduino pin high as well as the corresponding Arduino sketch, and some explanation on how the Arduino communicates with the Java app?
I am now starting with Arduino, and I have some experience with Java
I found this code on the net - will this work?
Java code
package arduino;

import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException {

    SerialPort serialPort = new SerialPort("COM3");
    try {
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("o".getBytes()));
        Thread.sleep(1000);
        System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("f".getBytes()));
        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }
  }
}

Arduino
  void setup()   {
  Serial.begin(9600);
  pinMode(8, OUTPUT);
  digitalWrite(8,HIGH);
  delay(500);
  digitalWrite(8,LOW);
  }

  int incomingByte = 0;

  void loop()
  {
 // send data only when you receive data:
    if (Serial.available() > 0) {
           int text = Serial.read();
           Serial.println(text);
           if (text == 'o') {

            digitalWrite(8,HIGH);

           }

           if (text = 'f') {

            digitalWrite(8,LOW);

           }
     }

  }

One word: Firmata. Google it. Try it.

I managed to finish my project and here is the code
Useful information:
To prevent reset on serial port open and close
https://tushev.org/articles/arduino/22 /* Add a 10-100 μF capacitor between reset and GND
 JAVA

 /* FIRST IMPORT JSSC LIBRARY */

package arduino;

import java.util.Scanner;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Arduino {

public static void main(String[] args) throws InterruptedException,     SerialPortException {

    Scanner scan = new Scanner(System.in);
    int nummer = 0;
 SerialPort serialPort = new SerialPort("COM4");

        while (true) {
            menu();
             if (scan.hasNextInt()) {
            nummer = scan.nextInt();
        } else {
            System.out.println("verkeerde ingave");
        }
        switch (nummer) {
            case 0:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("a".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
            case 1:
                 serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);
         serialPort.writeBytes("b".getBytes());//Write data to port
         serialPort.writeBytes("c".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;

                 case 2:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("d".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
                 case 3:
                serialPort.openPort();//Open serial port
        Thread.sleep(1000);
        serialPort.setParams(SerialPort.BAUDRATE_9600,
                             SerialPort.DATABITS_8,
                             SerialPort.STOPBITS_1,
                             SerialPort.PARITY_NONE);//Set params. Also you can set params by this string: serialPort.setParams(9600, 8, 1, 0);

         serialPort.writeBytes("e".getBytes());//Write data to port
           serialPort.closePort();//Close serial port
                break;
        }

}
}

public static void menu() {
    final String ANSI_CLS = "\u001b[2J";
    final String ANSI_HOME = "\u001b[H";
    System.out.print(ANSI_CLS + ANSI_HOME);
    System.out.flush();
    System.out.println("");
    System.out.println("    ************************************************************************************");
    System.out.println("    *      ***       ********   *******   **    **  *****  **      **      ******      *");
    System.out.println("    *     ** **      **    **   **    **  **    **   ***   ****    **    ***    ***    *");
    System.out.println("    *    **   **     *** ****   **     ** **    **   ***   ** **   **  **          **  *");
    System.out.println("    *   *********    **   **    **     ** **    **   ***   **  **  **  **          **  *");
    System.out.println("    *  **       **   **    **   **    **  **    **   ***   **   ** **    ***    ***    *");
    System.out.println("    * **         **  **     **  *******     ****    *****  **    ****      ******      *");
    System.out.println("    ************************************************************************************");
    System.out.println("");
    System.out.println("    By Emmanouil Perselis");
    System.out.println("");
    System.out.println("What would you like to do?");
    System.out.println("0.---");
    System.out.println("1.Toggle lights");
    System.out.println("2.Toggle air");
    System.out.println("3.---");
    System.out.println("4.---");

}
 }

ARDUINO SCETCH
 int led = 13;
 int led1 = 2;
 int led2 = 4;
 int led3 = 7;
 int led4 = 8;
 void setup() {
   Serial.begin(9600);
   pinMode(led, OUTPUT);
   pinMode(led1, OUTPUT);
    pinMode(led2, OUTPUT);
    pinMode(led3, OUTPUT);
    pinMode(led4, OUTPUT);
 }

 void loop() {
   char i= Serial.read();

   if(i=='a'){////////////////
     if(digitalRead(led)){////////////
   digitalWrite(led, LOW);  ////////////
  }else if(!digitalRead(led))//////////
   digitalWrite(led, HIGH);  //////////
 }

  if(i=='b'){////////////////
     if(digitalRead(led1)){////////////
   digitalWrite(led1, LOW);  ////////////
  }else if(!digitalRead(led1))//////////
   digitalWrite(led1, HIGH);  //////////
 }

 if(i=='c'){////////////////
     if(digitalRead(led2)){////////////
   digitalWrite(led2, LOW);  ////////////
  }else if(!digitalRead(led2))//////////
   digitalWrite(led2, HIGH);  //////////
 }

 if(i=='d'){////////////////
if(digitalRead(led3)){////////////
   digitalWrite(led3, LOW);  ////////////
  }else if(!digitalRead(led3))//////////
   digitalWrite(led3, HIGH);  //////////
 }

 if(i=='e'){////////////////
if(digitalRead(led4)){////////////
   digitalWrite(led4, LOW);  ////////////
  }else if(!digitalRead(led4))//////////
   digitalWrite(led4, HIGH);  //////////
 }
}

I had this problem with communication with Arduino Uno (I think that the Arduino Uno, and other boards, with this type of scheme, suffer this problem).
The DTR line on Arduino Uno is connected with RESET, including when you use the Arduino IDE Serial Monitor port, such that the parameter of DTR is false. Yeah, you can fix this with capacitor or catch place RESET EN on board. But when you set setting you can just write:
comport3.setParams(9600, 8, 1, SerialPort.PARITY_NONE, false, false);

The last parameter is DTR and its default is true, the second to last parameter is RTS (it defaults to true too). I set both of these parameters to false and my board reads commands from the computer without resetting.
I write this for other people who had this problem.

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


text:
Is there any easy way to change Arduino Wifi shield to ESP8266?
As the title says, is there any easy way to replace WiFi shield with ESP8266, with as little as possible modification to code?
Here is my ESP:

for the esp-01 in link, use Serial connection and AT firmware with WiFiEsp library. it is the most common option and Internet is full of tutorials

next time your question gets put on hold, please edit the question .... do not post another question

The old question was about rtpmidi, this is more general I think

Consider porting your sketch to esp8266 board like Wemos D1. The API of the ESP8266WiFi library is same as the API of the WiFi library.
To use esp8266 as network adapter, you have two wiring options.
If you have or buy an esp8266 module with SPI pins, you can connect the esp8266 over SPI like the WiFi shield is connected. Then you upload the WiFiSpiESP firmware to esp8266 and you include in your sketch WiFiSpi library instead of WiFi library.
Second option is to connect esp8266 over Serial or SoftwareSerial. The esp8266 should have AT firmware installed. The you can include WiFiEsp library in you sketch and initialize it with the Serial interface of your choice. You can find the WiFiEsp library in Library manager. Most new esp8266 modules have AT firmware installed at default.
There is one more option for Serial connection, if WiFiEsp wouldn't work for you. WiFiLink firmware and library
All mentioned libraries WiFiSpi, WiFiEsp and WiFiLink have the same API as the WiFi library so the rest of the code should work without changes.

I have wemos d1 uno around, should not be hard to port over. But my thesis already included mega and esp8266... So i tried to avoid them.

Anyway, will buying this solve my problem? Afaik it is mega with esp8266 as wifi inside. https://robotdyn.com/mega-wifi-r3-atmega2560-esp8266-flash-32mb-usb-ttl-ch340g-micro-usb.html

for Robotdyn Mega + WiFi the Serial option with WiFiEsp library. use dip switch setting for esp8266 on Serial 3 of Mega.

Thanks! I gonna buy robotdyn one soon. Seems easy enough.

after a while : buying robotdyn mega was one of the worst mistake I've ever made.

@RinaldoJonathan, why? the esp8266 with Mega is good. I write a new WiFiEspAT library and most of the time I work with Mega with esp8266 on Serial3. I have AT firmware in esp8266

getting esp-01 + mega counterfeit/clone in separate are far cheaper. Mine never successfully connect to wifi and the dip switch somehow very buggy (sometimes it randomly disconnects)

@RinaldoJonathan, then sorry. I don't have this board but I have other Robotdyn boards and some modules and the manufacturing quality is good with them


text:
Arduino Uno programed from a Nvidia Jetson tx2
I'm trying to program my Arduino Uno with a Jetson tx2 and get the error
avrdude: Send: 0 [30]   [20]
avrdude: ser_recv(): programmer is not responding
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00

The serial port is set to /dev/ttyS0
dmesg when the Arduino is plugged in returns
[78222.855639] usb 1-1: USB disconnect, device number 60
[78224.468387] usb 1-1: new full-speed USB device number 61 using xhci-tegra
[78224.605794] usb 1-1: feature bit otg_vbus_off set
[78224.610575] usb 1-1: New USB device found, idVendor=2341, idProduct=0043
[78224.617365] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[78224.624750] usb 1-1: Manufacturer: Arduino (www.arduino.cc)
[78224.630502] usb 1-1: SerialNumber: 55739323237351306122
[78224.636529] usb 1-1: ep 0x82 - rounding interval to 1024 microframes, ep desc says 2040 microframes
[78224.646057] xhci-tegra 3530000.xhci: tegra_xhci_mbox_work mailbox command 6

lsusb returns
Bus 002 Device 001: ID 1d6b:0003 Linux Foundation 3.0 root hub
Bus 001 Device 054: ID 413c:2107 Dell Computer Corp.
Bus 001 Device 065: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)
Bus 001 Device 001: ID 1d6b:0002 Linux Foundation 2.0 root hub

Did you notice that the log doesn't mention a device file?

I did not what does that mean I have to do

The version of the Arduino IDE contained in the Jetson repositories is buggy on the Jetson TX2 with Jetpack 3.2+ and the Arduino IDE in the repository is rather old.  Instead, try the beta related to Github Issue #7302.  This beta should work with the Jetson and other aarch64 platforms.  Many thanks to the wonderful people working to support this platform.
Steps
After downloading and unpackaging the build, perform the following steps:
#Install the OpenJDK Dependencies
sudo apt-get install openjdk-8-jre openjdk-8-jdk

#Remove the Packaged Java Folder
cd ${PATH}/arduino-PR-beta1.9-BUILD-69
sudo rm -r java

#Add armhf Architecture to Package Manager
sudo dpkg --add-architecture armhf
sudo apt-get update
sudo apt-get install libc6:armhf libstdc++6:armhf

#Install the Arduino IDE
sudo ./install.sh
sudo ./arduino-linux-setup.sh

#Reboot

Notes

The script arduino-linux-setup.sh handles the permissions for the IDE to talk to ttyACM0, updates the udev rules, and removes the pesky Modem Manger.
The armhf packages are necessay to prevent ctags from crashing.
If you are still having issues with CDC/ACM, install the module using the scripts from JetsonHacks

When you built your Jenson kernel, did you enable the CDC/ACM driver using menuconfig?
From Arduino Playground:

If you configured your own kernel, the driver is either under "Device
  Drivers => USB Support => USB Serial Converter Support => USB FTDI
  Single Port Serial Driver" or "Device Drivers => USB Support => USB
  Modem (CDC ACM) support". Select [Y], to have it "built in" to the
  kernel or [M] to have it built as a module.

I'm not familiar with Arduino and whether it would show up as /dev/ttyUSB0 or /dev/ttyACM0 per @Majenko.

The device should be /dev/ttyACM0, not /dev/ttyS0.
Since it doesn't provide you with that device it rather looks like it doesn't have the CDC/ACM device drivers installed or loaded.
Depending on what distribution of Linux you're running on there you may need to install additional packages (you certainly do for OpenWRT, but I have no clue what that device is you're using or what it's running).

Jetson's run Ubuntu. I have found posts saying it should show up as /dev/ttyUSB0, but I don't know how to have it do so.

Maybe ask on a site where someone knows what one of these Jetson things is. CDC/ACM, which is what the Arudino uses, will be /dev/ttyACM0. It's only /dev/ttyUSB0 for FT232 or other similar custom UART interfaces (CH340G, etc).

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


text:
Can increasing the size of the software RX buffer cause problem in Arduino Uno
If I were to increase the of the buffer array from 64 to say 512 will this bring any long term problem in the Arduino Uno.
Changing from this:
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 64 // RX buffer size
#endif

to this:
#ifndef _SS_MAX_RX_BUFF
#define _SS_MAX_RX_BUFF 512 // RX buffer size
#endif

This is the header file of the software serial.

The buffer is in the UNO's limited (2K) RAM; you'd be using 1/4 of it for the input buffer. If your app is small enough and simple enough (limited call depth, specifcally), there may still be enough RAM for your app to run successfully. If you have lots of globals (remember to include libraries when you're considering RAM use), allocate much memory from the heap (with new or malloc()) or have a complex call structure such that funcA() calls funcB() calls funcC() calls ... (etc) so that many functions' stack-frames remain allocated at once - at any point in your program - your program could suffer a stack-collision: the call-stack descends low enough that it can overwrite, or get over-written by, your heap or global data.
Why do you want so large an input buffer? Will data be coming in a high rate or in large bursts, while processing of the data will be infrequent or occur at irregular times? Given the limited RAM in the UNO, running complex programs on one can require something of a balancing act in how you use resources.
Update:

i was performing some AT commands with software serial and buffer limitation generated junk value

Other reasons why SoftwareSerial might return bad data are:

Using too high a baud rate (9600 baud seems to be about the max);
Code that turns the interrupts off too often or for too long;
Other devices creating too many interupts (perhaps a built-in timer running at a high rate).

The replies to most devices' AT commands that I know of are short enough to not require a huge receive buffer. Asking for list of WiFi SSIDs from an ESP8266 could generate a large reply but most responses should not overflow a more modest buffer.

Thanks for the advice the thing is that i was performing some AT commands with software serial and buffer limitation generated junk value  but i think by just editing my code a little a bit i was able to fix this problem but i still a little bit more buffer memory

Most arduino modules have 2k ram. So think about that. Whether you need more buffer or more working space. Keep in mind that other libraries are also using the same ram.

I am  sending some character over software serial and 64 byte limitation is generating junk values i therefore increased the default to four times for more space to store my buffer

@Nolawisolomon maybe you can send the length of the message first, and then send the rest like in http. Thus receiver knows how many bytes it needs to reserve.

@Nolawisolomon - the RX buffer has little to do with transmission, unless you mean that you are transmitting in a blocking fashion and not paying any attention to received data until your lengthy transmission is done.


text:
Atmega328p - PCB ISP pins for bootloader and sketch upload
I want to design my PCB with Atmega328p chip on it and I want to be able to burn Bootloader and sketch after that while everything is soldered on the PCB. So my question is, what would be the best way to do that? My current idea is to leave extra pins for burning a Bootloader, and to leave also extra pins for uploading the sketch, and to "unplug" other stuff connected on these pins (for example on hardware UART) by adding\removing jumpers.
I'm pretty new to all this stuff, so I'm not quite sure what's the best approach.

If you're leaving pins (SPI pins, by the way) for uploading the bootloader, why bother with the bootloader at all - just program direct using those ISP pins.

I'm pretty new to arduino programming, I thought that I must have bootloader uploaded first and then to upload my sketch. I didn't know that I can upload sketch directly without bootloader...can I?

Yes, you can. The bootloader is purely for convenience so you don't need a hardware programmer. Since you already have the hardware programmer you don't need the convenience of the bootloader.

By hardware programmer, do you mean another arduino which I can connect to my board like when I'm burning an bootloader, or it can be done even just with FTDI cable?

Another Arduino, yes, or something more convenient like a USBASP ($2 on eBay from China), but not an FTDI cable, no.

Ok, that is excellent news! You just saved me some extra time and space for design traces on PCB :) One more think then, when I'm using that hardware programmer, do I need to change something in my sketch, or I'm still using it as it is, the code I mean?

The code is the same. Just select a different programmer in the IDE.

One further advantage: you don't get the 2 second delay at startup while pin 13 (LED) blinks as the bootloader times out. Your sketch starts instantly and you don't get strange things happening on pin 13.

And based on this http://www.learningaboutelectronics.com/Articles/Program-AVR-chip-using-a-USBASP-with-10-pin-cable.php I basically just need to leave 6 pins, that 4th pin says NC I guess as Not Connected, and there's few for GND which can be just one I guess. @Mayenko feel free to answer and I will accept it as a valid answer. You helped a lot to me today to understand few new things, thanks.

The ISP header is RESET, MOSI, MISO, SCK, GND and +5V.

That USBASP from what I see in description (ebay\aliexpress) looks like it's not for ATMEGA328P, it's for  ATMEGA8 ATMEGA128. Can I use if for ATMEGA328P as well?

Realistically, you should design ATmega boards to support both ISP and bootloader pins.  The logic is simple:

Unless you buy pre-programmed chips, or have a programming fixture, you will need ISP either to load the firmware itself, or to load a bootloader.
Even if you plan to use only ISP for programming, it is still worth providing external connections to the UART pins for interacting with firmware during development; generally with ATmega-based Arduinos you do not have a breakpoint debugger, so debug messages on serial are your primary visibility into what is happening.
You should wire the reset line to somewhere that you can manipulate it, so you don't have to power cycle your firmware every time you want to restart it in testing.

Once you have done all that, you end up with support for both ISP and UART bootloader - regardless if you plan to use them both or not.


text:
Using two software serial - two UART
I have ATMega328p chip, and I have HC-06 on pin A5, A4 (RX, TX) and I have another device on pin 10, 9 (RX,TX).
I want to be able to send some command on BT via Bluetooth Terminal and pass raw (exact) command to that device unchanged just to log on my computer (on my serial monitor) incoming command from BT and to log the response from device the same way on serial monitor and pass unmodified to HC-06.
How can I do that?
I tried by using "listen()" method but sometimes I get some weird character while I'm transferring\reading data, so not sure how to do this.
All baud rates are 9600.

You can only reliably use one SoftwareSerial port at once.

Not even with that "listen" function?

Even with listen(). You can't do anything at all whilst writing on a SoftwareSerial port. That includes listening on another SoftwareSerial port. So anything that arrives on the first port whilst you are writing earlier data out of the second port will become corrupted or not arrive at all.

Your question isn't clear at all. Who sends the commands? Who responds? What exactly do you want to achieve?

I want to log communication between HC-06 and another hardware via Arduino. Mobile phone send command to HC-06, HC-06 to Arduino, Arduino to third device, and vice versa. What isn't clear there?

If this suits you, you can 1) connect HC06 and other devices directly. 2) connect one of the two serial through a resistor to the arduino TX pin, and the other to the RX pin. The arduino should only forward what it receives to the same serial again. The resistor should prevent back-injection in the serial line. BUT the most smart way to deal with this is to use a board with more serial interfaces

You can have high-speed debugging by utilizing either I2C or SPI to send to a second Arduino. That second Arduino can be devoted to receiving debugging information and passing it on (via serial to your PC).
I describe the process here.
The general idea is to add some stuff to the DuT (device under test) to output via SPI/I2C.
Example code:
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>

// conditional debugging
#if DEBUG

  #define beginDebug()  do { SPI.begin (); SPI.setClockDivider(SPI_CLOCK_DIV8); } while (0)
  #define Trace(x)      SPIdebug.print   (x)
  #define Trace2(x,y)   SPIdebug.print   (x,y)
  #define Traceln(x)    SPIdebug.println (x)
  #define Traceln2(x,y) SPIdebug.println (x,y)
  #define TraceFunc()   do { SPIdebug.print (F("In function: ")); SPIdebug.println (__PRETTY_FUNCTION__); } while (0)

  class tSPIdebug : public Print
  {
  public:
    virtual size_t write (const byte c)
      {
      digitalWrite(SS, LOW);
      SPI.transfer (c);
      digitalWrite(SS, HIGH);
      return 1;
      }  // end of tSPIdebug::write
  }; // end of tSPIdebug

  // an instance of the SPIdebug object
  tSPIdebug SPIdebug;

#else
  #define beginDebug()  ((void) 0)
  #define Trace(x)      ((void) 0)
  #define Trace2(x,y)   ((void) 0)
  #define Traceln(x)    ((void) 0)
  #define Traceln2(x,y) ((void) 0)
  #define TraceFunc()   ((void) 0)
#endif // DEBUG

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

The other Arduino (which receives the debugging information) simply echoes it to Serial:
char buf [1000];
volatile int inpoint, outpoint;

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

  Serial.println ();
  Serial.println (F("Commencing debugging session ..."));
  Serial.println ();

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // now turn on interrupts
  SPCR |= bit (SPIE);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register
int next = inpoint + 1;  // next insert point

  // wrap-around at end of buffer
  if (next >= sizeof buf)
    next = 0;

  if (next == outpoint)  // caught up with removal point?
    return;  // give up

  // insert at insertion point
  buf [inpoint] = c;
  inpoint = next;  // advance to next

}  // end of interrupt routine SPI_STC_vect

void loop (void)
{
  // insertion and removal point the same, nothing there
  noInterrupts ();  // atomic test of a 16-bit variable
  if (outpoint == inpoint)
    {
    interrupts ();
    return;
    }
  interrupts ();

  // display anything found in the circular buffer
  Serial.print (buf [outpoint]);

  noInterrupts ();
  if (++outpoint >= sizeof buf)
    outpoint = 0;  // wrap around
  interrupts ();

}  // end of loop

SPI is quite fast, so the overhead of doing the debugging should be slight. The receiving end can batch up the debugging information (up to a point which is about 1000 characters) and then send it to your PC via Serial.

I made a library out of the relevant code. The library is available from:
http://gammon.com.au/Arduino/SPI_Debugging.zip
Example using the library:
// make true to debug, false to not
#define DEBUG true

#include <SPI.h>
#include <SPI_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name

}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

There is a similar library for I2C debugging:
http://gammon.com.au/Arduino/I2C_Debugging.zip
Example of doing I2C debugging:
// make true to debug, false to not
#define DEBUG true
const byte SLAVE_ADDRESS = 100;  // which address debugging goes to

#include <Wire.h>
#include <I2C_Debugging.h>

long counter;
unsigned long start;

void setup() {
  start = micros ();

  beginDebug ();
  Traceln (F("Commenced device-under-test debugging!"));
  TraceFunc ();  // show current function name
}  // end of setup

void foo ()
  {
  TraceFunc (); // show current function name
  }

void loop()
{

  counter++;
  if (counter == 100000)
  {
    Traceln (F("100000 reached."));
    Trace (F("took "));
    Traceln (micros () - start);
    counter = 0;
    foo ();
  }  // end of if

}  // end of loop

All of the examples illustrate using a #define to turn the debugging output on or off, so you can leave the debugging prints there in case things go wrong, but with debugging disabled they won't have any penalty.

How can I do that?

You can't.
It is impossible to use two SoftwareSerial ports together. Simply because while you are writing to one port everything else stops. Interrupts are disabled, and receiving requires interrupts. So anything that arrives while you are sending will either be lost or corrupted.
The only solution is to use a board with multiple hardware UARTs like the Mega or any of the more powerful alternatives to Arduino such as chipKIT or Teensy.

Would using that hardware UART instead of second software UART fix the problem? For example to use one software serial for that bluetooth, and hardware UART for that other device...

While not having it tested yet. That would be the solution I'd try. The hardware UART gives you all the functionality for free without interfering with other parts of your software.


text:
Minimal ATmega328p Ethernet Configuration
What would be minimal schematic for ATMega328P in order to have communication over ethernet? So I'm not asking about attaching existing shields to existing Arduino board, but just for bare minimum of ATMega328P and ethernet on one board, so basically like minimal version of Arduino Yun.

Start with the schematic of the Arduino-Ethernet and start removing things you don't need.

This is schematic of ethernet shield? I noticed that there's already ATMega328-20MU on it, so this is basically independent module?

It's the Arduino Ethernet. Its basically an Arduino Uno with Ethernet build in.


text:
Connecting arduino ground with battery powered remote control ground
I soldered a cable to the button of a remote control and I want to simulate that button press by setting the pin to input mode and back to output (LOW) again.
For this to work I connected the ground of the battery (black wire) to the GND of the arduino.
Is this 100% safe if I hook the arduino up to the power grid or to my pc?
I also disconnected the ground pins and had my arduino connected to my pc and suddenly it worked too. I got a BSoD shortly after.

What is the voltage of the power grid?

I think the battery has like 17,5 volts.

had my arduino connected to my pc and suddenly it worked too ... what worked?

what kind of a remote control? ... you have provided almost zero information in your post.

The remote has a battery and buttons and an antenna. My goal is to be able to simulate a button click with an arduino. I also was able to simulate the button press without the two grounds connected.

All grounds should be connected to provide a common reference point.

Unless you use galvanic isolation.

Unless you use galvanic isolation (see below) then yes, you must connect the grounds together. That is vital (see here).
The main concern though is the voltage you are switching.  The Arduino cannot connect any of its IO pins directly to any voltage over 5V. Doing so will most likely damage your Arduino.
Instead, you need to use the Arduino to switch a device that will switch the button for you.  The simplest is a BJT or MOSFET:

simulate this circuit – Schematic created using CircuitLab
But there are a couple of other caveats you should consider. The most important one is to do with how far away the remote device is, and how it is powered.  Connecting the grounds of two devices that are very distant can get quite messy, since "ground" at different points may be at completely different potentials, and the voltage drop across the "ground" wire (wires don't have zero resistance) coupled with the existing ground connection through the power supplies creates a ground loop and introduces massive amounts of interference.  For this kind of arrangement, it is good to introduce ...
Galvanic Isolation
This electrically separates the two circuits completely. There is absolutely no electrical connection between your Arduino and the device you are switching.
The most common way of achieving this in low powered digital circuits is to use an opto-isolator (also called an opto-coupler).  This is basically an LED and photo-transistor together in a single package. Turn the LED on and the phototransistor turns on.  The basic arrangement is exactly the same as the circuit above, but the wire going in from the Arduino is connected to an LED:

simulate this circuit
Now you really don't care what ground potential is at the other end, nor how it is powered. As long as the opto-isolator can cope with the voltage it has to switch all will be good.  Nothing in the remote circuit can do any damage at all to the Arduino since there is no way for current to flow back from that circuit to the Arduino.

But I should not be scared that connecting the grounds and powering the arduino by pc or by dc will in any way damage the battery or do something to the power cirquit in my house?

Just connecting grounds? No. That can't hurt anything.  Connecting 17V to the Arduino's GPIO pin will kill the Arduino, but nothing else.


text:
Using serial.available to return number of bytes
My code:
char data;
int numOfBytes;
void setup() {
    Serial.begin(9600);
}
void loop()
{
    if (Serial.available() > 0)
    {
        int numOfBytes = Serial.available();
        Serial.print("numOfBytes: ");
        Serial.println(numOfBytes);

        data=Serial.read();
        Serial.print("data: ");
        Serial.print(data);
        Serial.print("\n-----------\n");

        delay(500);
    }
}

I expected that this code returns 5 and then 4,3,2,1.
But it returned: 1,4,3,2,1
Why?

This is because at the first execution only one byte was received. The Serial interface does not send the data in one big packet of 5 bytes, only because you typed five bytes and started the transmission of all with one press in enter. It is sending the bytes one by one, in other words serial (hence the name). The exact transmission time is dependend on many factors (especially, when other technologies are involved, like the USB interface, when you are transmitting over the Arduinos USB to serial converter).
In this case the first byte is sent, followed by a short break, then the other bytes. The Arduino is fast enough in checking the Serial interface to sense this at 9600 baud.


text:
What is the output format of PINxn on atmega328p
I have written this simple code to run on my Arduino:
#ifndef F_CPU
#define F_CPU 16000000UL // 16 MHz clock speed
#endif

#include <avr/io.h>
#include <util/delay.h>

int main(void)
{
  Serial.begin(9600);
  DDRD = 0x00;
  PORTD = 0x80; //activate pull-up resistor on first pin on port D

  while (1)
  {
    Serial.print(PIND);
  }
  return 0;
}

I simply set my D port as an input and read the value in a loop. The output of PIND is 253. What is this number representing? is it in decimals? where can I see a list of these? How can I see a binary repression of the PIN output (8 bits of them). I don not want to use bit shifting.

FYI, I ran your code with my MEga2560 and I all get 11111111 constantly.
Maybe you should try another PORT block or even another Arduino.

I just tried PORTB and it's all 1's 111111, (side question, why is port B having only 6 bits?). So whats going on with PORTD here, broken board?

Serial.print(PIND, BIN); will write the value in PIND to the serial port in Base-2 representation.

so 253 is decimal then (11111101 in base 2). isn't it supposed to be 1000 0000 since only pin 1 is turned into input? what does this number mean

That depends on what you have connected to all the pins of PORTD. If only pin 7 has something connected, and the others do not have the pull-up enabled, they are floating and could be any value.

I just enabled the pull up on all PORD by PORTD = 0xFF; with nothing connected to them and it's still outputting 11111101

From the Atmega 323p datasheet: "Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn", which is probably not what you meant to do. To read the current state of register D, you need to read PORTD, or
Serial.print(PORTD);

in your example.
Update:

... what is PIND used for ...

PINx is called the Port x Input Pins Address and a note under it says "Writing to the pin register provides toggle functionality for IO" and refers us to the general pin-driver circuit schematic (Section 41.2 in my copy of the datasheet). That section tells us that "Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn." That is the only reference to this register I could find.
Note that the PORTx registers are bi-directional; the same register is used for reading or setting the states of the port's bits.

Also i'm not Writing a logic one to PINxn anywhere, i'm just reading
  it

The datasheet doesn't mention what is read from the port, at least nowhere that I found, despite that the PINx register is described as Read/Write, so your guess is as good as mine! ¯\_(ツ)_/¯
But to read a port's data, you need to read its PORTx register.
Update 2:

6 & 7map to the crystal pins and are not usable

They are usable. You can use them for I/O or for an external crystal, but not both. The "why?" is properly the domain of Atmel's engineers but I'll take a stab at it and say that many more functions could be put on the chip than there is space for physical pins on the package. Since pin count is at a premium, functions have to be doubled up on the same pins; you get to choose what you need. SPI, PWM, or I/O on DIP B2&3; Reset and I/O on C6; Timer-counter 1 input, I/O, & PWM on D5, for a few examples. Nearly every pin has several possible uses (power and grounds being the notable exceptions). For my uses, I dedicate the Crystal, Reset, and UART pins to those functions, but I could imagine systems that might need to reassign any of them.

then what is PIND used for in this case? what does 253 represent, why using PINB instead gives me the correct output of all being 1's and PORTD isn't.

Also i'm not Writing a logic one to PINxn anywhere, i'm just reading it

Quick question, why is Arduino port mapping to Atmel chip not a direct map. For example, on PORTB, 6 & 7map to the crystal pins and are not usable, why is that? what If I wanted to use them?

byte valueB = PINB; // reads the value of portB, D14-D19, into the variable valueB

If you then
Serial.print (valueB,BIN);

you will see the value of D19 to D14 in binary, or 0s & 1s. I don't think leading zero's are shown, so that can be a little confusing.
Serial.print (valueB);

will show the same value in decimal.
253 = 0b11111101   0b indicates base 2 (binary) format.  0x is used fof hexidecimal format (0x00 to 0xFF for 0 to 255).
If you are using the IDE and have not changed the fuses from the Uno/Nano board type, the IDE is expecting a crystal or resonator on PB7 & PB6, so reading them will return a nonsense result, so you might as well mask them off before printing.
valueB = valueB & 0b00111111;

If the other pins do not have their internal pullup resistors turned on, or external pullup or pulldown resistors are not used, the pins are 'floating' and their low input current means that any external charge can easily change their reading - so valueB = PINB; will have erratic results.
If a port has been set to outputs, then all pins can be written to at once:
PORTB = 0b0011111111;  // set D19 to D14 high for example

The Serial port is at pin 0 and 1.
PORTD is for pin 0,1,2,3,4,5,6,7. That's the problem, you mess with the pins of the Serial port.
Note: When a crystal/resonator/clock is used, those pins are disconnected from PORTB. That means you may use PORTB and read and write 8 bits to it, the crystal will keep on running.

So basically I shouldn't use PORTD for inputs to be safe?

Quick question, why is Arduino port mapping to Atmel chip not a direct map. For example, on PORTB, 16 & 7map to the crystal pins and are not usable`, why is that? what If I wanted to use them?

After calling Serial.begin don't change any of those two bits in the registers. You can use the other six bits. The functionality of each pin is fixed. When using a crystal, you can no longer use those same pins for something else, since they are connected to the crystal. I'm not sure if I understand your question.

question is, atmega328p has 8 bits in port B. but Arduino has 6 (2 port are reserved for something else), why is that?

Portb.6 and Portb.7 are pins for the crystal. When no crystal is used, they can be normal digital pins. The atmega chip can not assign a function to an other pin. The serial port, the crystal, the i2c bus, the analog inputs, everything is fixed to certain pins. A single pin can however act as a number of different things.


text:
GPS is working but Distance is always showing 0. Can't calculate Distance in this code
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WebServer.h>
static const int RXPin = 4, TXPin = 5;
static const uint32_t GPSBaud = 9600;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);
float temp1, temp2;

const char* ssid = "LYN TECH";
const char* password = "pass word";
const char* host = "your host name";
const int trigPin = 2; //D4
const int echoPin = 0; //D3
long duration;
int distance;
int t = 27;

void setup()
{
    Serial.begin(115200);
    Serial.println();
    ss.begin(GPSBaud);

    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    Serial.begin(115200);
    delay(100);
    //Serial.print("Connected to..");
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
}

void checkGPS()
{
    if (gps.charsProcessed() < 10) {
        Serial.println(F("No GPS detected: check wiring."));
    }
}

void loop()
{

    while (ss.available() > 0) {
        // sketch displays information every time a new sentence is correctly encoded.
        if (gps.encode(ss.read()))
            if (gps.location.isValid()) {

                float latitude = (gps.location.lat()); //Storing the Lat. and Lon.
                temp1 = latitude;
                delay(2000);
                float longitude = (gps.location.lng());
                temp2 = longitude;
                delay(2000);

                Serial.print("LAT:  ");
                Serial.println(latitude, 6); // float to x decimal places

                Serial.print("LONG: ");
                Serial.println(longitude, 6);
            }
    }

    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("Connection failed");
        delay(1000);
        return;
    }

    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    distance = duration * 0.034 / 2;
    Serial.print("Distance: ");
    Serial.println(distance);
    Serial.println(WiFi.localIP());
    String url = "your url.php?dist=" + String(distance) + "&lat=" + String(temp1, 6) + "&lng=" + String(temp2, 6);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                "Host: " + host + "\r\n" +
                "Connection:close\r\n\r\n");
}

You never set duration to anything. Also... what? It looks like you're mixing ultrasonic range finding code in with your GPS system.

Exactly ! i have tried to merge ultrasonic code with my gps code. But i failed maybe ! GPS is working fine but distance can't calculation in this code.

Do you have an ultrasonic range finder?

am using ultrasonic sensor to measure distance .

So how about you actually read from it then?

Oh, and ditch those delays. There is no call to use delay where you use it. And introduce some concept of time into your sending of data, so you don't flood your web server.

in my code i have written how it will works...but unfortunately isn't working . Only gps portion is working. Can you plz rewrite it for me. so that i can test again. i have to must send value of measuring levels with gps data. plz help me..

You never set duration to anything. ...

can you please rewrite it for me so that i can test again .

No, I can't. Just add in the missing code. The line that you didn't copy over from wherever you found the code. The line that actually reads the duration from the echo pin and saves it in the duration variable.

distance= duration*0.034/2; thats was the missing portion . i found it now. Thanks a lot @Majenko . now encountered another problem is my gps portion is executing after executing 80 times of printing distance in serial monitor . i just wondered why its taking too times to get inside GPS portions ?

Can you plz rewrite it for me? No, strong no, that's not why we come here.

extreamly sorry dear @dandavis . for the first time i have posted question in here. In rewrite i have mean which portion is need to correct . didn't mean to whole bunch of code again. Thanks to all of you for help me a lots .

no problem, welcome to stack!

To actually do the distance measurement with the ultrasonic sensor, you have to read in the echo pulse, that comes from the sensor. This is normally done with the pulseIn() function. Without it, you won't get any meaningful value. You have 2 portions of code: GPS and Ultrasonic distance measurement. Nice you say GPS works, try an example code for measurement with the ultrasonic sensor and understand it completely. Then you can merge the two codes


text:
Sending data from webserver to Arduino
Hello Arduino enthusiasts! I've been working on a keypad lock system for school lately and I need some advice.Basically, my code checks if the entered passcode is the same than a predefined passcode stored in a variable. I must code a local web server hosted by my Arduino Mega board that allows someone to change the correct passcode remotely via Ethernet. I have coded a working program, but I am sure it can be better designed or done in an easier way, this is why I'm asking for advice on how I could improve the performances of my program or make it shorter. If you need further explanation, let me know and I'd be happy to explain. Thank you!
Here's my code(or if you think it's plain, with colors):
#include <SPI.h>
#include <Ethernet.h>

byte mac[] = { 0x90, 0xA2, 0xDA, 0x0E, 0xA5, 0x7E };
IPAddress ip(192,168,1,250);
EthernetServer server(80);

String HttpHeader;
String nwCode="";
int curCode=19988;

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

  if(Ethernet.begin(mac)==0){
    Serial.println("Failed to use DHCP");
    Ethernet.begin(mac, ip);
  }
  Serial.println(Ethernet.localIP());
  HttpHeader="";
}

void loop(){

  EthernetClient client = server.available();

  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (HttpHeader.length() < 16){
           if(nwCode.length()<5){
             if(isDigit(c)){
               nwCode.concat(c);
             }
           }
        }
        if (c == '\n') {
          if(nwCode.length()==5){
            curCode=nwCode.toInt();
            Serial.println(curCode);
          }
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println("");
          client.println();
          client.print("<form method=get>");
          client.print("<input type='password' name=code required>
");
          client.print("<input type=submit value=submit></form>");
          client.print("");
          nwCode="";

          client.stop();
        }
      }
    }
  }
}

In the void setup() I try to connect to the internet with DHCP, and if not, just connect with specified IP and MAC addresses. I also print the IP address used to host the webpage so we know what to type in our browser. Then in the void loop() I wait till someone visits the IP address and show them the webpage. Next, we read the incoming GET request(new passcode submitted) and make sure it's not any longer than 5 chars (correct passcode is 5 chars long), then I take only the numbers (remove GET and HTTP 1.1 from the request) and store them in the nvCode variable. Then if the request has ended and the passcode is 5 chars long, set the current code value to the new code(Without this step the serial monitor outputs 11 everytime the page is loaded or I make a request, I think this comes from the HTTP 1.1 and isDigit().)
I know there are better ways of doing this and the simpler and shorter the better, so any advice is much appreciated, thanks!
I have used Serial output for debugging purposes and to better show what the code is doing but I plan on removing that afterwards.
Here are the outputs:
This is what the Serial monitor outputs when I power the Arduino board.
(The IP is the address where the webpage is hosted)
This is the webpage hosted by the Arduino board.

After submitting a new passcode, it sends a GET request.

The Serial monitor output after sending the new passcode.

TL;DR the nwCode variable must collect the passcode entered in the HTML form and must set var curCode's value to it. nwCode being the new passcode code and curCode being the current passcode.
!UPDATE!
I just realized that I can change the passcode once, but if I try to change it again after, I get the wrong numbers on the serial monitor, so my code has a problem somewhere. Any help regarding this issue would be much appreciated.

also asked at https://forum.arduino.cc/index.php?topic=542266

+1 for properly indented code

@Juraj I asked on Arduino's forum too, but the answers weren't really what I was looking for.


text:
How to delay properly inside ISR
I am currently working on a little code which needs to react fast. Here is what I am trying to accomplish:
Using a sine wave phase detector I am detecting every zero crossing and feeding that pulse into the Arduino.
Using an ISR the Arduino detects this zero crossing pulse using RISING. Once one pulse has been detected AND I have pressed a button, I need there to be a delay of 0 - 10ms before switching on an output.
If I don't use an ISR and set a delay of up to 10ms inside the loop, it won't really be 10ms and it will be some other delay, nothing consistent. (I checked with an oscilloscope).
Only when using an ISR and using delayMicrosenconds() inside the ISR I can delay the output consistently for up to 10 ms everytime.
Now I have read that doing this is wrong...Even though it works perfectly. Which better way could I use?
Thanks!
EDIT: While 100% accuracy may not be possible, it needs to be as precise as possible. More important is the repeatability. Using my method I could reproduce the outcome everytime with an accuracy in the nano seconds range.

how critical is those 10 ms really?

If your program has nothing else to do during these 10 ms, and if you don't care about the Arduino timekeeping (millis() and micros()) getting off, and if you don't use libraries that rely on interrupts, then your method should be OK.

Those 10ms need to be 100% exact. I need to switch on an output which drives a TRIAC. The TRIAC will then turn on an electronic ballast at exactly the desired sine phase. I.e. if I delay for 5ms, the TRIAC will switch on AC at exactly 90°

“100% exact” is not achievable in the real world. Not with an Arduino nor with the most precise equipment available on earth.

The question of @ratchetfreak is very relevant because single cycle accuracy, while achievable, will require somewhat complex low-level programming. If you can live with a few 10 µs of jitter, then the problem is much easier. Please, edit your question to provide a reasonable answer to that question.

It's quite simple: You don't.
Instead you use your initial ISR to configure and enable one of the ATMega's Timer peripherals. Set that to the length of your required delay - then the ISR exists.
When the chosen time has passed the timer interrupt triggers, and you use that interrupt to turn on your output.

I have tried this. How would I enable for example Timer1 inside my initial ISR? TIMER1_OVF_vect and TIMER1_COMPB_VECT did not give me the expected results. When switching my output inside these routines, there was no delay.

Using the TimerOne library is easiest.

But would it be ok to completly configure the Timer1 inside the ISR? Setting prescaler, compare match register, etc?

Sure. Or do the config elsewhere and just turn it on in the ISR. Whatever makes more sense for your program.

You could configure the timer to make it trigger only once, using the technique used here: https://wp.josh.com/2015/03/12/avr-timer-based-one-shot-explained/  . (Though this might be overkill in this case. )


text:
RGB Not displaying Red when using LCD
I was testing my RGB (common anode) on its own playing with colours and got the red, green to work as desired.
However, when I connected my LCD board to my Arduino Uno as well as the RGB (using the same code prior and same output pins so I know the code isn't the issue) the RGB no longer displays red.
I assume it has something to do with the fluctuating voltage/current after I've put in the LCD but I cant work out how to resolve it. When its meant to be red it's just nothing, doesn't light up, green however still works.
#include <LiquidCrystal.h>
#define COMMON_ANODE
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int SelectCounter = 0;
int hours = 0; // start hours
int minutes = 0; //start min
int seconds = 5; //start seconds
int redPin = A1;
int greenPin = 2;
int bluePin = 3;
int digitposition = 0;
int readkey;
int speaker = A5;
int buttonPin = A4;
int buttonPushCounter = 0;   // counter for the number of button presses
int buttonState = 0;         // current state of the button
int lastButtonState = 0;

void setup() {
pinMode(speaker, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}

void loop() {
noTone(speaker);
setColor(0, 0, 255); // red

....... }

void trigger() {
  lcd.clear(); // clears the screen and buffer
 lcd.setCursor(6,0);
 lcd.println("MUM:      ");
 lcd.setCursor(4, 1); // set timer position on lcd for end.
 lcd.println("WAKE UP!    ");
 tone(speaker, 10);
 setColor(0, 255, 0);  // green
 delay(500);
 digitalWrite(A1, HIGH);
 digitalWrite(2, HIGH);
 digitalWrite(3, HIGH);
 noTone(speaker);
 delay(500);
 lcd.display();
 }

void setColor(int red, int green, int blue)
{
  #ifdef COMMON_ANODE
   red = 255 - red;
   green = 255 - green;
   blue = 255 - blue;
 #endif
  analogWrite(redPin, red);
  analogWrite(greenPin, green);
  analogWrite(bluePin, blue);
}

Without schematics and the code it's impossible to answer. However many libraries affects timers and all pwm channels on it. But I don't see why the LCD library should be using a timer.

Would what I've added suffice?

pin 1 is TX of Serial

You know that pins 0 and 1 are used for the Serial communication, right?

Yeah, of course, stupid mistake. So to make it work is all I need to do change red pin to A1 (only analog pins available) because that's not seeming to work, its now made it red, and turned the green one to a mix of yellow/red

I've changed the code accordingly to how it looks now

@AngusRyan and now it works or not? In any case, I suggest you to read the analogwrite arduino page. Particularly the part when they say "On most Arduino boards (those with the ATmega168 or ATmega328P), this function works on pins 3, 5, 6, 9, 10, and 11" and "You do not need to call pinMode() to set the pin as an output before calling analogWrite()"

The analogWrite works on PWM pins only.

Only the pins with a ~ next to it are PWM pins. The pin connected to the red led, pin A1, does not support PWM, so analogWrite will not have the desired effect.


text:
Using TCA9548A to read 30 ADCs
I want to read 30 differential ended analog sensors.
Using ADS1115 16 bit this is possible, but we end up having only 4 address on I2C, so i chose TCA9548A breakout board with 8 I2C multiplex channels,
Is it possible to read the ADC as shown in the block diagram
if yes, please help with code.

based on the datasheet for the tca9548a - what you propose is possible - help, would be to google arduino TCA9548A

If using arduino is not essential, this post could be moved to the electrical engineering stack exchange.


text:
How to print/display next menu item with menubackend.h?
I'm trying to make a navigational menu with sub menus to display on an OLED.  Have managed this OK, however I would like to display the next item on the same level, to encourage scrolling, but I am unable to figure this out.
I want to have it so that the current menu item is displayed, along with the next item one would reach if you scrolled downwards.  I know you can display the previous and current items easily with
  Serial.print(fromFlash(changed.from.getName()));

and
  Serial.println(fromFlash(changed.to.getName()));

respectively - but I would like to display the current and the next (below but on same level) item.  How can I do this?  I played around for most of today on this but am pretty stumped.
I've simplified the example given which is below.  Below that, I've included menubackend.h
Running on an ATMEGA328P chip.
#include "MenuBackend.h"

/*
    This is the structure of the modelled menu

    Settings
        Pin
        Debug
    Options
        Delay (D)
            100 ms
            200 ms
            300 ms
            400 ms
 */

#define TEST_FROMFLASH
#undef TEST_GETITEMNAMEFROMFLASH

const char itemNameSettings[] PROGMEM = "Settings";
const char itemNamePin[] PROGMEM      = "Pin";
const char itemNameDebug[] PROGMEM    = "Debug";
const char itemNameOptions[] PROGMEM  = "Options";
const char itemNameDelay[] PROGMEM    = "Delay";
const char itemName100ms[] PROGMEM    = "100 ms";
const char itemName200ms[] PROGMEM    = "200 ms";
const char itemName300ms[] PROGMEM    = "300 ms";
const char itemName400ms[] PROGMEM    = "400 ms";
const char itemNameshutdown[] PROGMEM = "shutdown";

static void menuChangeEvent(MenuChangeEvent changed);
static void menuUseEvent(MenuUseEvent used);
//this controls the menu backend and the event generation
MenuBackend menu = MenuBackend(menuUseEvent,menuChangeEvent);
//beneath is list of menu items needed to build the menu
MenuItem settings = MenuItem(itemNameSettings);
MenuItem pin = MenuItem(itemNamePin);
MenuItem debug = MenuItem(itemNameDebug);
MenuItem options = MenuItem(itemNameOptions);
MenuItem setDelay = MenuItem(itemNameDelay,'D');
MenuItem d100 = MenuItem(itemName100ms);
MenuItem d200 = MenuItem(itemName200ms);
MenuItem d300 = MenuItem(itemName300ms);
MenuItem d400 = MenuItem(itemName400ms);
MenuItem shutdown1 = MenuItem(itemNameshutdown);

//this function builds the menu and connects the correct items together
void menuSetup()
{
    Serial.println(F("Setting up menu..."));
    //add the file menu to the menu root
    menu.getRoot().add(settings);
    //setup the settings menu item
    settings.addRight(pin);
    //we want looping both up and down
       pin.addBefore(debug);
       pin.addAfter(debug);
       debug.addAfter(pin);
    //we want a left movement to pint to settings from anywhere
       debug.addLeft(shutdown1);
       pin.addLeft(settings);
    settings.addAfter(options);
    shutdown1.addAfter(settings);
    options.addAfter(shutdown1);
      options.addRight(setDelay);
      setDelay.addLeft(options);
      setDelay.addRight(d100);
      d100.addBefore(d100); //loop to d400
      d100.addAfter(d200);
      d200.addAfter(d300);
      d300.addAfter(d400);
      d400.addAfter(d100); //loop back to d100
      //we want left to always be bak to delay
      d100.addLeft(setDelay);
      d200.addLeft(setDelay);
      d300.addLeft(setDelay);
      d400.addLeft(setDelay);

}

#ifdef TEST_FROMFLASH

inline const __FlashStringHelper * fromFlash(const char * pStr)
{
    return reinterpret_cast<const __FlashStringHelper *>(pStr);
}

#endif

#ifdef TEST_GETITEMNAMEFROMFLASH

inline char * getItemNameFromFlash(const MenuItem & item, char * copyToBuffer, size_t bufferSize)
{
    strncpy_P(copyToBuffer, item.getName(), bufferSize);
    copyToBuffer[bufferSize - 1] = '\0'; // Make sure the buffer is null-terminated.

    return copyToBuffer;
}

#endif

/*
    This is an important function
    Here all use events are handled

    This is where you define a behaviour for a menu item
 */
void menuUseEvent(MenuUseEvent used)
{
    Serial.print(F("Menu use "));

#ifdef TEST_FROMFLASH
    Serial.println(fromFlash(used.item.getName()));
#endif

#ifdef TEST_GETITEMNAMEFROMFLASH
    char itemNameBuffer[31]; // 30 chars + '\0';
    Serial.println(getItemNameFromFlash(used.item, itemNameBuffer, sizeof(itemNameBuffer)));
#endif

    if (used.item == setDelay) //comparison against a known item
    {
        Serial.println(F("menuUseEvent found Delay (D)"));
    }
}

/*
    This is an important function
    Here we get a notification whenever the user changes the menu
    That is, when the menu is navigated
 */
void menuChangeEvent(MenuChangeEvent changed)
{
    Serial.print("Menu change ");

#ifdef TEST_FROMFLASH
    Serial.println(fromFlash(changed.to.getName()));

#endif

#ifdef TEST_GETITEMNAMEFROMFLASH
    char itemNameBuffer[31]; // 30 chars + '\0';
    Serial.print(getItemNameFromFlash(changed.from, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.print(" char is ");
    Serial.println(getItemNameFromFlash(changed.to, itemNameBuffer, sizeof(itemNameBuffer)));
#endif
}

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

    Serial.println(F("Revision 1.0."));

    menuSetup();
    Serial.println(F("Starting navigation:\r\n   Down: s   Left: a   Right: d   Use: e"));
}

void showAllNames()
{
#ifdef TEST_FROMFLASH
    Serial.println(fromFlash(settings.getName()));
    Serial.println(fromFlash(pin.getName()));
    Serial.println(fromFlash(debug.getName()));
    Serial.println(fromFlash(options.getName()));
    Serial.println(fromFlash(setDelay.getName()));
    Serial.println(fromFlash(d100.getName()));
    Serial.println(fromFlash(d200.getName()));
    Serial.println(fromFlash(d300.getName()));
    Serial.println(fromFlash(d400.getName()));
#endif

#ifdef TEST_GETITEMNAMEFROMFLASH
    char itemNameBuffer[31]; // 30 chars + '\0';

    Serial.println(getItemNameFromFlash(settings, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(pin, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(debug, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(options, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(setDelay, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(d100, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(d200, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(d300, itemNameBuffer, sizeof(itemNameBuffer)));
    Serial.println(getItemNameFromFlash(d400, itemNameBuffer, sizeof(itemNameBuffer)));
#endif
}

void loop()
{
    if (Serial.available()) {
        byte read = Serial.read();
        switch (read) {
        case 's':
            menu.moveDown();
            break;
        case 'd':
            menu.moveRight();
            break;
        case 'a':
            menu.moveLeft();
            break;
        case 'e':
            menu.use();
            break;
        case 'z':
            showAllNames();
            break;
        }
    }
}

MenuBackend.h
/*
||
|| @file    MenuBackend.h
|| @version 1.4
|| @author  Alexander Brevig
|| @contact alexanderbrevig@gmail.com
|| @contribution Adrian Brzezinski adrb@wp.pl, http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?action=viewprofile;username=vzhang
||
|| @description
|| | Provide an easy way of making menus
|| #
||
|| @license
|| | This library is free software; you can redistribute it and/or
|| | modify it under the terms of the GNU Lesser General Public
|| | License as published by the Free Software Foundation; version
|| | 2.1 of the License.
|| |
|| | This library is distributed in the hope that it will be useful,
|| | but WITHOUT ANY WARRANTY; without even the implied warranty of
|| | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
|| | Lesser General Public License for more details.
|| |
|| | You should have received a copy of the GNU Lesser General Public
|| | License along with this library; if not, write to the Free Software
|| | Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
|| #
||
*/

#ifndef MenuBackend_h
#define MenuBackend_h

#include <avr/pgmspace.h>

/*
    A menu item will be a container for an item that is a part of a menu
    Each such item has a logical position in the hierarchy as well as a text and maybe a mnemonic shortkey
*/
class MenuItem {
public:
    MenuItem(const char * itemName, char shortKey='\0' ) : name(itemName), shortkey(shortKey) {
        before = right = after = left = 0;
    }

    //void use(){} //update some internal data / statistics
    inline const char * getName() const { return name; }
    inline const char getShortkey() const { return shortkey; }
    inline const bool hasShortkey() const { return (shortkey!='\0'); }
    inline void setBack(MenuItem *b) { back = b; }
    inline MenuItem* getBack() const { return back; }
    inline MenuItem* getBefore() const { return before; }
    inline MenuItem* getRight() const { return right; }
    inline MenuItem* getAfter() const { return after; }
    inline MenuItem* getLeft() const { return left; }

    MenuItem *moveBack() { return back; }

    MenuItem *moveUp() {
        if (before) { before->back = this; }
        return before;
    }

    MenuItem *moveDown() {
        if (after) { after->back = this; }
        return after;
    }

    MenuItem *moveLeft() {
        if (left) { left->back = this; }
        return left;
    }

    MenuItem *moveRight() {
        if (right) { right->back = this; }
        return right;
    }

    //default vertical menu
    MenuItem &add(MenuItem &mi) { return addAfter(mi); }

    MenuItem &addBefore(MenuItem &mi) {
        mi.after = this;
        before = &mi;
        if ( !mi.back ) mi.back = back;
        return mi;
    }
    MenuItem &addRight(MenuItem &mi) {
        mi.left = this;
        right = &mi;
        if ( !mi.back ) mi.back = back;
        return mi;
    }
    MenuItem &addAfter(MenuItem &mi) {
        mi.before = this;
        after = &mi;
        if ( !mi.back ) mi.back = back;
        return mi;
    }
    MenuItem &addLeft(MenuItem &mi) {
        mi.right = this;
        left = &mi;
        if ( !mi.back ) mi.back = back;
        return mi;
    }
protected:

    const char * name;
    const char shortkey;

    MenuItem *before;
    MenuItem *right;
    MenuItem *after;
    MenuItem *left;
    MenuItem *back;
};

//no dependant inclusion of string or cstring
bool menuTestStrings1(const char *a, const char *b) { // a is in flash, b is in SRAM.
    for (uint8_t da = pgm_read_byte_near(a); da; da = pgm_read_byte_near(++a), b++)
    {
        if (da != *b)
            return false;
    }
    return (*b == '\0'); // We reached the end of a.  Strings are equal only if we reached the end of b too.
}
bool menuTestStrings2(const char *a, const char *b) { // a and b are both in flash.
    uint8_t da = pgm_read_byte_near(a); // Dereferenced a.
    uint8_t db = pgm_read_byte_near(b); // Dereferenced b.

    for ( ; da; da = pgm_read_byte_near(++a), db = pgm_read_byte_near(++b))
    {
        if (da != db)
            return false;
    }

    return (db == '\0'); // We reached the end of a.  Strings are equal only if we reached the end of b too.
}
bool operator==(MenuItem &lhs, char* test) {
    return menuTestStrings1(lhs.getName(),test);
}
bool operator==(const MenuItem &lhs, char* test) {
    return menuTestStrings1(lhs.getName(),test);
}
bool operator==(MenuItem &lhs, MenuItem &rhs) {
    return menuTestStrings2(lhs.getName(),rhs.getName());
}
bool operator==(const MenuItem &lhs, MenuItem &rhs) {
    return menuTestStrings2(lhs.getName(),rhs.getName());
}

struct MenuChangeEvent {
    const MenuItem &from;
    const MenuItem &to;
};

struct MenuUseEvent {
    const MenuItem &item;
};

typedef void (*cb_change)(MenuChangeEvent);
typedef void (*cb_use)(MenuUseEvent);

const char itemNameMenuRoot[] PROGMEM = "MenuRoot";

class MenuBackend {
public:

    MenuBackend(cb_use menuUse, cb_change menuChange = 0) : root(itemNameMenuRoot) {
        current = &root;
        cb_menuChange = menuChange;
        cb_menuUse = menuUse;
    }

    MenuItem &getRoot() {
        return root;
    }
    MenuItem &getCurrent() {
        return *current;
    }

    void moveBack() {
        setCurrent(current->getBack());
    }

    void moveUp() {
        setCurrent(current->moveUp());
    }

    void moveDown() {
        setCurrent(current->moveDown());
    }

    void moveLeft() {
        setCurrent(current->moveLeft());
    }

    void moveRight() {
        setCurrent(current->moveRight());
    }

    void use(char shortkey)
    {
        recursiveSearch(shortkey,&root);
        use();
    }

    void use() {
        //current->use();
        if (cb_menuUse) {
            MenuUseEvent mue = { *current };
            cb_menuUse(mue);
        }
    }

private:
    void setCurrent( MenuItem *next ) {
        if (next) {
            if (cb_menuChange) {
                MenuChangeEvent mce = { *current, *next };
                (*cb_menuChange)(mce);
            }
            current = next;
        }
    }
    void foundShortkeyItem(MenuItem *mi) {
        mi->setBack(current);
        current = mi;
    }
    char canSearch(const char shortkey, MenuItem *m) {
        if (m==0) { return 0; }
        else  {
            if (m->getShortkey()==shortkey) {
                foundShortkeyItem(m);
                return 1;
            }
            return -1;
        }
    }
    void rSAfter(const char shortkey, MenuItem *m) {
        if (canSearch(shortkey,m)!=1) {
            rSAfter(shortkey, m->getAfter());
            rSRight(shortkey, m->getRight());
            rSLeft(shortkey, m->getLeft());
        }
    }
    void rSRight(const char shortkey, MenuItem *m) {
        if (canSearch(shortkey,m)!=1) {
            rSAfter(shortkey, m->getAfter());
            rSRight(shortkey, m->getRight());
            rSBefore(shortkey, m->getBefore());
        }
    }
    void rSLeft(const char shortkey, MenuItem *m) {
        if (canSearch(shortkey,m)!=1) {
            rSAfter(shortkey, m->getAfter());
            rSLeft(shortkey, m->getLeft());
            rSBefore(shortkey, m->getBefore());
        }
    }
    void rSBefore(const char shortkey, MenuItem *m) {
        if (canSearch(shortkey,m)!=1) {
            rSRight(shortkey, m->getRight());
            rSLeft(shortkey, m->getLeft());
            rSBefore(shortkey, m->getBefore());
        }
    }
    void recursiveSearch(const char shortkey, MenuItem *m) {
        if (canSearch(shortkey,m)!=1) {
            rSAfter(shortkey, m->getAfter());
            rSRight(shortkey, m->getRight());
            rSLeft(shortkey, m->getLeft());
            rSBefore(shortkey, m->getBefore());
        }
    }

    MenuItem root;
    MenuItem *current;

    cb_change cb_menuChange;
    cb_use cb_menuUse;
};

#endif

You have a global variable menu, which is of type MenuBackend, which contains the structure of your menu system. One of the member functions of MenuBackend is MenuItem getCurrent(), which returns a reference to the currently active menu.
If you look at the class definition of MenuItem, you can see that among the public member functions, you have:
inline MenuItem* getBack() const { return back; }
inline MenuItem* getBefore() const { return before; }
inline MenuItem* getRight() const { return right; }
inline MenuItem* getAfter() const { return after; }
inline MenuItem* getLeft() const { return left; }

Since menu is a global, anywhere in your program, you ought to be able to use:
menu.getCurrent().getAfter();

to access the MenuItem after the current one. Likewise with just menu.getCurrent().

EDIT:
I add the following lines to your showAllNames() function, just to check:
Serial.println(fromFlash(menu.getCurrent().getName()));
Serial.println(fromFlash(menu.getCurrent().getAfter()->getName()));

And it seemed to work fine.

Excellent! I tried what you suggested but realised in my application it was displaying the one after the one I had just changed from.  So I used changed.to.getAfter()->getName())  and it works brilliantly!  Thank you so much for your help, absolutely made my day!


text:
12 V 6 A power supply for Arduino
I have 3 motors which work at 12 V 3 A, I have attached a 12 V 6 A power supply and seems to be working fine. However I was wondering if this can also power the Arduino as well.

As that 3A total for the motors. or 3A per motor? If the latter, then you need a 9A power supply, not 6A.

@Majenko only if the OP uses all 3 motors at once, if only two are used at a time 6A will be fine.

If you have 3 motors that use 3Amps combined then you have 3Amps spare and that's more than enough for an Arduino.
I don't understand this part very well but depending on the type of motors you might get noise on the power lines and this might affect you Arduino.  In which case you will need to add in something to smooth the power, which means adding in a capacitor or two and their value depends on the frequency of the noise.  (http://www.valvewizard.co.uk/smoothing.html)
Personally I'd give it a try and see, but there again it wouldn't be the first Arduino I'd fried :)

If I understand correctly, the voltage regulator on the arduino will filter out a lot of this noise.


text:
Why Arduino Mega 2560 throw error when i try to upload example
I'm try to connect my Arduino Mega 2560 to PC, but I think it's not easy as I imagine. I spent a lot's of time to install USB driver. Here is a screenshot:

When I try to upload blink example, Arduino IDE throw this error:
Sketch uses 656 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
avrdude: ser_open(): can't set com-state for "\\.\COM10"
avrdude: ser_drain(): read error: The handle is invalid."

Please help to run one simple example.
I think this screen may help to understand my problem:

Did you reboot your PC after installing drivers?

I install driver for this site and everything is working well.
driver download:  wch.cn/download/CH341SER_EXE.html
I'm recommend to unplug arduino first and install driver, after that plug and enjoy.
Here is a video:
https://www.youtube.com/watch?v=FhmG5J-AHrg

So - you don't have a genuine Arduino then... Some cheap far-east inferior quality clone...

Tried everything but in the end these Chinese drivers works. Yes its not a genuine arduino. but its open source and anybody can make and manufacture it.

What you can try is:

Use another USB port
Reopen IDE
Reinsert the USB cable
Use a different USB cable
Prevent using a USB 'box' in between
Try a different 2560 (if you have)
Restart computer
Check if it can be found in the system drivers
Reinstall IDE (after deinstall it).

However, as the author already mentioned the real solution is needed for some non-genuine Arduinos:

Install the CH driver e.g. at wch.cn/download/CH341SER_EXE.html

In that case the last option should fix it (maybe deinstall IDE first just for certainty)

nothing change, IDE can not connect to device.

You can also try another USB port and restarting the computer.

I'm installing this : http://www.wch.cn/download/CH341SER_EXE.html
and left only this problem: "Sketch uses 1462 bytes (0%) of program storage space. Maximum is 253952 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes."

@AvtandilKavrelishvili You should put this as your answer ... some Chinese products do not use the same officially Arduino components and this driver is needed to install in addition.

Btw, the other message about the memory is not a problem, it just says you use 0% (or at least negigible) amount of flash memory and 9 bytes of dynamic memory ... so plenty left to be used.

I also got the same error. Then I un-plugged my connections and pressed the reset button. Then I uploaded the default blink example to my board. Then it's working fine. Then again I made a connection to the board and it shows the same error again. Now, I un-plugged the GND pin; it's working again. So, in my case there was some thing wrong with my connections.


text:
Powering potientiometer/button with a digital pin
When I read articles/tutorials about the Arduino Uno, the potentiometer and button always get power from the 5 V pin instead of from digital pins.
May I know whether the two components above can be powered by digital pins?
What is the situation that the components must only get power from 5 V pin instead of digital pins?

First thing Digital I/Os are designed for operation not giving power to other devices. digital I/Os Fan out and source current is low(40mA) it's may not sufficient for all devices.  As per your question you can power button and some low power devices making that digital pin OUTPUT and HIGH pinMode (pin, OUTPUT) and digitalWrite (pin, HIGH)

You can likely use an I/O pin as an output to "power" fairly high-impedance devices such as pullup resistors for buttons, or even potentiometers of moderate to high total resistance.
A reason you might wish to do so would to be able to stop the device from draining power while the entire system is in a low-power sleep mode, or to otherwise disable it beyond merely ignoring its input.
However, it's worth noting that powering an analog device such as a potentiometer from an I/O pin is likely to inject noise and full scale voltage uncertainty into the signal so derived, as the output voltage under load may be neither the same as the supply rail, not "quiet".
And, of course, you must not attempt to use an I/O pin to power lower-impedance (aka more "power hungry") loads via an output pin.  Generally, active devices should not be powered in this way - especially ones such as radio transmitters, other microcontrollers or complex logic functions, ultrasonic transmitters, and definitely not motors, relays, or solenoids.


text:
How to work with non-traditional UART baud rates
I am trying, unsuccessfully to communicate, using my Arduino Nano, with a custom device at a baud rate of 800 kbit/s.
The Arduino code look like this:
void setup() {
  // Put your setup code here, to run once:
  Serial.begin(800000);
}

void loop() {
  // Put your main code here, to run repeatedly:
  delay(5000);
  Serial.println(0x2be1);
}

When I am trying to debug it with PuTTY the result is:

And when I change the baud rate to 400 kbit/s the result is (as it should be):

Any idea?

The Arduino Nano cannot do 800 kb/s. As you can see in the source
code, the bit duration is rounded to the nearest multiple of
8 CPU cycles. In your case, it is rounded to
3 × 8 CPU cycles, which yields a baud rate of
666.666 kb/s. That is 16% too slow, an error too large for any
communication to be possible.
At 400 kb/s there is no rounding error, so everything works fine.
Edit: Note that if you build your own barebones
Arduino, then either a 12.8 MHz or a 19.2 MHz
crystal should allow you to get that exact baud rate. But then
millis(), delay() and co. would all be off.


text:
I'm getting an error while uploading my code to esp8266 via an arduino (FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error)))
Arduino: 1.8.13 (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Legacy (new can return nullptr), All SSL ciphers (most compatible), dtr (aka nodemcu), 26 MHz, 40MHz, DOUT (compatible), 1MB (FS:64KB OTA:~470KB), 2, nonos-sdk 2.2.1+100 (190703), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

Executable segment sizes:

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

IRAM   : 26756   / 32768 - code in IRAM          (ICACHE_RAM_ATTR, ISRs...)

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

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

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

Sketch uses 257316 bytes (26%) of program storage space. Maximum is 958448 bytes.

Global variables use 26816 bytes (32%) of dynamic memory, leaving 55104 bytes for local variables. Maximum is 81920 bytes.

esptool.py v2.8

Serial port COM3

Connecting........_____....._____....._____....._____....._____....._____.....____Traceback (most recent call last):

  File "C:\Users\Reghunaath A A\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.2/tools/upload.py", line 65, in <module>

    esptool.main(cmdline)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 2890, in main

    esp.connect(args.before)

  File "C:/Users/Reghunaath A A/AppData/Local/Arduino15/packages/esp8266/hardware/esp8266/2.7.2/tools/esptool\esptool.py", line 483, in connect

    raise FatalError('Failed to connect to %s: %s' % (self.CHIP_NAME, last_error))

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header

_

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

I'm getting the above stated error message while I'm trying to upload a code to esp8266 via an arduino(I've removed the ATMEGA32 from my arduino). Sometimes it gets uploaded without a problem(very rarely) but mostly the upload fails.
I connected rx of arduino to rx of esp and same for tx too. 3.3v of arduino to enable and vcc of esp. graund of arduino to ground of esp and gpio0.
The code that I'm trying to upload:
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forevervoid lop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
  // but actually the LED is on; this is because
  // it is active low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

My settings:

EDIT: Also, I want to add one more thing when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

@jsotola bruh half of my question is missing. Let me update it.

@jsotola please check it out now.

do you put the esp8266 in flashing mode?

@Juraj yes I connected the esp0 to groung

io 0 to gnd, then reset?

@Juraj I left reset unconnected

@Juraj yes after connecting io 0 to ground i do a reset by unplugging and plugging back the groud of the esp8266

add to question the module you have, how did you wire it and how do you put it in flashing mode

@Juraj I aded the wiring info to the question and I want to share with you one more thing that I observed recently, when the message box says "Connecting........_____....._" during that time if i reset the esp the code starts uploading

to put the esp8266 in flashing mode, io 0 must be pulled-down at boot (power up or reset) simply to tell the bootloader to start in flashing mode. the bootloader checks if the pin is HIGH or LOW. no magic. for normal run io 0 must be pulled up.

You need to set esp 8266 to flash mode.
Please connect en PIN to Gnd pin.
Then flash again.