text:
How to calculate battery usage of my arduino project?
I want to measure power consumption and calculate the mAH value to know how much time would my battery can run the circuit.
I only got a multimeter and DC power supply.(Im not sure if this is enough to measure)
My project has a temp sensor and measures it every 15 mins. It's going to deep sleep mode and wakes up again to measure.
So how to measure the mAH for this circiut?

Depending on the model in question, the Arduino can be horribly inefficient. You are better off using the IC without all the funky stuff around. I recommend you to read Nick Gammons posts on power saving and power budget computation. Most Time you can estimate the power consumption from the datasheets and the up-time.

Can you measure the duration of the measurement while waking up?

A good answer to your question (as asked) has been offered. But maybe there's unasked question: "How can I get the maximum run time"? For that, we'd need to know what board you're using. Uno, f/ex, uses a lossy power supply that is on all the time, even during sleep, so sleeping won't help much. If you build a board with an efficient power supply, or use an off-board, efficient power supply that completely bypasses the Uno's(?) on-board one, you can do very much better. If you add more of those details, we could help you more.

I suggest using a second Arduino to make yourself an "Energy Meter".
Get a very small power resistor (0.1 Ohm) and power your project through it.
Second Arduino will measure voltage drop on it and that way you can get the current that goes through it using Ohms law. You can also measure the battery/power supply  voltage. Knowing those two values and micros each loop you can calculate actual hourly power consumption of the device.

Use the multimeter to measure the current. Put it in mA current mode, and wire it in series from the DC power supply + to the Arduino positive connection. With an Uno, readings will likly be in the 10s of mA all the time, and maybe a little higher when not in deep sleep mode. This assumes you are not powering the Uno from the USB port.


text:
Read Serial data from an arduino with c code
I am trying to receive data through the serial port from my SBC (a TS-7200), i am working with linux and handle serial communication using C/C++.To send data to the SBC  i'am using an arduino uno.
So basically the arduino is printing ASCII text data through Pin1 (Hardware Serial) in a loop with a 3ms delay.
From the SBC i read raw data in no canonical mode, ( in the code below are the parameters and configurations for the serial port) i'am trying to read one characters at a time, following the example from this page :
https:/ from this page/chrisheydrick.com/2012/06/17/how-to-read-serial-data-from-an-arduino-in-linux-with-c-part-3/.
but when i run the code it print the number 2 as 3, and the number 3 as f, I am not able to read ASCII characters.
I have tried several things but I have not been able to find the problem, Hope someone can help me.
Here is the Arduino code:
 #include <SoftwareSerial.h>
 SoftwareSerial mySerial(2,3); // RX, TX

 void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);

  }

 void loop() {

   Serial.print(2);

   delay(3000);

   Serial.print(3);

   delay(3000);

}

The c code from the linux side:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <termios.h>

char *portname = "/dev/ttyAM1";
char buf[256];

int main(int argc, char *argv[])
{
  int fd,stop = 0;

/* Open the file descriptor in non-blocking mode */
fd = open(portname, O_RDWR | O_NOCTTY);

/* Set up the control structure */
struct termios toptions;

/* Get currently set options for the tty */
tcgetattr(fd, &toptions);

/* Set custom options */

/* 9600 baud */
cfsetispeed(&toptions, B9600);
cfsetospeed(&toptions, B9600);
/* 8 bits, no parity, no stop bits */
toptions.c_cflag &= ~PARENB;
toptions.c_cflag &= ~CSTOPB;
toptions.c_cflag &= ~CSIZE;
toptions.c_cflag |= CS8;
/* no hardware flow control */
toptions.c_cflag &= ~CRTSCTS;
/* enable receiver, ignore status lines */
toptions.c_cflag |= CREAD | CLOCAL;
/* disable input/output flow control, disable restart chars */
toptions.c_iflag &= ~(IXON | IXOFF | IXANY);
/* disable canonical input, disable echo,
   disable visually erase chars,
   disable terminal-generated signals */
toptions.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
/* disable output processing */
toptions.c_oflag &= ~OPOST;

/* wait for 1 character to come in before read returns */
/* WARNING! THIS CAUSES THE read() TO BLOCK UNTIL ALL */
/* CHARACTERS HAVE COME IN! */
toptions.c_cc[VMIN] = 1;
/* no minimum time to wait before read returns */
toptions.c_cc[VTIME] = 0;

/* commit the options */
tcsetattr(fd, TCSANOW, &toptions);

/* Wait for the Arduino to reset */
usleep(1000*1000);
/* Flush anything already in the serial buffer */
tcflush(fd, TCIFLUSH);

while(stop == 0){

  /* read up to 128 bytes from the fd */
  int n = read(fd, &buf, 128);
  usleep(3000*1000);
  /* print how many bytes read */
  printf("%i bytes got read...\n", n);
  /* print what's in the buffer */
  printf("Buffer contains...\n%s\n", buf);
 }
 return 0;
}

This is what i see:
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3
2 bytes got read...
Buffer contains...
f
2 bytes got read...
Buffer contains...
3

has the TS-7200 a TTL Serial interface?

Hello Juraj,  no, it doesn't have a TTL  interface, only have 3 serial interface :
ttyAM0 (COM1), ttyAM1 (COM2), ttyAM2 (COM3) .

then how do you wire it to TTL Serial pin on Arduino?

I have a db9 connector, connected to the serial port COM2 of the SBC, using the r232 pinout. The transmition pin1 of the arduino (TXD) is connected to pin2 (RXD) of the db9 connector and the ground pin5 connected to the ground of the arduino .

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.

Thank you very much jose can u c, that was the problem.

RS232 uses +/- 12V (or sometimes +/- 5V), and is not compatible with TTL Serial, which uses 0V/5V. Also +12V in RS232 represents 0 and -12V represents 1; inverted from normal TTL.

source: Stack Exchange

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

sort: votes


text:
How to write http response from HttpClient to Serial monitor with a ESP32 (Wemos Lolin32)?
With my ESP32 Board, Wemos Lolin32, I would like to make a http GET request to "http://www.arduino.cc/asciilogo.txt", read the text file and print the text file to the serial monitor.
The question is: Why isn't basically the txt file written to the serial monitor? How can it be achieved? Do I need some kind of conversion of the char?
I am using similar code to that from this example https://www.arduino.cc/en/Tutorial/HttpClient.
Basically the code can be reduced to this minimal example:
#include <WiFi.h>
#include <HttpClient.h>

void setup() {

  Serial.begin(9600);

  WiFi.begin(ssid, password);
  Serial.println("Connecting to WiFi..");
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println(".");
  }
  Serial.println("Connected to the WiFi network");

  pinMode(LED_BUILTIN, OUTPUT);
  Serial.println("SETUP FINISHED");
}

void loop() {
  Serial.println("Connecting to httpClient");

 HttpClient httpClient;
  httpClient.get("http://arduino.cc/asciilogo.txt");
  while (httpClient.available()) {
    char c = httpClient.read();
    //Serial.print(c);
    Serial.write(c);
  }
}

The expected result is: I would like to see the characters from the txt file (https://www.arduino.cc/asciilogo.txt) in the serial monitor.
The actual result is: The connection to the WiFi can be established. In the serial monitor either question marks or strange symbols are displayed.
I have checked the baud and it is the same in the code and in the monitor. I tried to change this value, but it did not help.

When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.

it is http://arduino.cc/asciilogo.txt. without www. www is redirected to https. you can verify it from a browser

I have edited the URL, the result is the same.

Serial.write(c); if you read raw byte, then write raw byte. print converts number to text

The server also gzip encodes the content. He needs to add a Accept-Encoding: identity header.

Unfortunately it does not work.

Yes, I did change it to Serial.write(c);

It is pretty strange. Serial.write(c) and Serial.print(c) are producing exactly the same output.

When switching from HttpClient to HTTPClient and using String payload = http.getString(); Serial.println(payload); I can achieve the expected result.

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

@MichelKeijzers, there is no link. it is the right URL to use in the sketch in question

@Juraj ... sorry I am wrong; I was under assumption the link itself was the answer. Upvoted instead now :-)

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


text:
Trigger cheap wireless doorbell
I would like to trigger a simple wireless doorbell.
The doorbell uses 433Mhz. To read and send signals I am using the FS1000A Set (sender and receiver).
I've started by connecting the receiver to the Arduino and afterwards I uploaded the ReceiveDemo_Advanced (RCSwitch library). If I press the Doorbell Button it ouputs:
 Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 708 microseconds Protocol: 2
Raw data: 7272,444,1612,1464,588,1464,588,1464,588,440,1612,1472,568,1476,580,456,1596,452,1600,1476,580,1472,580,1468,584,444,1608,444,1608,448,1608,1464,584,1468,584,448,1608,444,1608,440,1608,448,1604,1472,584,444,1608,1468,584,1464,588,1464,592,440,1612,1464,588,444,1608,440,1612,1464,588,1464,600,

Decimal: 1987151104 (32Bit) Binary: 01110110011100011000010100000000 Tri-State: not applicable PulseLength: 727 microseconds Protocol: 2
Raw data: 7268,448,1604,1472,584,1468,580,1472,584,444,1608,1472,584,1468,588,444,1604,444,1608,1468,584,1472,588,1460,592,436,1616,440,1608,444,1608,1464,592,1464,588,440,1612,440,1612,440,1608,444,1608,1472,584,444,1608,1468,584,1468,588,1464,588,440,1612,1464,592,436,1612,440,1612,1464,592,1460,600,

Decimal: 1987151315 (32Bit) Binary: 01110110011100011000010111010011 Tri-State: not applicable PulseLength: 726 microseconds Protocol: 2
Raw data: 7272,444,1604,1472,584,1468,580,1468,588,444,1608,1468,588,1460,592,440,1612,440,1612,1464,588,1464,592,1460,592,436,1612,440,1616,436,1612,1468,584,1468,584,444,1608,444,1608,444,1608,444,1612,1464,584,444,1608,1468,584,1468,588,1460,588,444,1612,1464,592,436,1608,444,1612,1464,592,1460,600,

Now I am trying to send the signal via the FS1000A Set to the "Doorbell Receiver" but nothing happens. I tried it via the Binary send and via the Decimal send method. But the "Doorbell Receiver" remains silent.
Please help me!

go here https://test.sui.li/oszi/ and paste the raw data .... paste each raw data group separately .... you will see that the second binary: does not match

if you have two arduinos, then transmit the RF code from one arduino and receive on the other arduino .... see if the RF code matches what the doorbell button transmits


text:
Powering LED strips with two power banks and they randomly change different colors when i use the second power bank
So for one of my projects i want to power LED strips with power banks but once i try use the second power bank the LEDs half way through patterns jump to random different colors and then go back to the code im using to make sure they work, I dont think its a code issue as when i plug the power into my MEGA it works fine. I would use the MEGA to power the strips but i need 3 power sources to keep my strips at maximum brightness. would this be a voltage drop issue?
When I connected it to my 3 usb port power bank it works perfectly fine so it might be different currents causing it to jump im not to sure if im correct but its definitely something to do with using another power supply is causing my LEDs to randomly change multiple different colors randomly i just cant see if its a current or voltage issue. Any help would be greatly appreciated.
block diagram link

Greg, we don't know how to answer this. It can be many things. For example the GND level could be lifted by the extra power bank causing the data to turn into noise. This website is about questions and answers. You can update your question, but please remove your answer if it is not an answer.

