text:
ZS-040 (HC-05) blueetooth module Arduino Mega
I followed this tutorial http://www.martyncurrey.com/using-an-arduino-mega-with-a-hc-05-zs-040-at-mode/ and it seems that the AT mode is on. (the LED is blinking like it's supposed)
I connected my pins like this:

BT VCC to Arduino 5V out. Disconnect before running the sketch
BT GND to Arduino GND
BT RX (through a voltage divider) to Arduino TX1 (pin 18)
BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)

This is the code I run: (from the tutorial)
// Basic Bluetooth test sketch 5a for the Arduino Mega.
// AT mode using button switch
// HC-05 with EN pin and button switch
//
// Uses serial with the host computer and serial1 for communication with the Bluetooth module
//
//  Pins
//  BT VCC to Arduino 5V out. Disconnect before running the sketch
//  BT GND to Arduino GND
//  BT RX (through a voltage divider) to Arduino TX1 (pin 18)
//  BT TX  to Arduino RX1 (no need voltage divider)   (pin 19)
//
// When a command is entered in to the serial monitor on the computer
// the Arduino will relay it to the Bluetooth module and display the result.
//

char serialByte = '0';
const byte  LEDPIN = 13;

void setup()
{
    pinMode(LEDPIN, OUTPUT);

    // communication with the host computer
    Serial.begin(9600);

    Serial.println("Do not power the BT module");
    Serial.println(" ");
    Serial.println("On the BT module, press the button switch (keep pressed, and at the same time power the BT module");
    Serial.println("The LED on the BT module should now flash on/off every 2 seconds");
    Serial.println("Can now release the button switch on the BT module");
    Serial.println(" ");
    Serial.println("After entering AT mode, type 1 and hit send");
    Serial.println(" ");

    // wait for the user to type "1" in the serial monitor
    while (serialByte !='1')
    {
        if ( Serial1.available() )   {  serialByte = Serial1.read();  }
    }

    // communication with the BT module on serial1
    Serial1.begin(38400);

    // LED to show we have started the serial channels
    digitalWrite(LEDPIN, HIGH);

    Serial.println(" ");
    Serial.println("AT mode.");
    Serial.println("Remember to to set Both NL & CR in the serial monitor.");
    Serial.println("The HC-05 accepts commands in both upper case and lower case");
    Serial.println(" ");
}

void loop()
{
    // listen for communication from the BT module and then write it to the serial monitor
    if ( Serial1.available() )   {  Serial.write( Serial1.read() );  }

    // listen for user input and send it to the HC-05
   if ( Serial.available() )   {  Serial1.write( Serial.read() );  }
}

I want to mention that the baud rate is set to 9600 and Both NL & CR is also set.
The problem is when I insert 1 in the Serial Monitor and nothing happens. How can I solve this problem?

Solution
Connection:

Bluetooth RXD to Arduino Mega pin 11
Bluetooth TXD to Arduino Mega pin 10
Bluetooth VCC to Arduino Mega 5V
Bluetooth GND to Arduino Mega GND

I used this code:
#include <SoftwareSerial.h>

#define RxD 10
#define TxD 11

SoftwareSerial BTSerial(RxD, TxD);

void setup(){
  // replace BAUDRATE as suggested
  BTSerial.begin(BAUDRATE);
  Serial.begin(9600);
  BTSerial.print("AT\r\n");
}

void loop(){

  if (BTSerial.available())
    Serial.write(BTSerial.read());

  if (Serial.available())
    BTSerial.write(Serial.read());

}

after setting AT mode as described in the tutorial above.
I tried running the code with BAUDRATE starting from 9600 to 460800:


text:
ESP8266 can't read parasitic DS18B20 temperature (reset during conversion, 85°C)
tl;dr at the end
I was running two DS18B20+PAR temperature sensors without any problems for the last two years on an ESP-01 module running on 3.3V on GPIO 2 using a 4.7K pullup resistor.
Now, wanting to develop a new firmware I started the development with new versions of everything (Arduino IDE and libraries), but now, with the exact same hardware setup that worked flawlessly for two years, the sensor always returns 85°C (error code for reset during conversion). I suspect that somehow, I don't know how, the ESP does not leave the data pin powered anymore.
To test this, I recompiled and flashed my old firmware that was running fine for two years and lo and behold, it still returned 85°C. Trying to isolate the issue, I flashed the old binary of the firmware and it returned the correct temperatures again.
To isolate the issue further, I tried numerous versions of the OneWire (2.3 to 2.3.2) and DallasTemperature (3.7.3 to 3.7.9) libraries, but to no effect. I am still getting 85°C all the time.
I also tried to compile it using Arduino IDE and PlatformIO, but both yielded the same issue still.
Trying on another ESP8266 (Wemos D1 mini and nodeMCU) did not change anything.
Slowly I am suspecting that the issue lies in the ESP8266-Arduino framework updating something or a change in the compiler, which now breaks keeping the data pin configured as output during the conversion.
Older versions of the ESP8266-Arduino framework (tried 2.2, 2.3, and up until latest) also produced the same error still.
A workaround, of course, is to use a lower value pullup resistor so that the sensors take power through that instead of the powered microcontroller pin. (One parasitic sensor requires 1K, two 470 Ohms) But this is not a solution.

Last weekend I debugged a bit deeper into the issue:
The OneWire library definitely leaves the pin as output (last macro called is DIRECT_MODE_OUTPUT()) and also the correct bit in the GPE pin mode register is set to output (1) during the conversion.
As far as I can see, the pin should be at 3.3V, but the oscilloscope definitely says the pin is dragged down too low (1.5V) during conversion. So it's only pulled up that far by the 4.7K pull-up resistor and not the GPIO pin for whatever reason...
I poked around here and there in the library but could not find the error. From what I can see, the code says that it should be working fine and my old binary says the hardware works fine too, but obviously it doesn't...
After five hours of unsuccessful debugging I gave up again.
I also opened an issue at the official OneWire GitHub Repo, but got no reaction in two weeks.
I will update this question in the following days by testing on other Arduino IDE versions and operating systems. Also, I want to try out the library fork from orgua to see if the issue happens in his library too.

tl;dr
- DS18B20+PAR with 4.7K pull-up always returns 85°C (error code indicating too little power on the data line) with newly compiled firmwares
- Hardware setup is working fine with old .bin
- Old code and new code freshly compiled yields error
- Doesn't depend on the library versions or what sketch is used
- Lower value pull-up resistor works, but is a dirty workaround
Hopefully someone else is able to reproduce or has already experienced this issue and is not satisfied with the workaround of using a lower pull-up resistor?

What pin are you using?

