text:
ESP32 - `Brownout detector was triggered ` upon Wifi begin
I'm Using an ESP32 - NodeMCU. One of the MCU's is acting weird upon boot, while at start I thought it was something to do with its sleep cycle. But, it seems that even on a minimal code as shown below, I get this message at the Serial output: Brownout detector was triggered
void setup()
{
  Serial.begin(9600);
  Serial.println("\nBegin");
  Serial.println(bootCounter);

  WiFi.begin("Xiaomi", "guy");

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

Edit 1: attaching MCU picture.
Can someone please explain ?
Edit 2: A workaround
stop alerting

Can you link to the actual board you are using?

@Majenko See edit 1

Those boards have an inherent weakness in that they don't provide enough decoupling capacitance for the module.
Not all modules are quite the same, and some have more internal decoupling than others (not by design, just due to component tolerances).
I have found that unless you provide adequate decoupling of your own some modules work just fine and some don't. Some brown-out and some fail to flash.
For all my designs now I always provide both a 100nF and an 10uF capacitor right at the power pins of the module. However those boards don't provide anything like that.
You need to modify the board to add a capacitor (about 10uF) directly across the power and ground pins (pins 1[ground]-2
[3.3v]) of the ESP32 module. I like to use an 0805 MLCC capacitor as they fit nicely across the pins and are discrete, but they can be tricky for a novice to solder. So an electrolytic through-hole capacitor can be a simpler proposition (make sure you get the polarity right).

Since I was it with solar panel and a battery, those RTC variables are vital to survive a proper boot. Can you please add a diagram foradding  capacitors?

Not really. You just connect one side to the GND pin (pin 1) and the other to the 3.3V pin (pin 2).

10uF and 100 nF in parallel ?

No, you just need the 10uF.

OK - soldered, and it helps!! ( when powered via 3.3v pin ), BUT when connected through USB i get this error constantly ( without booting at all ). what should I do about it ? Do you recommend adding this cap to all boards now ?

I always add a cap when designing an ESP32 board. Adding it to all development boards can't hurt, that's for sure.  For USB the on-board regulator may be a little weak, or your USB voltage may be a little reduced, maybe from a USB cable with too-thin wires.

I had the same problem. I found that solution in a forum on Github, which helped at once:
#include "soc/soc.h"
#include "soc/rtc_cntl_reg.h"
void setup(){
WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

Yes, I use it too now

Hey this work for me, thank you very much. even though i realized this is power issue, but It can be done with setup software :O

It is not a solution, it just suppresses the warning and may lead to other issues. Like other answers, you should try changing the cable, fixing the solder, or adding capacitors. If nothing works then I would say go with this. I tried it but it started showing different errors.

I came across the same issue on my experiments.
What sorted the issue for me was powering the ESP-32_CAM from the 5V pin on the programmer. Take the cable off the 3V and plug it into the 5V pin on the cam. Then use the jumper on the programmer to select the 5V.
I hope this makes sense and that it helps someone.

After some Tests i recognized, that the problem is between the miro-USB-connector to the Vin Pin. So i soldered a thin wire from Pin 5 of the USB-Connector (5V-Pin) to the Vin-Pin of The Dev-Board.
And it works without Problems.

for me it happend using batteries for solar panel uses ( while it didn't happen some other boards on same setup )

Swapping USB cable solved my issue of continuous brownout detector triggering.
I tried some above answers. Disabling brownout detector as suggested by Vahe Arakelyan helped on Blink sketch, but WiFi including sketches would still fail to run.
Then started to suspect HW and power failure. Did not soldering pins as suggested by user73106, but this made me notice voltage fluctuation. So swapped USB cable and this seemed to keep the voltage steady enough for good operation... It looks like some cable/connector fault may limit the current to allow some low power sketch to run but to fail on more current drawing sketch.

It could even be a software issue, i.e Code, if you use LedCWrite without its setup then it causes this issue.


text:
Is it possible to get which pin generated interrupt?
I wrote some code that handles rotary encoder using an interrupt, but I would like to get which pin generated the interrupt, so I'll be able to handle many interrupts in a single method.
Something like:
void ISREncoders()
{
  int pin = GetCurentInterruptPin(); // <============= this
  int dataPin = dataPins[pin];
  int data = DigitalRead(dataPin);
  if(data == HIGH)
  {
    encoders[pin] += 1;
  }
  else
  {
    encoders[pin] -= 1;
  }
}

Is it anyhow possible?

As mentioned in the answer this is not possible. Still, after peeking some encoder libraries that use interrupt found out that they do the following:
The Encoder class contains several static ISR methods hard coded.
As you create new objects it increments an internal counter and sets proper ISR method on the interrupt.
This is for sure the best solution available, but this is not at all scalable, for instance if you have an imaginary board with thousand pins that handle thousands encoders you will have to hard code each ISR method.

A common data, clock endoder. (when you rotate it generates a clock, and data contains rotation direction information). The objective is to use a single method to handle multiple encoders, I would like to know wich pin generated the interrupt.

What if user rotates two encoders at the same time, and inspite of possibility, two clock pins are in HIGH state?

keep a list of the states of the interrupt pins ... compare list at an interrupt .... anyway, your question is a general programming question ... there is no Arduino component in your question

Polling clock pin is OK, this is not the problem. The question is how to acquire which pin generated the interrupt, so, using interrupts I don't need to constantly poll clock pins. Posted here because it is an arduino (like) issue, and haven't found any information on this on Google. If anyone closes it I would understand. Thanks for your time and effort.

two clock pins are in HIGH state ... there is a flaw in your thinking (not related to your question though) ... your thinking should be two clock pins transition from LOW to HIGH state (or vice versa)

i said compare list at an interrupt ... do not poll constantly ... check the state of all the pins when interrupt is received ... anyway, it may be possible to determine which pin generated the interrupt through hardware, but that would be hardware dependent ... you said nothing about the hardware you are using

Imagine this scenario: two clock pins are in LOW state, they transact (at the same time) to HIGH state, this would generate two interrupts, which interrupt came from which pin? I should handle both encoders once, and skip next interrupt? This is for sure cumbersome to implement, just getting which pin generated the interrupt is easier and more elegant solution. With all due respect a simple: "No it is not possible actually" would be more useful from your part.

Let us continue this discussion in chat.

It is not possible to know which interrupt caused the ISR to be called. The INTFx flag gets cleared when the interrupt routine is called, so you lose that information (which is a shame).
The closest you could do is to have a separate ISR for each pin which just calls the common routine with a parameter to say which ISR it was executed via. That will add some extra latency though as it has to make an extra function call, but that can be somewhat mitigated by having the common function marked as always_inline, which means the compiler will duplicate it and place it within the code where it's being called from. This reduces latency but increases code size.
static ISREncoder(uint8_t pin) __attribute__ ((always_inline)) {
    // Do stuff with the `pin` variable
}

void ISR0() { ISREncoder(2); }
void ISR1() { ISREncoder(3); }

source: Stack Exchange

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

sort: votes


text:
How to send a number as a byte?
I want to send a number between 0 and 120 as a byte over Serial port. I'm working on a project that involves sending ultrasonic sensor readings over Bluetooth to an Android. I would like to send the entire reading as a byte and I think this can be done because an signed byte ranges from -128 to 127. However, the byte received in my Android app doesn't show the correct sensor reading. Here's the relevant code snippet:
  while (true){
      //ultrasonic sensor sends out signal
      digitalWrite(trigPin, LOW);
      delayMicroseconds(2);
      digitalWrite(trigPin, HIGH);
      delayMicroseconds(10);
      digitalWrite(trigPin, LOW);
      pinMode(echoPin, INPUT);
      duration = pulseIn(echoPin, HIGH);

      cm = (duration / 2) / 29.1;   // Divide by 29.1 or multiply by 0.0343
      inches = (duration / 2) / 74; // Divide by 74 or multiply by 0.0135
      // max range is 156 inches, but our app will only display up to 100 inches
      inches = min(127, inches);
      Serial.print(inches, BIN);
      delay(50);

In my Android app written in Java I read the value like this:
b = (byte) inputStream.read();

For example, if inches is 100 and I send that over Serial port, how can I expect to get the same reading in my Android app?

The problem is the BIN in your print statement.  Everything is ALWAYS binary.  The BIN means to break that binary up into ascii digits 0 and 1.  So if you send
Serial.print(21, BIN);
then the print function takes 21 as a binary number, 00010101 and then sends those binary digits as ascii.  So what goes out on the wire is 8 separate bytes, it goes 48, 48, 48, 49, 48, 49, 48, 49 as 48 and 49 are the ascii codes for 0 and 1.
What you want to do is just to send the raw byte.  So use Serial.write instead.  The print functions convert things to ascii representations but the write function just sends the raw bytes out.  So if you write:
Serial.write(inches);

Assuming that inches is a byte type variable then it just sends the raw byte out.

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


text:
Problem reading input data using SoftwareSerial library
I can't read data using SoftwareSerial library, because SoftwareSerial.available() is always 0, no matter what I do.
I'm trying to communicate 2 Arduinos Uno, the 1 Serial (name of the first Arduino Uno) and 2 Serial (name of the second Arduino Uno). The 2 Serial will send data to 1 Serial, and 1 Serial will receive this data through a Software Serial port, and then re-write the data received to Hardware Serial Port, but I can't read this, and when I try to print what is available is software serial port, always shows 0. I know that I can do the otherwise, but I'm testing this, because in my future project I will need to use this software serial port to read input data, so this is just a test.
The pic of my simulation with the circuit is this:
My code is:
For 1 Serial (the data receiver):
#include <SoftwareSerial.h>

SoftwareSerial portOne (7,8);

String str1;

void setup()
{
  // Start the hardware serial port
  Serial.begin(9600);
  portOne.begin(9600);

}

void loop()
{
  while (portOne.available() == 0)
  {

  }
  str1 = portOne.readString();
  Serial.println(str1);
}

For 2 Serial (the data sender):
String str;

void setup()
{
  Serial.begin(9600);   // put your setup code here, to run once:

}

void loop()
{
  Serial.println("Testing from serial port2");
  delay(2000);
}

I have already read in another topics of this forums and in the internet, but any of them worked for me.
Thanks in advance.
EDIT 1: I'm only simulating both of Arduinos on Proteus, I don't have the hardware with me right now. The image wasn't clear enough, so I hope this one is better to see the wiring diagram. I'm using Virtual Terminal at the Serial Ports so I'm able to see what is being written at the Serial Ports.

How should they ever communicate? In your wiring image I don't see any connections between the Arduinos. If that is not thr real wiring diagram, then please show it. Have you connected RX to TX and vice versa? And it seems, that you are currently only using a simulator? Which one are you using? Or do you really use the real hardware? (Thats a big difference)

I'm using Proteus to simulate, because I will only get the hardware in 2 weeks, so I'm trying to finish code before they arrive. Sorry if it isn't clear enough, but in Proteus you can link them with the labels to facilitate the view. I will edit my post with a more clear image with the wiring diagram.

Don’t the simulated Arduinos need their grounds connected, as they would in reality?

@StarCat Doesn't look like that's even possible in proteus... no GND or power pins.

I wonder... is SoftwareSerial even possible in simulation...? It barely works on real hardware.

@Majenko, You’re right. If that’s the level of simulation then I doubt it’s advanced enough to correctly simulate SoftwareSerial.

This article (updated today) says, that it should work.

In Proteus we don't have to connect to power supply or gnd phisically, it is like he is already connected internally.  The thing is Software Serial can be used in simulation to send messages, the thing is, I don't know if it can be used to read the messages received through Software Serial Ports.

@chrisl this article only shows the sent message, and this I can do easy at Proteus, but I couldn't find any article, video or anything simulating the Software Serial to read a message in Proteus. But thank you for your time and effort.


text:
Arduino using delay in I2C receiveEvent
I have read before that you can't use delay() inside I2C receiveEvent because it is an ISR.
What I want to do is as follows: I have a servo connected to my Arduino Uno and I want to control that using an I2C signal. Since I want to decrease the speed of the servo, I was previously using a loop with delay inside, which doesn't work when the function is called by I2C.
This is the code that I used before to control the servo:
void setServo(bool status) {
    if (status) {
        for (int pos = 0; pos <= 180; pos += 5) {
            servo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    } else {
        for (int pos = 180; pos >= 0; pos -= 5) {
            wasteFlapServo.write(pos);
            delay(50);
            Serial.println(pos);
        }
    }
    servoStatus = status;
}

How could I still control the speed of the servo even if I use I2C? Thanks for your help.
Kind regards,
Moritz

You are using 2 servos : servo and wasteFlapServo  ?

Note that Serial.println() is another no-no during an ISR. Any sort of serial communication is quite slow.

@DuncanC Though there the problem is more with the serial data not getting send. print() just places the data in the buffer. The actual transmission is done via ISRs, which place each byte into the UART hardware register. So all the data would fill the buffer, untils it's full. And the data would only get send, when going out of the ISR. I think in the newer core versions print will also not block at full buffer, when inside an ISR, though I don't remember, where I read that

The general way of doing long things triggered by an ISR is to simply set a flag insode the ISR, which then gets checked inside void loop().
volatile byte flag = 0;

void loop(){
    if(flag){
        // Do something here
        flag = 0; // reset the flag
    }
}

void receiveEvent(int howMany){
    flag = 1; // set flag, if correct data was received
}

Here keep the following in mind:

The loop() needs to run fast to react fast. Long delays are doing other long stuff there will impact the responsiveness of the code. Depending on your plans for the exact behavior, the usage of delay() is generally not good. You should look into the BlinkWithoutDelay example, that comes with the Arduino IDE. It is worth learning that rather early.

flag mus be declared volatile, to tell the compiler, that is may change at any time. Otherwise it might optimize the variable away.

flag is of type byte here. It is imprtant, that this flag only has a single byte, because reading and writing of a single byte cannot be interrupted. Multi-byte variables get read or written in multiple COU cycles, thus it would be possible, that the interrupt writes parts of the variable, while you are reading it in the main code. That would lead to garbled data. By using a single byte, you avoid using critical sections for keeping the reading in main code save. For a flag thats way simpler.


text:
using PN532 chip on arduino
I've recently purchased an NFC-PN532 module online, which I connected to my arduino board and tried to get working. After connecting the pins and using the PN532 adafruit lib I encountered and error where the board was not being picked up. I was using the 'readMifareClassic' example from the lib and uploaded the example to the board and it resulted in the image below where I would receive a '?' or the first print output which is 'hello' in the code.
I'm not that experienced with NFC atm and so im seeking some guidance on what may be the issue. If you need more information please leave a comment.
Thank you

the example has 115200 baud for Serial. your Serial Monitor is set to 9600 baud

thanks Juraj, but the chip is not being picked up now and feel as though it might be due to the wiring though i connected the pins according to the code, yet its not picking it up

but that is a different Question

A very common error when PN532 module is not recognized, is that you are not using the right bus (I2C, SPI, UART).
Make sure:
In Arduino sketch make sure to follow carefully the lines that need to be commented out.
On the PN532 make sure that DIP switches match your bus configuration


text:
Power supply for Seeeduino Xiao
The Seeeduino Wiki claims that it can run on 3.3V/5V. It doesn't specify if it can step down higher voltages. I am looking to power the XIAO using a battery. It usually uses a USB-C cable which can provide 5V. Will I need to step the voltage down, or does it behave like a normal Arduino Nano and automatically step down the voltage?

Have you successfully used a 6v powersupply to power up the XIAO? I asked on Seeeduino Xiao forum and they said 5V is maxium, if higher it will damage the board.

Hey @NeungChung, I was looking into this as part of a project, but ended up finding out that I didn't need to use the XIAO anymore, so unfortunately I can't answer your question. Did they provide any details as to why this is the case? I'd say that the answer below is pretty detailed.

If you scroll down on that page you link to you can see the power circuit. It uses an XC6206 voltage regulator which has a maximum input voltage of 7V and a dropout voltage that could be as high as 680mV.
So you can feed between about 4V and 7V in to the VIN pad and it will step it down to 3.3V. Anything below 4V and you will go "out of regulation" though the system may still run down to lower voltages. If you go above 7V you will blow it up.

Thanks a lot! A 6V power supply will work perfect.

Make sure it's a regulated 6V supply. Unregulated power supplies tend to output voltages much higher than their published voltage under very low load. You might well exceed your 7V "do not exceed" voltage limit at the low current draw of a microcontroller.

@DuncanC The OP specifies a battery...

@Majenko initially they mentioned a battery, but their last post said a "6V POWER SUPPLY." I took that as a change of plan.

@DuncanC Whereas I take "power supply" to be any source of power, including batteries.

You quoted a value from ABSOLUTE MAXIMUM RATINGS table. Values from ELECTRICAL CHARACTERISTICS apply for normal operation, which limits the input voltage to 6V.

A batch of 60 XAIO ESP32C3's will not power on using a 3.3V DC supply applied to pins 3V3 and GND. They only power on using a 5V input applied to pins 5V and GND.
The test rig was a bench DC power supply.
The XIAO ESP32C3 seems to power on as low as 4.1V DC applied to the 5V pin.
No external component is required, just a direct connection from the bench power supply to the 5V pin. Therefore the posts somewhere on the internet about needing a diode in the path of the positive supply do not appear to be necessary.
Note that the ESP32C3 were not programmed, ie. they arrived from the factory and were powered without downloading any code to them. Thus the posts about sleep mode are not applicable as the 3.3V and 5V behavior should then be identical, but they are not.


text:
Why is there a need of use delay() after using Serial.flush() in the program
This code is a part of a long code for understanding serial communication and the functions related to it.
char buffer[18];
int red, green, blue;
int RedPin = 11;
int GreenPin = 10;
int BluePin = 9;

void setup()
{
Serial.begin(9600);
Serial.flush();
pinMode(RedPin, OUTPUT);
pinMode(GreenPin, OUTPUT);
pinMode(BluePin, OUTPUT);
}

void loop()
{
if (Serial.available() > 0) {
int index=0;
delay(100); // let the buffer fill up
int numChar = Serial.available();
if (numChar>15) {
numChar=15;
}
while (numChar--) {
buffer[index++] = Serial.read();
}
splitString(buffer);
}
}

In void setup(), Serial.flush() is used. On internet, I have read that it flush out any character present in a serial line. After calling it we can be sure that all the data has been sent before moving on to the next line of the program.
In void loop(), in the first if condition, delay(100) ensures to fill the buffer. Basically, buffer is the place in memory where the received serial data is stored prior to processing.
The question is that is there any need of using delay(100), if we call the Serial.flush() initially because it ensures that all the serial data has been transmitted (as in serial transmission one bit is transmitted at a time)? Does it takes further time to store the transmitted data in the memory (buffer) and does this is the reason to use delay(100)? Please clarify why delay(100) is used after calling Serial.flush(), I am confused.

flush() changed usage in Arduino many years ago. the first use was to 'eat-up' all input. now it is flush the TX buffer. from change log for Arduino 1.0 "Serial.flush() now waits for transmission of outgoing data rather than discarding received incoming data."

Serial.flush() waits for transmission of outgoing data. But does this waiting time includes the storage of data in the buffer? As we use delay() in the further part of code.

No. The use of flush here is in appropriate.  It is not needed there.  This was written by someone who doesn’t understand what it does.  You can just remove that flush line.

The delay in loop is unrelated.  That’s waiting for the sender to finish sending.  This is a poor blocking method.  There are far better ways to write this code.  You should probably put this one in the rubbish bin and find something written by someone who knows what they’re doing.

flush() does nothing here. no data to flush are in transmit buffer at start. and how would it help with receiving?

The Serial.flush() is doing nothing. It delays until all bytes have been sent out of the UART. Since nothing has been sent it's not got anything to wait for.
The delay after the available call is very bad practice. It's a really really bad way of dealing with serial reading.
You should read this for a better understanding of serial communication.


text:
How to convert RGB values to Intensity
I made an arduino color sensor with tcs3200 and arduino uno. I have coded the arduino to find the RGB values when I place the color paper below the sensor. How can I derive the intensity using the RGB values.

How do you define "intensity"?

I remember a formula that calculated luminance (perceived brightness) using simple weights applied to the red, green, and blue values in a light source.
This formula allows for the fact that the human eye is most sensitive to green light and least sensitive to blue light.
The Wiki article on HSV/HSL has these different weightings for R,G, and B. (In all of the following, Y' is the computed brightness value.)
Y' = 0.2989 • R + 0.5870 • G + 0.1140 • B
Y' = 0.2120 • R + 0.7010 • G + 0.0870 • B
Y' = 0.2126 • R + 0.7152 • G + 0.0722 • B
Y' = 0.2627 • R + 0.6780 • G + 0.0593 • B

All of them weigh green more than the other 2. I didn't read the article closely enough to understand the different weightings of the different formulas. Perhaps they convert colors using different color models like Adobe RGB and sRGB.
See the link at https://en.wikipedia.org/wiki/HSL_and_HSV for more information.

There is no simple way to have a formula from the RGB values to intensity.
Also, there is intensity that can be measured with an intensity meter/sensor, but what people (humans, or each individual) consider more intensity (perceived intensity) is not fully related.
However, some things I found when I had a similar problem:

Typically a LED value of 0 is OFF, 1 is shining a little and 255 a lot. However, the difference in (perceived) intensity between value 1 and 10 is much higher than between e.g. 100 and 255.
Also, each LED color has a different intensity, e.g. red seems more bright than blue or green, with the same R, G or B value for the DMX lights I have, as can be read from the remarks from Duncan C and Majenko below, red is less bright than others.
Also, it depends on the physical device probably (it could have an internal algorithm to convert an RGB value to some power driven to the LED(s)).

What you can do is measure for each value and color the intensity with an intensity meter or sensor.
Or, in case you are more interested in the perceived intensity, manually check two LEDs with values to and create your own intensity algorithm.
I ended up having 3 arrays (for R, G, B), having for each value from 0-255 an 'intensity' value. I did it partly by measuring, partly by manually checking.

Red seems more bright?!? That doesn't sound right. The human visual system is most sensitive to green light. Red and blue wavelengths are much less visible at the same intensity.

Red is used for night-time illumination as the eyes are less sensitive to it and doesn't cause the irises to contract ruining your night vision. Green is used for night vision because the eyes are more sensitive to it.

Maybe 'my' Chinese DMX light has already some kind of algorithm inside because red is more bright than others, but in general it is not. I will change my answer

@Majenko: red is used for night-time illumination because the L cone cells in the retina are sensitive to it, while the rods are not. The rods are responsible for night vision and, since the can't see the red light, that light doesn't inhibit them.

@MichelKeijzers That's probably more down to lensing than brightness.

@EdgarBonet too technical...

@Majenko Could be true ... anyway I made these RGB tables to make the brightness (according to me) better.


text:
nRF24L01 - Measuring distance using time elapsed
For school usage, my team and I are working on a wristband that will alert the user if they are too close to another wristband (for social distancing). The problem is measuring distance using radio waves. Since I cannot use signal strength, I'm thinking about calculating distance from time taken to transfer some data and velocity (which will be around the speed of light). I discarded the idea of using ultrasound because it is too easily interfered with by other obstacles.
My plan is along the lines of this:

Sensor 1 and 2 are synchronised to a clock.
Both will run a
"stopwatch", and the time values should be exactly the same at the
same time.
Sensor 1 sends out a message to Sensor 2. The message
contains the time at which the transmission started.
Sensor 2
receives the message, immediately records the time of reception, and
calculates the time taken for data to travel
d = v/t
Vice-versa

If the distance is smaller than the radius, a warning is triggered in the form of a vibration motor.
Limitations include clock speed; I intend on using a Seeeduino XIAO, an Arduino-compatible board. The clock speed is max. 48MHz, meaning that the smallest increments it can measure is 20.82 nanoseconds. I also calculated that it would take 13.33 nanoseconds to travel two metres (the former distance to keep in public). Hence, with the clock speed available to me, I can only measure 3m and beyond.
Assuming I was happy with this distance, would I be able to do this using one single Arduino sketch? I know that Arduino programs can only run one at a time. Would a constant background clock/stopwatch be too complex? Could you give me any other pointers?

You'd want an atomic clock strapped to each user's back for those kinds of timing accuracies...

@Majenko Timing accuracies aside, would it be possible for that kind of code to be run simultaneously? Run a counting clock whilst constantly sending radio pulses? Subroutines?

If you write it properly you can make it like two things are running at the same time, but that won't get you around the basic physical barriers that make it impractical.

the ultrasound idea may actually work ..,some type of a ping exchange .... perhaps a unique sequence of pulses could be transmitted ... when the sequence is received, a response would be sent .... the originator of the exchange would listen for the response and, when received, calculate the round trip .... a radio link could be used for administrative functions, such as system synchronization

@jsotola Ultrasound sensors have a narrow detection angle and area - typically about 30 degrees. If I used it on a wristband, I might pick up false positives from objects around me such as tables and chairs, not to mention the fact that I could be standing right in front of someone and not pick them up. Ultrasound cannot penetrate objects... they are useful because they bounce off them.

how about this .... radio is used to assign every wrist band a spot in a queue so that there is no interference between bands .... when a band has its turn, it sends out a synchronizing radio message and an ultrasonic pulse.... all the other bands wait for the ultrasonic pulse ... any band that receives the pulse before a timeout value will be deemed to be too close ... a radio message would be used to alert of proximity .... it makes no difference if the ultrasonic pulse is reflected from an object .... the ultrasonic transmitter and receiver would have to be made omnidirectional

Omnidirectional ultrasonic sensors are expensive, and this is a school-wide project. Thanks for your ideas, but I have chosen to go with BLE.

13.33 nanoseconds is actually 4 meters. The NRF send bits at 2Mpbs, using FSK. So the transmission is divided in chunks 250ns. So don't expect ns precision from the signal detection logic inside the NRF.

@Gerben My mistake... Originally I had planned for the signal to go from S1 to S2 then back to S1, thus making the formula v=2d/t and d=vt/2. Thanks for pointing this out. I have abandoned this idea anyway, and am now pursuing BLE. It's not accurate, but it's what I need.

Speed-of-light-delay measurements are not practical for the use-case you propose. As Majenko suggests in his comment, you'd need EXTREMELY accurate time measurement, as well as high speed radio-frequency signal processing. Any measurements you do through software will be far too inaccurate as a result of the software timing.
Apple's iBeacons (which are based on BLE) offer immediate, near, medium, and far distance readings that are based on signal strength. You should be able to achieve something similar with your own wristbands using BLE. The different distance thresholds would have some slop to them, but it should be possible to get decent results.

How about if I subtracted process time from the overall time? I know that the RF module takes 2us to process each bit.

No. This WILL NOT WORK without specialized hardware.

I am looking into BLE - it looks like it's what I need.

@Hari5000: Re “the RF module takes 2us to process each bit”: do you mean it always takes exactly 2.000 µs? Or is it more like (2.00±0.01) µs?

@Hari5000 The official Covid-19 API from google and Apple also uses BLE beacons. They have chosen that approach for a reason. Distance calculation between two arbitrary (and moving) points in that range are not that easy. BLE is the way to go for best and easiest results.

Maybe not "best" results, but easiest, and good enough, results, using inexpensive hardware.


text:
Connect two SD cards to one Arduino board and copy from one to another
I'm trying to connect 2 SD cards to an Arduino Uno board.

My first question is: Is it possible to connect two SD cards to one Arduino simultaneously?
The second question is: If it is possible to connect 2 SD cards, How can I copy card 1 data to card 2

My project goal is to copy data from one peripheral memory to another peripheral memory when an external interrupt occurs.
Can anyone help me please ?

Yes, SD cards use the SPI bus so you can connect more than one.  They will each need their own chip select line.  To copy just read from one and write what you read to the other.  Super simple.  If none of this makes sense then do some study on dealing with a single SD card.  Once you got the basics hooking up two will be trivial.

Just watch out cause some cheap SD modules don’t release the line when you deselect them.  They won’t let anything else on the SPI bus work without some minor modifications.  Buy good quality stuff and it shouldn’t be a problem but if you go for the cheapest thing you can find then you’ll need to study this issue as well.

Thanks for your help & good answer :). Actually this is not a real project and I should simulate it using Proteus simulator. Do you have any good tutorial for how to deal with SD cards in Arduino? @Delta_G

@user67463 have you tried googling for a tutorial? There are tons of them

There are literally hundreds of those tutorials all over the internet.  Finding one will be far easier than writing this code.  If you open the Arduino software and check the examples there are examples of how to use an SD card.  Start there.  Or just google “Arduino SD” and start reading.

One extra hint for you since you say you want to do this in response to an interrupt.  Don’t try to do this inside the interrupt handler.  Let the ISR set a flag and have the loop function see that and handle the reading and writing there.

You can't do it with your Arduino-Uno (and usual SD libraries).
SD cards are organized in 512 byte "sectors". You need at least one sector for the file system itself and one sector for the data. If you try to have two files open simultaneously, all your 2048 bytes RAM are required for the SD buffers and you can't return from the file open() call any more.

You could do a block-by-block copy of the SD card, instead of actually reading the file system. Downside is that the SD to copy to has to be as large, or bigger as the original card. And that copying always takes the same (long) amount of time, no matter "full" the card is

@Gerben: correct. (That's my "usual SD libraries" restriction)  If you have old 64 MB SD cards, you might do that full copy. But the sentence "when an external interrupt occurs" makes me think user67463 tries to ride a dead horse.


text:
Nano: All digital pins do not output anything
New user here. Using the examples provided on the Arduino IDE software I could produce melodies with a piezo buzzer, or have a blinking LED.
Not anymore. No digital pin is giving anything. I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.
So I tried connecting an output digital pin (13) to an Analog input pin, or any one that can be put as input (A7, D5, etc.) (with a resistor so not to destroy the little thing).
const char out=13;
const char  in=8;
char         i=0;
void setup() {
  Serial.begin(9600);
  pinMode(out, OUTPUT);
  pinMode(in,  INPUT);
  digitalWrite(out, LOW);
}
void loop() {
  if(i&1){
    digitalWrite(out,i&2?HIGH:LOW);
  }else{
    Serial.println(analogRead(in));
  }
  i++;
  delay(50);
}

The output has been 0, whichever digital pin it is connected to.
How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

I currently use a breadboard
The ground is connected correctly (to GND)
It stopped working between uses, last time I was trying a Tone(out,val) melody
I'm measuring the out-pin value by connecting it to an analog in-pin with a resistor in series
I did set the out-pin as such during setup. (pinMode(out, OUTPUT);)

So! Looks like I didn't understand the codes for the digital pins. I thought we had to use the pin number, but the digital pin number (say 10 for D10) is what it takes to address it. And I was always referring myself back to the schematic for each pin -_-.
As well with the accepted answer, I needed to pull down (or up? still can't figure it out!) the input pin with a resistor to ground.
Thanks everyone!

Welcome! Could you add a little more information about your setup. Do you use a breadboard? Do you have GND correctly connected to your external components? When did it stop working? How are you measuring the pin’s output? Did you set the pins to OUTPUT in setup()?

Thank you StarCat! I have added the information thank you!

Do you have a multimeter available to measure the voltage on the output pins and the supply voltage? Is the Nano behaving normally otherwise?

A6 and A7 are analogue inputs only. They can't do digital reading or writing.

Thanks Majenko and StarCat! I don't have a multimeter available, but the reading with analogRead starts high and go lower and lower.

Did you set the pins to OUTPUT?  Show the whole code.

Added the corrected code Thank you Delta_G!

Your sketch works on a Nano (clone) that I have

I am using a high-brightness white LED with a 10kΩ resistor to bring the brightness down to a bearable level, so the current drawn is about (5v-2.2v)/10kΩ = 0.28mA. This is a low level of current and should be safe for poking around with.

I can see the embedded LED blink if I program the Pin 13, but no impact outside of it.

That suggests that the ATmega328P is essentially undamaged and that at least the IC leg connected to D13 is working as it should.

How can I actually find out if, by any chance, I successfully (!) damaged all my digital pins?

Without a multimeter or other tools,  I would take a LED and resistor that draw less than 5mA, test them between VCC and GND to make sure they work
Then I would use the resistor and LED to check the output of each of the D2 to D13 outputs using your existing sketch.
When the onboard LED blinks, I am able to attach a LED and series resistor to pin D13 and get it to blink.

I wasn't sure what you intended by setting in to 8 so I later changed your program as follows:
const char  in=A1;

and I got this output on the serial monitor after connecting a jump lead from D13 to A1
0
1010
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1009
0
1008

If I pivot the LED away from pin D13, I can use a jump lead as a test probe

Main points:

pick a high resistor value that minimises current drawn but is still easily visible.
check the LED works! (is right way around etc)
use a jump lead as a probe.

There are more sophisticated test circuits you could build with a FET etc but this would normally be enough for me to decide if an Arduino's outputs are damaged.

Extract from ATmega328 datasheet - note the max current draw per pin is 40mA. Exceeding that is probably the easiest way to damage the IC but if the onboard LED labelled "L" (and connected to D13) works, it means that part of the IC is undamaged.

I'm impressed by how nice people already are, thank you! That is an exhaustive answer and shows you spent actual time to solve my issue. I'll test it and let you know what's the results!!


text:
Arduino Micro: 69 is supposed to show up when I press 1 on the keypad, however some weird number (15 in this case) is showing up
// **I AM ALSO GETTING WEIRD CLUELESS DELAYS WHEN I PRESS BUTTONS ON THE MODE MENU**

/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

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

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

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

int timeV, thrustV, massV, gravityV;

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

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

bool keyDetect = false;
bool menuKeyDetect = false;
bool goHomeDetect = false;

bool countDownDetect = false;
bool countDownOutput = false;
bool twrCalDetect = false;

String timeValue, thrustValue, massValue, gravityValue;

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcd.clear();

  Startup();

  timeV = constrain(timeV, 15, 120);
}

void loop() {
  PressKey();

  if (menuKeyDetect == true) {
    PressMenuKey();
  }

  if (goHomeDetect == true) {
    GoHome();
  }

  if (countDownDetect == true) {
    CountDownSequence();
  }

  if (countDownOutput == true) {
    CountDownOutputSequence();
  }
}

// Pages & Sections
void Startup() {
  lcd.print("Jeb's Launch");

  lcd.setCursor(0, 1);
  lcd.print("Control System");

  delay(3000);

  lcd.clear();
  lcd.print("Alpha Build 0.70");

  lcd.setCursor(0, 1);
  lcd.print(" STUDIO HORIZON");

  delay(3000);

  lcd.clear();
  lcd.print("Welcome, Kerman");

  lcd.setCursor(0, 1);
  lcd.print("Press any key...");

  keyDetect = true;
}

void ModeMenu() {
  menuKeyDetect = true;

  lcd.clear();
  lcd.print("1. Countdown");

  lcd.setCursor(0, 1);
  lcd.print("2. TWR");
}

void CountDown() {
  lcd.print("Time (sec): ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
  countDownDetect = true;
}

void TwrCal() {
  lcd.print("Thrust: ");

  lcd.setCursor(0, 1);
  lcd.print("# to continue...");

  goHomeDetect = true;
}

// Actions & Behaviours
void PressKey() {
  char key = keypad.getKey();
  if (key) {
    Serial.println(key);
    if (keyDetect == true) {
      lcd.clear();
      ModeMenu();
      keyDetect = false;
    }
  }
}

void PressMenuKey() {
  char key = keypad.getKey();
  if (key == '1') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      CountDown();
      menuKeyDetect = false;
    }
  } else if (key == '2') {
    Serial.println(key);
    if (menuKeyDetect == true) {
      lcd.clear();
      TwrCal();
      menuKeyDetect = false;
    }
  }
}

void GoHome() {
  char key = keypad.getKey();
  if (key == '*') {
    lcd.clear();
    ModeMenu();
  }
}

void CountDownSequence() {
  char key = keypad.getKey();

  if (key == '0') {
    timeV = timeV + 0;
  }

  if (key == '1') {
    timeV = 69;
  }

  countDownDetect = false;
  countDownOutput = true;
}

void CountDownOutputSequence() {
    lcd.setCursor(13, 0);
    Serial.println(timeV);
    lcd.print(timeV);
}

According to the documentation, the getKey() function is
non blocking. This means it does not wait for a key to be pressed:
it instead returns immediately whether a key has been pressed or not. If
no key has been pressed (i.e. most of the time), it returns a NUL
character, which has the numeric value zero and evaluates to false in
a boolean context. Hence the idiom:
char key = keypad.getKey();
if (key) {  // if a key has actually been pressed
    // handle it
}

The CountDownSequence() function fails to account for this:
void CountDownSequence() {
  char key = keypad.getKey();  // no check for NUL

  if (key == '0') {
    timeV = timeV + 0;  // this has no effect at all
  }

  if (key == '1') {
    timeV = 69;  // this is what you would expect to be executed
  }

  countDownDetect = false;  // these two lines tell the rest of the
  countDownOutput = true;   // program that we are done.
}

Since key will almost certainly be '\0', the program will move to
the next step without ever initializing timeV.
As a side note, I recommend you try to rewrite your program as a finite
state machine. A single state variable would make it less
confusing and easier to understand than the current collections of
booleans.

Edit: Expanding on the idea of the finite state machine. I tried an
implementation of your concept based on it.
For handling a menu system, where the user can navigate through several
on-screen “pages”, the most obvious first approach is to have one state
per page displayed. For this program, these states could be:

MENU, which offers the choice to move to either of the following two
pages
SET_COUNT allows the user to set the countdown duration
TWR allows him to compute the thrust/weight ratio
COUNT_DOWN actually runs the countdown timer

In the following, I added an extra transitional state called START
that comes right before MENU. This is not required, and its only
purpose is to avoid code repetition by having a single transition
(START → MENU) responsible for actually drawing the menu.
When implementing a finite state machine, my first recommendation would
be to start by drawing a state diagram like this:

In this diagram, each transition is labeled with the event that triggers
it. The events are key presses, save for “finished” which means that the
countdown is done. The state diagram can become significantly more
complex than this as you add new functionality. It is, however, a very
good way of designing your system from the point of view of user
interaction.
Once you are happy with the state diagram, the coding is just a matter
of translating it to a switch/case construct, with one case per
state. Here is my take at it:
/*
   Jebediah's Launch Control System for Kerbal Space Program
   Alpha Build 0.70
   An Open-Source Project by John Seong
*/

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

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

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

byte rowPins[ROWS] = {12, 11, 10, 9};
byte colPins[COLS] = {8, 7, 6};

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

LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);

// Show a two-line message on the LCD.
void lcdShow(const char *line0, const char *line1) {
  lcd.clear();
  lcd.print(line0);
  lcd.setCursor(0, 1);
  lcd.print(line1);
}

void setup() {
  Serial.begin(9600);
  lcd.begin(16, 2);
  lcdShow("Jeb's Launch", "Control System");
  delay(3000);
  lcdShow("Alpha Build 0.70", " STUDIO HORIZON");
  delay(3000);
  lcdShow("Welcome, Kerman", "Press any key...");
  while (!keypad.getKey()) ;  // wait for key press
}

void loop() {
  static enum {START, MENU, SET_COUNT, COUNT_DOWN, TWR} state = START;
  static uint32_t last_second;  // millis() value on last full second
  static int count;             // countdown value

  char key = keypad.getKey();

  switch (state) {
    case START:  // transitional state
      lcdShow("1. Countdown", "2. TWR");
      state = MENU;
      /* fallthrough */
    case MENU:
      if (key == '1') {  // Countdown
        lcdShow("Enter time", "seconds: ");
        count = 0;
        state = SET_COUNT;
      } else if (key == '2') {  // TWR
        lcdShow("Thrust:", "# to continue...");
        state = TWR;
      }
      break;
    case SET_COUNT:
      if (key >= '0' && key <= '9' && count <= 99) {
        lcd.print(key);
        count = 10 * count + (key - '0');
      } else if (key == '#') {
        lcdShow("Take off in", "     seconds");
        // Force a refresh on entering COUNT_DOWN:
        last_second = millis() - 1000;
        count++;
        state = COUNT_DOWN;
      } else if (key == '*') {
        state = START;
      }
      break;
    case COUNT_DOWN:
      if (millis() - last_second >= 1000) {
        last_second += 1000;
        count--;
        if (count == 0) {
          Serial.println("Take off!");
        } else if (count < 0) {
          state = START;
          break;
        }
        lcd.setCursor(1, 1);
        lcd.print(count<10 ? "  " : count<100 ? " " : "");  // pad
        lcd.print(count);
      } else if (key == '*') {
        state = START;
      }
      break;
    case TWR:
      if (key == '*' || key == '#') {
        state = START;
      }
      break;
  }
}

Note the comment “fallthrough” between START and MENU. This
indicates that the lack of break at this place is intended: the
processing of the MENU case will follow right after the processing of
the START case, in the same loop iteration. The purpose of the fall
through is to not loose the current key press, if any. If this is not
important, you could put a regular break here and defer the handling
of MENU to the next loop iteration.
Note also that the key presses are checked with tests of the form
if (key == SOME_VALUE), which means there is no need for an extra
if (key) to test whether there was an actual key press.


text:
Arduino glitches and makes 240 < 7 and -240 > 7
I'm experimenting with the joystick and the MAX7219 module (8x8 LED display) and i made this program:
#include "LedControl.h"

LedControl lc=LedControl(11,13,10,1);

int Xo = 36;
int Yo = 34;

int xPin = A1;
int yPin = A0;
int buttonPin = 7;

int xPos = 0;
int yPos = 0;

int Xvel = 0;
int Yvel = 0;

int lastMapX = -1;
int lastMapY = 0;

void setup() {
  pinMode(xPin, INPUT);
  pinMode(yPin, INPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  Serial.begin(9600);
  lc.shutdown(0,false);
  lc.setIntensity(0,8);
  lc.clearDisplay(0);
}

void loop() {

  Xvel = joystickMap(xPin, Xo);
  Yvel = joystickMap(yPin, Yo);

  if (Xvel == 0 and Yvel == 0) {
    Xvel = lastMapX;
    Yvel = lastMapY;
  }

  yPos = yPos + Xvel;
  xPos = xPos + Yvel;

  if (xPos < 0) {
    xPos = 0;
  }else if (yPos < 0) {
    yPos = 0;
  }else if (xPos > 7) {
    xPos = 7;
  }else if (yPos > 7) {
    yPos = 7;
  }

  lc.clearDisplay(0);
  lc.setLed(0,xPos,yPos,true);

  Serial.print("x=");
  Serial.print(yPos);
  Serial.print(" y=");
  Serial.print(xPos);
  Serial.print(" buttonpress=");
  Serial.print(digitalRead(7)==0);
  Serial.print(" x>7=");
  Serial.println(xPos > 7);

  lastMapX = Xvel;
  lastMapY = Yvel;

  delay(100);
}

int joystickMap(int in, long offset) {
  int firMap = map(analogRead(in), 0, 1023, -102, 100)+offset;
  if (firMap == 0 or firMap == 1 or firMap == -1) {
    return 0;
  }else if (firMap > 0) {
    return 1;
  }else if (firMap < 0) {
    return -1;
  }
}

it should make it for the player impossible to stop. But there is a glitch witch allows you to go off-screen. If you are in any corner and you go diagonally to the opposite corner you just go through. Here  is a screenshot with the program and the serial monitor:

My Arduino is a UNO R3. How can i fix this glitch?

Read your code where you are printing your values. Read it carefully. It's behaving exactly as you are telling it...

don't you think, that tying the conditions for x and y together with else if is incorrect? x and y are independent coordinates, so why should the limitations on y being only imposed, if the limitations on x weren't imposed? Split your if conditions up into one set for x and one set for y


text:
Make WiFi Router Using Arduino board
void switch_led() {
bool SwitchReading = digitalRead(SWITCH);
if (SwitchReading == HIGH) {
Serial.println("Now pressed....");
state = state + 1;
if (state % 2 != 0) {
  digitalWrite(LED, HIGH);
  char data1[] = "{""LDRValue"": 88888888}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data1));
    client.println();
    client.print(data1);
    Serial.println("1.finish");
  }
  Serial.println("2.finish");
}
else {
  digitalWrite(LED, LOW);
  char data2[] = "{""LDRValue"": 1111111111}";
  Serial.println("\nStarting connection to led server...");
  if (client.connect(server, 8040)) {
    Serial.println("connected to post server");
    client.println("POST /api/sensor HTTP/1.1");
    client.println("Host: 192.168.2.116:8040");
    client.println("Content-Type: application/json");
    client.print("Content-Length: ");
    client.println(sizeof(data2));
    client.println();
    client.print(data2);
    Serial.println("3.finish");
  }
  Serial.println("4.finish");
}
delay(500);
   }
}

It works perfect for the first and second posts in both Arduino and API but at the third post it works fine on Arduino but it takes long time on the API(about 2 minutes to get the post). The fourth and the fifth posts also works fine but the sixth is same as the third. Knowing

no "Connection: close" and client.stop()?

PS Host shouldn't contain the port number. That is; client.println("Host: 192.168.2.116:8040"); should be client.println("Host: 192.168.2.116");


text:
3pin (GND, 12V, tach) 12v FAN control using PWM
I know there are fans out there that have a dedicated PWM input, but I like to know if I can PWM control a fan that does not have such a dedicated PWM input. So...
If I have a 3 pin 12v fan like the Noctua NF-A20 with connections:

GND
12 V
tach out (RPM measurement)

Can I control its speed by PWM on the 12V supply voltage (using a MOSFET most probably)?
Would the tach out still work?

I think that is OK AFAIK, I remember controlling my car's robot normal DC motor with PWM very well, yet the only  thing I hate about it is it did make a lot of noise, yet I used this noise to generate a small tone when I turn on the robot :)

you can run such fans at 5v too, many do to keep them silent...

I am powering from usb 5v. I could implement a arduino controlled step up boost 5v-12v’(eg based on mt3608) instead of pwm. Wondering what what be best pure voltage controlled or pwm....

Or straight from i2c like here https://www.monolithicpower.com/en/mp8859-integrated-dc-dc-buck-boost-converter-with-i2c-control

Yes, and yes.
You have to modulate the +12V rather than GND because the output is referenced to ground. That means you need to use the classic N+P channel FET arrangement:

simulate this circuit – Schematic created using CircuitLab

Why 2 mosfets? One fet berween 12 and fan 12v controlled directly from the arduino should work no? (With pull down on gate of course)

@HixField The Arduino's 5V logic level is too low to switch off the P fet. It is possible to emulate M2 with the GPIO by using LOW for on and INPUT for off, but you can't do that with PWM. M2 turns the Arduino's GPIO into "open drain" and is used to turn M1 on and off.

I would use a logic level fet such as the http://www.aosmd.com/pdfs/datasheet/AO3400A.pdf that works straight from 5v logic

What I dont understand is how the tach output can still work if the fan is not powered (briefly by pwm)? Is it using a mechanical contact?

@HixField logic level has nothing to do with it; 5v and 0v are both "on" states given a ~12v source on a p-chan fet.

@dandavis I would think this would also work? https://arduinodiy.wordpress.com/2012/05/02/using-mosfets-with-ttl-levels/ this means switching on the low side?

the 12v is the problem, and getting an ardunio to 11v is just as hard as getting it to 9v. When sinking with an n-chan, 5v turns on the vast majority of nfets, but 3.3v is usually too little for all but logic level specs. When sourcing with a pchan, vgs-th is subtracted from the source voltage, not added to the source voltage.

Ah I get it. We must have a stable GND because the tach otherwise would fail! So we must switch on the high side hence the 2 fet setup

bingo. i actually would switch the common with a simple nchan fet; i don't think the tach needs 12v anyway. you can pull the n-chan down with a npn bjt as well. there's also several opto-isolators that can drop-in as well, no fet needed.

@dandavis The "tach" is a hall effect sensor. If you switch the "common" (ground) then you don't have a ground for the tach's output circuit, so you don't get proper readings (i.e., you only get readings when the N-fet is on, and garbage when it's off). It's essential to switch the +12V and not the ground.

thanks for this great info and help!

@Majenko: interesting. from what i can tell you're right, but i've used sink pwm and tach in a esp-32 based PSU project and it worked. Maybe the pwm frequency was high enough, the rpm low enough, and the intrinsic capacitance high enough that it worked out...

@dandavis Quite possibly. You want the PWM to be >25kHz to avoid and the RPM will be below 3000 RPM typically.

Could the tach input pin use the Arduino's internal pullups? or are those (20-50k) too low-value for a clean waveform at fan RPMs?


text:
What is the maximum "wattage" can be pushed into an ATMega328 ADC pins?
I was doing some Ohm's Law calculations to calculate the voltage output from a 2-resistor voltage divider, the input will be with a maximum of 12 volts, I want the ATMega328 to measure that voltage, so I simply thought of putting two resistors in series with values of 330 ohms and 220 ohms like this:

simulate this circuit – Schematic created using CircuitLab
Theoretically on paper the maximum voltage outputting from the node going to the ATMega328 is ~4.8V, but I want a special safety feature, I want to put in mind that at anytime the ground connection can be hung open (to simulate a lose breadboard connection, bad soldering joint etc...) now based upon my understanding if there is no ground connection, the voltage going to the Arduino will be 12V which is a killer, as after looking on the ATMMega328 datasheet it states that

28.1 Absolute Maximum Ratings. Voltage on any pin except RESET with respect
to ground => VCC + 0.5

The current will be limited by the 330ohm resistor to only 36mA which I think is a lot, I thought of doubling the resistors values to 330000 and 220000 by that the current will be limited to only 36uA. Again based upon my understanding there is still 12V going to the Arduino but wouldn't it directly drop if the ground connection was cut off ? That's why I ask what is the maximum input power to an Arduino?

This is actually a special case that is undocumented, and in fact not as simple as you would at first think.
The input port itself is not actually what is in question here. Instead every IO pin on the Arduino, be it set to INPUT or OUTPUT, has a set of ESD protection diodes on them. These look like this:

simulate this circuit – Schematic created using CircuitLab
The "IO MODULE" when in INPUT mode can pretty much be ignored, since it is a very high impedance. Just like a (roughly) 10MΩ resistor to ground. Very very little current will flow that way.
D2 is also reverse biased so that direction can be ignored.
So the current will want to flow through D1 to the VCC rail (+5V).  The diodes have approximately a 600mV forward voltage (which is where the VCC + 0.5 comes from).
So we can recalculate, given those parameters, what the current flowing through the diode will be to the 5V rail:

Voltage difference = 12V - 5V - 0.5V = 6.5V
Current = V/R = 6.5/330 = 19.7mA

The recommended maximum (from what I can gather) is only 1mA.  You have 20x that.
So you will need at least 20x higher resistances. 10kΩ in the upper half and 6.8kΩ in the bottom half.  That will give you 4.85V on the output at 12V and limit you to 0.65mA in a failure situation.
It also gives you an output impedance of a little over 4kΩ which is below the recommended maximum of 10kΩ for the ADC input.
You can further protect your input by adding a 5V zener diode and small series resistor on the ADC pin so if the voltage goes above 5V it clamps it and protects the pin.

simulate this circuit

The current will want to flow through D1 to the 5V rail? What? The voltage to be sampled needs to be between 0 and VCC (5V). If it's lower than 5V, won't D1 be reverse-biased and the potential will be applied to the ADC (which is a capacitor, if I remember correctly)

I thought that as long as you stayed within your voltage limits, the ADC was a capacitive input?

Oh, I see. I read the OPs question more carefully. He's looking to avoid destroying the input if the ground side of his voltage divider is left open and he pumps 12V into the pin. Yeah, wouldn't a 5V zener diode we the way to go?

@DuncanC Belt and braces. Keep the current < 1mA and add the zener. If one fails the other protects.


text:
Arduino exercise that i have no idea how to do
The messages received by the Arduino take the form: $ Ba, Pb, Rc #
Where $ represents the beginning of the message, # represents m, and B, P, and R are characters representing B button, P period and R repetition.

`a 'designates the button to be read, which can be 1, 2 or 3.
`b 'designates the time (in seconds) that the button should be expected to be pressed.
`c 'designates the number of times the button is expected to be pressed during the indicated period.

For example, with the message: $ B2, P4, R2 #
you want to know if button 2 has been pressed twice for four seconds. If condition is verified, then the Arduino must send the message $ MSG, TRUE # where MSG represents the message received without the start and m message characters. Otherwise, you must send the message $ MSG, FALSE #.
Incoming messages must respect the format presented. If not, the condition is not checked and the message $ NOK, MSG, KON # must be sent as a response.
I have no idea how to do this since im new to arduino

Hasn't your teacher given some information on how to start? In how to use Serial, how to parse strings? These things can also be found online via google

There are examples of how to parse a comma separated list of data on our network: https://arduino.stackexchange.com/search?q=parse+comma The website cplusplus.com has a good description of C++ functions: http://www.cplusplus.com/reference/cstring/strtok/

do the project on paper first ... pretend that you are the Arduino ... think about what you would do as the message is arriving

To begin, forget the Arduino for a moment and assume the task of determining true or false from $....# message. Think about what you would have to do, step by step, to accomplish this. (e.g.: Read the buttons; Record the time and the button states. Is there a message from the Serial port beginning with '$'? Then read the rest of the message. etc.) Then, for each of those steps, do the same thing again: write down the smaller steps to accomplish what that step requires. Do that until you can't break it down any further.
Those small steps should each look like something you could do in C++ code (sometimes called "Arduino" code, but it's really C++). Start replacing each English (or your language) steps with the C++ equivalent. Do this until all of the human-language steps are written in C++.
There will inevitably be mistakes. Fix one or a few at a time. When you're stuck, ask here, something like "Here is my (well formatted) code. I tried [this]. I expected to see [that]. But what happened instead was [something else]. How can I fix it?"; or: "I am getting this error message [with its complete text including any line numbers, please] from the compiler. What does it mean, and how could I have found that out on my own?"
Small steps....


text:
Problem using 2 motors
I would like both the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning. At the moment, when I push the joystick on x-axis and my x variable increases both motors spin, but when I push it in the opposite direction and x decreases, only motor A spins. Additionaly when I connect the arduino to the power (usb cable to my pc), motor B spins for approx 1 second and then stops.
This is the circuit I have (sorry for a lack of schematic, let's hope this wonderful drawing is enough):

The code:
int MotorAA = 7;
int MotorAB = 8;

int MotorBA = 11;
int MotorBB = 12;

int x = 0;

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

  pinMode(MotorAA, OUTPUT);
  pinMode(MotorAB, OUTPUT);

  pinMode(MotorBA, OUTPUT);
  pinMode(MotorBB, OUTPUT);

  digitalWrite(MotorAA, LOW);
  digitalWrite(MotorAB, LOW);

  digitalWrite(MotorBA, LOW);
  digitalWrite(MotorBB, LOW);
}

void loop() {
  x = analogRead(A0);
  Move();
  Serial.println(x);
}

void Move() {
  if (x == 0){
    return;
  }

  if (x > 520)
  {
    digitalWrite(MotorAA, HIGH);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, HIGH);
    digitalWrite(MotorBB, LOW);
  }
  else if (x < 480)
  {
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, HIGH);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, HIGH);
  }
  else{
    digitalWrite(MotorAA, LOW);
    digitalWrite(MotorAB, LOW);

    digitalWrite(MotorBA, LOW);
    digitalWrite(MotorBB, LOW);
  }
}

How much current are the motor pulling?  Powering DC motors off the Arduino board is usually a recipe for smoke.  The 5V pin is not there to power your project.  You need to power the motors separately.

@Delta_G Thank you for answering. I've connected the motor driver module to the usb charger with 5V and still the same. When I connected the meter between the motor driver and the motor it showed ~0,12A.

@jsotola Good point, I'll update the post. I would like the motors to spin the attached wheels forward when I push the joystick forward and vice versa. When the joystick is still, the motors should stop spinning.

isolate the area of failure ... swap the A lines with the B lines ... does the problem stay with the motor? ... does it move ? .... switch the motors ... does the problem follow the motor? .... that kind of testing will allow you to determine where the failure is occuring

@jsotola Strangely enough, when I left only the ground and power connected to the driver, motor B acts the same. I thought that without powering the motor a and b pins on the driver, it shouldn't move.

the motor will turn only if IA and IB are different ... you can remove the Arduino .... plug the L9110s into the breadboard .... connect all four inputs to ground ... connect the motors .... now connecting any one of the four inputs to V+ should run one of the motors .... test all of the four inputs, one at a time

@jsotola I did what you said and I think there's a problem with the pin B-IA, which when connected to power doesn't spin the engine. I've looked at the module and saw that there's some solder missing(I think?) on R5 image could this be the cause?

The Arduino can definitely not power that many motors. The Arduino's max output current is 0.1A and you might be drawing around 0.5A. Use an external battery like a LiPo battery for the motor controller.
NOTE: Please watch out! Drawing that many amps from Arduino can kill it! So please use the LiPo or normal batteries!


text:
Communication between 2 arduino boards
I am not really 100% too sure how to do this but I am trying to make my arduino UNO communicate with my arduino MEGA. The reason why I needed to do this was because I was using the RFID module along with a TFT display and the problem I faced is that on the arduino mega they both needed pin 53. Luckily I have an arduino UNO so I just went for that instead for the display. I am trying to use the analogWrite() function to send analog signals from my MEGA over to the UNO so that the TFT display on the UNO can display the results. The UNO would also read the analog inputs coming from the MEGA. This did not work very well. The analog inputs are being sent from the MEGA but the UNO is not reciving them. I am using a PWN pin on the MEGA to send the analog output to the UNO.
This diagram shows what I mean:

These are the 2 compotents I am using:
https://i.stack.imgur.com/CqXdB.png
TFT display

RFID

This shows how the libary sets out the pins. I am only a beginner so I personally don't want to mess around with the libary.

Use Serial or I2C or SPI. Never try this sort of thing with analogue, it's just not realistic.

How do you use those? I am quite new to all of this.

Start by googling for some tutorials. There's no shortage.

What was the deal with pin 53?  What were they using it for?  Sounds like SPI in which case they can just share it.  Perhaps figuring that out first would be smarter and you won’t end up with such a convoluted design.  If it’s not about SPI then most likely you can switch one of them to

Also note that a PWM signal is alternating 5V and ground.  It isn’t a true analog signal.  When you try to read it with the other Arduino you won’t get an analog reading.  You’ll get 0 sometimes and 5V sometimes.

@Delta_G pin 53 is used for an RFID module

@Delta_G Do you know at all how you can send analog signals on an arduino because there is a analogWrite() function

Pin 53 is just the default Slave Select pin for SPI. You can pick literally any pin instead of 53. There's nothing special about it (unless you're doing SPI slave mode).

@Majenko I think the RFID module uses SPI. The issue is that I have a display which uses SPI and an RFID module that uses SPI and they both cannot use it at the same time.

Yes they can. That's the whole point of SPI. The only pin that needs to be unique is the SS pin, All the others can be shared. And you can change pin 53 for any other pin

I have what modules I am using above:

If you have "shields" that mount on top of the Arduino then cut pin 53 off the top level one and solder a wire from there to another pin somewhere else. If you don't have "shields" then just plug the slave select pin from one of the modules into a different pin.

@Majenko I don't have the tools to do that!

Then get the tools. Those are basic tools for working with electronics. Arduino isn't LEGO®, it's electronics. Real electronics.

Take the wire that connects to pin 53 of the RFID module and plug it into another hole on the Arduino. Look at the number next to that hole. Read the manual for the RFID library you are using and look for the words "chip select" or "constructor" or "slave select" and it will tell you where to stick the number you just read.

@Majenko, I don't have sheilds, I think the RFID documentation specifically mentions that pin 53 needs to be used and additionally this is the same for the TFT display

@Majenko The picture above shows what I mean

The RFID neither knows nor cares what pin it's using. Only the library cares, and most of those have a specific way of telling it what pin you want to use. RTFM for the library, not the RFID.

@Majenko I am only a beginner so I personally don't want to mess around with the library.

I'm not telling you to "mess around" with the library. I am telling you to read the manual. Or at the very least tell us what library you are using so we can point you to the paragraph that tells you how to use a different SS pin!

@Majenko Here is the libary: https://github.com/miguelbalboa/rfid

You see in the table of pins on that page you link to? See the little [2] next to pin 53? Click it. It takes you to a bit that says "Configurable, typically defined as SS_PIN in sketch/program."

All the examples have #define SS_PIN ... in them where you can change the pin that you want to use instead of 53. The constructor has MFRC522 mfrc522(SS_PIN, RST_PIN) where you can put any pin numbers you like (or just redefine the macros to be something else).

You can use the I2C interface.
TX:
// Wire Master Writer
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Writes data to an I2C/TWI slave device
// Refer to the "Wire Slave Receiver" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(); // join i2c bus (address optional for master)
}

byte x = 0;

void loop() {
  Wire.beginTransmission(8); // transmit to device #8
  Wire.write("x is ");        // sends five bytes
  Wire.write(x);              // sends one byte
  Wire.endTransmission();    // stop transmitting

  x++;
  delay(500);
}

RX:
// Wire Slave Receiver
// by Nicholas Zambetti <http://www.zambetti.com>

// Demonstrates use of the Wire library
// Receives data as an I2C/TWI slave device
// Refer to the "Wire Master Writer" example for use with this

// Created 29 March 2006

// This example code is in the public domain.

#include <Wire.h>

void setup() {
  Wire.begin(8);                // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600);           // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c);         // print the character
  }
  int x = Wire.read();    // receive byte as an integer
  Serial.println(x);         // print the integer
}

Schematic:

Image by Dronebot Workshop; check out their tutorial for more info: https://dronebotworkshop.com/i2c-arduino-arduino/

This is perfect! Thank you so much! :)

You are welcome!

What is the address 8 part?

That is just any address both the boards communicate on. It can be any number but it has to be the same on both sides.

Isn't the RX pin pin 0 and the TX pin is pin 1 thought or vice versa?

Can you show a schematic that shows this? It might help me to get a better understanding.

Yes so this is the wire library can doesn't use the Serial put. I will put the schematic in the answer.

Can it work with different boards? I am using an arduino MEGA and an arduino UNO

Yes, for the mega, right next to the Serial pins, there is an SDA and SCL pins. Use those. Also, remember to connect both of their grounds together, or else it will NOT work.

Have you potentially got a schematic using a mega and uno? (I am quite new to the arduino)

I put the schematic in the answer.

What if you want only 1 way communication

This is one way. One is TX and the other is RX.

Pin 53 is just the default "slave select" pin. There is nothing special about it. You can use any other pin as slave select, as long as the libraries for your devices allow it (check the documentation and tutorials for those libraries).
You cannot transmit information with analogWrite() since it isn't really analogue (it's PWM), and analogue doesn't have enough definition for reliably representing more than a handful of discrete values anyway.

I realize I'm later here, but: As an AVR SPI master, you cannot allow your SS pin to go low as input.  So if you chose something other than 53 (or SS on an AVR generally) to be your slave select line, you'd still want to set 53 to be OUTPUT, or INPUT_PULLUP, or INPUT and pulled up externally.  Otherwise you may be taken out of master mode by noise on the pin.  Not that it goes against your main point, but here is still one thing to be aware of that is special about 53/SS with regard to SPI master.


text:
NodeMCU LUA ESP8266 12E Issues with Programming
I recently bought the NodeMCU ESP8266 to work on an embedded project, and for whatever reason, the board will only allow me to upload Arduino sketches when I unplug and replug in the board via the Micro-USB cable. I don't have any jumper wires connected to pins in the board--just the Micro-USB cable. The IDE gives me the following:
esptool v0.4.13-1-gf80ae31 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to nodemcu
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
An error occurred while uploading the sketch
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
warning: espcomm_sync failed
error: espcomm_open failed
error: espcomm_upload_mem failed

Like I said, it programs fine when I unplug and replug in the board, but it is quite a nuisance to do this every time. I'd like the board to automatically start running my code after uploading. Here's what I've tried/found:
-I've made sure the baud rates are matching in the device manager and the upload speed tab in the IDE.
-The device is in fact being picked up in the device manager with the correct driver: USB-SERIAL CH340.
-I've tried pressing the flash button before programming.
-I've tried connecting the ground pin on the NodeMCU to GPIO pin 0.
-Tried reinstalling drivers.
-Tried switching boards.
This may also explain why my serial monitor is so inconsistent as well; sometimes it outputs nothing and sometimes it outputs garbage, but that's a separate issue that I won't worry about for now. Can someone please help me out here? I've referenced a lot of other posts on here as well as tutorials but none have helped me thus far.
Thanks

what board or reset method do you select in Tools menu?

I selected the NodeMCU 1.0 (ESP-12E Module) for the board. There is no reset method option unless I select "generic ESP8266 module".


text:
Arduino Nano-combo NRF2401
I am using two nano-combo for a RC car and when the remote emitter battery is too down if the car was running and battery finally empty the car was still running...is there any way by programming to check communication between the two nanos and solve this problem??. Thanks.
here is the code:
//Receiver program
#include <SPI.h>;
#include "Mirf.h"
#include "nRF24L01.h"
#include "MirfHardwareSpiDriver.h"
Nrf24l Mirf = Nrf24l(10, 9);
void setup()
{
Serial.begin(9600);
Mirf.spi = &MirfHardwareSpi;
Mirf.init();
Mirf.setRADDR((byte *)"FGHIJ"); //Set your own address (receiver address) using
5 characters
Mirf.payload = sizeof(datos);
Mirf.channel = 90;             //Set the used channel
Mirf.config();
//Serial.println("Listening...");  //Start listening to received data
void loop()
{
if (Mirf.dataReady()) { //When the program is received, the received data is
output from the serial port
Mirf.getData(datos);
delay(5);
if (datos[7] >= 150) {     //motor forward
analogWrite(3,0);
analogWrite(5,255);

}
if (datos[7] <= 90) {    motor back
analogWrite(3,255);
analogWrite(5,0);

}
if (datos[7] > 90 && datos[7] < 150 or datos[7] == 0) { //motor stop
analogWrite(5,0);
analogWrite(3,0);

}
}
}
it works perfect I can control dc motor no problem but if remoto control battery is low or empty then no communication with NANO receiver and the motor spin itself non stop.
I try different things in the void loop like:
if (!Mirf.dataReady()) {
analogWrite(5,0);
analogWrite(3,0);  }
but still the same problem. So that´s why must be something inside Rf library to check if remote control NANO comms is off I don`t know...
Thanks

Surely. You can program your Arduino to stop, if no data was received for a specific amount of time. Though we cannot really give you more advice without more information from you. Please include your code into the question (and format it correctly as code). Also please give us more information, how everything is connected.

use a heartbeat signal

You can do somthing like:
while(radio.hasData()){
}

This works in the NRFLite library. I don't know about other libraries like RF24 etc.


text:
Sending AT Command for sms to arduinoShield
i have a Arduino GSMShield and I want to send SMS.
When the module try to connecting to the network, it print AT+CREG?
Dont know why cause there's no serial.println for this
int8_t answer;
int onModulePin= 2;
char aux_str[30];

//Change here your data
const char pin[]="";
//const char phone_number[]=" number OK";
const char sms_text[]="Test-Arduino-Hello World";

void setup(){

  pinMode(onModulePin, OUTPUT);
  Serial.begin(115200);

  Serial.println("Starting..");

//  power_on();

  delay(3000);

  //sets the PIN code
  sprintf(aux_str, "AT+CPIN=%s", pin);
  sendATcommand(aux_str, "OK", 2000);

  delay(3000);

  Serial.println("Connecting to the network..");

  while( (sendATcommand("AT+CGREG?", "+CREG= 0,1", 500) ||
    sendATcommand("AT+CGREG?", "+CREG: 0,5", 500)) == 0 );

  Serial.print("Setting SMS mode..");
  sendATcommand("AT+CMGF=1", "OK", 1000);    // sets the SMS mode to text
  Serial.println("Sending SMS");

  sprintf(aux_str,"AT+CMGS=\"%s\"", phone_number);
  answer = sendATcommand(aux_str, ">", 2000);    // send the SMS number
  if (answer == 1)
  {
    Serial.println(sms_text);
    Serial.write(0x1A);
    answer = sendATcommand("", "OK", 20000);
    if (answer == 1)
    {
      Serial.print("Sent ");
    }
    else
    {
      Serial.print("error ");
    }
  }
  else
  {
    Serial.print("error ");
    Serial.println(answer, DEC);
  }

}

void loop(){

}

void power_on(){

  uint8_t answer=0;
  Serial.println("2/2..");

  // checks if the module is started
  answer = sendATcommand("AT", "OK", 2000);
  if (answer == 0)
  {
    // power on pulse
    Serial.println("2*3..");
    digitalWrite(onModulePin,HIGH);
    delay(3000);
    digitalWrite(onModulePin,LOW);

    // waits for an answer from the module
    while(answer == 0){     // Send AT every two seconds and wait for the answer
      answer = sendATcommand("AT", "OK", 2000);
        Serial.println("3*2..");

    }
  }

}

int8_t sendATcommand(const char* ATcommand, const char* expected_answer, unsigned int timeout){

  uint8_t x=0,  answer=0;
  char response[100];
  unsigned long previous;

  memset(response, '\0', 100);    // Initialice the string

  delay(100);

  while( Serial.available() > 0) Serial.read();    // Clean the input buffer

  Serial.println(ATcommand);    // Send the AT command

    x = 0;
  previous = millis();

  // this loop waits for the answer
  do{
    // if there are data in the UART input buffer, reads it and checks for the answer
    if(Serial.available() != 0){
      response[x] = Serial.read();
      x++;
      // check if the desired answer is in the response of the module
      if (strstr(response, expected_answer) != NULL)
      {
        answer = 1;
      }
    }
    // Waits for the answer with time out
  }
  while((answer == 0) && ((millis() - previous) < timeout));

  return answer;
}


text:
Problems with detecting button digital state
I am trying to start an event after pressing and holding the FLASH built-in Nodemcu button for a specific time, I wrote two functions, one for debouncing and detecting the state, the other is to detect the pressing time, I'm not getting any result unless I decrease the input pressing time to less than 1s, which makes the button works as a single-push button, I think i have a problem with debouncing the button, I can't figure out where it is?
/**
* @brief debounces the button and returns the current level high or low
*
* @return int the button state 0: low, 1: high, -1 indetermined
*/
int button_state(int btn)
{
    int const DEBOUNCE = 200;
    static int hi = DEBOUNCE;
    static int lo = 0;
    if (digitalRead(buttonPin[btn]))
    {
        if (hi < DEBOUNCE)
        {
            hi++;
        }
        if (lo > 0)
        {
            lo--;
        }
    }
    else
    {
        if (lo < DEBOUNCE)
        {
            lo++;
        }
        if (hi > 0)
        {
            hi--;
        }
    }

    if (hi == DEBOUNCE)
    {
        return 1;
    }
    else if (lo == DEBOUNCE)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}
/**
 * @brief Detects the button state and starts a time to calculate pressing duration
 *
 * @param btn input button pin
 * @param PressTime Desired pressing duration to compare to
 * @return int returns 1 when PressTime is reached
 */
int PressNHold(int btn, int PressTime)
{
    int lastButtonState = 0, Startpressed = 0, endPressed = 0, holdTime = 0,
    buttonState = button_state(btn);
    if(buttonState != -1)
    {
        if (buttonState != lastButtonState)
        {
            if (buttonState == 1)
            {
                Startpressed = millis();
            }
            else
            {
                endPressed = millis();
                holdTime = endPressed - Startpressed;
                if (holdTime >= PressTime)
                {
                    Serial.printf("Button %d pressed for %ds or more\n", btn, holdTime);
                    holdTime = 0;
                    return 1;
                }
            }
        }
    }
    lastButtonState = buttonState;
}
.....

void loop {

if (PressNHold(buttonPin[1], 5 * 1000) == 1)
  {
   //launch your event
  }

I don’t follow your debounce routine.  It is very unorthodox.  Perhaps it would do some good to study some other existing debounce code and write something that we know works.

the debounce code looks like it should work .... it would be easier to read if the if statements were one-liners .... replace the PressNHold code to just print a timestamp at button transitions ... that may help narrow down the area of failure

Does your button have a pulldown resistor?

turns out that it is very simple, I shouldn't put buttonPin[1] a variable for PressNHold, I had to put just1, buttonPin was used already in button_state, also, PressnHold local variables should be declared static to not get a reset after function execution.


text:
Arduino Uno R3 cannot detect GPRS Shield SIM900
I am new to Arduino which I got only this week for my project which sends sms from my windows     application.
I have Arduino Uno R3 and GPRS Shield (Simcom) Sim900  (S2-1040S-Z0912)
I am currently following this guide > https://educ8s.tv/arduino-gsm-shield/
As of the moment I have problem connecting the Sim900 to Arduino (I think Arduino cannot detect Sim900). The Arduino is working properly as my PC detected it. Also I confirm that the SIM900 is working properly as I can call the Sim inside and it is ringing (also the led on the device is blinking almost every 3 secs or so)
I found this, but I'm planning to use USB powered only as I only need the SMS feature so I am stacking the SIM900 on top of the Arduino.
How to communicate the Arduino board with SIM900?
I am using this library http://www.tinyosshop.com/datasheet/GSM_GPRS_GPS_Shield_GSMSHIELD.rar
and below is the sketch:
#include "SIM900.h"
#include <SoftwareSerial.h>
#include "sms.h"
SMSGSM sms;

int numdata;
boolean started=false;
char smsbuffer[160];
char n[20];

char sms_position;
char phone_number[20];
char sms_text[100];
int i;

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

    if (gsm.begin(9600))
    {
        Serial.println("\nstatus=READY");
        started=true;
    }
    else
        Serial.println("\nstatus=IDLE");

    if(started)
    {
        if (sms.SendSMS("214", "?15001"))
        {
          Serial.println("\nSMS sent OK.");
        }
        else
        {
          Serial.println("\nError sending SMS.");
        }
    }
};

void loop()
{
    if(started)
    {
        sms_position=sms.IsSMSPresent(SMS_UNREAD);
        if (sms_position)
        {
            Serial.print("SMS postion:");
            Serial.println(sms_position,DEC);
            sms.GetSMS(sms_position, phone_number, sms_text, 100);
            Serial.println(phone_number);
            Serial.println(sms_text);
        }
        delay(2000);
    }
};

and here is the output
Trying to force the baud-rate to 9600

1200
2400
4800
9600
19200
38400
57600
115200
ERROR: SIM900 doesn't answer. Check power and serial pins in GSM.cpp

status=IDLE

What I have tried so far:
I tried the sketch with SoftwareSerial mySerial(7, 8); and SoftwareSerial mySerial(9, 10) which i found on other tutorials but didn't work.
I tried modifying GSM.cpp and modify the value of _GSM_TXPIN_  and _GSM_RXPIN_  to 7, 8 and 9, 10 but didn't work.
Found that the pin on my Arduino is RX=0 and TX=1, and SIM900 is TX=0 and RX=1, tried the SoftwareSerial code above but with 0, 1 and GSM.cpp with 0, 1 but still not working.
I am currently still trying every other sketch i find on the internet but nothing works.
EDIT:
This is the link for the module i bought
https://www.lazada.com.ph/products/sim900-gsm-shield-i267689740-s379728457.html?mp=1
I cant find the link for the datasheet of this specific module so I will try to include the picture of the module

Can you provide a link to the actual module you are using? Does it have jumpers on it to change the TX and RX pin assignments?

Hi @Majenko, Please see the edit on the bottom of my question. Thanks

After many trials, I found the solution to my problem, thanks to @Majenko for mentioning the jumpers.
I am still stacking the SIM900 module on top of Arduino.
Switching the jumpers from D1 and D0 to D8 and D7 solved the problem (see green square on the pic)
I don't know why it needs to be on D8 and D7 since on board it says TX=0 and RX=1 and vise-versa for Arduino

Then used the below sketch from this tutorial > https://lastminuteengineers.com/sim900-gsm-shield-arduino-tutorial/
#include <SoftwareSerial.h>

//Create software serial object to communicate with SIM900
SoftwareSerial mySerial(7, 8); //SIM900 Tx & Rx is connected to Arduino #7 & #8

void setup()
{
  //Begin serial communication with Arduino and Arduino IDE (Serial Monitor)
  Serial.begin(9600);

  //Begin serial communication with Arduino and SIM900
  mySerial.begin(9600);

  Serial.println("Initializing...");
  delay(1000);

  mySerial.println("AT"); //Handshaking with SIM900
  updateSerial();
  mySerial.println("AT+CSQ"); //Signal quality test, value range is 0-31 , 31 is the best
  updateSerial();
  mySerial.println("AT+CCID"); //Read SIM information to confirm whether the SIM is plugged
  updateSerial();
  mySerial.println("AT+CREG?"); //Check whether it has registered in the network
  updateSerial();
}

void loop()
{
  updateSerial();
}

void updateSerial()
{
  delay(500);
  while (Serial.available())
  {
    mySerial.write(Serial.read());//Forward what Serial received to Software Serial Port
  }
  while(mySerial.available())
  {
    Serial.write(mySerial.read());//Forward what Software Serial received to Serial Port
  }
}

With this, it displays correct output on serial monitor based on the tutorial and I can confirm that its working as well on my windows form application as it can send sms from the application.

0 and 1 are the hardware serial pins.  If you are using Serial elsewhere in your code then you can’t use 0 and 1 for the shield.  They’re already in use by the hardware serial.  You are creating a software serial.  It’s not a real serial port.  It’s software pretending to be a serial port.  That won’t use hardware serial pins.

If you want to use 0 and 1 then get rid of all the software serial business and just use Serial to talk to the shield.  But that means you can’t use it for other purposes and it also means complications when you want to upload new code.


text:
How to upload code to an Arduino Uno using HC08 Bluetooth module
How do you upload code to an Uno from a Mac using the HC08 Bluetooth module? I know I need to use this wiring.

Anyone know?

you can only upload to Uno over RX/TX and the Arduino must be reset to bootloader


text:
Fail getting readings from Radar sensor HW-MS03
I try to work with a new sensor - HW-MS03 v.06 sensor. Connecting it pin to pin (v+ to 5v, Sig to digital-input, and GND to GND ), both to Arduino Uno and ESP8266 Wemos mini, and got same results:
Only once on every port I got proper readings ( 1 for detection for 2 sec, and 0 for no- detection). Most of the time it was a solid 1.
Code was very simple , just printing its digitalRead of the designated pin.
When tried to pull-down the signal, using a 1K resistor, It never got 1 again.
To be sure it is not a malfunctioned sensor I tried with the other one I have, but again- same results.
link to purchased product
Appreciate any help.
Guy

Wow, that is some quality documentation: "Recommended qualified power supply, ie output voltage, current and ripple factor are standard power supplies, otherwise it is a movie" And the specifications link doesn't provide any info about voltage or current requirements. I think you're on your own figuring that one out.

"it is a movie....." this is the best spec I've encountered

What do you suppose the writer is trying to say? It was word salad to me.