Schematic or other wiring diagram?

Sorry my last link wasnt working heres a block diagram of what ive wired up so far link

You should embed the image / diagram in your question. Your link is not public.

https://drive.google.com/file/d/1-EDED7WAER_BU6tCumgxvPttGHeGSt7O/view?usp=sharing here is a public link sorry i though i made it public my apologizes the P1,P2,P3,P4 are the power bank ports

you need include the drawing of your circuit in your question, not in a comment.

These are USB power-banks? You need a way to tie the grounds together somehow. Try tying all the ground lines from your LED strips together and also connecting a wire from one of the LED strips to a ground line on your Arduino.
The USB connections should connect ground between the power bank and the device it's connected to, so by tying the grounds on the LED strips together, that should connect the grounds on the power banks as well.

Duncan that was the issue making the power bank and the LEDs their separate common GNDs fixed the random lightning of LEDs thank you so much!!!

Glad I could help. You still need to add your drawing to your question though.


text:
Nodemcu + GSM IOT-GA6
I've connected my NodeMCU to GSM module using GND, RX and TX.
I use At Comand Tester. When I try to get sim status or something I get error for example:

Unable to get Sim status.

Only AT comand returns

AT
OK

When I send any AT comand to GSM module I can see that the diode on the module blink.
How can I solve this problem?
Let me know if you need more informations to help me.

Please, post your full code, schematic circuit (also a picture if you want) and GSM module model.

Gsm module is in the post's title. If I test with at comands it means that I don't have any code. Pictures I will add as soon as it is possible

link I'm trying to use this module

I mean, what sketch are you upload on NodeMCU board?

I have't uploaded anything


text:
Arduino Analog pins go all to high problem
I was taking measures from the  outputs of an OpAmp when all the sudden measure 5 volts from all pins of the Arduino Mega for no reason. I disconnected the Arduino and loaded the Firmata and test. All the pins are reading high to 1023.. 5 volts are been output for no reason even when I have the Analog Ping to input.
Sketches code are loading and the lights look normal. I did noticed the processor chip getting hot and the voltage in the breadboard line to the Arduino Analog pins reading 7 volts.
Is this a sign of a serious damaged to my device?

Probably. It should not get hot. Was something connected to the pins that draws so much current that it could get hot? What are the power voltages for the OpAmp? Higher than 5v?

I doubt. A voltmeter the same output line from the OpAmp read 7 volts. But the reading returned to normal 35 ml after  disconnecting the wiring to the  arduino analog  pin. Also, only 3 of the pins where connected to OpAmp device measuring input voltage, output and the ground.  All the arduino pins ( except A0) are stuck in HIGH.

The voltage of the atmega2560 can be -0.5v to +5.5v when the atmega2560 is powered with 5.0v. A voltage of 7v might damage it. It is possible to blow only a part of the chip. When you are sure that al least one pin is blown, then you should get rid of it because it is possible that other parts inside the chip are damaged as well. I'm still not 100% sure that the chip is damaged, because when uploading a sketch, pin 0 and 1 must be working.

Can this chip me removed and replaced easily? Please point to any source to this repair surgery.

Ask someone with smd soldering skills, but it is a large chip which makes it very hard. What was the cause? How did the 7V get to the pins of the atmega2560? A 5v opamp with rail-to-rail output is no problem. When using higher voltages, a voltage divider or protection resistor should be used.

That is exactly what puzzles me. First I was using an old OpAmp which is a NOT rail to rail operating under  a -12 to + 12  power supply. I had everything set up to amplified a small mV signals to a range of o to 5 V.  This last was going to Arduino Analog Pin.  Is ther any possibility that the USB power line from computer to Arduino spikes to 7 volts? Or this was something that got crossed at the OpAmp beardboard?

A USB port does not spike to 7v, so it must be something at the breadboard. For the atmega microcontroller it is allowed to push 1mA into a pin. It can be more but that is not specified, it might be in the range of 5mA continous and 20mA peak (just a wild guess). For example a protection resistor of 4k7 to a analog pin input will protect up to 10.2v (and a lot more when using the unspecified numbers). Just a simple protection resistor can prevent a lot of problems and it introduces only a little more noise and a little more inaccuracy.

@jot please change your comment to an answer to up-vote you accordingly

A high voltage at a pin can damage the microcontroller partially.
The ATtiny microcontrollers can sometimes survive a voltage of 7 V.
The ATmega microcontrollers are damaged by that voltage.
The ATmega2560 is older and even more critical with voltages, it can not work at 16 MHz below 4.5 V and gets easily damaged with voltages above 6 V.
When the microcontroller runs at 5.0 V, a input pin can have -0.5 V to +5.5 V.
When the microcontroller gets damaged, it can be damaged partially. It is impossible to determine which parts of the chip are still okay. Therefor a partially damaged microcontroller should not be used anymore.
Solution:
A simple solution is a protection resistor in the signal path to the analog input.

simulate this circuit – Schematic created using CircuitLab
According to application note AVR182, it is allowed to push 1 mA into a pin or pull 1 mA from a pin for the ATmega microcontrollers. That current flows via the internal ESD diodes to VCC or from GND.
With a protection resistor of 4k7 before an input, the microcontroller is protected up to: 1mA * 4k7 + 5.5V = 10.2 V.
The internal ESD diodes can have more than 1 mA, but the maximum is unspecified. It is also dangerous when for example the ATmega is put into sleep mode. Then the 1 mA can lift the VCC voltage and still damage the ATmega microcontroller.
When a voltage divider is used (two resistors, R1 and R2) and the internal reference is used, then the voltage divider can be designed to be protected against very high voltages. For example with a ATmega2560, internal reference of 2.56V, R1=47k, R2=10k. This can measure up to 14.6 V and be protected up to 78 V.

My understanding is that the ATmega implements sleep mode by gating the clock, with Vcc still applied to the whole chip.

@EdgarBonet yes, so a current pushed into a analog or digital pin can lift the vcc above 5v (if the voltage has nowhere else to go), and can damage the chip. Should I explain it better?


text:
SOLVED: Strange phenomenon with avrdude: stk500v2_ReceiveMessage(): timeout only with ATmega250 on windows 7x64
I know this problem has been reported multiple times but in my case I think there is a different light on it.
My desktop is a w7x64 box and I also have a notebook with w10.
Both system have the arduino IDE 1.8.5 with the latest updates.
The desktop though has more boards and drivers as it is my main development system.
I have at ATmega2560 clone with CH340 which used to work on my desktop about half a year ago when I tried to get an LCD touch shield to work.
Yesterday I tried to resume on it and I got the ubiquitous timeout error.
So I removed the shield and tried the basic blink sketch but no change.
I tried an arduino nano and there was no problem to upload the blink sketch.
Then I tried different USB cables and ports but the timeout problem with the ATmega persisted.
So I went to the notebook and the ATmega worked like a charm.
Now I know that the board is ok as well as the cable.
The port is also ok as the nano worked on it smoothly.
I also tried the upload from an elevated command prompt with the verbose option but it gave me no further clue.
The output is below:
C:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/bin/avrdude -vvvv -CC:\Users\Pete\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino14/etc/avrdude.conf -v -patmega2560 -cstk500v2 -PCOM34 -b57600 -D -Uflash:w:T:\TMP\arduino_build_330193/Blink.ino.hex:i

avrdude: Version 6.3-20171130
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

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

         Using Port                    : COM34
         Using Programmer              : stk500v2
         Overriding Baud Rate          : 57600
STK500V2: stk500v2_open()
STK500V2: stk500v2_getsync()
STK500V2: stk500v2_send(0x1b 0x01 0x00 0x01 0x0e 0x01 0x14 , 7)
avrdude: Send: . [1b] . [01] . [00] . [01] . [0e] . [01] . [14]
STK500V2: stk500v2_recv(): avrdude: ser_recv(): programmer is not responding
avrdude: stk500v2_ReceiveMessage(): timeout

Does anybody have an idea how to further tackle the problem?

Is there a reason to stay behind with an old version? There has been problems with the version from the Microsoft Store. Try to remove the old version and install the newest: https://www.arduino.cc/en/Main/Software It is possible that the usb-serial drivers have a problem, perhaps you can try to remove them before installing the new version. It is also possible that there is a problem with the hidden "Arduino15" folder. You can delete that folder before installing a new version.

if you upload a sketch that prints on Serial, does it print to Serial Monitor on your desktop?

I downloaded the 1.8.8 release of the arduino IDE but the version of avrdude is the same as on 1.8.6. Thus the command line output does show the same timeout problem as before. As I said the Nano works without problems. It can print on serial too. The Mega does not upload and the print on serial is not working on the desktop. On the notebook there is no problem printing on serial.

I found the problem coming from a mismatch of the port speed setting and the baudrate in the avrdude command.
It seems that the ATmega is very sensitive to timing issues.
After I did set everything to 115200 it works on my w7 box like on the notebook.

where did you set the baud rate? avrdude sets the baud rate


text:
How can I power up my Arduino Nano for project of Rocket Data logging?
I am building a Model Rocket for which I need arduino nano to log data.But,I dont know how to power it up once it goes off the ground.Can anyone explain?

How about a lithium battery?  They are very light and have enough voltage (~4 V)

Yup,I heard of them but real problem is I really don't know anything.I am absolute beginner.Can you help me ?Can you help me how to connect battery and arduino either nano or micro or esp8266?I need to consider weight factor also to lift the rocket.So,with minimum weight and maximum efficiency which is better?


text:
Arduino, RS232 and SIM800L EVB 2.0 (not responding on AT command)
I buy a SIM800L EVB 2.0 modul for Arduino (https://www.aliexpress.com/item/SIM800L-V2-0-5V-Wireless-GSM-GPRS-MODULE-Quad-Band-W-Antenna-Cable-Cap/32465337183.html).
First I tested modul with all pins connect to Arduino. Modul successfully response on AT commands (but not register on network).
Next day is the same. So I connect modul +5V and GND to external power supply with 1000uF capacitor (as in comments on Aliexpress). Modul successfully connected to the network - my GSM number was accessible) (additional GND pin on modul I connect to Arduino GND on digital GND pin).
But modul is not longer respoding on AT command.
So I tested with USB - serial cable (pin 2 and 3 with GND 5) - modul register on network, but not response on AT command (tested via Putty with different baud speed) - no answer.
What else can I try? How to tested if Rx and Tx on modul works or how to know if I accident burned pins on modul or Arduino or USB-serial cable.
Thanks for every reply.

RS232 is where here? in setup with external power supply, did you connect the ground between Arduino and the module?

My mistake -  I thought serial cable for PC (USB). Yes I connect GND modul with Arduino and with power supply.

USB is different then RS232 and both are different from TTL-Serial on Arduino and module. you should not wire USB to TTL-Serial

Ok tnx for explanation. I add additional test with Arduino and SIM800L.
Digital PIN 10 and 11 is fine - I try with other modul and it's working. So how to test Rx and Tx pins on SIM modul. I measured pin with voltmeter - one is 5V, other is 2.5V. Normal?

We've solved the problem (my firends) - one of the transistor on the modul was broken. Now works fine.

I burned out 2 of mine just few minutes ago after connecting to my ESP8266 NodeMCU's UART0, not sure about why, it is really weird. My ESP 8266 have a 3.3V UART0, no way to burn this 5V module out