I am using GPIO2. (But it's still weird, that the unmodified hardware setup works with the old binary but not the new)

The datasheet specifies a "strong pullup" specifically mentioning using a MOSFET for the strong pullup. Still it doesn't answer the question of why the old libraries worked.

Do you know what versions were used to build the old binary? Can you guess based on the lastest libraries as of the build date?

The datasheet probably assumes an old microcontroller with no output drivers, that can't supply even a mA. The ESP8266 however has an output driver of up to 12mA, so that should be no problem. At least in theory, as the old code worked flawlessly.

I compiled the old code roughly in June 2016 and already tried all libraries from that date accordingly (as stated in the text), but still with the same result . Although I did not try an old Arduino IDE version from that time yet. But I will soon.

One last possibility: it looks like the esp8266-arduino package included a OneWire library in version 2.0.0 but it was removed in 2.1.0.

I just tried that today, still no change at all 85°C all the time...

source: Stack Exchange

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

sort: votes


text:
ATtiny85 (Digispark) with 433mhz RF transmitter not working
I have the following components:

ATtiny85 Digispark
433mhz Mini Low Power RF Transmitter

I got a communication flow transmit/receive working between two Wemos D1 and like to outsource the transmitting part now to a ATtiny85. I used the same code as for the Wemos:
#include <RCSwitch.h>

RCSwitch mySwitch = RCSwitch();

void setup() {
  pinMode(1, OUTPUT);
  mySwitch.enableTransmit(2);
}

void loop() {
    mySwitch.send("000110110001010100010001");
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
}

But the serial monitor for the Wemos does not receive any communication. I went so far that I built up the communication between the two Wemos again and connected only the data pin of the transmitter to the ATtiny85 in order to exclude any voltage problems (ATtiny gets 5V, transmitter likes <3.6V).
Now I am out of ideas. How can I debug the problem or what else can I try?
Requested setup:

And your ATtiny runs at 8MHz, while the Wemos runs at 80 or 160MHz? What are the used supply and logic voltages? The seller page says you should use 2.0-3.6V for the transmitter. Does the transmitter still work when you re-attach it to a Wemos? IMHO the next low-level debugging step (after checking voltages) would be use a logic-analyzer to compare the timing diagrams for the TX pin between the boards, as these are timing-ciritcal in the microsecond range (https://github.com/sui77/rc-switch/blob/master/RCSwitch.cpp#L523)

@MaximilianGerhardt The ATtiny runs on 16.5Mhz and Wemos on 80Mhz. Didn't know that it is critical to have the same timing - how do I do that? The transmitter is working fine (i power it by the second wemos and only connect the data pin to the ATtiny)

Timing analysis would be done with a logic analyzer (e.g. salae logic clone, extremely cheap, https://www.youtube.com/watch?v=rR5cEFRO9_s). So even if you feed 5V I/O Levels to the transmitter from the ATTiny but use the 3.3V supply from the weemos (and common GND I suppose) it works? Can you edit your question to include the working Wemos and non-working ATTiny circuits (with power supplies included)?

Nice to see it resolved, you should mark your answer as correct. Side note: Your right circuit is wrong in the sense that you don't have common ground between them. It might be just by chance that your two power supplies (if they come from the same computer, e.g.) have the same GND, but in general these can be at different potentials;the "3.3V" with respect to the GND of the 1st power supply might be a compeletly different voltage with respect to the GND of the 2nd pow.supply. That's why you should connect the GNDs of the power supplies together (https://www.youtube.com/watch?v=vhZQbFeEfPM)

But it seems like the transmitter just didn't like 5V I/O levels (as the datasheet said), which you have successfully resolved by making your ATTiny run on 3.3V. Another solution would be to add a level shifter (example) from 5V to 3.3V, but you'd still need a 3.3V supply for the transmitter. So I think you're overall better off with running on 3.3V entirely.

@MaximilianGerhardt I need to wait one day to mark it as resolved ;)

I got it to work. The last comment of @Maximilian Gerhardt about I/O output got me thinking and I read up on it. So if I use 5V to power the ATtiny the I/O output voltage representation for 1 and 0 are significantly higher then with 3.3V. So now I underclocked the ATtiny to 8Mhz in order to use a 3.3V power supply. This way the I/O output matches the transmitters expectations. Now the communication is working.
Thanks for your help Max!

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


text:
SyslogAppender for log4esp
I'd like to "merge" two Arduino libraires, namely log4Esp on one side and Syslog on the other, hence creating a syslog appender for log4esp.
My problem is that log4esp's Appender prototype expects a method to return an instance of Print to which it'll write the message.
Syslog can't be used in this way.
==> Question : How to create a "Print buffer" / where can I find which class extends Print?

Cerber, question for you https://arduino.stackexchange.com/questions/58502/library-mixing-log4esp-syslog-for-esp8266

Class Print is a base class of Arduino streaming. Stream is a derived class and adds reading capability. Print has only one abstract method write to write one byte to output or buffer. It is easy to implement a derived custom class.
The classes derived from Stream are classes for hardware and software serial like HardwareSerial for Serial singletons and different software serial implementations. From Stream is derived class File of the SD and SPIFFS library, TwoWire class for Wire singleton object, etc.
Class Client is derived from class Stream and is a base class for Arduino standard TCP networking. Examples of derived classes are EthernetClient, WiFiClient. For UDP, class UDP is derived from Stream, of course with implementations like EthernetUDP, WiFiUDP.
You can see this in the source code in local source file folders or in GitHub repositories.

perfect answer, very clear ! Thanks @juraj


text:
Arduino program has suddenly stopped updating
I am writing a speedo/odometer program which was all working beautifully until I introduced an LCD screen and code for the LCD.
The screen works on power up, displays the distance recorded on an SD card, toggles from miles to km on the press of a button, but no longer runs my calculate method when invoked. The method has stopped working, or at least it's not updating with the latest information anymore when the method instructs it to. Any help would be greatly appreciated.
In case it matters, I am powering the project from an HTC one M8. Maybe it's lack of juice that is causing the issue, or just bad programming?
My code:
#include <Arduino.h>
#include <SPI.h>
#include <SD.h>;
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

int InterruptPin = 2;
//int PowerPin = 3;
int ButtonPin = 4;
int SDPin = 7;

volatile long km = 0; // SAVE
volatile float kmTemp = 0; // SAVE
volatile int kmrevs = 0; // SAVE
volatile long miles = 0; // SAVE
volatile float milesTemp = 0; // SAVE
volatile int milesrevs = 0; // SAVE

volatile int kph = 0;
volatile int mph = 0;
volatile unsigned long start = 0;
volatile unsigned long stop = 0;
volatile float secs = 0;
volatile float speed = 0;
volatile float temp = 0;

volatile int buttonState = 0;
volatile int lastButtonState = 0;
volatile boolean riding = false;

File myFile;

LiquidCrystal_I2C lcd(0x27, 16, 2);

void calculate(){
    riding = true;

    // KPH SPEED CALCULATOR
    stop = millis() - start;
    start = millis();
    temp = (float)stop;
    secs = temp / 1000;
    speed = 1.854 / secs;
    speed = speed * 3.6;
    kph = speed;

    // MPH SPEED CONVERTOR
    float x = kph * 0.6214;
    mph = x;

    // KM DISTANCE CALCULATOR
    kmrevs++;
    if (kmrevs == 540){
        km++;
        kmrevs = 0;
        kmTemp = kmTemp + 0.00116;
    }
    if (kmTemp >= 1.0){
        km++;
        kmTemp = kmTemp - 1.0;
    }

    // MILES DISTANCE CALCULATOR
    milesrevs++;
    if (milesrevs == 868){
        miles++;
        milesrevs = 0;
        milesTemp = milesTemp +0.072;
    }
    if (milesTemp >= 1.0){
        miles++;
        milesTemp = milesTemp - 1.0;
    }

    // PRINT DATA TO LCD & SERIAL
    buttonState = digitalRead(ButtonPin);
    if (buttonState == HIGH){
        lastButtonState = buttonState;
        Serial.print(kph);
        Serial.print("kph  ");

        Serial.print(km);
        Serial.print("km  (");
        Serial.print(kmTemp, 6);
        Serial.println(")  ");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(kph);
        lcd.print("kph");
        lcd.setCursor(0,1);
        lcd.print(km);
        lcd.print("km");
    }
    if (buttonState == LOW){
       lastButtonState = buttonState;
        Serial.print(mph);
        Serial.print("mph  ");

        Serial.print(miles);
        Serial.print("miles  (");
        Serial.print(milesTemp, 6);
        Serial.println(")");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(mph);
        lcd.print("mph");
        lcd.setCursor(0,1);
        lcd.print(miles);
        lcd.print("miles");
    }

    // SAVE DATA TO SD CARD
    SD.remove("test.txt");
myFile = SD.open("test.txt", FILE_WRITE);
    if (myFile) {
        myFile.print(km);
        myFile.print(" ");//
        myFile.print(kmTemp, 6);
        myFile.print(" ");//
        myFile.print(kmrevs);
        myFile.print(" ");//
        myFile.print(miles);
        myFile.print(" ");//
        myFile.print(milesTemp, 6);
        myFile.print(" ");//
        myFile.print(milesrevs);
        myFile.close();
    }
    else {
        // SD SAVE ERROR
        Serial.println("Save Error");
    }
}

void setup(){
    pinMode(ButtonPin, INPUT_PULLUP);
    pinMode(InterruptPin, INPUT);

    // POWER LCD SCREEN
    //lcd.begin(16,2);
    lcd.init();
    lcd.backlight();

    // LAUNCH SERIAL CONNECTION
    Serial.begin(9600);

    // LOAD DATA FROM SD CARD
    SD.begin(7);
    myFile = SD.open("test.txt", FILE_READ);
    if (myFile) {
       while (myFile.available()) {

       km = myFile.parseInt();
       kmTemp = myFile.parseFloat();
       kmrevs = myFile.parseInt();
       miles = myFile.parseInt();
       milesTemp=myFile.parseFloat();
       milesrevs = myFile.parseInt();

       }
    myFile.close();
    }
    else {
        Serial.println("Read Error");
    }

    // ATTACH INTERRUPTS
     attachInterrupt(digitalPinToInterrupt(2), calculate, RISING);

    // LOAD START SERIAL & LCD SPEED
    buttonState = digitalRead(ButtonPin);
    if (buttonState == LOW){
        // MPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0mph  ");

        Serial.print(miles);
        Serial.print("miles  (");
        Serial.print(milesTemp, 6);
        Serial.println(")");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(mph);
        lcd.print("mph");
        lcd.setCursor(0,1);
        lcd.print(miles);
        lcd.print("miles");
    }
    if (buttonState == HIGH){
        // KPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0kph  ");

        Serial.print(km);
        Serial.print("km  (");
        Serial.print(kmTemp, 6);
        Serial.println(")  ");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(kph);
        lcd.print("kph");
        lcd.setCursor(0,1);
        lcd.print(km);
        lcd.print("km");
    }
}

void loop(){
    buttonState = digitalRead(ButtonPin);

    // ZERO SPEED ON SLOW ROTATION
    if (riding == true){
    long period = millis() - start;
    if (period == 4150){
    if (buttonState == LOW){
        // MPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0mph  ");

        Serial.print(miles);
        Serial.print("miles  (");
        Serial.print(milesTemp, 6);
        Serial.println(")");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(mph);
        lcd.print("mph");
        lcd.setCursor(0,1);
        lcd.print(miles);
        lcd.print("miles");
    }
    if (buttonState == HIGH){
        // KPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0kph  ");

        Serial.print(km);
        Serial.print("km  (");
        Serial.print(kmTemp, 6);
        Serial.println(")  ");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(kph);
        lcd.print("kph");
        lcd.setCursor(0,1);
        lcd.print(km);
        lcd.print("km");
    }
    }
    }

    // CHANGE READING WHEN PRESSED
    if (buttonState != lastButtonState){
        long period = millis() - start;
        if (buttonState == HIGH && period < 4150){
        // KPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print(kph);
        Serial.print("kph  ");

        Serial.print(km);
        Serial.print("km  (");
        Serial.print(kmTemp, 6);
        Serial.println(")  ");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(kph);
        lcd.print("kph");
        lcd.setCursor(0,1);
        lcd.print(km);
        lcd.print("km");
        }
        if (buttonState == HIGH && period > 4150){
        // KPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0kph  ");

        Serial.print(km);
        Serial.print("km  (");
        Serial.print(kmTemp, 6);
        Serial.println(")  ");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(kph);
        lcd.print("kph");
        lcd.setCursor(0,1);
        lcd.print(km);
        lcd.print("km");
    }
    if (buttonState == LOW && period < 4150){
        // MPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print(mph);
        Serial.print("mph  ");

        Serial.print(miles);
        Serial.print("miles  (");
        Serial.print(milesTemp, 6);
        Serial.println(")");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(mph);
        lcd.print("mph");
        lcd.setCursor(0,1);
        lcd.print(miles);
        lcd.print("miles");
    }
    if (buttonState == LOW && period > 4150){
        // MPH DISPLAYED
        lastButtonState = buttonState;
        Serial.print("0mph  ");

        Serial.print(miles);
        Serial.print("miles  (");
        Serial.print(milesTemp, 6);
        Serial.println(")");

        lcd.clear();
        lcd.setCursor(0,0);
        lcd.print(mph);
        lcd.print("mph");
        lcd.setCursor(0,1);
        lcd.print(miles);
        lcd.print("miles");
    }
    }
}

Its usually a bad idea to do so much in an ISR (interrupt service routine)   Those other functions you call from in there may need interrupts to be enabled to operate properly.   You should do as little as possible in there (maybe just update the tick count) then do all your other processing in another function called from the main loop.

using your current configuration, you may miss some ticks, even if it was working, as updating the LCD,printing all that information, and saving it to an SD card probably takes longer then the time in between ticks.  It would be much better to write to the SD card is larger 'chunks' of data, to eliminate the overhead of opening and closing the file everytime.

You are using millis, doing serial prints and SPI transfers inside an ISR, all of which are red flags. I'd re-program it to just switch a boolean variable and push the needed data into globalal variables; then process the values and save them in loop. See https://arduino.stackexchange.com/questions/22212/using-millis-and-micros-inside-an-interrupt-routine/22237#22237 and https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969

Clearly, it looks as though everyone agrees that the problem probably lies in the lengthy ISR....I do remember reading that once upon a time. I think I may reprogram it along the lines you guys have said. I would have been  removing all the print() statements anyway as its only for testing, but looks like I'd have a problem regardless. Further, you said to save to SD in bigger chunks......do you mean something like whack all the values into one variable and save that, rather than making 6 tasks?

Thanks guys, taking the labour out of the ISR has solved the problem perfectly. Unfortunately, the advice wasn't given as an answer so I'm unable to credit you for it, but appreciate the solutions given. Thanks.

Looks like I can't accept my answer either!  .....can someone throw a few words in an answer do that I can accept. Cheers.


text:
Interesting issue with my wifi Car project
Hello so i build a nodemcu wifi controlled car, everything works fine expect i have one small issue, currently i have 2 9v batterys, one of them is connected to motor controller and other one is connected to nodemcu.. but the nodemcu's 9v battery gets hot in a minute and stops working. What am i doing wrong? + is connected to vcc and - is connected to grnd on nodemcu.

Have you measured the current flow from the battery that's getting hot with a multimeter? Have you checked for shorts? Do you need a common ground between the two batteries? Can you upload a complete schematic of your project by using the schematic tool (Ctrl+M)?

zinc-carbon battery? i did not think that they made those anymore.

the nodemcu's 9v battery gets hot in a minute and stops working. What am i doing wrong?

You're using a 9V battery.
Those batteries are useless. They have very little capacity, and can provide very little current. The NodeMCU needs a lot of current.
Choose a better battery. Maybe a Li-Poly battery would be good (mobile phone batteries are good for this).

This site suggested 9v batterys http://henrysbench.capnfatz.com/henrys-bench/arduino-projects-tips-and-more/powering-the-esp-12e-nodemcu-development-board/

LG B4 18650 li-ion battery 2600mAh 3.7V, is this okey?

@SezerYıldız No the site said This is my least favorite option. I don't call that a recommendation ;-) For the 18650 you may need a Step-up booster and deep discharge protection if not built in.

18650s are good cells. I'm not sure what the LDO dropout on the NodeMCU is off hand, but since a lithium cell is nearer 4.2V when fully charged it should be good for most of its charge range.

alright, i will open one of my xianomi powerbanks and extract the li ion batterys!

@SezerYıldız keep the protection circuitry on them intact and connected. That will prevent overdischarge and overcharging; both of which can be dangerous.

@ratchetfreak Over-discharge of a single cell isn't dangerous. It's not even unrecoverable. What is dangerous is over-discharge of a single cell in a multi-cell (series) pack which causes that cell to reverse charge with the current flowing from the other cells causing copper to pierce the electrolyte layer causing a short internally.

Why crack out the cells out of a power bank? Just use the 5V / 1A (probably) output of that power bank to power the NodeMCU. That's less work for the LDO / less heat to produce than with the 9V battery, and the USB power bank can output much higher currents.

Size? Maybe it's a large power bank, but only 1 cell would suffice for the project...

Yes majenko its a small car, but i have a big powerbank thats why i took out one soon i will post a picture


text:
how long should interrupting signal last?
I want to apply the interruption of a program with a RISING signal from a pin. How long should the signal rise to be considered as the interruption?

What microcontroller are you using? Have you looked up its datasheet on minimum rise / glitch rejection times?

If edge or toggle interrupt is selected, pulses that last longer than one clock period will generate an interrupt. Shorter pulses are not recommended to generate an interrupt.

Source (page 91, chapter 17.2.1 "External Interrupt Control Register A")

Thank you very much for your answer and the substantial link.


text:
Saving a .txt file to SD Card and Reading each content data to txt file then save it to a variable
I am new to arduino I am trying to create an arduino project that Saving a .txt file to SD Card and Reading the txt file then save it to a variable data type "Long" named 'savednum'. I had successfully can save the txt file and read it, however the problem lies in storing the read txtfile, when I read the txtfile and stored it in savednum and then serial print the savednum it gives different/ random numbers which is not equal to the data in the .txtfile that I store and read. I am wondering what seem to be wrong? Any suggestion is really appreciated. I thank you in advance.
#include <TMRpcm.h>
 #include <SD.h>
 #include <SPI.h>
 #define SD_ChipSelectPin 4 //using digital pin 4 on arduino nano 328

 TMRpcm tmrpcm; // create an object for use in this sketch

File myFile;

char serialData;

int i = 0;
long n1 = 123456789;
long n2 = 245678918;

long savednum =0;

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

 }

Serial.print("Initializing SD card...");

 if (!SD.begin(SD_ChipSelectPin)) {
Serial.println("initialization failed!");
 while (1);
}
Serial.println("initialization done.");

 myFile = SD.open("NEWDATA.txt", FILE_WRITE);

if (myFile) {
Serial.print("Writing to NEWDATA.txt...");
myFile.println(n1);
myFile.println(n2);

myFile.close();
Serial.println("done.");
} else {

Serial.println("error opening NEWDATA.txt");
}

myFile = SD.open("NEWDATA.txt");
if (myFile) {
Serial.println("NEWDATA.txt:");

while (myFile.available()) {
  Serial.write(myFile.read());
// here the code I tried to read .txt file and store it in long
savednum = myFile.read();
Serial.println(savednum);
}

myFile.close();

}

}

void loop()
 {

  }

Side note: Do yourself and your readers a favor and format the code properly, either by using Arduino IDE features (tutorial here) or some online beautifier. It'll be much easier to spot errors this way.

myFile.read() reads just one byte from the file - not the whole file or even a whole line.
You're reading one byte, then printing it. Then reading a second byte, storing that in a variable, then printing the variable. Then you loop back to the beginning again.
So you're printing alternate "odd" bytes, and storing / overwriting the variable with "even" bytes. So you just get nonsense.
You're storing the data in your file as ASCII text, so it's necessary to read the entirety of each line and then convert that string of characters into a number. Or read each character in turn and manipulate your total value for the line.
For example:
long savedNum = 0;
long numberOne = 0;

while (myFile.available()) { // Something left to read
    char c = myFile.read(); // Get the next character
    if (isdigit(c)) { // It's a number 0-9
        savedNum *= 10; // Make room by decimal shifting to the left
        savedNum += (c - '0'); // Convert the character to a number and add it to the total
    } else if (c == '\n') { // End of line
        Serial.print(F("The number is: "));
        Serial.println(savedNum); // Show us the number
        numberOne = savedNum;  // Store it somewhere else - enhance this for multiple numbers.
        savedNum = 0;  // Reset to 0 ready to read the next line
    }
}

The Arduino API (Stream class) also includes some handy helper functions, such as:
int num = myFile.parseInt(); // get the next integer

There's no parseLong() though, but despite its name, parseInt() actually returns a long.  That reads characters up until it gets a non-numeric character and converts them to a long using the same method as in my example. It doesn't distinguish lines, though, so can be used to get separate numbers on the same line, such as 32847,2345534,12,-43.
With your file though you may need to filter out the extra \r that may be in there from the line endings or you'll get missing numbers.

Hi thank you very much for your answer it really helped me alot now I am successfully store the data from the .txt file to a variable however I have one last question because here I saved 18characters in the txt file I wanted it to split by 9 characters then distribute it in to two data type long variable named Storenum1 and storenum2 is it possible? Hope you can help me. I am really thankful for your help.

You're not storing 18 characters. You're storing 2 strings of up to 9 characters each, plus line endings (because you wrote with println).  So you get two lines in your file of nnnnnnnnn\r\n.  My example will read each line in turn - it's up to you to decide what to do with the savedNum value for each line.

Thank you now I understand thank very much for you good explanation and answer  I tried to study how to store in two variables. I really appreciate your help thank you

Is this method the same as using an EEPROM ?

@R1S8K No. An EEPROM reads and writes individual bytes to memory locations. An SD card works with files and streams of data.

I'm working with the lcd128x64, I'm stuck these days in developing the most important function to set one pixel and how to deal with buffers. The SD card would be the perfect solution for loading pictures. I'm wondering what is the best way to develop a good GUI in the lcd128x64? Is it better to load images of the GUI instead of drawing each element ? Anyway, I might open a new thread about developing the perfect pixel set function.

It all depends exactly which display it is. I have spent lots of time writing drivers for LCD and TFT displays, and know that for most GLCD displays it is far better if you have the memory available to create a buffer internally to store the current image and update parts of it in bulk.


text:
Arduino and Python
Does anyone know how do I get Arduino and Python talking to each other? I would essentially like to write my code and export it somehow to the arduino-uno.

Other than with pyserial?

No, can I use Pyserial?

For a python interpreter running on a microcontroller you need quite a lot of ressources (flash, SRAM, speed,..). Consider to either change the board to something like an ESP8266, ESP32 or Feather M0, or live with C/C++ and the smaller boards. The Arduino Uno simply can't run it on 2KB RAM and 32kB Flash.

So how would I get Python to interact with Arduino?

'Arduino' is a framework, a set of library functions which you can use to make your microcontroller do something, so to say. When you use the language Python with MicroPython or CircuitPython, you're using that new framework. Then it's not running an Arduino Core anymore.

What do you mean "interact"? Do you mean run Python on an Arduino or Arduino code communicate with Python code on the PC?

Arduino code communicate with Python code.

http://playground.arduino.cc/interfacing/python

Would you have any examples of how Python might be used with Arduino?

You can not run python on an UNO. If you want to use python on a microcontoller you should look into boards supported by MicroPython or Circuit Python

The Arduino communicates with the PC (and vice-versa) normally using Serial.  You can use the PySerial module in your python code to open the Arduino's serial port and read and write data, and the Serial object in your Arduino code likewise.
What that data is, and what it means, though is up to you to decide upon and program.


text:
Arduino +CCLK at command parsing
I have arduino leonardo and sim800h module. I don't seem to find the problem in my program, this is probably the 5th time I'm rewriting it. Please someone tell me what should I change to work normally. I decodes the answers, but some chars seem to disappear and sometimes appear again. With time only +CCLK stays everything else is gone. Also the time should update all the time, but the seconds stay the same for 5-10 seconds.
This is the code:
const long interval = 200;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0;

char enabledtime = 0;

char readenabl = 0;

char foundchar[6];

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
  if (Serial1.available () > 0) {
    if (foundchar[0] == '\n') {
      /*for (byte a = 0; a < 255; a = a + 1 ) {
        serialdata[a] = 0;
        }*/
        readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }

    if (foundchar[0] == '\r') {
      readenabl = 0;
      //pointingfinger = 0;
      enabledtime = 0;
      rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
    rtcy1[1] = serialdata[searchcharpos + 9];
    rtcy1[2] = '\0';
    rtcm1[0] = serialdata[searchcharpos + 11];
    rtcm1[1] = serialdata[searchcharpos + 12];
    rtcm1[2] = '\0';
    rtcd1[0] = serialdata[searchcharpos + 14];
    rtcd1[1] = serialdata[searchcharpos + 15];
    rtcd1[2] = '\0';
    rtch1[0] = serialdata[searchcharpos + 17];
    rtch1[1] = serialdata[searchcharpos + 18];
    rtch1[2] = '\0';
    rtcmm1[0] = serialdata[searchcharpos + 20];
    rtcmm1[1] = serialdata[searchcharpos + 21];
    rtcmm1[2] = '\0';
    rtcs1[0] = serialdata[searchcharpos + 23];
    rtcs1[1] = serialdata[searchcharpos + 24];
    rtcs1[2] = '\0';
    }
    foundchar[0] = foundchar[1];
    foundchar[1] = foundchar[2];
    foundchar[2] = foundchar[3];
    foundchar[3] = foundchar[4];
    foundchar[4] = foundchar[5];
    foundchar[5] = Serial1.read();

    if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K') {
      readenabl = 1;
      pointingfinger = 0;
    }
    if (readenabl == 1) {
      serialdata[pointingfinger] = foundchar[0];
      serialdata[pointingfinger + 1] = 0;
      pointingfinger++;
    }
  }
  }
}