text:
Replace mechanical switch with electrical switch or relay
I have a remote controller for a portable heater, and working on a small project to be able to control the fan on/off from an arduino with Bluetooh HM-10 module. I thought a solenoid might work by mounting on top of the remote but it doesnt have enough force, I want to remove/desolder the mechanical button and figure out a way to control it without the switch but kind dont really know what circuit
I should use, kind of just learning how to use arduino.
Images of remote and button traces below.
Any idea how I could wire this up to arduino via some switch/relay circuit? Any circuit design / schematic would be helpful

Is that a battery powered remote control? Often a opto-coupler is possible, but for this I would use a mechanical contact. Some small 5v reed relays require only 20mA. The arduino uno can drive that directly (without transistor).

Would I solder the relay or remove the button and solder on to the pads?

Don't forget to edit your original question if you have additional thoughts to make the question better. 2. Caution, try a much safer project.  A heater project may go wrong and start a fire.  Try a low voltage light.  3. With out knowing the voltage and current handled by the part your are replacing it is difficult to make recommendations.  That said, if the switch is N.O. then likely you could simply solder the N.O. contacts of the relay across the switch.

I would not remove the button, but solder two wires. To prevent that the wires break, attach them to the board. For example drill a hole and use a cable tie. I often also use hot glue to stick the wires to the board so they don't move where they are soldered.

I would unsolder the switch then solder in a FET in the configuration shown below. The FET will act as a switch and may be controlled with any digital output from your Arduino board. When selecting a FET makes sure you find something that will fit the foot print you have to work with on your board, and the gate-source threshold voltage is rated to handled 5V.

Great thanks! Would a BJT NPN transistor work aswell?

@condo1234 yes...a BJT NPN would accomplish the same task but the FET is less of a load on your Arduino board and more efficient than the BJT. When you have 5vdc on the base of your BJT you will have a constant base-emitter current (BJT load). With the same 5vdc on the FET gate you only need to initially drive the FET capacitance (FET load).

Thanks, would an IRF540n work ok?Also with the 10k resistor can I just link that directly to an arduino ground pin?

@condo1234 Yes, that could work as long as you don't exceed Vds and Vgs (data sheet specs). That it a pretty beefy FET for what otherwise looks like a low power application. Conceptually you have the idea; now you just need to go through some trial-and-error (design iteration) to get the circuit to do what you want it to do for you.  The grounds should be tied together on your Arduino board and the circuit board if they are sharing a circuit (in this case the switch). This is to ensure both circuits are referencing the same ground potential.

@condo1234  If you want to get into circuit design I would advise you to download a Orcad Lite (Free Version of Orcad). This will allow you to layout your circuits and run simulations to help determine how the circuit will behave. Heres the link: https://www.orcad.com/resources/download-orcad-lite


text:
Arduino Mega PWM - 100ms Period - SSR and Heater
I'm not very advanced in Arduino "core" functions, so I need your help.
I'm using a Solid State Relay in order to control a heating element, with a PID Library (PID_v1.h) to obtain the OUTPUT of the PWM.
The code itself is not a problem, so that I'll not post it here.
Summarizing, this is the code where I send the PWM to the Relay:
    analogWrite(RELAY_OUT, outputValue);
I've found in this article that:
"The analogWrite function is used to set the duty cycle of a PWM pulse train that operates at approximately 500 Hz. Thus, with a frequency = 500 Hz, the period is = 2 ms."
My concern is that the response time of the relay (FOTEK SSR-60 DA) is 10ms (to turn on or to turn off), but I DO NOT KNOW how to configure Arduino PWM to work accordingly to this Relay, in a period greater than 10ms.
I've found in some pages some people changing the clock frequency in order to have a "fast pwm", but I need to know what values I have to use to get a "slow pwm", for a period greater then 10ms.
Can you help me with that? I've been searching a lot for this answer, but I could not find any "definitive"answer.
Thank you in advance!
Everton

I don't think you can PWM those FOTEK SSRs at 100Hz! They only turn on at the zero crossing and stay on the while half wave. So depending on how in sync your timer is with the 50Hz of the mains, the relay will be ON all the time, or OFF all the time.

You need a different kind of PID. Most PID code have the option to use a on/off output instead of a analog value for PWM. For a heater the minimal time between a chance can be 5 seconds to 1 minute, depending on the fysical system. Have you read this page about the relay: https://playground.arduino.cc/Code/PIDLibrary If you want to use that Solid State Relay, then you have to ignore its response time (it is not how fast it can be turned on and off all the time) and you have to ignore everyone else who is still talking about PWM.

Do you know how fast the physical system is?  Heaters are often controlled very slowly as compared to the ~10ms zero crossing response of a SSR.  House-sized furnaces often have a duty cycle more than a minute, and electric ranges have duty cycles on the order of seconds.  If the heater is on at full power, how fast can the temperature change? Sampling and adjusting should be 5-20 times faster than the process time constant, and you could use the PID_v1 output with your SSR to control a heater at, for example, a 5min by 10ms = 30000 step resolution.

Thanks a lot guys! I've tried to implement the solution using the MEGA registers as you suggested, but I think I'll not use PWM with this SSR anymore. I liked the suggestion from @Jot and will implement a on/off control. As I'm going to heat 60 liters (15 gallons) of liquid in my beer machine, I believe the period from 1 to 5 min will suit to my needs. Thank you very much for all your fast and useful replies!

I'd suggest using the TimerOne library.
Call Timer1.initialize(10000) in setup.
Then call Timer1.pwm(pin, duty); in your loop. Where pin is 11, 12, or 13 for the MEGA, and duty is between 0 and 1023.

As a physical interpretation, this sets a 10 second duty cycle, with 10/1024=9.78ms resolution, which matches the speed specs of the SSR.

Use ATmega PWM registers directly, in order to achieve about 100Hz PWM (10ms period).
This is an example of 10ms PWM period with 50% duty cycle on Arduino Mega (Pin D11):
/* Setup PWM pin D11 as Output */
   pinMode(11, OUTPUT); //D11/PB5/OC1A

   /* Timer/Counter Control Registers: TCCRxx */
   TCCR1A = 0;            //Clear register
   TCCR1B = 0;            //Timer/Counter stopped (CS12=0,CS11=0,CS10=0)

   TCCR1A = (1<<WGM11)  | //Fast PWM mode 16-bit (WGM13=1,WGM12=1,WGM11=1,WGM10=0)
            (1<<COM1A1);  //Set output HIGH during Duty Cycle peiod of OC1A

   TCCR1B = 2                     |   //Prescaler: divide by 8
            (1<<WGM12)            |
            (1<<WGM13);

   /* Set PWM frequency */
   ICR1   = 20000; // Period expressed in tick (10ms)

   /* Clear PWM counter */
   TCNT1  = 0;

   /* Set duty cycle to 50% */
   OCR1A  = 10000;

I didn't test it, but I think that it's correct.
Read this and this for details.


text:
Mesh with star topology
In my project I have an issue. I have more than 2 mesh network with Arduino + nRF240L01 with a star topology (one Arduino is master another 6 Arduino + nRF240L01 are the slaves likewise I can be able to have more than 2 networks).
So I want to communicate only with one mesh network but not to another. Is the different addressing enough to separate the networks? And I would like to have sample code as well.

Ideally you'd pick a different channel too - that way they won't interfere with each other on a physical level.

found this .... http://tmrh20.github.io/RF24Network/ .....  maybe you can use tree topology


text:
RS485 Wrong Results in Serial Monitor(Controllino) - Right Results with Logic Analyzer
After searching the internet and trying different examples, I always get the same wrong response in the serial monitor.
Picture 1 shows the wrong results. At first i thought it was decimal and I just had to convert it to ASCII. But that wasn't the problem.
Picture 2 shows the results that I expect. It's from the Logic Analyzer that sits on a breadbord to "sniff" the communication.
I expect N+0000.0\r
Picture 3 shows the settings or the logic analyzer. Please ignore the "SPI MISO" it's just an old description.
I have no other approach left in my mind.
I would appreciate any hint. :) Thank you in advance.
You will find the Arduino sketch below the pictures.

#include <SPI.h>
#include <Controllino.h>  /* Usage of CONTROLLINO library allows you to use CONTROLLINO_xx aliases in your sketch. */

const int numBytes = 20;
int incomingBytes[numBytes];   // for incoming serial data

void setup() {

  /* Initialize serial port for debug messages. */
  Serial.begin(9600);

  /* Initialize CONTROLLINO RS485 direction control DE/RE pins and Serial3 */
Serial3.begin(9600,SERIAL_8N2); //Initialisierung Serial Controllino(RS 485)
  //Beim Mega oder Maxi Zugang zum /OVL pin und RS458 /RE DE Pins
  //Zuweisung /RE (PJ5) DE (PJ6) pins als Ausgang (1). Für /OLV (PE7) als Eingang (0)
  DDRJ |= B01100000;
  DDRE &= B01111111;

  //Controllino_RS485Init(9600);
  //Controllino_RS485RxEnable();

  Serial.println("Recieving RS485...");
}

void loop() {

DatenEmpfangen();
delay(1000);
DatenAnzeigen();
}

void DatenEmpfangen()
{
  static byte ndx = 0;
  int rc;
  PORTJ &= B10011111;//Empfangen MODUS
  //Controllino_RS485RxEnable();
  delay(1000);
  do
  {
    if (Serial3.available() > 0)
    {
     // digitalWrite(CONTROLLINO_D1, HIGH);
     rc = Serial3.read();

     incomingBytes[ndx] = rc;
     ndx++;
    }
  } while (Serial3.available() > 0);
}

void DatenAnzeigen()
{
  static byte count = 0;
  //int Xor = 0;
  //Xor = receivedIntegersA[0];
  Serial.println("Daten");
  for (count=0;count<9;count++)
  {
    Serial.println((incomingBytes[count]));
  }

}

first chage type of incomingBytes to byte (for printing). use println(incomingBytes [count] , HEX)

https://majenko.co.uk/blog/reading-serial-arduino

@ Juraj - that doesn't work. The Hex Values are completely different compared to the correct output of the logic analyzer.

@Majenko - i don't get any output at all. I uploaded the sketch here: https://github.com/AndreasNRW/WS_RS485

@Majenko - i'm sorry, your linked example works great. The terminating character in my case was \r not \n. Very nice blog post. Thanks a lot.


text:
Error - invalid conversion from 'char' to 'const char*', Not able to connect on pubnub server using node mcu
I have node mcu with ESP8266 wifi module. When i am trying to upload an example code then its not working.
This is the Error:-
inline PubSubClient* PubNub::subscribe(const char* channel, int timeout)

                      ^

exit status 1
invalid conversion from 'char' to 'const char*' [-fpermissive]

Code:-
#include <ESP8266WiFi.h>
#define PubNub_BASE_CLIENT WiFiClient
#define PUBNUB_DEFINE_STRSPN_AND_STRNCASECMP

#include <PubNub.h>

const char *ssid =  "mym404";     // replace with your wifi ssid and wpa2 key
const char *pass =  "786110786";

char pubkey = 'pub-c-4a9cdbca-5688-4939-a852-f63cf6743980';
char subkey = 'sub-c-9b4067ae-1293-11e9-b4a6-026d6924b094';

char pubchannel = 'demo_keyset';
char subchannel = 'demo_keyset';

void setup() {
    /* For debugging, set to speed of your choice */
    Serial.begin(9600);

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

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

    /* Start the Pubnub library by giving it a publish and subscribe
       keys */
    PubNub.begin(pubkey, subkey);
}

void loop() {
    /* Maintain DHCP lease. For other HW, you may need to do
       something else here, or maybe nothing at all. */

    /* Publish message. You could use `auto` here... */
    PubNonSubClient *pclient = PubNub.publish(pubchannel, "\"message\"");
    if (!pclient) return;
    PublishCracker cheez;
    cheez.read_and_parse(pclient);
    /** You're mostly interested in `outcome()`, and,
        if it's "failed", then `description()`.
    */
    Serial.print("Outcome: "); Serial.print(cheez.outcome());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.outcome()));
    Serial.print("description: "); Serial.println(cheez.description());
    Serial.print("timestamp: "); Serial.println(cheez.timestamp());
    Serial.print("state: "); Serial.print(cheez.state());
    Serial.print(' '); Serial.println(cheez.to_str(cheez.state()));
    pclient->stop();

    /* Wait for news. */
    PubSubClient *sclient = PubNub.subscribe(subchannel);
    if (!sclient) return; // error
    String msg;
    SubscribeCracker ritz(sclient);
    while (!ritz.finished()) {
        ritz.get(msg);
        if (msg.length() > 0) {
            Serial.print("Received: "); Serial.println(msg);
        }
    }
    sclient->stop();

    delay(1000);
}

Code is taken from pubnub arduino github example - https://github.com/pubnub/arduino/blob/master/examples/AdafruitFeatherM0WINC1500/AdafruitFeatherM0WINC1500.ino

are you able to compile PubNubDemo.ino?

change char * subchanel to const chat *  subchanel

Tried but now it gives this error - invalid conversion from 'int' to 'const char*' [-fpermissive] , even pubnubDemo.ino shows same error.

problem was in the declaration of API keys and channel on the above code
Here is the right code:-
const char * pubkey = "publisher key from your account";
const char * subkey = "subscriber key from your account";

const char * pubchannel = "demo_keyset";
const char * subchannel = "demo_keyset";


text:
I need help makeing a light flash while a stepper is constantly moving
The starter code.
#include <Stepper.h>

const int stepsPerRevolution = 120;  // change this to fit the number
// for your motor of steps per revolution

// initialize the stepper library on pins 8 through 11:
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

int stepCount = 0;         // number of steps the motor has taken
int LEDPin = 13;
void setup() {
  // initialize the serial port:
  Serial.begin(9600);
  pinMode(LEDPin,OUTPUT);
}

void loop() {
  // step one step:
  myStepper.step(1);
  Serial.print("steps:");
  Serial.println(stepCount=456);
  stepCount++;
  delay(35);
}

I want a light to flash in 15 sec increments while my stepper keeps moving. I basically want to combine that code with this one:
int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  digitalWrite(LEDPin,HIGH);
  delay(6000);
  digitalWrite(LEDPin,LOW);
  delay(6000);
}

do you have a question? ............ note: delay(6000); causes the arduino to stop for 6 seconds ..... examine the code of the BlinkWithoutDelay example sketch

In your loop() function, call two new functions. Let's call those maybeStep() and maybeBlink(). Each one of those reads the time, millis(), and subtracts the saved time when it last performed its action (stepping or toggling the LED). If that difference is >= the interval for that action, do the action and update the saved time to the current time.
Remember to make the saved times 'static' (or global) so they won't get over-written when these function return.
The BlinkWithoutDelay example program gives the general idea of how to read the clock instead of calling delay(), to decide when to perform each action.
Update:

new at Arduino and don't quite know what you mean?

Your loop function would something like this:
void loop(){
   maybeStep();
   maybeBlink();
}

Notice that loop now does nothing but call your action functions. Here's an outline of one of the action functions:
void maybeStep(){
   if the time_now > than the time_we_last_stepped by 35 millisec, then
      step again and store the new time_we_last_stepped;

   return;
}

Notice that this function may or may not take a step! It decides whether to step by reading the time and comparing it to the time of the previous step. But either way - step, or no step - it returns quickly. The maybeBlink() function will work exactly the same way: compare the time it last toggled the LED on or off to the amount of time it should wait between toggles. Then either toggle it (and save the time and on/off state) or not, and in any case, return to the loop.
Done this way, your loop() function will call those action function very frequently - way more often than the actions need to take place. Most of those times, nothing will happen. But every once in a while (a "tiny while" in human terms), one of those functions will take a step or switch the LED. If you write your code this way, loop() could call dozens or hundreds of such functions and all of those actions could still take place on time.
The key to this programming technique - called non-blocking programming - is that the action functions be very brief . They must decide quickly whether something needs to be done, and either do it or not, then return immediately.

thank you, but I am new at Arduino and don't quite know what you mean?

The delay() function causes the Arduino program to stop in it's tracks and "count to 100". While it's doing that, it's not doing anything else.
Therefore delay is not an option when you're trying to do more than one thing at a time.
you need to rewrite your code to use the millis() function to tell if your desired amount of time has passed. something like this:
unsigned long nextLEDTime = 0;
bool ledState = false;
#define delay 6000

int LEDPin = 13;
void setup()
  pinMode(LEDPin,OUTPUT);
void loop()
{
  if (millis() >= nextLEDTime) //if it's time to toggle the LED
   {
     ledState = ! ledState;  //Invert the LED state
     digitalWrite(LEDPin, ledState);
     nextLEDTime = millis() + delay;  //Set nextLEDTime to the next time we need to do something
   }
}

Then you need to do the same thing with your stepper motor code, creating a separate variable to track the next time you want to do something with the stepper motor.
Put all your code in a single loop function that checks bot the nextLEDTime and the nextStepperMotorTime and takes appropriate action at the correct time for each thing you want to handle.


text:
Interfacing TTP229 touch sensor with arduino and gsm module
I have been working on an Arduino based call and message project which I am following from this link https://circuitdigest.com/microcontroller-projects/call-and-message-using-arduino-sim900-gsm.
This project uses a membrane keypad for inputting the phone number and etc., but I intend to use a TTP229 16 channel Touch sensor module.
I need help in taking input from the touchpad rather than the keypad. As I need to submit the project within a month it is my humble request if someone can help.
Thanks for replying!

how does the touch panel communicate with the arduino?  ..... what code are you using? ..... what problems are you facing?

It communicates over serial im using the below code to get the data from the sensor.http://forum.hobbycomponents.com/viewtopic.php?f=73&t=1781&hilit=hcmodu0079

I am able to fetch the data from the sensor but i am not able to call that function in the main gsm program.


text:
WS2812 Matrix colour problem. Power?
I have 8 8x8 WS2812 Matrix LED boards connected together to make 2 16x16 matrices. I have them connected with Dupont wires.
I also power the 2 16x16 with Dupont wires that are connected to a 5v 60Amp PSU (More Leds will be added later). The PSU power  should easily support the LED power requirements however, if I set the brightness anything over 30...the first matrices start to get reddish at the end. They start white but as the end they are orange/red.  If I set the brightness to 20-25 they are white. So there must be something with the power but I have 60amps...Can it be that the Dupont cables are the bottleneck? The cables don't get hot...so I guess they are ok?
Any help is highly appreciated.
Thanks
V.A

Measure the voltage before and after the jumper wires.

If I have brightness 20, i get 4.6V at the last matrix...if I increase it to the max of 255, I get 2.6v at the last matrix...So you are right. Fore some reason a have a voltage drop although the matrices are designed to be interconnectable...with Vin and Vout on the board. Can you can think of any solution to this?

Some of the cheap jumpers I have are so small, they maybe have 7 tiny strands of copper. The voltage drop over them is significant enough that they aren't usable for transmitting power, only signal/data level.

I soldered some cables from an ATX power supply but have the same results...It only does it when using white as there are all three colours at max brightness. I am going to try some cable that is used in wall sockets...let's see.

Connect the power/gnd to both ends of the matrix  to relieve the current flow across the individual boards power traces.  May have to connect in the middle as well.

I tried that. It improves so that I can use 60 Brightness but anything over that causes issues. I will increase wire gauge and see what happens...

Use at least AWG20 and power each possible spot on the matrices (in and out). All the energy not reaching the LEDs is fried in the DuPont wires. Use Ohms law.


text:
MKR WIFI 1010 Providing 3.3V to breadboard
The Arduino MKR WIFI 1010 product page says "The microcontroller on the MKR WIFI 1010 runs at 3.3V, which means that you must never apply more than 3.3V to its Digital and Analog pins. Care must be taken when connecting sensors and actuators to assure that this limit of 3.3V is never exceeded. Connecting higher voltage signals, like the 5V commonly used with the other Arduino boards, will damage the MKR WIFI 1010."
and yet it only has a 5V pin. I have a sensor that requires a 3.3V pin so I'm guessing my only option is to use a Logic Level Converter.
My question is if the MKR Digital and Analog pins can only take 3.3V, why is there only a 5V pin instead of a 3.3V pin to connect to a breadboard?

I agree that it is unclear and the documentation is not complete, but the VCC pin is the 3.3V output meant to power sensors. In the documentation tab of the MKR ZERO is explanation: https://store.arduino.cc/arduino-mkrzero

Thanks @Jot If you add that as an answer I'll mark it as the solution.

In short: VCC = 3.3V
The Arduino MKR WiFi 1010 board documentation is not complete. Well, at least they have the warning that the processor is running at 3.3V and the voltage levels of the pins should never be above 3.3V.
The page of the Arduino MKR ZERO has more information in the "documentation" tab. The VIN pin is the 5V power input, the 5V pin is unregulated 5V output (when the board is powered by USB or the VIN pin) and VCC is the regulated 3.3V output.
The term "VCC" means that it is the voltage at which the processor is running. Since it is a 3.3V Arduino board, it is the 3.3V voltage pin. That 3.3V should be used to power sensors. The "Tech Specs" tab at the MKR ZERO tells that it can supply up to 600 mA. That is the same for the MKR WiFi 1010, because the same AP2112K-3.3 voltage regulator is used.


text:
AD7606 DAQ and datalogging
I'm making a Data Acquisition System for force impact usign an AD7606 from Analog Devices, an Arduino DUE and a load cell. I already tested it following this guide an making the proper changes for Arduino DUE and some potentiometers for simulating the input signals. I can read variable 1-5 V signals pretty good but when I tried to read mV signals from my load cell I can't see any changes in the Visuino Scope. I've read some forums and using an amplifier is recommended. However, when I read the AD7606 datasheet it says that since it has a High Analog Input Impedance and Internal amplifiers, a previous  amplification phase isn't needed. Also, I want to avoid the noise from the external amplifiers.
I also tested my load cell using the HX711 ADC and it works fine, but I can't use it for my application because of its limited sampling frequency (80 Hz). AD7606 can give up to 200 kilo samples per second.
Does any one knows if I'm missing something for my input signal? if an amplifier is really nedded can you recommend me one?
Thanks

which load cell are you using and how is it connected?

It is a full Wheatstone Bridge made with 4 350 ohm straing gauges. 2 coils are fed.


text:
Help with placing a function please
I am trying to call a function that will turn a stepper motor a number of steps depending on the value submitted through the serial console. For an example, if I submit 50, the motor should turn 50 steps clockwise (and counter clockwise for  a negative value).
#include <Stepper.h>
#define STEPS 200
Stepper stepper(STEPS, 8, 9, 10, 11);