This is the output:

Thanks!

Try to reduce it to an absolute minimalistic example. Trigger the request once, then read all available characters repedeately. Try this sketch: https://pastebin.com/sRJy63Dt Do you get the full response?

Oh, I do see a fatal problem: The baud rate for Serial is the same as those of Serial1. Printing a debug stuff or whatever is extremely slow on Serial. Increase to at least 115200 baud on Serial so you can eliminate the possibility of waiting too long for serial writes.

I get full response, even if interval = 200. Now I need to search the + and copy with offsets all the parameters. But how? Increasing speed seemed logical, but in this case it didn't change much.

I think you should change your approach to reading and processing the serial data. After sending a request over Serial, you should spin in a loop until the end of the answer is received (double \r\n I think?). In that loop, just dump the received data into a buffer. After it was received completely, analyze the received response (split into year, month, day, et cetera). I think you are loosing to much time in your combined "read and process" method with a billion variable assignments before each read.

Can you give an example of a full response string? You might be able to just sscanf the integers out of there.

this is the output your program gives: `Sending request
+CCLK: "04/01/01,06:33:06+00"
OK` I was actually able to use the idea for the loop in my program and so far it's working fine now

If it's working you can maybe write up a full answer on the code and techniques used to get it working.

This is the final working program that requests the time and parses the answer:
const long interval = 1000;
static long currentMillis;