int serial_input = Serial.read();

void setup() {
Serial.begin(9600) ;
stepper.setSpeed(30);
}

void loop() {
}

void turnMotor(serial_input){
  stepper.step ( serial_input ) ;
}

And here are the errors I get:
Motor4.ino:12:28: error: variable or field ‘turnMotor’ declared void
Motor4.ino:12:16: error: ‘serial_input’ was not declared in this scope
Motor4.ino:117:28: error: variable or field ‘turnMotor’ declared void

Thank you

you can't call Serial.read() outside function

I see my error as you explained

As Juraj already explained, you cannot use Serial.read() outside a function.
What you probably want is to call it within the loop, or a function called from loop (via other functions).
Than you can call also turnMotor from Loop or a function called from loop. The value (int serial_input) probably doesn't have to be global anymore, but that depends on the time where you assign the value and where you call turnMotor.


text:
Ideal voltage level for attachInterrupt()
Well I am working on old textile machines, it is taking motor RPM with ISR. I want to read this RPM and publish on web. but the output voltage of this old system is 0 and 22 Volt. (0 Volt when the infrared light comes into the gap in the disk, 22 volt  when the infrared light see the photocell). if I try to read this data I see 17.000 - 18.000 RPM while actual RPM was 1600. I cant read true RPM. I suspect input signal voltages which is 0 and 22 Volts. I don't think Arduino UNO works in this voltage range but I cant see any info at docs. voltage divider with 0 - 2.2 volts I have dropped but still did not work. what is the ideal voltage level for attachInterrupt() command. I am using klon arduino uno (Arduino Uno R3 SMD CH340 Chip - Klon Arduino Uno )
Also are there ane filter  to prevent interference I am using long wire (100 meter)?
this is my code
int encoder_pin = 2; // pulse output from the module
unsigned int rpm; // rpm reading
volatile byte pulses; // number of pulses
unsigned long timeold;
// number of pulses per revolution
// based on your encoder disc
unsigned int pulsesperturn = 12;
void counter()
{
   //Update count
   pulses++;
}
void setup()
{
   Serial.begin(9600);
   pinMode(encoder_pin, INPUT);
   //Interrupt 0 is digital pin 2
   //Triggers on Falling Edge (change from HIGH to LOW)
   attachInterrupt(0, counter, FALLING);
   // Initialize
   pulses = 0;
   rpm = 0;
   timeold = 0;
}
void loop()
{
   if (millis() - timeold >= 1000) {
      //Don't process interrupts during calculations
      detachInterrupt(0);
      rpm = (60 * 1000 / pulsesperturn )/ (millis() - timeold)* pulses;
      timeold = millis();
      pulses = 0;
      Serial.print("RPM = ");
      Serial.println(rpm,DEC);
      //Restart the interrupt processing
      attachInterrupt(0, counter, FALLING);
   }
}

The interrupt signal is assumed to be a digital input signal of 0v or 5v (for an Arduino Uno, which is a 5v arduino board). You need a voltage divider which is two resistors to bring the 22v down to 5v. For example r1=33k and r2=10k (for 5.1v, close enough). Perhaps you need a capacitor of 1nF parallel to r2 to filter spikes and noise. Please check the links in your question, don't give links to something that requires to log in. The 100 meter cable is a serious problem. What kind of cable do you use? Can you put the arduino near the engine? The code in the loop is not okay.

You are awesome, I've checked links. 100 meter cablo there is no The voltage drop, is it still a problem? What happens if it happens. "Can you put the arduino near the engine?", no because there are 20 machines.Also where is the problem in "loop"

"100 meter cablo there is no The voltage drop, is it still a problem? "  You have a 100 meter antenna. What happens if you pick up disturbances from other sources, do you think that might matter?

Use an optocoupler, then the input voltage can be anything and the data is a bit more robust.

@ctrl-d If the signal can output enough current for a opto-coupler, that would be a good solution. With a shielded cable and a current as signal (instead of a voltage). Maybe it is possible, but it requires some electronics skills to make it work.


text:
How to assign text stored in a local file to a string at compile time
I'm developing a program that uses the HTML server in the WiFi101 library.
My hardware does not have SD card storage so all source html needs to be stored as strings in the sketch at compile time.  To aid in development I want to keep my html files separate from the sketch and include them at compile time.
Is there a way to use #include in the Arduino IDE and assign the included file to a string/char array constant?  If so can the path to the included file be relative to the sketch's path?
Notes:
Similar question on Stack overflow:
https://stackoverflow.com/questions/410980/include-a-text-file-in-a-c-program-as-a-char
Edit:
There are lots of great answers here to solve this in a more robust fashion. The correct thing to do is setup a proper build system.  If I were to set this up I'd be temped to try something like Gulp since you could easily minify/lint your web content.
As this is a small project I ended up just running the HTML through a minifier service and copy/pasted into strings.

look at the toneMelody example in the IDE

Check this. Not sure it is easy to adapt that to the Arduino IDE though.

No way for what you want in the Arduino IDE. UECIDE supports it though... - although UECIDE doesn't support the SAMD boards yet.

on SAMD Arduino architecture you could use FlashStorage instead of SD card

This will probably not work with the Arduino IDE. If you are willing to
go through a Makefile-based workflow, you can install this generic
Arduino Makefile, which should make things easier.
With that Makefile installed in /usr/share/arduino/Arduino.mk, the
following test worked on an Arduino Uno. It is based on the objcopy
trick from the article Embedding of binary data into
programs.
Project's Makefile:
BOARD_TAG    = uno
MONITOR_PORT = /dev/ttyACM0
OTHER_OBJS   = text.o

include /usr/share/arduino/Arduino.mk

text.o: text.txt
    avr-objcopy -I binary -O elf32-avr -B avr:5 $< $@

text.txt:
Hello, World!

include-blob.ino
extern "C" const uint8_t _binary_text_txt_start[];
extern "C" const uint8_t _binary_text_txt_size;

void setup() {
    Serial.begin(9600);
    Serial.write(_binary_text_txt_start, (size_t) &_binary_text_txt_size);
}

void loop(){}

The program just prints “Hello, World!”, but if you modify text.txt and
retype make, it will print whatever you had in this file. Please note
that the text is not NUL-terminated, so you have to use the
_binary_*_size symbol to know its size.

I found another way to include a literal file (html, css, or other) and assign it to a constant string without resorting to make files:
Add one line of code on top of your html (css, js, etc) file, and another at the bottom, and save it with an extra .h extension. Then include that file in de Arduino IDE.
This could easily be done by a (manually executed) script, every time those files are changed.
const char *indexHtml = R"====( // added by script
<html> <!-- original .html file -->
.
.
.
</html> <!-- end .html -->
)===="; // added by script

The variable name can be derived from the original filename. The result is saved with an extra .h extension. In the .ino (or .cpp) you can then include this file:
#include index.html.h

This will compile in the Arduino IDE.

C++ has 'raw string literals'. You can put a constant string, without escaping special characters, into the source code between an opening and closing 'tag'. You can choose the tag to be something that is not in the raw string. In following example the tag is =====.
const char* s1 = R"=====(Hello
"World")=====";

is same as
const char* s2 = "Hello\n\"World\"";

This way you can put your large strings into separate .h files and include them. On AVR use PROGMEM to save RAM.

How does that help you include the contents of a file into that string literal?

@Majenko, the h file is The File then.

But the h file isn't the file. The .html file is the file. The OP doesn't want to have to manually convert that .html file into a header file for inclusion (and I can understand that if there are lots of HTML files that he wants to edit often).

@Majenko, this is an option if he doesn't want to use a SD card or other file system

An easy way to do this is to write a C program to convert your files that you want included into your source into a form that looks like:
byte file_001[] = { 0x00, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0A,
                    0x01, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C,

                    ...

                    0x03, 0x01, 0x02, 0x04, 0x0A, 0x00, 0x01, 0x02, 0x04, 0x0C };

The converted file can contain binary data without issue instead of just ASCII.
You can then access the file directly using:   file_001[index]


text:
HTTP PUT method on NodeMCU/ESP8266
I've been trying to send a put request from my esp8266 for a while not but I can't figure out why it doesn't work and there are barely any posts about put requests online
I keep getting errors around int httpCode = http.sendRequest("PUT", String(data));
Error log: https://gist.github.com/dkbay/ab3fedf5e89d841d25b24fb829df74ef
#include <ESP8266HTTPClient.h>

#define LED_BUILTIN 2

const char* ssid     = "Some SSDI";
const char* password = "Some wifi password";

int wifiStatus;

void setup() {

  Serial.begin(115200);\
  pinMode(LED_BUILTIN, OUTPUT);
  delay(200);

  // We start by connecting to a WiFi network

  Serial.println();
  Serial.println();
  Serial.print("Your are connecting to;");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    digitalWrite(LED_BUILTIN, LOW);
    delay(500);
    digitalWrite(LED_BUILTIN, HIGH);
    Serial.print(".");
  }

}

void loop() {
  wifiStatus = WiFi.status();

  if(wifiStatus == WL_CONNECTED){

    HTTPClient http;

    http.begin("http://google.com/");
    http.addHeader("Content-Type", "application/json");
    String data = "{\"on\":false}";
    int httpCode = http.sendRequest("PUT", String(data));
    String payload = http.getString();

    Serial.println(httpCode);
    Serial.println(payload);

    http.end();
     Serial.println("");
     Serial.println("Your ESP is connected!");
     Serial.println("Your IP address is: ");
     Serial.println(WiFi.localIP());
  }
  else{
    Serial.println("");
    Serial.println("WiFi not connected");
  }
  delay(1000); // check for connection every once a second

}

what should it do and what does it? Shouldn't 'false' in json be in ""?

@Juraj It wasn't in quotes when I made it in node... It should send a "PUT" request to my hue lights to update them but instead it htrows this error https://gist.github.com/dkbay/ab3fedf5e89d841d25b24fb829df74ef

it doesn't compile,
not "doesn't work". use  sendRequest("PUT", data.c_str());

HTTPClient http;
http.begin("http://google.com?on=false");
http.addHeader("Content-Type", "application/json");
int httpCode = http.sendRequest("PUT", "");
String payload = http.getString();

try with this code, if server .php,
get data by $_REQUEST


text:
What's going wrong with my EEPROM?
I've been chipping away at a project for a long time now and I've found a serious bug.
Basically the user has an 8x8 grid, and each cell in this grid has a number of properties.
I want to be able to save all of these properties as a 'profile' within the EEPROM, and previously this worked OK but now seems to have a few bugs.
The most prominent of which is that when I save a grid to a profile (Say profile 3), and then load the next profile (profile 4, in this case) the far right column of profile 3 appears in the far left column of profile 4.
LikeWise, saving a filled in grid to profile 1, and then saving an empty grid to profile 2 causes the RIGHT hand column of profile 1 to be cleared.
It used to work great in a previous version but there was completely different hardware in place supporting the GUI making it impossible to load older versions of the code and test how it was working then.
Here is the code where I save / load profiles

#include <EEPROM.h>
#include"EEPROMAnything.h"
const int profileSize = 224; // Actually everything is only half the size you thought (WTF but ok)

void saveProfile(int profileNum)                               // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Saving...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8); // Original
  tft.print(" Bytes");
  setLine2();
  tft.print("please wait");
//  tft.sendBuffer();

  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      saveConfiguration.ROMcellType[ROMRow][ROMCol]      = cellType[ROMRow][ROMCol];
      saveConfiguration.ROMindexVal[ROMRow][ROMCol]      = indexVal[ROMRow][ROMCol];
      saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol]  = MIDIVariable[ROMRow][ROMCol];
      saveConfiguration.ROMcellChannel[ROMRow][ROMCol]   = cellChannel[ROMRow][ROMCol];
      saveConfiguration.ROMorientation[ROMRow][ROMCol]   = orientation[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol]  = faderGroundX[ROMRow][ROMCol];
      saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol]  = faderGroundY[ROMRow][ROMCol];
    }
  }

  EEPROM_writeAnything((profileNum*profileSize), saveConfiguration);

  delay(500);
  menuState = 1; // Go back to main menu
  menuLocatorY = 0; // Otherwise text will not show on next screen;
  updateScreen();
}
//{EEPROM_writeAnything(profileNum*profileSize, configuration);}

void loadProfile(int profileNum)                              // saves the complete current configuration of the system to memory under a profile for later restoration
{
  tft.fillScreen(BGCOL);// Clear the screen.
  tft.setTextSize(2);
  setLine0();
  tft.print("Loading...");
  setLine1();
  tft.print(sizeof(saveConfiguration)/8);
  tft.print(" Bytes.");
  setLine2();
  tft.print("please wait");

  initGrid(); // Clear any information regarding the current grid. Shouldn't really be neccesary but makes code safer.

  EEPROM_readAnything(profileNum*profileSize,saveConfiguration);
  for (int ROMRow = 0; ROMRow< 8; ROMRow++)    // Populate the ROM Structure
  {
    for (int ROMCol = 0; ROMCol < 8; ROMCol++)
    {
      cellType[ROMRow][ROMCol]      = saveConfiguration.ROMcellType[ROMRow][ROMCol];
      indexVal[ROMRow][ROMCol]      = saveConfiguration.ROMindexVal[ROMRow][ROMCol];
      MIDIVariable[ROMRow][ROMCol]  = saveConfiguration.ROMMIDIVariable[ROMRow][ROMCol];
      cellChannel[ROMRow][ROMCol]   = saveConfiguration.ROMcellChannel[ROMRow][ROMCol];
      orientation[ROMRow][ROMCol]   = saveConfiguration.ROMorientation[ROMRow][ROMCol];
      faderGroundX[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundX[ROMRow][ROMCol];
      faderGroundY[ROMRow][ROMCol]  = saveConfiguration.ROMfaderGroundY[ROMRow][ROMCol];

      /*
      if (cellType[ROMRow][ROMCol] == 3)
      {
        customValue = orientation[ROMRow][ROMCol];
        customMessage =   indexVal[ROMRow][ROMCol];
        MIDIVariable[ROMRow][ROMCol] = 0;   // Sets read fader value to 0 initially,   the customvalue variable is used to control physical orientation in this function
        customChannel = cellChannel[ROMRow][ROMCol];    // The MIDI channel the given cell is assigned to
        initType3(ROMRow,ROMCol);
      }
      */

    }
  }

    // Here we go back to the grid view
    delay(500); // Just so user can see message
    menuState = 2; // Go back to Grid View
    menuLocatorX = 0;
    menuLocatorY = 0; // Otherwise text will not show on next screen;
    updateScreen();
}
//{EEPROM_readAnything((profileNum*profileSize), configuration);}

Here is the declaration of the struct I am using
//-------------------------------EEPROM STRUCTURE -------------------------------------------
struct config_t   // I think this will allow EEPROM saving made easy
{
  int ROMcellType[8][8];  // [Row][Column] States the type of input assigned to the cell.  Top left = 0,0 Row, Column    // Celltype 9 will be a reservation cell for the faders.
  int ROMindexVal[8][8];       // States the note value / Command  assigned to the cell
  int ROMMIDIVariable[8][8];   // Used to retain desired velocity / Current value of continuous input.
  int ROMcellChannel[8][8];    // The MIDI channel the given cell is assigned to
  int ROMorientation[8][8]; // Keeps track of the direction of orientation of large modules
  int ROMfaderGroundX[8][8]; // Keeps track of where the 'root' of the fader is
  int ROMfaderGroundY[8][8]; // Keeps track of where the 'root' of the fader is
} saveConfiguration;
//--------------------------------------------------------------------------------------------

IndexVal, cellType, etc are all global variables (I know, I know, global variable bad)
And last of all, the header file with my base level EEPROM functions
#include <EEPROM.h>
#include <Arduino.h>  // for type definitions

template <class T> int EEPROM_writeAnything(int ee, const T& value)
{
    const byte* p = (const byte*)(const void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          EEPROM.write(ee++, *p++);
    return i;
}

template <class T> int EEPROM_readAnything(int ee, T& value)
{
    byte* p = (byte*)(void*)&value;
    unsigned int i;
    for (i = 0; i < sizeof(value); i++)
          *p++ = EEPROM.read(ee++);
    return i;
}

It's been a while since I wrote this code so I'm a little lost in it myself.
I should probably add that if I save to profile 1, mess around testing the other profiles, then load profile 1 again it's always correct.
Also, the part where it prints sizeof(saveConfiguration) does return 224, and I've also removed the "/8" just to check that there was no rounding error.
If I double the value of profileSize it simple halves the number of profiles I have available by spacing them out by the size of the struct in memory.
Please ignore the (if cellType == 3) section, this is used for a type of object that uses 3 consecutive cells and is a whole can of worms in itself.
For the sake of this test I'm just using celltypes that are modules that use a single cell.
I feel like I really need to make some progress with this soon for the sake of my own mental wellbeing.
Anyone able to help?
Further info for the commenters:
The board I am using is a PJRC teensy 3.5.
The /8 was to display the number of Integers being saved. I think when I originally wrote this code I mistakenly thought that the device was 8 bit, and estimated the profile size to be 448.
I believe the EEPROM is 16 bits wide?

What board are you using? And why do you think you would want to divide the size by 8...?

EEPROMAnything can be replaced by EEPROM.put and EEPROM.get.

I'll add that info. 2 Secs.

Ok so replacing with .put and .get works, but I get the exact same issue.

Depending if you are on an 8 bit or 32 bit Arduino your profile is either 896 or 1792 bytes in size. Not 224. (Why do you think /8 is an option?)
I am guessing that you are on a 32-bit Arduino since 1792/8 = 224.
1792 is more EEPROM than any normal Arduino has, anyway.  Even if you were on an 8-bit Arduino and the profile size was 896 there would only be room for one in the EEPROM.
I think you need to re-think your strategy somewhat to either massively reduce the amount of data you are saving, or change where you are storing the data to.

So the teensy 3.5 is a 32 uController with 4096 bytes of EEPROM.
As it stands, I could probably encode the X and Y position into a single variable as neither value can be > 8.
I am considering including a larger external EEPROM in the final design but for now the first few profiles should still work OK, even if the profile size is worst case scenario, right?
I can save stuff to the other profiles OK but I get the issue where the far right and left columns overwrite the a column inthe  next / last profile respectively

I think the /8 comes from the code originally being written on an arduino mega?

I can see no place ever for a /8 regardless of what the code was written for.  The size is the size. If you try working with an eighth of the size then yes things are going to get messed up.

If you are storing values < 256 then there is no need to use int - it's 4x larger than you need. Use uint8_t.

Yeah good shout, this is definitely an artifact from previously working with a smaller Ucontroller.

Having changed the struct and global vars to uint_8 sizeof returns 448 (which was what I have on my spreadsheet where I planned all of the memory allocation.) We are getting somewhere! :)

Ok so now the bug has changed...
I have completely cleared profile 5,6, and 7 and created a 'cross' with inputs of 2 different types going diagonally from corner to corner.
The remaining 6 free cells in the far right and left columns are set to a different celltype.
when I save this to profile 6 ; Profile 5 is unchanged, but profile 7 has a copy of profile 6 in it, but the 4th column has 6 inputs of a totally different type to the ones used for testing, with the top an bottom cells empty.
What a headache.

This behaviour doesn't occur when saving to any profiles below 6 which is great!

Thanks a lot Majenko, that was very helpful.
I also noticed my system configuration (Different to the grid config and only a few bytes) saving function was set to save at an address that would cause the struct to wrap around in the EEPROM.
Changed this so that rather than starting at 9* profilenum, it starts at 8* profilenum (Its only a few bytes.) This fixed the new bug :)

@GigaJoules Excellent. I'm glad you learned the tools to fix the problem. I don't like it when people demand I spoon feed them the answer ;)


text:
How to properly run four DC motors with an Arduino?
I am working on a project where I have four DC motors that are controlled by two L293D motor drivers. Two of the motors act as the wheels of the robot, and the other two act as a mop.
The Arduino board is powered through the USB port. The DC motors are powered by the L293D motor driver through the 5 V pin on the Arduino.  Alongside the motors, an ultrasonic sensor and a water sensor are also using the 5 V pin.
This is what the robot should be doing:
The robot will move forward. If it senses an obstacle through the ultrasonic sensor, it will turn right. If it senses water through the water sensor, the robot will stop moving and the mop will start spinning. After cleaning the water spillage, it will move forward again, just like what it did before.
It seems like the motors are not getting enough power, because whenever I place it on the floor, it doesn't move.
The base / platform of the robot is plywood, which is heavy for the robot, and I think this is a factor that affects the spinning of the wheels.
I also have a 9 V battery, which I think could power the motors, but I don't know how to connect it. How am I supposed to connect it to the L293D motor driver? I think I should connect the positive side of the 9 V battery to the VCC 2 pin of the L293D motor driver. But, where should I connect the negative side of the 9 V battery?

Try A power buss as the main power distribution source

With out knowing the demands of the motors (how much current they need under a given load) it is difficult to answer your question.  But, in most Arduino designs:

Motors are powered independently of the Arduino.  And when Arduino Uno is powered through its USB port it should be realized that most common USB power sources are only obliged to offer up to 500mA of current.
The motor's power source likely needs to be capable of providing several Amps. A common 9 Volt battery only contains about 500mAh and will likely drain in 10s of minutes if it works at all.

Consider the power pack used in common portable electric power tools.  This should give you a perspective of the type of power you will need in order to create a robot with multiple motors.


text:
Why Would Declaring a Global Variable Change How An Unrelated Conditional is Evaluated?
Here is my entire sketch. This is my first Arduino project.  I included all of it because I don't know what's relevant.  I am printing out to a 4-digit 7 segment display.  To do that I use sprintf to format the contents of a char[] called tempString  and that gets sent to the display. I declared a new local char[] each time I needed one.  I had a problem with the Arduino Pro Mini running out of memory.   I tried declaring a global chart[] and reusing it when I needed it, but that changed the way the program executed.  That was the only change I made.
After I made that change, the Arduino would always evaluate this true:
 if (countDownTimer.TimeCheck(0, 0, 0))

The CountDownTimer was always evaluating to a time of 0, even after it had been assigned a valid time and the timer hadn't started running. I verified I was setting it correctly, but by the time the conditional was reached, the Timer was back to 0.
If I remove the global declaration for tempString[] and go back to locals the logic works as designed.  I made tempString[] smaller as a local and that seems to have fixed the memory issue but I would like to know why declaring a global caused a problem.
 #include <SoftwareSerial.h>