byte searchcharpos = 0; //To determine where is the + in +CCLK in the char array

char serialdata[256]; //Array to store the chars before parsing

char rtcy1[3]; //Current year  Format: yy\0
char rtcm1[3]; //Current month  Format: mm\0
char rtcd1[3]; //Current day  Format: dd\0
char rtch1[3]; //Current hour  Format: hh\0
char rtcmm1[3]; //Current minute  Format: mm\0
char rtcs1[3]; //Current second  Format: ss\0

byte pointingfinger = 0; //index of the array

char enabledtime = 0; //this variable is set to 1 every second and set to 0 after parsing is done

char readenabl = 0; //this is set to 1 when is finished reading from serial

char foundchar[6]; //small buffer that works as a shift register to hold only the command for comparison

void setup() {
  Serial.begin(9600); //USB to Computer
  Serial1.begin(9600); //UART to Modem
  Serial1.print("ATE0\r"); //Disable echo
}

void loop() {
  if (millis() - currentMillis >= interval) //This is done every second
  {
    Serial1.print("AT+CCLK?\r");

    Serial.println("=========");
    Serial.print(serialdata[searchcharpos]);
    Serial.print(serialdata[searchcharpos + 1]);
    Serial.print(serialdata[searchcharpos + 2]);
    Serial.print(serialdata[searchcharpos + 3]);
    Serial.print(serialdata[searchcharpos + 4]);
    Serial.print(serialdata[searchcharpos + 5]);
    Serial.print(serialdata[searchcharpos + 6]);
    Serial.print(serialdata[searchcharpos + 7]);
    Serial.print(serialdata[searchcharpos + 8]);
    Serial.print(serialdata[searchcharpos + 9]);
    Serial.print(serialdata[searchcharpos + 10]);
    Serial.print(serialdata[searchcharpos + 11]);
    Serial.print(serialdata[searchcharpos + 12]);
    Serial.print(serialdata[searchcharpos + 13]);
    Serial.print(serialdata[searchcharpos + 14]);
    Serial.print(serialdata[searchcharpos + 15]);
    Serial.print(serialdata[searchcharpos + 16]);
    Serial.print(serialdata[searchcharpos + 17]);
    Serial.print(serialdata[searchcharpos + 18]);
    Serial.print(serialdata[searchcharpos + 19]);
    Serial.print(serialdata[searchcharpos + 20]);
    Serial.print(serialdata[searchcharpos + 21]);
    Serial.print(serialdata[searchcharpos + 22]);
    Serial.print(serialdata[searchcharpos + 23]);
    Serial.print(serialdata[searchcharpos + 24]);
    Serial.print(serialdata[searchcharpos + 25]);
    Serial.print(serialdata[searchcharpos + 26]);
    Serial.print(serialdata[searchcharpos + 27]);
    Serial.print(serialdata[searchcharpos + 28]);
    Serial.print(serialdata[searchcharpos + 29]);
    Serial.print(serialdata[searchcharpos + 30]);
    Serial.print ("=========");
    //Serial1.print("AT+CCLK?\r"); //ask for the time
    //delay(50);
    Serial.println("");
    Serial.println("=====");
    Serial.println(millis());

    Serial.println("YEAR: ");
    Serial.print(rtcy1[0]);
    Serial.println(rtcy1[1]);
    Serial.println("MONTH: ");
    Serial.print(rtcm1[0]);
    Serial.println(rtcm1[1]);
    Serial.println("DAY: ");
    Serial.print(rtcd1[0]);
    Serial.println(rtcd1[1]);
    Serial.println("HOUR: ");
    Serial.print(rtch1[0]);
    Serial.println(rtch1[1]);
    Serial.println("MINUTE: ");
    Serial.print(rtcmm1[0]);
    Serial.println(rtcmm1[1]);
    Serial.println("SECOND: ");
    Serial.print(rtcs1[0]);
    Serial.println(rtcs1[1]);

    enabledtime = 1;

    currentMillis = millis();
  }

  if (enabledtime == 1) {
    if (Serial1.available () > 0) {
      /*
        if (foundchar[0] == '\n') {
          readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }

        if (foundchar[0] == '\r') {
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
        }
      */
      foundchar[0] = foundchar[1];
      foundchar[1] = foundchar[2];
      foundchar[2] = foundchar[3];
      foundchar[3] = foundchar[4];
      foundchar[4] = foundchar[5];
      foundchar[5] = Serial1.read();

      if (foundchar[0] == '+' && foundchar[1] == 'C' && foundchar[2] == 'C' && foundchar[3] == 'L' && foundchar[4] == 'K' && foundchar[5] == ':') {
        readenabl = 1;
        pointingfinger = 0;
      }
      if (readenabl == 1) {
        while (foundchar[0] != '\n') {
          if (Serial1.available() > 0) {
            serialdata[pointingfinger] = foundchar[0];
            serialdata[pointingfinger + 1] = 0;
            pointingfinger++;
            foundchar[0] = foundchar[1];
            foundchar[1] = foundchar[2];
            foundchar[2] = foundchar[3];
            foundchar[3] = foundchar[4];
            foundchar[4] = foundchar[5];
            foundchar[5] = Serial1.read();

          }
        }
        readenabl = 0;
        //pointingfinger = 0;
        enabledtime = 0;
        rtcy1[0] = serialdata[searchcharpos + 8]; //getting first char with its offset
        rtcy1[1] = serialdata[searchcharpos + 9];
        rtcy1[2] = '\0';
        rtcm1[0] = serialdata[searchcharpos + 11];
        rtcm1[1] = serialdata[searchcharpos + 12];
        rtcm1[2] = '\0';
        rtcd1[0] = serialdata[searchcharpos + 14];
        rtcd1[1] = serialdata[searchcharpos + 15];
        rtcd1[2] = '\0';
        rtch1[0] = serialdata[searchcharpos + 17];
        rtch1[1] = serialdata[searchcharpos + 18];
        rtch1[2] = '\0';
        rtcmm1[0] = serialdata[searchcharpos + 20];
        rtcmm1[1] = serialdata[searchcharpos + 21];
        rtcmm1[2] = '\0';
        rtcs1[0] = serialdata[searchcharpos + 23];
        rtcs1[1] = serialdata[searchcharpos + 24];
        rtcs1[2] = '\0';
      }
    }
  }
}


text:
What is the minimal possible latency between arduino and PC
Case specifications:

PC OS: Debian 9, x64 arch
Starting time point: i have a 1kb buffer on arduino that i want to send to host PC
Ending time point: i have recieved the buffer in a custom written C\C++ app running on a host PC
I want to send such a buffer once a second

What is the minimal possible latency - time passed between starting and ending points? and with what communication type? (serial?)

Depends on what Arduino.

Best chance would be via Serial (i.e. USB-UART bridge) and the highest possible baud-rate (about 1 Megabit). If your MCU has WiFi or LAN maybe that's even faster, but we can't tell because you didn't tell us what MCU you are running on.

We would also need to know exactly what you mean by serial. USB->USB? TTL->RS232?

i have none by hand, otherwise i could write simple ping test and measure it by myself

RubberDuck, yes we would need to know what type of serial connection works better for realtime reaction/response. And it seems it's better known to owners/users of the platform

Someone managed to send debugging info at 5.3 Mb/s through a custom software serial implementation. At that rate a 1 KiB buffer should go through in less than 2 ms.

Isochronous USB transfers have the lowest latency. I don't, though, think latency is the term you are after.

Seems you are actually asking about transfer speeds not latency.

There is more to low-latency communication than just squirting data as fast as you can (though that is an important part of it).
One thing people often forget is that the Arduino can only (easily) do one thing at a time. While you're sending your buffer to the PC it can't be sampling and filling your buffer.  If you have a buffer which fills up over the period of 1 second and you want to send that buffer to the PC when full, what happens during the subsequent second while you're sending the buffer? The buffer can't be being filled while it's being sent.
Using a normal UART to USB connection as most of the normal Arduino boards (Uno, Mega, etc) use the fastest you can reasonably expect is around 1MBaud. That's about 100kB/s.  Less if you use a cheap Chinese clone with a CH340G.  Even at 100kB/s your 1kB buffer, if sent completely raw and in binary, would take around 10ms to transfer. But getting the computer to make any sense of that raw data would be hard. So you'd need to wrap it in some form of protocol (up to you to design that...) so you may get half that speed (or worse depending on your protocol design).
And during that time not much else can happen.
For smooth low-latency communication of data it is much more preferable to use "ping-pong" buffers and interrupt- or DMA-driven sampling of your data. That means that one buffer is receiving your data from whatever source, and the other is being sent to the PC. Once the first buffer is filled up they reverse roles. However, the little 8-bit Arduinos aren't really suited for that kind of thing:

They don't have much RAM to waste on two buffers
They don't have interrupts with priorities to allow samples to occur while sending
They don't have DMA to do background transfers of data to/from peripherals

If latency is really that critical you would be better using one of the ARM-based Arduinos, such as the Due, where you can also then take advantage of a high-speed native USB interface which can give much higher throughput than a UART connection. Your choice of USB endpoint can also influence the latency of your design:

Isochronous - Lowest latency, small packets, not guaranteed to be delivered
Interrupt - Medium latency, small packets, delivery guaranteed
Bulk - High latency, large packets, delivery guaranteed

Isochronous is used mainly for audio where you would notice the slightest delay in sound, but wouldn't necessarily notice or worry about a slight glitch in the quality. Interrupt is used for things like HID where you need it to respond to you pressing the keys on your keyboard nice and fast, but you're never sending much data (64 byte packet limit on interrupt transfers).  Bulk is used for things like CDC/ACM (Serial over USB) where you may want to tranfer lots of data but wouldn't notice if it's pausing for a few ms every now and then (HS USB has a 512 byte packet limit on bulk transfers, FS USB has a 64 byte limit).
One of the great things with a direct USB connection is that underneath it is all packet-based, so you can use that as your transfer protocol if you know what you're doing. Don't just rely on the CDC/ACM "pipe", but instead make use of the underlying USB protocol to send individual packets which the receiving program can then understand and break apart into the right data without adding any extra protocol overheads.
For more advanced USB programming the Teensy and chipKIT cores have far more sophisticated USB support than the Arduino core, so you may fancy taking a look at their offerings in the way of boards that may suit your needs better.

Thanks for such a great academic answer. Now i can formulate thing in a correct terms. I am interested in measuring USB RTT (or ping time) when operating with bidirectional Isochronous design in mind. For example, i can send like 8-byte packets with timestamp inside from host pc, and recieve it back to measure RTT, just like in ICMP echo. I bought MEGA 2560 board yesterday for that purpose. I was quite interested - what numbers could i see and is it suitable for realtime operations where decision logic is offloaded from arduino to more powerful PCs\GPUs?

it is not exactly what you ask, but yesterday I tested the speed with this sketch:
void setup() {
  Serial.begin(460800);
  delay(5000);
}

void loop() {
  Serial.println();
  unsigned long start = millis();
  for (unsigned long i = 0; i < 1000000L; i++) {
    Serial.write('A');
  }
  Serial.flush();
  Serial.println();
  Serial.println(millis() - start);
  while(true);
}

to receive on linux to file:
stty -F /dev/ttyACM0 460800
(stty raw; cat > received.txt) < /dev/ttyACM0

the sketch measured 20000 ms to push that 1MB over Serial. the Arduino is Mega 2560. at 921600 baud not all data were transfered.
EDIT: Nano 328p clone with CH340 complete only at 230400 baud in 45000 ms

could you run some simple ping (RTT) test for me please? i have no platform by hands. test is the following: 1) arduino must send back just what it recieves, and 2) host runs clock_gettime() to get its current 64-bit timestamp and sends it to arduino, and 3) when it recieves timestamp difference (RTT) and displays it.

clock_gettime() has near microseconds precision so its would be good estimate of RTT for realtime application


text:
GPS not display
so im currently trying to do a a project whereby if my sensor is active, it will display my location. but, it seems that when the sensor is active, it only display location of lat: 0.00 , long: 0.00 on my LCD display.
help me to solve this problem.
#include <LiquidCrystal.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

SoftwareSerial mySerial(9,10);
char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int RXPin = 13, TXPin = 8;
static const int GPSBaud = 9600;
TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  mySerial.begin(19200);   // Setting the baud rate of GSM Module
  delay(20000);
  ss.begin(GPSBaud);
  Serial.begin(115200);
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);
  lcd.begin(16, 2);
  String latitude = String(gps.location.lat(),6);
  String longitude = String(gps.location.lng(),6);
      lcd.clear();
      lcd.setCursor(2,0);
      lcd.print("VeCAS System");
      lcd.setCursor(3,1);
      lcd.print(">>Begin>>");
      delay (5000);

}

void loop ()
{
  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      Serial.println("KNOCK, KNOCK");
      bAlarm = true;
      digitalWrite (6, HIGH);
      Serial.println(knockVal);
      delay(100);

      while (ss.available() > 0)
    gps.encode(ss.read());
    if (gps.location.isUpdated())
       lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();

    }
   }

 else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
      delay(100);
    }
   }
  }