#include <CountUpDownTimer.h>
#include <EEPROM.h> //Needed to access the eeprom read write functions

//values for EEPROM
int stepsToWrite = 0;
int stepsToRead = 0;
int priorValue = 0;

// addresses to write to and read from
const int thirtySecondAddress = 0;  // constant
const int threeMinuteAddress = 4;   // constant
int addressToUse = 0;   // this will change depending on time user selects

// set uo the serial display
const int displayTx = 5;  // the pins we need to create the software serial instance
const int displayRx = 7;   // we will only use Tx
SoftwareSerial s7s(displayRx, displayTx);

//set up the timer
CountUpDownTimer countDownTimer(DOWN);
const long displaychangeInterval = 10000; // in milliseconds
const long countdownInterval = 1000; // in milliseconds

long previousMillis = 0; // for changing between time left and step count
long previousTimerMillis = 0;  // for updating the display with the new time
const int thirtySecondTime = 30;
const int threeMinuteTime = 180; // 3 minutes expressed as seconds
int timerStartValue = 0;  // needed for some control logic

// booleans to control what is displayed
bool doDisplayStepCount = false;
bool doDisplayCountDown = false;
bool doDisplayHighScore = true;  // we want to display this at startup

// set up the buttons
const int timerbuttonPin = 6;     // the number of the timer pushbutton pin
const int resetbuttonPin = 4;     // the number of the reset button pin

int timerbuttonPushCounter = 0;   // counter for the number of button presses
int timerbuttonState = 0;         // current state of the button
int timerlastButtonState = 0;     // previous state of the button

int resetbuttonPushCounter = 0;   // counter for the number of button presses
int resetbuttonState = 0;         // current state of the button
int resetlastButtonState = 0;     // previous state of the button

int stepsTaken = 0; // the number of steps (jumps)
boolean timerStarted = false;

// for the force resistor
const int FSR_PIN = A0; // Pin connected to FSR/resistor divider
const float VCC = 5.10; // Measured voltage of Ardunio 5V line
const float R_DIV = 3265.0; // Measured resistance of 3.3k resistor

double currentForce = 0;
double previousForce = 0;
boolean previousPos = false;
boolean currentPos = false;

boolean doChangeDisplay = false;

char tempString[4];
void setup() {

  boolean debug = true;
  if (debug)
  {
    EEPROMWriteInt(thirtySecondAddress, 0);  // zero out EEPROM
    EEPROMWriteInt(threeMinuteAddress, 0);  // zero out EEPROM
  }
  // start serial connection
  Serial.begin(9600);

  // set up pins
  pinMode(FSR_PIN, INPUT);
  pinMode(timerbuttonPin, INPUT);
  pinMode(resetbuttonPin, INPUT);

  // serial display
  // Must begin s7s software serial at the correct baud rate.

  // Clear the display
  //  The default of the s7s is 9600.
  s7s.begin(9600);
  //clearDisplay();  // Clears display, resets cursor
  // s7s.print("-HI-");
  // delay(1000);

  displayHighScores();

}

void loop() {

  // Serial.print("freeMemory()=");
  // Serial.println(freeMemory());

  //  Serial.println("Starting loop");
  // button pushes
  // if tinmerbuttonPushCounter = 1, set timerValue to 30 seconds
  // if 2 pushes, set to 3 minutes and reset push counter to 0

  //Serial.println("Reading timer button, state is: " + timerbuttonState);
  timerbuttonState = digitalRead(timerbuttonPin);
  // Serial.println("Reading reset button, state is: " + resetbuttonState);
  resetbuttonState = digitalRead(resetbuttonPin);

  // compare the buttonState to its previous state

  if (timerbuttonState != timerlastButtonState)
  {
    Serial.println("selecting time");
    if (timerbuttonState == HIGH)
    {

      doDisplayHighScore = false;
      timerbuttonPushCounter++;
      // if the current state is HIGH then the timer button went from off to on:
      if (timerbuttonPushCounter == 1)
      {
        doChangeDisplay = false;
        doDisplayCountDown = true;
        timerStartValue = thirtySecondTime;
        addressToUse = thirtySecondAddress;
        Serial.println("timer button pushed: " + String(timerbuttonPushCounter));
        Serial.println("start value: " + String(timerStartValue));
        clearDisplay();
        setDecimals(0b010000);  // Turn on colon
        sprintf(tempString, "%04d", thirtySecondTime);
        Serial.println("Timer set to: " + String(tempString));
        s7s.print(tempString);
      }

      else if (timerbuttonPushCounter == 2)
      {
        timerStartValue = threeMinuteTime;
        addressToUse = threeMinuteAddress;
        doChangeDisplay = true;

        int timerinminutes = timerStartValue / 60;
        Serial.println("timer button pushed: " + timerbuttonPushCounter);
        Serial.println("start value  " + timerStartValue);
        timerbuttonPushCounter = 0;
        clearDisplay();
        setDecimals(0b010000);  // Turn on colon
        sprintf(tempString, "0%d00", timerinminutes);
        Serial.println("Timer set to: " + String(tempString));
        s7s.print(tempString);
      }
    }  // end of if timer state high

    // Delay a little bit to avoid bouncing
    delay(50);
  }
  // save the current state as the last state, for next time through the loop
  timerlastButtonState = timerbuttonState;

  // for reset button, logic is much simpler
  // if state is high, button has been pushed so reset everything
  if (resetbuttonState != resetlastButtonState)
  {
    if (resetbuttonState == HIGH)
    {
      Serial.println("Reset button pushed!");
      doDisplayHighScore = true;
      resetStepCounter();
      // Delay a little bit to avoid bouncing
      delay(50);
    }
  }

  resetlastButtonState = resetbuttonState;

  // step pad logic
  int fsrADC = analogRead(FSR_PIN);
  previousForce = currentForce;
  currentForce = calculateForce(fsrADC);
  // trying this using force values
  // when we step force is always positive
  // when we lift our foot force is always negative

  if (currentForce > 0)
  {
    currentPos = true;
    Serial.println("Force detected!");
    delay(1000);
  }
  if (previousForce < 0)
  {
    previousPos = true;
  }

  if (currentPos && previousPos)
  {
    // start the timer on the first step
    if (!timerStarted)
    {
      Serial.println("First steop!");
      timerStarted = true;
      // Serial.println("Timer start value: " +String(timerStartValue));
      countDownTimer.SetTimer(0, 0, timerStartValue);
      countDownTimer.StartTimer();

      //  char tempstring[10];
      sprintf(tempString, "%4d", countDownTimer.ShowMinutes(), countDownTimer.ShowSeconds());
      Serial.println("Timer set to: " + String(tempString));
      //  Serial.println("Timer started");
      //  delay(2000);
      doDisplayCountDown = true;
    }

    stepsTaken++;
    Serial.println("Step Detected!");
    currentPos = false;
    previousPos = false;
  }

  // if timer is 0 we have run out of time
  // this needs to be done here as it must always be done and can't depend
  // on displayCountDown being true

  if (timerStarted)
  {
    if (countDownTimer.TimeCheck(0, 0, 0))
    {
      //Serial.println("out of time");
      //delay(500);
      timerStarted = false;  // set timerRunning to false
      countDownTimer.StopTimer();
      if (timerStartValue == thirtySecondTime)
      {
        WriteHighScore(thirtySecondAddress, stepsTaken);
      }

      if (timerStartValue == threeMinuteTime)
      {
        WriteHighScore(threeMinuteAddress, stepsTaken);
      }
      Serial.println("wrote high score");
      delay(500);
      // clearDisplay();
      //displayStepCount();
      // resetStepCounter();

      // displayCountDownTimer();
    }

    //else

    if (!(countDownTimer.TimeCheck(0, 0, 0))) // && timerStarted)
    {

      countDownTimer.Timer(); // run the timer
      Serial.println("Timer is running");
      // timer logic
      // every 10 seconds, change booleans on what gets displayed
      unsigned long currentMillis = millis();
      // the last 10 seconds only display the step count
      //if (countDownTimer.TimeCheck(0, 0, 10))
      // {
      //
      //   displayStepCount();
      // }

      // else
      //  {

      if (doChangeDisplay)
      {
        if ((currentMillis - previousMillis) >= displaychangeInterval)
        {
          // save the last time we checked the interval
          //  Serial.println("10 second interval!");
          previousMillis = currentMillis;

          // if this is true, set it to false
          // set the countdown display to true
          if (doDisplayStepCount)
          {
            doDisplayStepCount = false;
            doDisplayCountDown = true;
          }

          else
            // countdown display is true, so set it to false
            // and set stepcount display to true
          {
            doDisplayStepCount = true;
            doDisplayCountDown = false;
          }

        }
      }

      // only display step count if this is the interval to do it
      if (doDisplayStepCount)
      {
        displayStepCount();
      }

      // only display countdown timer if this is the 10 second interval to do it
      if (doDisplayCountDown)
      {
        displayCountDownTimer();
      }

      //  }

    }
  }

}

// Send the clear display command (0x76)
//  This will clear the display and reset the cursor
void clearDisplay()
{
  s7s.write(0x76);  // Clear display command
}

// Turn on any, none, or all of the decimals.
//  The six lowest bits in the decimals parameter sets a decimal
//  (or colon, or apostrophe) on or off. A 1 indicates on, 0 off.
//  [MSB] (X)(X)(Apos)(Colon)(Digit 4)(Digit 3)(Digit2)(Digit1)
// (0b010000) - colon only
//  (0b111111) - all decimals
void setDecimals(byte decimals)
{
  s7s.write(0x77);
  s7s.write(decimals);
}

void resetStepCounter()
{
  timerbuttonPushCounter = 0;
  if (timerStarted)
  {
    countDownTimer.StopTimer();
    timerStarted = false;
  }

  // clean up
  stepsTaken = 0;
  clearDisplay();
  timerStartValue = 0;
  doDisplayHighScore = true;
}

void displayStepCount()
{
  setDecimals(0b000000);  // Turn off the colon
  // Will be used with sprintf to create strings
  sprintf(tempString, "%04d", stepsTaken);
  Serial.print("Steps taken: " + String(tempString));
  clearDisplay();
  s7s.print(tempString);
}

void displayCountDownTimer()
{
  // example formats
  //sprintf(tempString, "%4d", deciSecond); //Convert deciSecond into a string that is right adjusted
  //sprintf(tempString, "%d", deciSecond); //Convert deciSecond into a string that is left adjusted
  //sprintf(tempString, "%04d", deciSecond); //Convert deciSecond into a string with leading zeros
  //sprintf(tempString, "%4d", deciSecond * -1); //Shows a negative sign infront of right adjusted number
  unsigned long currentMillis = millis();
  int seconds = 0;
  int minutes = 0;

  // only update the display if 1 second has passed
  // if(currentMillis - previousTimerMillis >=  countdownInterval)
  // CountUpDownTimer TimeHasChanged() returns boolean (in seconds)

  if (countDownTimer.TimeHasChanged())
  {
    // previousTimerMillis = currentMillis;
    seconds = countDownTimer.ShowSeconds();
    Serial.println("Time left: " + seconds);
    minutes = countDownTimer.ShowMinutes();
    sprintf(tempString, "%02d%02d", minutes, seconds);

    clearDisplay();
    setDecimals(0b010000);  // Turn on colon
    Serial.println(tempString);
    s7s.print(tempString);
  }
}
void EEPROMWriteInt(const int p_address, const int p_value)
{
  byte lowByte = ((p_value >> 0) & 0xFF);
  byte highByte = ((p_value >> 8) & 0xFF);

  EEPROM.write(p_address, lowByte);
  EEPROM.write(p_address + 1, highByte);
}