void gpsTrack()
{
      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
      delay (5000);

          lcd.clear();
          Serial.print("Latitude= ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" Longitude= ");
          Serial.println(gps.location.lng(), 6);

          lcd.setCursor(0,0);
          lcd.print("LAT:");
          lcd.setCursor(5,0);
          lcd.print(gps.location.lat());
          lcd.setCursor(0,1);
          lcd.print("LON:");
          lcd.setCursor(5,1);
          lcd.print(gps.location.lng());
          delay(1000);
          lcd.clear();
}

If you put the GPS on Serial (pins 0 & 1) and the GSM on AltSoftSerial (pins 8 & 9), it could work.  You will have to disconnect pin 0 to upload new sketches over USB.  I assume that you have an UNO or Nano, because you didn't say which Arduino you are using.
Like Majenko said, this will never work with two SoftwareSerial ports.  SoftwareSerial is very inefficient, because it disables interrupts for long periods of time.  This can interfere with other parts of your sketch or with other libraries.  And it cannot send and receive at the same time.  This answer provides complete details.
You may also want to take a look at my NeoGPS library.  It is smaller, faster, more reliable and more accurate than all other GPS libraries.  Even if you don't use it, you should read the page about choosing a serial port.  There are also many tips on the Troubleshooting page.
NeoGPS, AltSoftSerial and NeoSWSerial are available from the IDE Library Manager, under the menu Sketch -> Include Library -> Manage Libraries.
BTW, you can't use delay like that.  You must constantly read and decode the GPS characters.  The sketch will lose many, many GPS characters, preventing it from ever getting complete GPS information.  You have to do something like this:
#include <LiquidCrystal.h>
#include <NMEAGPS.h>
#include <AltSoftSerial.h>

AltSoftSerial gsmPort; // receive pin 8 to GSM TX, transmit pin 9 to GSM RX

char msg;

int knockPin = 7;                   // Use Pin 7 as our Input
int knockVal = HIGH;                // This is where we record our shock measurement
boolean bAlarm = false;
int knockValue = digitalRead(6);
unsigned long lastKnockTime;        // Record the time that we measured a shock
int knockAlarmTime = 500;           // Number of milli seconds to keep the knock alarm high

static const int GPSBaud = 9600;
NMEAGPS gps;
gps_fix fix;
#define gpsPort Serial // RX pin 0 to GPS TX, TX pin 1 to GPS RX

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup ()
{
  gsmPort.begin(19200);   // Setting the baud rate of GSM Module

  gpsPort.begin(GPSBaud);
  //Serial.begin(115200);  // gpsPort *is* serial
  //  Serial Monitor has to be set at 9600 (lower right
  //    corner of Serial Monitor window)
  Serial.println("GSM SIM900A BEGIN");
  pinMode (knockPin, INPUT) ;       // input from the KY-031
  pinMode (6, OUTPUT);

  lcd.begin(16, 2);
  lcd.clear();
  lcd.setCursor(2,0);
  lcd.print("VeCAS System");
  lcd.setCursor(3,1);
  lcd.print(">>Begin>>");
  delay( 1000 );
}

void loop ()
{
  // Check for GPS characters (always!)
  if (gps.available( gpsPort )) {
    fix = gps.read(); // save the latest GPS fields in one structure
    gpsTrack();       // show the latest GPS fields
  }

  // Check for knocks

  knockVal = digitalRead (knockPin) ; // read KY-031 Value

  if (knockVal == LOW)                // If we see a knock
  {

    lastKnockTime = millis();         // record the time of the shock
                                      // The following is so you don't scroll on the output screen
    if (!bAlarm)
    {

      bAlarm = true;
      digitalWrite (6, HIGH);

      Serial.println("KNOCK, KNOCK");
      Serial.println(knockVal);

      lcd.clear();
      lcd.setCursor(4,0);
      lcd.print("KNOCK!");
      lcd.setCursor(3,1);
      lcd.print("Detected");
    }
  }
  else
  {
    if( (millis()-lastKnockTime) > knockAlarmTime  &&  bAlarm)
    {
      Serial.println("no knocks");
      bAlarm = false;
      digitalWrite (6, LOW);
    }
  }
}

void gpsTrack()
{
  Serial.print("Latitude= ");
  if (fix.valid.location)
    Serial.print( fix.latitude(), 6);
  Serial.print(" Longitude= ");
  if (fix.valid.location)
    Serial.println( fix.longitude(), 6);

  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("LAT:");
  lcd.setCursor(5,0);
  if (fix.valid.location)
    lcd.print( fix.latitude() );
  lcd.setCursor(0,1);
  lcd.print("LON:");
  lcd.setCursor(5,1);
  if (fix.valid.location)
    lcd.print( fix.longitude() );
}

Notice that it also checks the location validity flag before using the lat/lon values.  Your GPS may not know the location, perhaps due to bad satellite reception.

Thank you for ur answer. i am using board Uno. so i try to use ur code, but it wont work since it is board Uno.

Oh, yes, you must run your Serial Monitor at 9600, not 115200 (I edited that line above).  Then it will work on an UNO IF you connect the GPS to pins 0 & 1, as described.  It does not send/receive anything to the GSM, so that doesn't matter.  Read the link on "choosing a serial port".

I get this error message. Error compiling for board Arduino/Genuino Uno. why ? huhu

haha sorry i forgot to download the library.

You have two SoftwareSerial ports. You can't reliably use two of them at once. Only one can be set to receive data, and that one is the first one you define. You can switch between them with the listen() function, but it's not recommended.  If you never want to receive on one of them then it's (almost) fine, but when sending on any of them nothing can be received anywhere (not even on the hardware Serial port).
Adding to setup() after ss.begin(GPSBaud):
ss.listen();

may make it work for the time being, but as soon as you start doing anything more with mySerial you could run into trouble.
If you need more than one serial port in your design then you really should be looking at using a more capable board with more hardware UART ports.

yeah i try to put ss.listen(); after ss.begin(GPSBaud) but it error.


text:
How to prevent shoot-through when swiching a motor with a bridge?
Ideally, when wiring a motor with an H-Bridge one would ensure that all "open" operations are performed before and "close" operations in order to prevent a short circuit. How does one ensure that these operations are performed in order when using a bridge?
I see on some forums that the L298 IC is a recommended bridge for controlling motors with the Arduino, but this condition is seemingly never discussed. It is not an issue with the speed of modern ICs or are the common tutorials overlooking shoot-through in the interest of simplicity?

It's only an issue with discreet components when driving each part separately and manually. It's not an issue with a dedicated bridge chip.

Shoot through may be desirable when the H-bridge is fed from a constant current source to prevent interruption of that source. Does L298N allow this?

You only get this kind of problem when you are manually controlling the high- and low-side switches manually.  Bridge chips seldom make you do that and include the logic and drive circuitry within them so that you just control a HIGH or LOW to a "leg" and it switches the two transistors properly for you.
You normally get an "enable" and a "direction" input.
For instance, take the L298 internal circuit:

If we look at the left-most transistor pair you can see they are driven by a pair of gates. One has an inversion on the input.  The gates are mainly there to AND the enable signal in, but the inversion on the upper input of the lower gate is the vital thing. That makes sure that one transistor is on when another is off. You can't turn both on, or both off - you only have a single signal that indicates which should be on.
Of course, that circuit is very simplified, and there is additional circuitry that ensures that during the switching period one transistor switches off before the other switches on.  Matched transistors with known switching characteristics, adding offsets to the base voltages with diodes, etc are all methods that are used internally.
With MOSFET based bridges it's less of an issue since gate threshold (VGS) come into play and choosing and matching the transistors correctly automatically creates a "dead zone" in the switching input voltage range.

Thank you, examining the internal wiring diagram is helpful.


text:
Wiring parallel TFT with ESP32
I have this Parallel LCD TFT. I want to connect it with an ESP32 (NodeMCU). I am using the TFT_eSPI library.
In the TFT_eSPI documentation, it says that the connection should be as following:
// The ESP32 and TFT the pins used for testing are:
//#define TFT_CS   33  // Chip select control pin (library pulls permanently low
//#define TFT_DC   15  // Data Command control pin - use a pin in the range 0-31
//#define TFT_RST  32  // Reset pin, toggles on startup

//#define TFT_WR    4  // Write strobe control pin - use a pin in the range 0-31
//#define TFT_RD    2  // Read strobe control pin  - use a pin in the range 0-31
//#define TFT_D0   12  // Must use pins in the range 0-31 for the data bus
//#define TFT_D1   13  // so a single register write sets/clears all bits.
//#define TFT_D2   26  // Pins can be randomly assigned, this does not affect
//#define TFT_D3   25  // TFT screen update performance.
//#define TFT_D4   17
//#define TFT_D5   16
//#define TFT_D6   27
//#define TFT_D7   14

P.S. My tft does not have DC PIN. So, I wired nothing to GPIO15
After I wired the TFT, the ESP32 stop responding to flash process. and obviously, it did not run anything(even if I flash it without the screen and then wiring it again)
My question is:

What is the mistake did I do? How can I link this parallel LCD with ESP32

How did you wire the 5V pin of the display? When attached to an uno/mega2560 it gets power over this (and possibly the 3v3) pin.

DC is the same as RS (or LCD_RS on your board).

@LotPings External 5v power supply

Sorry for the Late reply, I had the same issue.
You cant have anything connected to pin 15 or 2 during flash


text:
Best method of detecting peg in hole
I’ve got a large wall with 1” holes scattered about. I’ve got some wooden pegs that fit perfectly into these holes. Now I’m thinking of creating a light installation based on the pegs, but i’m Struggling to find a way of detecting when a peg has been inserted into any hole.
What’s the best method of detecting them? I was thinking a stop switch that’s just placed on the edge of the hole to the peg activates it, but i’m Not sure how well that can be detected or if it would bend with use

Maybe photo interrupters, reflective photo interrupters or even switches

I prefer not using switches. Moving part will wear out over time.

do an image search for microswitch .... some are rated for more than 10 million operations

Thats the term – stop switch is just what it's used for the 3D printer here.  I think it's the most analog way of detecting it, which means it's the less complex of all the options

We can't tell you the "best" method.  It depends on too many details we don't have.
Here are some options:

A reed switch at the bottom of the hole and a magnet on the peg.
A photo sensor at the back of the hole -- the peg blocks the light.
As you suggest, a switch at the side of hole.
Use contrasting colors on the wall and the pegs and detect the pegs using a camera and some sort of image processing (not an Arduino solution)

I think you are going to need to build some prototypes and experiment to find the best option for you.

Reed switch might be an option, have to think of how this is mounted and how the peg has a magnet integrated, or maybe a line detector sensor and paint the pegs black in a similar vein to the colour detection?

Alternative for the reed-switch would be a hall-effect sensor. Alternative for the photo-sensor on both sides of the hole, would be to measure reflected light instead using e.g. a  TCRT5000.


text:
When to use PROGMEM?
I believe PROGMEM is used to store large data (e.g. strings) that don't change. So it frees up the SRAM.
in the Ardunio Reference it is mentioned that.
"Using PROGMEM is also a two-step procedure. After getting the data into Flash memory, it requires special methods (functions), also defined in the pgmspace.h library, to read the data from program memory back into SRAM, so we can do something useful with it."
If I have to load the data into SRAM before using it then how is it efficient than directly stroing into SRAM by defining vaiable normally

... Because it doesn't stay in SRAM...

Say you have a string of 1000 characters in Flash, and you want to print it to Serial.  Yes, you need to load it into RAM in order to pass that data around the place for printing. But, do you need to put all of it in RAM at once?  No.  You only need one character at a time.  So instead of taking 1000 characters and allocating 1000 bytes of RAM and copying the whole shebang into RAM then printing it, you just need to allocate 1 byte of RAM* and copy each character in turn and print it.
Since you can only read one character at a time from flash there's no advantage in reading the whole lot anyway.

*Actually, because of compiler optimizations, this probably never even touches RAM and just stays in a CPU register.

If you have a constant c-string (char array) in your code without F macro or progmem, then the string is copied into RAM at start an stays there.
If in a function you use the F macro or you create a char buffer of some size and copy the progmem string into the buffer, on function return the variables are deleted from stack and the memory is released.
In case of some big array, if you put it into progmem and then in the code when you need to lookup a value in that array, you need to copy to RAM only one array item at time not the whole array.

Like Majenko said, you do not need to put everything you have in flash storage into RAM at once.  You can move items into SRAM as necessary, and reuse the memory once you're done.
However, you are not limited to moving one byte at a time.  There are functions defined in avr/pgmspace.h that can handle moving data for you.
For instance, you could do something like:
const struct mystruct_s my_value PROGMEM = { value = 1234 };

// ...

struct mystruct_s working_copy;
memcpy_P(&working_copy, &my_value, sizeof(struct mystruct_s));
int foo = working_copy.value / 2;

At the expense of using more RAM. Even if on the stack it may be too much (worst case).


text:
How to listen to multiple server ports with ESP8266?
I'm using WeMos D1 R2. I'm trying to listen to both ports 1992 and 1993. This is my current code:

    #include
WiFiServer server_1992(1992);
WiFiServer server_1993(1993);

void setup() {
    Serial.begin(9600);
    WiFi.begin("MySSID", "MyPassword");
    while (WiFi.status() != WL_CONNECTED){
        delay(500);
        Serial.print(".");
    }
    Serial.println(" connected");

    server_1992.begin();
    server_1992.setNoDelay(true);
    server_1993.begin();
    server_1993.setNoDelay(true);
}

void check_server(WiFiClient* client, WiFiServer* server, const char* text){
    if (client->connected()) {
        if (client->available()){
            unsigned char c[250];
            client->readBytes(c, 1);
            Serial.print(c[0]);
            Serial.print(" ");
        }
    } else {
        client->stop(); //Adding it here like Juraj said. Not tested.
        *client = server->available();
        if (*client) Serial.print(text);
    }
}

void loop() {
    WiFiClient client_1992, client_1993;
    while (1){
        check_server(&client_1992, &server_1992, "1992 connected \n");
        check_server(&client_1993, &server_1993, "1993 connected \n");
    }
}

The problem is when the client(s) disconnect from the hotspot, my code keeps waiting for data forever without trying to acquire new client (with client = server->available();).
Solution: for now I ask the client "Hey are we still connected?" every few seconds and manually kick the client out if it doesn't reply.
More on this
Sorry if it's wrong to link other question here, I just hope people who have the same problem as mine can find the solution.

stop the client if it is not connected

If i understand it correctly, you mean close the client from the client side right (not the server side)?
The disconnection happens when my phone turn off / disconnect from wifi so I don't think I can close the connection properly?

no. stop the esp8266 side of the socket when it is not connected, before you ask if new client is available. there are more tcp states of the connection and after the client side disconnects, it is not established (what connected tests), but not closed either

I will test it when I can get back home, is it like the one I added to the code ?(before the *client = server->available();   )

yes, that is what I meant. I am not sure if it helps, so I do not write it as answer until you test it. I use extensively esp8266 from Atmega over WiFi Link at it has it's own tricks. there the stop() solves this kind of problem

Didn't work.It seems like "client->connected()" isn't doing too well checking the connection. The client->connected() seems to still think it's connected when I turn off my phone WiFi.

You could try to read all buffered data before stop(), because connected() checks if data are available in buffer: while (client.read() != -1);

It doesn't work.
For now I will use a timer to check if the client haven't sent any data in the last 10 seconds and kick the client out that way my server won't be stuck forever in the loop. Ugly solution.

it is not ugly for unexpected disconnections

Use the    client.status()    function to check if the client is connected
Returns 4 if connected and 0 if not
I don't have detailed information about its use and I found it by chance
You can check other output modes of this function
If you get any other information, please let me know.
void loop()
{

  WiFiClient client_8080;
  WiFiClient client_8081;

  delay(200);
  Serial.println(client_8080.status());
  Serial.println();
  Serial.println();

  while (1)
  {

    if(client_8080.connected())
    {

      delay(200);
      Serial.println(client_8080.status());
      Serial.println();
      Serial.println();

      while (client_8080.available())
      {

        delay(200);
        Serial.println(client_8080.status());
        Serial.println();
        Serial.println();

        Serial.print(client_8080.available());
        char Buffer_8080 = client_8080.read();
        Serial.println(Buffer_8080);
        client_8080.println(Buffer_8080);

      }

       while (Serial.available())
      {
        client_8080.print(Serial.available());
        client_8081.print(Serial.available());
        char Buffer_Serial = Serial.read();

        client_8080.println(Buffer_Serial);
        client_8081.println(Buffer_Serial);
      }

    }else if (!client_8080.connected())
    {

       Serial.println(client_8080.status());
       Serial.println();
       Serial.println();

      client_8080 = server1.available();

       Serial.println(client_8080.status());
       Serial.println();
       Serial.println();

      Serial.println("server lisening to port 8080 ");

    }

    //_______________________________________________

    if(client_8081.connected())
    {
      while (client_8081.available())
      {

        Serial.print(client_8081.available());
        char Buffer_8081 = client_8081.read();
        Serial.println(Buffer_8081);
        client_8081.println(Buffer_8081);

      }

      while (Serial.available())
      {
        client_8080.print(Serial.available());
        client_8081.print(Serial.available());
        char Buffer_Serial = Serial.read();

        client_8080.println(Buffer_Serial);
        client_8081.println(Buffer_Serial);
      }

    }else if (!client_8081.connected())
    {
      client_8081 = server2.available();

      Serial.println("server lisening to port 8081 ");

    }

  }
}


text:
Arduino String: use a non-null-terminated char array?
I'm using a library that takes a String as it's parameter (https://github.com/gmag11/painlessMesh)
I want to pass char arrays that is binary (UTF-8) data that also contains null-bytes (0x00). Right now, the resulting String is cut off at the first null-byte as expected. I know the full length of the char array, is it possible to construct an Arduino String while passing the arbitrary length, so that the full String also contains the null-bytes including the data that follows after, up until the pre-set length?
I had this problem before and then I solved it by converting the UTF-8 data to hex and then add a null-byte. I was hoping there is a more elegant way, since this forces me to double the data-size.
Thanks!

A "String" can't have null characters inside it, so why do you need to pass in data that is not a "String"? Is it because you need to send a message payload that is not a "String"?

The only zero byte the UTF-8 encoding produces is the null character. If the zero byte is anywhere but at the end, then it's not UTF-8.

@josecanuc I don't want to use a String, it's just that the library asks me to pass one.

Assuming you are talking about the function
bool painlessMesh::sendBroadcast( String &msg, bool includeSelf = false)

Then you'll see that ultimately, the library passes msg into the function buildMeshPackage where it constructs a JSON message (see here)
String ICACHE_FLASH_ATTR painlessMesh::buildMeshPackage(uint32_t destId, uint32_t fromId, meshPackageType type, String &msg) {
    debugMsg(GENERAL, "In buildMeshPackage(): msg=%s\n", msg.c_str());

    DynamicJsonBuffer jsonBuffer;
    JsonObject& root = jsonBuffer.createObject();
    root["dest"] = destId;
    //root["from"] = _nodeId;
    root["from"] = fromId;
    root["type"] = (uint8_t)type;

    switch (type) {
    case NODE_SYNC_REQUEST:
    case NODE_SYNC_REPLY:
    {
        JsonArray& subs = jsonBuffer.parseArray(msg);
        if (!subs.success()) {
            debugMsg(GENERAL, "buildMeshPackage(): subs = jsonBuffer.parseArray( msg ) failed!");
        }
        root["subs"] = subs;
        break;
    }
    case TIME_SYNC:
        root["msg"] = jsonBuffer.parseObject(msg);
        break;
    default:
        root["msg"] = msg;
    }

    String ret;
    root.printTo(ret);
    return ret;
}

Even if you did construct a String with null terminators in it, the moment it gets put into the JSON string it destroys everything. JSON by default doesn't support binary data strings (reference).
So, the library is a problem because it happily passes data as JSON messages, and that's bad if you want binary data transported. You could use Base64 or the more efficient http://base91.sourceforge.net/ encoding though to mitigate this a little bit, or search for a different lib.

Wow! Thanks for the fast answer. Alright, I guess I have to settle for non-binary then.. Thanks!

The key part of this answer is to encode your "binary" data. This has been done for ages, and email messages still commonly have base64-encoded "text" for binary file attachments. If the framework takes Strings, then you must convert your binary data to something that looks like a string.

I would've upvoted your answer if I could :) (low rep blocks that at the moment)


text:
TMP36 not working with arduino uno?
I have an Arduino Uno hooked up with a TMP36 and an ESP8266 to send the temperature reading to a PHP file which receives the post request and stores it in a text file.
The ESP8266 and PHP works fine and I'm positive of that. But the temperature my code gets are ridiculous and change a lot. I'll include my code and a Fritzing sketch and the URL to the data.txt (you can see the results real time). It might be a problem with my code or something else I'm not sure I've fiddled around to no success and hopefully some fresh eyes will help.

Most of the code is copypasta as I've never used ESP8266 before.
#include "SoftwareSerial.h"

String ssid ="correctssid";
String password="correctpwd";

float val=0;
int temppin = 2;
float volts=0.0;
float tempC=0.0;

SoftwareSerial esp(6, 7);

String data;
String server = "www.elijahdur.co.uk";
String url = "/arduino/esp8266/file.php"; //I've changed this just well because

void setup() {
  esp.begin(9600);
  Serial.begin(9600);
  reset();
  connectWifi();
}

void reset() {
  esp.println("AT+RST");
  delay(1000);
  if(esp.find("OK") ){
    Serial.println("Module Reset");
  }
}

void connectWifi() {
  String cmd = "AT+CWJAP=\"" +ssid+"\",\"" + password + "\"";
  esp.println(cmd);
  delay(4000);

  if(esp.find("OK")) {
    Serial.println("Connected!");
  }

  else {
    connectWifi();
    Serial.println("Cannot connect to wifi");
  }
}

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

void httppost () {
  esp.println("AT+CIPSTART=\"TCP\",\"" + server + "\",80");//start a TCP connection.

  if( esp.find("OK")) {
    Serial.println("TCP connection ready");
  }

  delay(1000);

  String postRequest =
  "POST " + url + " HTTP/1.0\r\n" +
  "Host: " + server + "\r\n" +
  "Accept: *" + "/" + "*\r\n" +
  "Content-Length: " + data.length() + "\r\n" +
  "Content-Type: application/x-www-form-urlencoded\r\n" +
  "\r\n" + data;

  String sendCmd = "AT+CIPSEND=";//determine the number of caracters to be sent.

  esp.print(sendCmd);
  esp.println(postRequest.length());

  delay(500);

  if(esp.find(">")) {
    Serial.println("Sending..");
    esp.print(postRequest);
  }

  if( esp.find("SEND OK")) {
    Serial.println("Packet sent");
  }

  while (esp.available()) {
    String tmpResp = esp.readString();
    Serial.println(tmpResp);
  }

  esp.println("AT+CIPCLOSE");

}

The txt file is located at http://elijahdur.co.uk/arduino/esp8266/data.txt
Sometimes is will straight up give -50 and it's because it reads 0 and takes away the 5V from the analog.
Any help is greatly appreciated thank you!
EDIT: Apologies, but I had mixed up my sensors and was using an LM35, it still does not work however so I'm still stuck :/

Have you tested the temperature sensor by itself, without the ESP8266?

First off, as a general debugging tip: Always use a minimal example to only test one component to make sure it works. You should have tested the temperature sensor on its own, then the ESP8266 WiFi connection.
Second, regarding this code:
  /* as global variable */
  float val=0;

void loop () {
  val = analogRead(temppin);
  volts = val * 5.0;
  volts /= 1024.0;
  tempC = (volts - 0.5) * 100;

  String string = (String) tempC;
  data = "data=" + string;
  httppost();

  delay(30000);
}

The line String string = (String) tempC; looks very suspicious to me. You are casting a float to a String object, i.e., you re-interpret it with a cast operator. That should not work because a float is not a String object.
What should work is creating a new String object using its constructor, i.e., write
 String string(tempC);

If this is does not work, use the sketch at https://learn.adafruit.com/tmp36-temperature-sensor/using-a-temp-sensor, change sensorPin to 2, double check your wiring and remove the ESP8266.
And as 3rd note: You are hooking up your Arduino's TX directly to the ESP8266's RX pin, according to your schematic. This will damage the ESP8266 module, because it is a 3.3V device and should only receive 3.3V signals -- your Arduino Uno outputs 5V as a logic 'high'. You need a voltage divider or a logic level shifter between them.

Thanks, as i edited i was actually using an LM35 (apologies) but it still doesnt work and i get results like these https://hastebin.com/isifakiwef.ini. That is with 5 second intervals and they seem just to bounce between 0 and 40?

I changed around some cables and now i consistently get 120C, what on earth is happening? I thought this could be fahrenheit but thats still 46C?

@ElijahD-R Did change GND and VCC? Reverse polarity kills your sensor. You seem to be confused about your sensor. Are you absolutely sure it's an LM35 and no TMP36? Can you edit the question to show a picture and your current code? Does this example sketch work for you?

I'm going to say that I probably at one point reversed the polarity... Time to find a new temperature sensor, got any recommendations?

Pretty much any 'Arduino' labeled temperature sensor works, if you don't special requirements on temperature range or accuracy. Maybe something like a DHT11, DHT22 will work for you too? Your old sensor type would also be okay, just make sure you've got the wiring correct and run a minimal test sketch as first thing.

If you don't need the arduino for learning purposes you could also just get a module for the ESP8266-01 with a DHT-11 for less than $5 and program the ESP8266 directly

This instructables does the TMP36 part very similar using tempPin=0 instead 2 ,
I'd try that code because there shouldn't be a negative value as long you are measuring room temperate and the TMP36 is not defective.
According to these curves

and table from the TMP35/36/37 data sheet

you should measure 700-750mV (with VS 3V)

Your coment suddenly vanished partly. If the returned voltage is lower than expected, could it possibly be a TMP35/37 sensor and not a TMP36?

Apologies, i just noticed its a LM35 and the sheet i was given with my package was incorrect (it was a bundle and in my box it said TMP36 and online it says LM35)

I'm now using some LM35 code but i still get fluctations? https://hastebin.com/okakudifel.makefile The first number is the number recorded by analogRead and the second one is when that is multiplied by 0.48828125.

The analogread should return an integer between 0 and 1023 for voltages between 0V and 5 V the diagram is for a Vs of 3V. What do the readings say if output to serial?


text:
USB upload to Pro Micro (32u4)
My project is based around the ATMEGA32u4 microcontroller.
I followed the Arduino Pro Micro schematic to design my own board layout and build a custom PCB, soldered on the components.  Then I used the Arduino IDE to successfully upload the Arduino bootloader with SPI.
Currently I can also upload programs to my `32u4 over SPI (using "in-serial programming").  Tested that with Blink.
But I cannot upload programs with the USB, like you would normally be able to do with a Pro Micro.  What things should I look for to debug this?
avrdude: Version 6.3, compiled on Jan 17 2017 at 12:00:53
     Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
     Copyright (c) 2007-2014 Joerg Wunsch

     System wide configuration file is "C:\Users\Myname\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino9/etc/avrdude.conf"

     Using Port                    : COM12
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

When you program the blink sketch using ISP, you overwrite the bootloader!!! Did you set the correct fuses? How did you program the bootloader?

Oh, I did not know that.  I used an Arduino UNO as a SPI master to upload the bootloader to my 32u4.  After that I uploaded a blink sketch the same way.  I will try uploading the bootloader again and then the sketch via USB.

Yes, that worked.  Thanks, would have taken me a long time to work that out.  I will post a reply.

It’s one of those gotchas. Glad you got it working now.

The answer, as kindly pointed out by Gerben, is that ISP program upload overwrites the bootloader.
Only upload the bootloader via ISP, then switch to USB for uploading Arduino sketches.


text:
ESP8266 check if TCP client disconnected...informally
Hi with ESP8266WiFi library, I usually check for connection of a TCP client with client.connected().
But it seems to still return true if my TCP client in an unexpected way (like disconnect to WiFi/ Power loss/...). Which leaves my program stuck in a infinite loop.
Is there a more reliable to check for connection status?

You have the inherent problem that a TCP connection is terminated by an explicit "FIN" message from the terminating party, followed by a FIN-ACK and ACK.

Refer to here.
If your client (or server) just powers off without closing the connection properly, that's it. The connection hangs up and no data will be transfered if it is not explicitly handled.
If you must know whether the client is still there, you must use a heartbeat meachanism. That is, after some period time without a response has passed, query the connection party with a "heartbeat" message and see if it responds after a given maximum time. The other way around would be to make the client send a periodic "Keep Alive" message which holds up the connection as long as it is sent repeadetly.
Refer to here and here.

Thank to your answer I understood the general idea.  I can't find any way to check for the KeepAlive message in the ESP8266 library. So I manually send data to client after x idle seconds, close the connection if the client doesn't reply. On the back of my mind I feel like there would be an built-in way to do this, is there?

@MoonFan I couldn't easy find a general piece of code that does it in all cases. You'll have to implement one yourself using a timer to keep track of timestamps (last message received / sent, ...). Besides millis you could a more sophisticated timer library.


text:
Why call a USB connection a serial connection?
Does anyone know why Arduino calls a USB connection a serial? When I hear a serial connection I automatically think of a male pin connection and not a USB connection. Also not sure if this a Linux term or just an Arduino thing.

Where did you get the association of "serial" with "male pin connection" from?

Serial Cable, DB9/DB9 Male to Female Cable https://en.wikipedia.org/wiki/D-subminiature

Universal Serial Bus.......................................

universal SERIAL bus

As @ratchetfreak answered, USB is a Serial bus. But there is more.
The microcontroller on Arduino boards has one or more built-in peripherals called UARTs, which stands for Universal Asynchronous Receiver-Transmitter.
This is what the Arduino core calls a Serial port. It uses the same kind of protocol as the old DB-9 serial ports on PCs and such, but at 5V or 3.3V logic levels. Contrast this 0V to 5V voltage swing to indicate Logic LOW and Logic HIGH with the RS-232 standard for the old PC serial ports, which use a +12V to -12V swing to indicate such.
But PCs today don't often have the old RS-232 serial port. They instead have the new USB - Universal Serial Bus - port. On the Arduino board is chip that communicates on one side via USB with the PC and tells the PC that it provides the equivalent of the old COMPORT or /dev/ttyS* serial device; and on the other side via UART with the microcontroller on the Arduino board.
It's like we are "emulating" the old PC serial ports in software over the new USB bus, which itself is a serial communication system, though much more complex than a plain UART.

and on Atmegas with native USB support the singleton object is called SerialUSB

On most Arduinos Serial is not a USB connection. It is a UART (real serial) connection which is used to communicate with a USB to UART adaptor (often made out of another small MCU, the ATMega16U2).  It's only from that chip onwards that it is USB.  Between the main MCU and that USB interface chip it is serial. The same serial you get from pins 0/1 (literally: it's hardwired together).
Indeed, the first Arduino prototype (that grew out of the Wiring project) had no USB at all - only Serial. The USB to UART adaptor was added later. But it still remains a Serial interface.

Almost all the ways protocols used to communicate on arduino are Serial.  USB,UART, I2C, SPI. Serial means one bit at a time, then the other way is Parallel communication which is what printers used to use. This allowed a whole byte to sent at one time(there were 8 data lines). As clock speeds increased there was no longer a need to have these big bulky,expensive cables and connectors. So away went parallel connections from common computer/electronics applications.

MMIO also uses parallel communications.

Yes, and there are many applications were parallel communication is still used, espessically between devices 'inside' a computer where you need to send a lot of data really fast.  And I am sure its still used with external devices to some extent. I was just saying that it went away as a 'normal' way of connecting external devices.