//This function will read a 2 byte integer from the eeprom at the specified address and address + 1
int EEPROMReadInt(const int p_address)
{
  byte lowByte = EEPROM.read(p_address);
  byte highByte = EEPROM.read(p_address + 1);

  return ((lowByte << 0) & 0xFF) + ((highByte << 8) & 0xFF00);
}

void WriteHighScore(int address, int value)
{
  // int valueRead = EEPROMReadInt(address);
  //if (valueRead < value)
  // {
  EEPROMWriteInt(address, value);

  delay(500);
  sprintf(tempString, "%04d", value);
  Serial.print("high score: " + String(tempString));
  clearDisplay();
  s7s.print("-HI-");
  delay(500);
  clearDisplay();
  s7s.print("SCOR");
  delay(500);
  clearDisplay();
  s7s.print(tempString);
  delay(500);

  // }
}
void displayHighScores()
{
  int thirtySecondScore = EEPROMReadInt(thirtySecondAddress);
  int threeMinuteScore = EEPROMReadInt(threeMinuteAddress);
  sprintf(tempString, "%04d", thirtySecondScore);
  Serial.println("thirty second score: " + String(tempString));
  sprintf(tempString, "%04d", threeMinuteScore);
  Serial.println("Three minute score: " + String(tempString));

  clearDisplay();  // Clears display, resets cursor
  s7s.println("-HI-");
  delay(1000);
  clearDisplay();
  Serial.println("SCOR");
  s7s.print("SCOR");
  delay(1000);
  clearDisplay();
  sprintf(tempString, "%04d", thirtySecondScore);
  Serial.println(tempString);
  s7s.print(tempString);
  delay(1000);

  clearDisplay();
  sprintf(tempString, "%04d", threeMinuteScore);
  Serial.println(tempString);
  s7s.print(tempString);
  delay(1000);
  clearDisplay();
}

float calculateForce(int pinvalue)
{
  // Use ADC reading to calculate voltage:
  float fsrV = pinvalue * VCC / 1023.0; // 1023 is # of units of voltage between 0 and 5V
  // Use voltage and static resistor value to
  // calculate FSR resistance:
  float fsrR = R_DIV * (VCC / fsrV - 1.0);
  // Serial.println("Resistance: " + String(fsrR) + " ohms");
  // Guesstimate force based on slopes in figure 3 of
  // FSR datasheet:
  float force;
  float fsrG = 1.0 / fsrR; // Calculate conductance
  // Break parabolic curve down into two linear slopes:
  force = (fsrG - 0.00075) / 0.00000032639;
  return force;
}

add a position for terminating zero in tempString. tempString[5]. now the 0 is written by sprintf to memory after the array

This line:
sprintf(tempString, "%04d", thirtySecondTime);

writes 5 characters to tempString, the four digits and a terminating null.  You only gave the array room for four.
This:
Serial.println("Timer set to: " + String(tempString));

is a total waste of resources.  If you want to talk about memory usage then don't use the String class and definitely don't use it where it simply is not needed.
Write that as:
Serial.print("Timer set to: ");
Serial.println(tempString);

or better yet from a memory standpoint as:
Serial.print(F("Timer set to: "));
Serial.println(tempString);

thanks.  I was reading about String() memory usage and will change that.  Most of the serial output will be removed after I am done with all the debugging.  From @Juraj comment I did some research and now understand the termination.


text:
NodeMCU burned, did I something fundamental wrong?
I have a NodeMCU where I connected a LED strip (WS2812b, which operates at 5V).
NodeMCU is powered via USB 5V. The used power adapter can supply 2.5A max.
I don't have a separate power supply for the LED strip yet, so I connected it to VIN/GND of the NodeMCU.
That worked.
Yesterday, I took the NodeMCU (without led strip) to my PC and uploaded an updated sketch.
After that, back in the living room, I connected the NodeMCU with the led strip and the USB power supply.
I didn't need an ambilight at the moment so I left it off.
After 5 minutes, I smelled something burned. As you can see in the second image, the component below ground is burned.
I had this setup successful running for a week (with ambilight turned on for several hours) and had no issues at all.
Did I something fundamental wrong?
Any guess, why it works flawless and then suddenly burned after just 5minutes?
Any tip/suggestion is very appreciated!

The white component on the right is a DHT22 temperature sensor and has been added for completeness.

The resistor and LED on the right are not used, they were just plugged in from a previous setup.
Best regards
Casper

Yes, you did something fundamentally wrong.
The component that blew up is a diode.  It is designed to protect the USB from voltage being injected into the board.
That diode can handle an absolute maximum of 1A.
Any fault on your LED strip connection (a short to ground) will cause that diode to vacate the premises. As yours did.
The purpose of the VIN pin (as the label suggests) is as a voltage input. It's not really designed to provide power to other devices, especially as the ESP8266 itself can take more than half that 1A power budget when communicating.  You should not use VIN for powering anything more than maybe a couple of low power sensors. LED strips are a big no-no.

Something happened to me yesterday.  I had made sure that the diode & regulator could handle the stress of 14 V ( this unit is installed  in a voat).
The diode blew as soon as the ignition was turned on.  However I noticed that the 10 uF. capacitor was still smoldering away.   That should not have happened.
I removed both faulty components & tested the board.  All OK!
Replaced the diode and the capacitor with a 10uF/20VW diode and the board works fine with 14.4 V input (when battery is charging).
So, I reckon the prpblem is that the capacitor has insufficient voltage rating(6V?) and goes short circuit.  The schotky diode will try and pass AMPS and it fails.
Solution replace the 10uF de-coupling capacitors with capacitors of known rating.
There is no real way of knowing what rating capacitors were used in the manufacture.
Lee


text:
Servo starts to shake when I added SIM900.begin(19200);
Hello I'm working on this mini project. This project works this way, Whenever someone type wrong password, LCD will display "Access Denied" and send an alert to SMS using GSM module.  I used 2 Arduinos for this project, The 1st Arduino is powered up by my laptop this is where the signal pins are connected the RX/TX of GSM is connected in (pin 10 and 11) respectively and the LCD is in pin (2-9) and Servo to (A4) . The second Arduino I used is powered up with a charger and used it for GSM power source it function well as it blinks every 2 sec. I'm really wondering why my servo is shaking whenever I add the  SIM900.begin(9600); at the setup in Arduino IDE?
This is the code

#include <Keypad.h>
#include <Password.h>
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>

#include <SoftwareSerial.h>
SoftwareSerial SIM900(10, 11);

LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
Password password = Password( "9999" );
Servo myservo;

const byte ROWS = 4;
const byte COLS = 4;

char keys[ROWS][COLS] = {
    {'1','2','3','A'},
    {'4','5','6','B'},
    {'7','8','9','C'},
    {'*','0','#','D'}
};

byte rowPins[ROWS] = {3, 4, 5, 6};
byte colPins[COLS] = {7, 8, 9, 10};

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
int pos = 0;

void setup(){

  Serial.begin(9600);
  SIM900.begin(9600);

  myservo.attach(13);
  lcd.begin(16, 2);
  lcd.print("Arduino Password");
  lcd.setCursor ( 0, 1 );
  lcd.print (" Door  Lock ");
  delay ( 2000 );
  setup1();

}
void setup1(){

  lcd.clear();
  lcd.home();
  lcd.print("Enter your code:");
  keypad.addEventListener(keypadEvent);
}

void loop(){
  keypad.getKey();
}

//take care of some special events
void keypadEvent(KeypadEvent eKey){
  switch (keypad.getState()){
    case PRESSED:
        Serial.println(eKey);
        switch (eKey){
          case '4': checkPassword(); break;
          case '2': password.reset(); break;
          case '8': lock(); break;
          default: password.append(eKey);
     }
  }
}

void checkPassword(){
  if (password.evaluate()){
    lcd.clear();
    lcd.print("Access granted");
    delay(1000);
    unlock();
  }else{
    lcd.clear();
    lcd.print("Access denied");
    delay(2000);
    sendSMS();
    delay(1000);

  }
  password.reset();
  delay(1000);
  setup1();
}

void unlock(){
  lcd.clear();
  lcd.print("Unlocking...");
  delay(2000);
  pos = 90;
  myservo.write(pos);
  lcd.clear();
  lcd.print("Unlocked! Press");
  lcd.setCursor(0, 1);
  lcd.print("* to lock!");
  delay(1000);
}

void lock(){
  lcd.clear();
  lcd.print("Locking...");
  delay(1000);
  pos = 0;
  myservo.write(pos);
  setup1();
}
void sendSMS() {

  SIM900.print("AT+CNMI=2,2,0,0,0\r");
  delay(100);
  SIM900.print("AT+CMGF=1\r");
  delay(100);
  SIM900.println("AT + CMGS = \"+6XXXXXXXXXX\"");
  delay(100);
  SIM900.println("Wrong password Typed");
  delay(100);
  SIM900.println((char)26);
  delay(100);
  SIM900.println();
  // Give module time to send SMS
  delay(5000);
}

Servo.h use interrupts to generate the control signal. However, SoftwareSerial really messes interrupts up.
You can't use SoftwareSerial with anything that relies on interrupts for timing, like Servo.h.
Solutions:

Use a better Arduino with an unused hardware UART
Use an external hardware PWM controller to drive the servos
Use the internal hardware PWM (you'd need to find a library to do this) to drive the servos.

You can't use SoftwareSerial with anything that uses Timer1.  You can use all the other interrupts that you want.

Is there any library available for gsm that won't messes interrupts? or can you  suggest a best article for the internal hardware PWM ?

@Delta_G SoftwareSerial disables interrupts when sending. It also blocks all interrupts while receiving. You can't sensibly use SoftwareSerial with any timer interrupts and have it do anything reliable.

@Chard You may get better luck with AltSoftSerial. I did see a hardware PWM library around once, but I can't recall where. Ask Google - she knows.

I tried to replace SoftwareSerial to AltSoftSerial but stil the servo is shaking.

Btw I'm using Arduino Uno

@Chard Get a more suitable board then - or an external PWM servo driver module.

So it means there's no possibility to work this project on Arduino Uno? why? is it because of the interrupt pins?

It is possible - it just isn't easy. You need a good understanding of the underlying hardware. The problem you have is lack of suitable hardware resources, so are having to use software emulation ("Bit Banging") to get around it. And that doesn't work well when you're trying to do other things as well.

Both SoftwareSerial and Servo are trying to use the same hardware timer, Timer1.  There are other servo libraries like ServoTimer2 that will allow you to use SoftwareSerial and there are other soft serial libraries that will allow you to use Servo.  It is a pretty common topic that comes up a lot.  If you search a little bit you should find several solutions.

I used the #include"ServoTimer2.h" and remove the #include<Servo.h>. but the servo is still shaking.

SoftwareSerial does not use a timer.  It uses PCINT to trigger reception, and both reception and transmission of data use a "tuned delay" based on _delay_loop_2 which is a hard blocking loop written in assembly (in delay_basic.h).