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:
Arduino ESP8266 Ticker interrupted by DallasTemperature/OneWire?
I have been using the Ticker to blink a led successfully.
However, now I am fetching temperature from a DS18B20 in the main loop (which is using the OneWire library) and the blink is now erratic.
Is the Ticker suspended by the DallasTemperature/OneWire library?
It this suspending interrupts or something?
Maybe using the same interrupt?

Ticker does not interrupt your code. It is a OS-timer and will call your function once the time is elapsed.
The Tiker callback can be interrupted by a "real" interrupt or another Task with higher priority and does not provide any reliability - it will just be called.
A solution (not the best) would be to disable manually all interrupts, if you can't solve it in another way.
If you just want a blinking led, you should use a Timer interrupt as your callback is short and fast. Maybe with the ICACHE_RAM_ATTR attribute.

OS-timer means it's get called after the loop() or during a yield() is that correct?

@HixField sorry, I didn't wrote it correctly. It is called during the loop. It will "interrupt" the loop, but not another interrupt and not an important operation (like an access to the SPIFFS). It will for example executed once the SPIFFS-transaction is over or once the SPI/OneWire-interrupt is over. (A HW-Timer can interrupt also a SPIFFS-access).

Hmm ok. It is strange though because I just changed my DS18B20 implementation to a non blocking one (in the loop) and now everything is working fine. I checked the DS18B20 lib and the only thing it does to "block" was a while(...) {} (without any yield). I do have the impression that the ticker can be inrerrupted by blocking functions...

I ran into a problem using libraries with sensor DS18B20 in ticker. If I request the temperature through millis(), then everything is fine. When I request the temperature in the ticker, I get "Panic core_esp8266_main.cpp:137 __yield". Unfortunately I can't explain it.

This doesn't really provide an answer to the question. To ask another question, just click Ask Question above. If you wish, include a link to this question to help provide context.

You're right: this is not an answer, just more information. I made a mistake: I posted this text in the wrong place. Should have been in the comments.

source: Stack Exchange

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

sort: votes


text:
Reset arduino nano after disabling tx/rx
I know, i am a bit dummy sometimes and i don't know why i actually did this but here it is. I have an arduino nano and i want it to use an external power via the the Vin port using a 12V external power supply. I thought this would be as simple as replacing the usb power supply by my external 12V power supply on the Vin pin.
But nothing works so i did some digging on the problem and after many tries like soldering the pins 25 and 26 of the FTDI or connect the TX/RX pins to the GND. Concerning that last point, because the TX/RX was still flashing after beeing connected to the GND i have put in my program this two lines to force TX/RX to be disabled and this is my mistake :
digitalWrite(0,LOW);
digitalWrite(1,LOW);

And now what a surprise i can't load a program in my arduino nano anymore even using another arduino to burn the bootloader. And i get this message :
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x38
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x31

I would like to come back to my factory arduino nano and/or enable once again the TX/RX connections ...

it is not the problem of the code. if you reset the Nano the bootloader runs for 2 seconds and has UART setup correctly and not affected by setup() of your sketch. so remove wires from RX and TX pin

Nothing is plugged on RX and TX pins

After some more tries something actually worked reinitialising the TX/RX pins, but i don't know why really. I wired RX pin to the reset and i loaded an empty code into the arduino, after that i was able to load any program into my arduino again. Problem solved, but why it solved the problem is the question now.

please do not use an "answer" to post a comment

post a new question about it ... include the sketch that "broke" the arduino

You could also do this: in the IDE, select File:Preferences and turn on Verbose outputs.
Press & hold reset, that puts all the IO pins into Inputs, then start a download.
When the compiler process shows "compilation complete, xxxxxx bytes of 32xxx used" or similar, release the Reset button.
That allows the bootloader code to run and talk to the PC over the serial pins - before your sketch has chance to run and write the 2 serial pins low.
It might take a couple of tries to release Reset at the correct time. Be patient try a few times with just a short sketch to clear out the offending code:
void setup();
void loop();

That would do it.

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


text:
Rotary Encoder gives "wrong" patterns?
I am trying to learn how to use a Rotary Encoder together with an LCD display where I can use the encoder to choose Letters that will be printed in the LCD.

This is the kind of result I should be getting, but instead I am getting this:
1  2  3  4  5  6  7  8  9  10  11  12  13  14  15  16
c  d  e  f  0  1  2  3  4  5   6   7   8   9   a   b
10 00 10 00 11 01 11 01 10 00  10  00  11  01  11  01
A:
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0
B:
0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1
Shouldn't I be getting a sort of
001100110
100110011
pattern to be able to tell which way it is rotated?
How can I fix this?
I am using the following connections:

I don't understand what you mean with these patterns. Please explain more, how you get to those patterns and what exactly you didn't expect

How are we supposed to know what's wrong with your code if we can't see it?

you are misunderstanding how to use the encoder ... you do not read the two bits and look for patterns ... you wait for A to change ... that tells you that the encoder moved ... the state of B at the time of the change tells you the direction of rotation ... to make it simple, look for only the rising edge of signal A


text:
"expected primary-expression before '.' token" in debug code
I'm making some code for school, and is adding debug code to it. When compiling, I get the error as written in the title. This is the code in question:
#define DEBUG 1

#ifdef DEBUG
#define Serial.println(x) DEBUG_PRINT(x)
#else
#define DEBUG_PRINT(x)
#endif

And the code in my void setup, which has Serial.begin:
#ifdef DEBUG
Serial.begin(9600);
DEBUG_PRINT("Asteroid");
#endif

What am I getting wrong? I get the feeling it's my define text, but I'm unsure.
Thank you for your time
Gaarden

Macros cannot contain a .. Thus you cannot define a macro Serial.println(x). You probably wanted to define it the other way around anyway.
#define DEBUG_PRINT(x) Serial.println(x)

I switched them around, per Kwasmich's comment. Now the error message is "expected ';' before 'Serial'"

Somewhere in your code (not shown above) you have a DEBUG_PRINT statement where in the line before that you have skipped the ;

Didn't know it would give me an error message on that line if a line further down had a problem. Thank you!

@Kwasmich You posted an answer as a comment. Please make a proper answer. Then you will get rep for it, and Stack Exchange will consider the question answered. Win win!

@NickGammon, I see this as typographic error (and I will downvote an answer to this question). I voted to close

@Juraj Typographical errors are errors too.  Besides, this isn't a typographical error. A typographical error would be Serial.print1n(). This is a lack of understanding of how macros work and should be formed on the part of the OP and deserves aiding the OP in improving their understanding.

In short: you have your macro backwards.
Macros are not formed as "Take this set of commands and call it X" but "Make this macro X and have it equate to this set of commands".
Where you have:
#define Serial.println(x) DEBUG_PRINT(x)

it should instead read:
#define DEBUG_PRINT(x) Serial.println(x)

When you call it, because the macro doesn't contain a semi-colon in it, you need to specify the semi-colon as if you were calling a function:
DEBUG_PRINT("Aardvark");

You can omit the semi-colon only if you have a semi-colon in your macro:
#define DEBUG_PRINT(x) Serial.println(x);

and then:
DEBUG_PRINT("Aardvark")

By doing it that way your "empty" macro now does become truly empty when used.  Without the semi-colon in the macro you would have to use:
DEBUG_PRINT("Aardvark");

Which for the empty variant would end up as:
;

Not always desirable, and can cause some problems.
So by adding the semi-colon into the macro you can omit it from the usage of the macro, and your empty variant now becomes:

You defined the pre-processor macro the wrong way around.
Think it is like an assign statement. You come up with a name and assign something to it.
#define SHORT_NAME(ARG) some_real_function_that_has_an_awkward_long_name(ARG)
See the manual of your favourite compiler GCC for reference.
It is always a good idea to do that when using features you haven't used before. Sometimes it can be enlighting.


text:
DS3231 and EEPROM
Currently to get time/date i'm using DS3231 module with the RTClib library, i want to use the Atmel 24C32 chip on the module to store some small values (temperature etc).
Can i use the current library AND an external EEPROM library (which one?) OR i need to change my RTC library in order to use EEPROM feature?

why not use the EEPROM of your MCU?

@Juraj because built in EEPROM have a limited number that can be write, i think it's 100,000 times.

every EEPROM has 'limited' count of writes. you have an Arduino Uno with removable ATmega328?

@Juraj yes but 24C32 have write cycle of 1 million times instead of 100,000 times of ATmega328.

Can i use the current library AND an external EEPROM library (which one?)

Yes. Devices on an I2C bus are separate devices and use their own separate libraries.

https://playground.arduino.cc/Main/LibraryForI2CEEPROM/

is this a proper library to use?

It's the first hit on Google so I guess so. I don't use Arduino and have my own chipKIT DTWI based library so I don't know.

just in case anyone stumble upon this question; i tested this library and it's working.


text:
How to write a float value EEPROM
I'm using this library for my DS3231 which have a Atmel 24C32 on it.
i have a float value which increases by 0.5, like:
27.50
28
28.50
...
the code is like this:
float lowTemp= 10.5

float highTemp= 10.5

void setup(){
  lowTemp = i2c_eeprom.read(100);
  highTemp = i2c_eeprom.read(101);
}
void loop(){
  if ((menuswtichStatus == HIGH) && (lcdWelcome == HIGH)) {
    previousMillis = millis();
    lcd.clear();
    menuScroll++;
    lcdClear = 1;
    lcdClear2 = 1;
  }
  if (menuScroll == 1) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Minimum  ");
    lcd.print(lowTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      lowTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      lowTemp -= 0.5;
    }
  }
  if (menuScroll == 2) {
    lcd.setCursor(0, 0);
    lcd.print("Temperature set:");
    lcd.setCursor(0, 1);
    lcd.print("Maximum  ");
    lcd.print(highTemp);
    lcd.print((char)223);
    lcd.print("C ");
    if (plusSwitchstatus == HIGH) {
      highTemp += 0.5;
    }
    if (minusSwitchstatus == HIGH) {
      highTemp -= 0.5;
    }
  }
  if (menuScroll == 3) {
    lcd.setCursor(0, 0);
    lcd.print("   Saving the");
    lcd.setCursor(0, 1);
    lcd.print("   Settings...");
    delay(1000);
    i2c_eeprom.write(100, lowTemp);
    i2c_eeprom.write(101, highTemp);
    delay(1000);
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("    SETTINGS");
    lcd.setCursor(0, 1);
    lcd.print("     SAVED!");
    delay(2000);
    menuScroll = 0;
    lcdClear = 0;
    lcdClear2 = 0;
  }
}

i have the library and stuff up there, it's just an example of my code...
The float value is not saving(written), what's the solution?

multiply by two before writing as an integer or a byte

@jsotola i don't know how...!

perhaps you need to be asking more basic questions about bytes, integers, floats, strings, etc.

You have multiple options:

According to jsotola's remark: the easiest is to multiply your value by 2, store it, and after reading, divide it by 2. In one byte you can store a value from 0 to 127.5 (255 / 2), or if you use signed from -64.0 to +63.5. Of course you also can use an offset in case you know the value cannot be less than e.g. -20.
If you need a higher range, you can still multiply it by 2, but store it in two bytes. Split the value in a 'high value' (value % 256) / 256, and a 'low value' (value % 256).
If you want to store the value completely, than use sizeof(float) to find the length, and a for loop to write each byte, starting from the first byte of the float until the last one.


text:
16 bit PWM doesn't go to absolute 0V
void setup() {
  Serial.begin(9600);
  setupPWM16();
}

uint16_t icr = 0xffff;

void loop() {
  analogWrite16(9, 0);
}
void setupPWM16() {
  DDRB  |= _BV(PB1) | _BV(PB2);       /* set pins as outputs */
  TCCR1A = _BV(COM1A1) | _BV(COM1B1)  /* non-inverting PWM */
        | _BV(WGM11);                 /* mode 14: fast PWM, TOP=ICR1 */
  TCCR1B = _BV(WGM13) | _BV(WGM12)
        | _BV(CS10);                  /* prescaler 1 */
  ICR1 = icr;                         /* TOP counter value (freeing OCR1A*/
}

/* 16-bit version of analogWrite(). Works only on pins 9 and 10. */
void analogWrite16(uint8_t pin, uint16_t val)
{
  switch (pin) {
    case  9: OCR1A = val; break;
    case 10: OCR1B = val; break;
  }
}

Using the code above I can achieve 16 bit PWM signal, but when writing 0 in analogWrite16 it output ~33mV. I know that I can set the PWM pin low but yet again it don't output 0V.
I'm guessing beside the ATMEGA offset the Arduino UNO board it self ground is raised either because it's being fed from USB or the board circuitry and PCB traces resistance. or both?
because ~33mV offset is a lot, is it normal?
How can I make Arduino to start at 0V or at least reduce that 33mV offset to 1-2mV?

You've got two possibilities:

You can't have full off in "non-inverting PWM" mode
You can't have full on in "inverting PWM" mode

In the Arduino core it's solved by turning off the PWM output and setting logical 0 or 1 for corner values.
And if you need full off but you don't need full on, you can use inverted PWM mode.

How do I use inverted mode? is there a code that I have to modify?

You just have to change COM1A/COM1B (it's in the datasheet) values and compute correct value for OCR1A/OCR1B (something like 0xFFFFU - val)


text:
How to wire a hall effect sensor to arduino?
it's a UGN3503 hall effect sensor, in some schematics they used a 100uf capacitors and data connected to analog pin and in some a pull up resistor and data connected to digital pin.
as someone new to both electronics and arduino i'm a bit confused on how to wire the sensor to the arduino.
what i want is just simply read the data from sensor and if the number is above or under defined value do something.
do i need a pull up resistor and/or capacitor?
what's the right and standard way to wire a UGN3503 to arduino?

The UGN3503 that you use gives out a analog voltage that changes when there's a magnetic field present. So this sensor needs to be connected to an analog pin.
If there is no field present the voltage is around 2.5Volt. If the south pole of a magnetic field is present the voltage will be higher that 2.5V. With a north pole the voltage will be lower that this 2.5Volt. The amount of higher/lower voltage is based on the strength of the field.
A capacitor near the sensor could help reduce, so called, noise. Though 100µF is too high. I think you mean 100nF (0.1µF).
The pull-up is for other types of hall-effect sensors. Some of these sensors just give a HIGH of LOW output, based on whether a magnetic field is present. Those you connect to a normal input pin.


text:
Trying to get pseudorange data out of NS-RAW GPS
I have an NS-RAW CPGPS and I am trying to get GPS Data using an arduino. Do I just use the serial to get the data out of it and just convert and extract the data to what I need?

yes, that is correct

so i looked at the document for the data, how would you convert it? http://navspark.mybigcommerce.com/content/AN0030_1.4.35.pdf


text:
Is DS18B20 temperature sensor makes Arduino processing slow?
I recently run into a problem that causing my whole code processing slow down, for example i had a millis timer set for one minute but it took 1:30m to finish, pressing buttons was laggy etc.
After hours of digging and commenting out codes piece by piece i finally found out what is causing the slow down!
my DS18B20 temperature sensor DATA pin is connected to pin A0 when i remove the library and related codes to the sensor processing became MUCH faster more snappier/responsive...
After googling a bit i realized that everyone connected the sensor to pin 2 of Arduino!
So is the processing slow because DS18B20 is on pin A0 instead of pin 2 or there's something wrong with the sensor itself or it is because of This library?

Indirectly it's the library.
That library uses the OneWire.h library.  The OneWire protocol requires some reasonably precise timing, and because of the the OneWire.h library turns off interrupts while it communicates.
While interrupts are disabled nothing else can happen. That means that the timer interrupt that drives millis() can't "tick" - so the millis count doesn't increase while you communicate with the temperature sensor.

Hi Majenko, which library do you suggest?

There's not really anything you can do on an Arduino. You just have to put up with it and maybe compensate for the time taken communicating.

you mean changing the library not gonna fix the problem?

You would need to do it in hardware. Maybe with a DS2482-100 I2C to OneWire adapter.

this library is not using the onewire.h library. there's no other way?

Yes it is.  In the header file: #include <OneWire.h>

The software function managing the 1-wire protocol generally has several non-interruptable sections in order to ensure the bus timings.  This can make your processor unavailable for long periods of time.
Worse, some implementations do not allow any interrupt at all.
And even if your implemenation would allow being interrupted, it is generally blocking the main loop as it is not executed in an interrupt itself.
Using a hardware implementation for the 1-wire control instead of a full software would release the CPU from managing the timing and waiting for the 1-wire to complete.  But such hardware implementation are not commonly available in microcontrollers.
There is however a middle way.  An open source implementation using the microprocessor's or controller's UART to ensure the timings is available ( https://github.com/MaJerle/onewire_uart ) - MAXIM also has an application note for it ( https://www.maximintegrated.com/en/app-notes/index.mvp/id/214 ).
This also offloads the processor and it can be interrupt driven.
Is the processing slow because DS18B20 is on pin A0 instead of pin 2 ?
That might have an influence if the processor that is on your Arduino board would have a (partially) 1-wire compatible source on another pin, in which case the libary would have to take advantage of that.
Is there something wrong with the sensor itself?
That would not be generally the case, but in case you have two sensors on the same bus, the 1-wire protocol is slower as it needs to find all peripherals and the master has to indicate which one it is addressing.
Is it because of "This library"?
It is not because of that library, but there are other implementations (see the link above) that use hardware resources to improve performance at the cost of using a hardware resource (some MCU's have only 1 HW UART so you'ld not have a second one if you also need RS232 communication for instance on other signal lines).

the UART thing seems pretty awsome but too advanced for a user like me, i tried to read the documents but the more i read more i lost! we connect one side of UART to two transistor and other side goes to arduino? i'll pick your answer as correct one if you please help me figure this out...

The 1-wire bus is bidirectionnal, so it must be possible for the slave to pull the line low.  Standard TX operation of a UART is to always drive the output.  The application note (https://majerle.eu/documentation/ow/html/page_appnote.html ) proposes a solution where two cascaded transistors transform the TX in an open-drain output.  The same application note indicates that if your uC allows opendrain on the output itself, that you do not need this (it is said that the STM32 allows this) - in that case the TX and RX pins are connected together.  In both cases you have a true one-wire bus.


text:
Do we have an alternative for millis() function?
This is actually a follow up question to this question, so basically I'm using DS18B20 temperature sensor which requires Onewire.h library that interrupts millis() function.
Luckily i have a DS3231 RTC module which I'm using it with RTClib library, is there any way to use that module as a timer instead of millis() function?

You can use the SQW output of the module to indicate the passage of precisely 1 second. Every time it transitions from LOW to HIGH one second will have passed.
RTCs cannot give you times of higher resolution than 1 second, but they can give you that 1 second granularity to a high accuracy.

Thanks, but i don't know how to do that! can you please provide a link to an article/tutorial?

digitalRead(). When it changes from LOW to HIGH you know a second has gone by.


text:
How to send data from one Arduino to another isolated?
I have no experience about serial communications, with that being said; I have two circuits isolated from each other and each have a ATMEGA8 reading a voltage on their ADC.
I want one of them to send ADC data to another without having a common ground. I know that I can do it with a Bluetooth or Wi-Fi "module" but I'm looking for an easier way, like maybe with an optocoupler but again I'm not aware of the limits.

What's the cheapest and simplest way to do this? and basically how it's done?

There's a lot of information about making two Arduinos talk to each other but I couldn't find much information/documentation on isolated communications.

So you still want communication via a wire, but just with isolated grounds? Then yes, the optocoupler is the correct way, one for each UART/Serial line. You can find tutorials on how to use an optocoupler on the web. Do you have any specific questions about it?

@chrisl I'm not lazy, I just couldn't find it. can you please link one of those tutorials on how to use optocouplers for serial communications?

I didn't want to suggest, that you are lazy. I would suggest to read a generic tutorial about optocouplers, not directly involved with UART/Serial. They are pretty simple components, so the general principle is also how they are used for Serial. When you understand how they work and how they are wired you should be able to build them into your Serial path. I guess you searched for tutorials directly with the Serial lines, but there are many tutorials when searching only for optocoupler tutorials.

@chrisl I know how optocouplers works, I just don't know how to implant it as serial communicator.

A few seconds on google images looking for "optoisolator uart" yields a number of possible circuits.

One example: https://github.com/TaaraLabs/OptoIsolatorFTDI/blob/master/OptoIsolatorFTDI-sch.png

@Majenko Thank you.

[Consolidating an answer from the comments]
A wired connection using Optical isolation (aka Optocouplers) is the recommended way to solve this problem.
There are tutorials available online regarding optical isolation (e.g., https://www.electronics-tutorials.ws/blog/optocoupler.html; https://bestengineeringprojects.com/interfacing-optocoupler-with-arduino/).
One (of many) possible example circuit was noted as:

Note that, on this schematic, the pin labeled “RXI” on the left should be connected to one Arduino's TX, whereas the “RXI” on the right should be connected to the other Arduino's RX.


text:
NodeMCU second HARDWARE serial TX as a debug port
I'm using a NodeMCU board to send commands to my home electricity switching box - using RS485 communication.
For that, I've connected MAX485 TTL-to-RS485 converter module to my TX and RX pins.
Currently, I can see the serial commands (that my program sends via RS485) also on my Serial monitor (in Arduino IDE), because the CH341 on the NodeMCU is bridged to the serial pins of it.
My problem is that if I want to send debug strings to my Serial monitor (like 'time was updated using NTP') - the RS485 bus will get them also.
I found some documentation about second TX pin available that can be used for debug messages, but I have 2 questions:

Will it be a HARDWARE port? I don't want to load another library and deal with software Serial ports.
Is there a way to get its output via the USB cable connected between the NodeMCU and my computer? Or will I have to connect another USB converter externally to that port to get its output into computer?

Many thanks!

Just found now a board ESP-32, which supposed to be very similar to NodeMCU, but has another 2 (one usable) UART ports. Not a solution to my current project, but should be considered in the future for such need.

ESP8266 Arduino core has Serial1 as write only hardware Serial on io 2 as TX. IO 2 is D4 on NodeMcu and Wemos D1 mini.
To use the USB chip of the NodeMcu/Wemos with Serial1 you could wire io 2 (D4) to TX. This would not disturb the flashing mode, because bootloader would still listen on standard Serial pins. I tested it.
And for RS485 adapter swap the Serial to io 13 (D7) as RX and io 15 (D8) as TX with the Serial.swap() command.


text:
Buzzer interfere with thermistor reading
This is how i wired the thermistor and buzzer:

simulate this circuit – Schematic created using CircuitLab
And the code:
#define RT0 10000
#define B 3977
#define R 10000
float RT, VR, ln, TX, T0, VRT;

void setup() {
  T0 = 25 + 273.15;
}

void loop() {
  VRT = analogRead(A3);
  VRT = (5.00 / 1023.00) * VRT;
  VR = 3.3 - VRT;
  RT = VRT / (VR / R);
  ln = log(RT / RT0);
  TX = (1 / ((ln / B) + (1 / T0)));
  TX = TX - 273.15;
}

When i connect the buzzer it causes a bit of voltage drop which messes with temperature reading, How can i get a steady temperature reading while having a buzzer in the circuit?

Use the output of the LF33CV as your AREF?

How much is the voltage dropping? Can you simply use a power source, that can handle the buzzers current, without dropping the voltage? And in your schematics the buzzer is connected permanently, so the voltage drop should be consistent, which means, that you would be able to work around it by measuring the resulting voltage and include that in your calculations

@Majenko how? connect the 3.3V to the AREF pin AND thermistor?

@chrisl i didn't measure the voltage drop but it should be ~1V, it's an active buzzer. buzzer is controlled with MCU, i just didn't add that to the schematic...

@newbie Yep. and set analogReference(EXTERNAL); -- https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/

You can use the output of your regulator as the reference voltage for your analog readings. That way, no matter what the voltage you voltage divider for the thermistor uses, the "upper" voltage that the ADC uses is always the same as the thermistor's voltage.
Simply connect the output of the regulator to the AREF pin, and set the ADC to use the external voltage reference:
analogReference(EXTERNAL);

Now you have the range 0-1023 covering 0-3.3V (or whatever the voltage is the regulator is outputting), and because the output of your voltage divider is just a ratio of that voltage, that ratio will always be a ratio of 1023, regardless of what the voltage happens to be.
You have, in effect, removed the voltage from the equation. All you are left with is the value as a fraction of 1023, which is then directly proportional to the resistance of the thermistor.

I did just what said and the reading is steady even with voltage drop, a side question; in this line VR = 3.3 - VRT; voltage is defined 3.3V but i'm getting false reading with that and have to change it to VR = 5 - VRT;. isn't AREF voltage and the voltage on the thermistor/resistor voltage divider 3.3V? why i have to define it 5V to get proper temperature reading?

Because in the line before you have 5v for the voltage. Change that to 3.3v.

After a bit of research i realized that LF33Cv is not a reliable Vref, do you suggest LM336 or TL431?

Stability doesn't matter for this application. Nor does the voltage. You could use any voltage that is within spec of the ADC and the results will be the same. You only care about an accurate Vref if you are comparing something external to that Vref. You're not.  You're just looking at a ratio of two resistors between Vref and GND.  The formula for R2 can be reduced to just (A * 10000) / (1023 - A) where A is the value read from the ADC. There's no voltage in there at all. It all cancels out.

Thanks and sorry for question after question... i have a hall effect sensor UGN35 which is also connected to to analog pin and the analog reading is changing with voltage drop, in this specific case should i change the Vref source to TL431 or is it something that can be fixed with software?

@newbie Maybe you should be addressing why you are getting a voltage drop instead of trying to compensate for it.

even turning on a simple LED causes changes in analog reading of the hall effect sensor! it's not much but it is something... should i ask this in a separate question?

Yeah. And provide a full detailed schematic.

Take the regulator output to another analog input. Read that just before you read the thermistor. Use that voltage in your voltage divider calculation. The buzzer activity should be the same (ideally, off) during both readings.


text:
How can I connect 6 solenoid locks to an arduino
Im in college and our research is about a fingerprint based door lock system.  We really dont have any idea about arduino.  Now we bought arduino mega for our research but I dont know how to connect all 6 solenoid locks to an arduino.  Please help It would be very much appreciated if you answer and it will be very helpful to us. I know there are same research about this in the internet but  i cant find any of these.  If you have any website about this research it would be very helpful.  Thanks

You simply cannot connect a solenoid to an Arduino, because an Arduino only outputs control signals and no power lines. There are 8 channel relais boards to put in between, if you want to minimIze self built electronics.

How much current do the solenoids need to engerize their coils? Solution might be as simple as using a TPIC6A595 shift register to sink current. http://www.ti.com/lit/ds/symlink/tpic6a595.pdf  Available at Digikey.com If more than 350mA is needed, a discrete driver could also be used per solenoid, consisting of N-Channel MOSFET such as http://aosmd.com/res/data_sheets/AOI4286.pdf and a diode across the solenoid coil to dissipate coil generated current when the MOSFET turns off.

Supposing the lock you use is a simple solenoid that works with 12V, you should connect them to the output of a relay module, and then connect the Arduino to the module. Like this example here: link.
You will probably want to connect each solenoid to an individual relay, so you can activate each one of them individually. With that in mind you might want to use an 8-channel relay module like DataFiddler recommended. example
You will need a 12V power supply, and be sure to check the current drawn from your solenoids and see if the power supply can handle it.

To follow up on CrossRoads' suggestion of a power MOSFET circuit, there is more detail on how to do it in an answer over in the Electrical Engineering group. Digikey.com is a great source for components.
https://electronics.stackexchange.com/questions/29065/how-to-control-a-12v-solenoid-valve-with-a-mosfet

You aren't going anywhere without external drivers. The Arduino simply can't output that much current. 8 channel drivers are widely available. Remember to connect an external power source.


text:
Trouble GETing over HTTPS on the ESP32
I am having some trouble doing a GET request over HTTPS on the ESP32. I am using the BasicHttpsClinet example from the ArduenoIDE. Here is the code.
/**
   BasicHTTPSClient.ino

Created on: 14.10.2018

*/

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#include <WiFiClientSecure.h>

const char* rootCACertificate = \
"-----BEGIN CERTIFICATE-----\n"\
"super_secret certificate"\
"-----END CERTIFICATE-----";

// Not sure if WiFiClientSecure checks the validity date of the certificate.
// Setting clock just to be sure...
void setClock() {
  configTime(0, 0,"cn.pool.ntp.org", "pool.ntp.org", "time.nist.gov");

  Serial.print(F("Waiting for NTP time sync: "));
  time_t nowSecs = time(nullptr);
  while (nowSecs < 8 * 3600 * 2) {
    delay(500);
    Serial.print(F("."));
    yield();
    nowSecs = time(nullptr);
  }

  Serial.println();
  struct tm timeinfo;
  gmtime_r(&nowSecs, &timeinfo);
  Serial.print(F("Current time: "));
  Serial.print(asctime(&timeinfo));
}

WiFiMulti WiFiMulti;

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("Master_2.4G", "wittyercheese551");

  // wait for WiFi connection
  Serial.print("Waiting for WiFi to connect...");
  while ((WiFiMulti.run() != WL_CONNECTED)) {
    Serial.print(".");
  }
  Serial.println(" connected");

  setClock();
}

void loop() {
  WiFiClientSecure *client = new WiFiClientSecure;
  if(client) {
    client -> setCACert(rootCACertificate);

    {
      // Add a scoping block for HTTPClient https to make sure it is destroyed before WiFiClientSecure *client is
  HTTPClient https;

  Serial.print("[HTTPS] begin...\n");
  if (https.begin(*client, "https://my_end_point.com/something_or_other")) {  // HTTPS
    Serial.print("[HTTPS] GET...\n");
    // start connection and send HTTP header
    int httpCode = https.GET();

    // httpCode will be negative on error
    if (httpCode > 0) {
      // HTTP header has been send and Server response header has been handled
      Serial.printf("[HTTPS] GET... code: %d\n", httpCode);

      // file found at server
      if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
        String payload = https.getString();
        Serial.println(payload);
      }
    } else {
      Serial.printf("[HTTPS] GET... failed, error: %s\n", https.errorToString(httpCode).c_str());
    }

    https.end();
  } else {
    Serial.printf("[HTTPS] Unable to connect\n");
  }

  // End extra scoping block
}

delete client;
  } else {
    Serial.println("Unable to create client");
  }

  Serial.println();
  Serial.println("Waiting 10s before the next round...");
  delay(10000);
}

I am getting the following when I run the sketch
[HTTPS] GET... failed, error: send header failed

Guessing this is related to the issue reported here: https://github.com/espressif/arduino-esp32/issues/2670
I tried updating my esp-arduino libraries( to get the latest code with the fix mentioned in the Github issue) by redoing the steps from here: https://github.com/espressif/arduino-esp32/blob/master/docs/arduino-ide/mac.md#installation-instructions-for-mac-os
But I still get the same issue error.
I have double-checked my server, I know that the esp32 has not managed to make it to the endpoint yet.
I have tested the GET endpoint in my browser and it works fine. I have compared the certificate to the one hardcoded in the sketch file. They match.
How do I update my arduino-esp32 libraries to get the fix mentioned in the GitHub issue?


text:
Homodyne detection for arduino
In your code https://gist.github.com/edgar-bonet/0b03735d70366bc05fc6 for homodyne detection, is there a way to make the frequency detected a range of frequencies? For example detecting between 3kHz and 4kHz?
Thanks in advance!

It may be possible to modify that program in order to get such a large
frequency range:

change the local oscillator frequency to 3.5 kHz
drastically shorten the filter's time constant in order to get a
wider passband

However, the homodyne detection scheme is best suited for building very
narrow band filters. In your case, the upper limit you want is quite
close to the Nyquist frequency (4,808 Hz), so I suggest you use a
high-pass, rather than a band-pass filter. The simplest high-pass you
can get is a numerical derivative:
y[n] = x[n] − x[n−1]
The gain of this filter is 2×sin(π×f/fsamp), so you get the
−3 dB cutoff at fsamp/4 ≈ 2,404 Hz. If you need
something better, you may want to try a higher order filter. But then
you get deep into the territory of digital filter design, which can be
tricky, especially if you have no experience with the z-transform or you
want to implement the filter in fixed point.
Edit: If you really want a bandpass, the simplest I can think of is
this two-pole filter:
y[n] = 0.360 x[n] − 0.885 y[n−1] − 0.552 y[n−2]
It will give you a maximum gain of roughly 1 at about
3.43 kHz, and −3 dB cutoffs at 3 and 4 kHz. A
straightforward floating point implementation would be:
float filter(float x)
{
    static float y1, y2;
    float y = 0.360 * x - 0.885 * y1 - 0.552 * y2;
    y2 = y1;
    y1 = y;
    return y;
}

You should convert this to fixed point if you want to use it, otherwise
I doubt your Arduino will have the processing power to run every sample
through it. Below is a plot of this filter's gain, compared with the
simple derivative, which I divided by 2 in order to normalize its
gain:

Note that the gain gets flat as you approach the Nyquist frequency, and
stays relatively high (above −5.4 dB).

Thanks for your answer, but can you maybe show a code that already has that bandpass implemented in your previous code. We are not really experienced with Arduino so we really cannot figure out what exactly to change in your code... Thank you so much for your answers already though!


text:
How to change the resolution of DS18B20?
I'm using DS18B20 sensor with this library, the 750ms delay is causing problem in timer part of my code. the code below is from DallasTemperature.cpp:
// returns number of milliseconds to wait till conversion is complete (based on IC datasheet)
int16_t DallasTemperature::millisToWaitForConversion(uint8_t bitResolution) {

    switch (bitResolution) {
    case 9:
        return 94;
    case 10:
        return 188;
    case 11:
        return 375;
    default:
        return 750;
    }

I'm reading the temperature like this:
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS A0
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

void setup() {}

void loop () {
    float currentTemp = sensors.getTempCByIndex(0);
    sensors.requestTemperatures();
}

sensor is not connected in parasite mode, and there is only one sensor.
How can i change the resolution from 12 to 9 bit?

Simple:
sensors.setResolution(9);

It normally defaults to 9, but then probes the connected device to find the maximum resolution it supports and sets it to that. This would normally be done in sensors.begin() which you omitted from your snippet above. If you don't have that it will be on 9 bit anyway, and also the bus probably won't work regardless.

thanks, do i have to declare the address too? sensors.begin(); sensors.setResolution(9); should be in void setup?

sensors.begin() finds the number of sensors connected and works out the maximum resolution supported. sensors.setResolution(9) sets the resolution for all future transactions for all connected devices.

Seems to work better:
sensors.setResolution(tempDeviceAddress, TEMPERATURE_PRECISION);


text:
ESP8266 using deep sleep, http connection fails after 360 successful connections
I am building a monitoring device for my chicken stable. Therefore, I want to measure temperature, humidity, and a reed switch every minute and send the results to a server, then sleep 60s and repeat. It works fine for a couple of hours, but then fails continously. I can see the esp connecting successfully to the access point (in the AP web interface), but the http request gives me a -1 (connection refused) status code on the esp (and doesn't reach the server. Can anyone tell me how to debug this further? Here's the ESP code:
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>

// WiFi credentials.
const char* WIFI_SSID = "myssid";
const char* WIFI_PASS = "mypass";

Adafruit_BME280 bme; // I2C

void connect() {

  unsigned long wifiConnectStart = millis();

  // Connect to Wifi.
  //Serial.println();
  //Serial.println();
  //Serial.print("Connecting to ");
  //Serial.println(WIFI_SSID);

  WiFi.disconnect();
  delay(10);

  WiFi.persistent(false);
  WiFi.mode(WIFI_OFF);
  WiFi.mode(WIFI_STA);

  WiFi.begin(WIFI_SSID, WIFI_PASS);

  while (WiFi.status() != WL_CONNECTED) {
    // Check to see if
    if (WiFi.status() == WL_CONNECT_FAILED) {
      //Serial.println("Failed to connect to WiFi. Please verify credentials: ");
      delay(10000);
    }

    delay(20);
    //Serial.print(".");
    // Only try for 15 seconds.
    if (millis() - wifiConnectStart > 15000) {
      //Serial.println("Failed to connect to WiFi");
      return;
    }
  }

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  unsigned long timePassed = millis()-wifiConnectStart;
  //Serial.println("Connecting time in milliseconds: ");
  //Serial.println(timePassed);
}

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

  Serial.println("Device Started");
  Serial.println("-------------------------------------");
  Serial.println("Running Deep Sleep Firmware!");
  Serial.println("-------------------------------------");

  connect();

  if (!bme.begin())
  {
    Serial.println("Could not find BME280 sensor at 0x77");
  }

  bme.setSampling(Adafruit_BME280::MODE_FORCED,
                  Adafruit_BME280::SAMPLING_X1, // temperature
                  Adafruit_BME280::SAMPLING_X1, // pressure
                  Adafruit_BME280::SAMPLING_X1, // humidity
                  Adafruit_BME280::FILTER_OFF);

  pinMode(D5, INPUT_PULLUP);

  bme.takeForcedMeasurement();

  bool chickdoor = digitalRead(D5);

  float temperature = bme.readTemperature();
  Serial.print("Temperature = ");
  Serial.print(temperature);
  Serial.println(" Celsius");

  //int32_t pressure = bmp.readPressure();
  //Serial.print("Pressure = ");
  //Serial.print(pressure);
  //Serial.println(" Pascal");

  //Serial.println();

  float humidity = bme.readHumidity();
  Serial.print("Humidity = ");
  Serial.print(humidity);
  Serial.println("%");

  StaticJsonBuffer<300> JSONbuffer;
  JsonObject& JSONencoder = JSONbuffer.createObject();

  JSONencoder["temperature"] = temperature;
  JSONencoder["humidity"] = humidity;
  JSONencoder["chickdoor"] = chickdoor;

  char JSONmessageBuffer[300];
  JSONencoder.printTo(JSONmessageBuffer, sizeof(JSONmessageBuffer));
  Serial.println(JSONmessageBuffer);

  //http debug stuff:
  //Serial.print("DNS #1, #2 IP: ");
  //WiFi.dnsIP().printTo(Serial);
  //Serial.print(", ");
  //WiFi.dnsIP(1).printTo(Serial);
  //Serial.println();

  //IPAddress resolvedIP;

  //if (!WiFi.hostByName("my.domain.here", resolvedIP)) {
  //  Serial.println("DNS lookup failed.  Rebooting...");
  //  Serial.flush();
  //  ESP.reset();
  //}
  //Serial.print("my.domain.here");
  //Serial.print(" IP: ");
  //Serial.println(resolvedIP);

  WiFiClient client;
  HTTPClient http;

  http.begin(client, "http://my.domain.here/chickinfo");
  http.addHeader("Content-Type", "application/json"); //Specify content-type header

  int httpCode = http.POST(JSONmessageBuffer); //Send the request
  String payload = http.getString(); //Get the response payload
  Serial.print("HTTP status code: ");
  Serial.println(httpCode); //Print HTTP return code
  Serial.print("HTTP response: ");
  Serial.println(payload); //Print request response payload
  http.end(); //Close connection

  Serial.println("Going into deep sleep for 60 seconds");

  ESP.deepSleep(60e6); // 60e6 is 60 seconds
}

void loop() {
}

why is the server refusing the connection?

reduce your code to the least amount of code that still exhibits the problem

The server log did not show the connection at all @jsotola. I upgraded the board (and with it, the httpclient library) in the Arduino IDE and it has been working for 24 hours now.

post that as an answer and then you can accept it as a solution ... other people with similar problem will be able to find it


text:
esp32 http client response only 200 didn't receive the data after that
i am using esp32 as a client and using following example. So here i am getting header response only that is 200. I am not getting any response after that. here is the example
#include <WiFi.h>
#include <HTTPClient.h>

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

void setup() {

  Serial.begin(115200);
  delay(4000);
  WiFi.begin(ssid, password);

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

  Serial.println("Connected to the WiFi network");

}

void loop() {

  if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status

    HTTPClient http;

    http.begin("http://jsonplaceholder.typicode.com/comments?id=10"); //Specify the URL
    int httpCode = http.GET();                                        //Make the request

    if (httpCode > 0) { //Check for the returning code

        String payload = http.getString();
        Serial.println(httpCode);
        Serial.println(payload);
      }

    else {
      Serial.println("Error on HTTP request");
    }

    http.end(); //Free the resources
  }

  delay(10000);

}

given url works with me as well. but if i give other url then i am getting response as 200 only. but not receiving json data which is present on the request url.

Your code works without any problem. What do you means "but if i give other url"? BTW, if you are using esp32, don't tag esp8266.

A 200 response doesn't guarantee that your payload will actually contain any data. It depends on the server. The server might determine to respond with a 200 code but still not return any JSON code for your request.
I am not at all sure, but the server may be rejecting your request because it doesn't like your user agent. I have seen my own ESP8266 supply ESP8266HTTPClient as its user agent for HTTP requests. You can see from the source code of the HttpClient class that this is the default:
HTTPClient::HTTPClient()
    : _client(nullptr), _userAgent(F("ESP8266HTTPClient"))
{
// etc...
}

You might consider setting the user agent for your http client object:
http.setUserAgent("Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0");

If you'd like to investigate a bit more, you might use curl from the command line (this works on linux) to emulate the http request being formulated by your ESP device:
curl -vA "ESP8266HTTPClient" http://jsonplaceholder.typicode.com/comments?id=10

On my linux machine, this returns all the HTTP header information, followed by some JSON for the url you've specified in your code:
[
  {
    "postId": 2,
    "id": 10,
    "name": "eaque et deleniti atque tenetur ut quo ut",
    "email": "REDACTED@EXAMPLE.COM",
    "body": "voluptate iusto quis nobis reprehenderit ipsum amet nulla\nquia quas dolores velit et non\naut quia necessitatibus\nnostrum quaerat nulla et accusamus nisi facilis"
  }
]

Maybe try that with the other url and see what comes out?
You might also modify your post with the Serial output of your sketch to provide more detail.


text:
Sending sine wave from MATLAB and reading on Arduino Uno
I am working on timing issues associated with sampling data at high rates and storing it on an SD card (ADC delays, clock drifts and file I/O time). For this experiment, I thought of sending a sinusoidal wave to an analog pin on the Arduino Uno, and have the board read the samples. Can I eliminate the need for a function generator and instead use the Matlab Support Package for Arduino to send the sinusoid to the Arduino? (I guess this would mean two programs simultaneously, a Matlab program for generation of a sinusoid and an Arduino sketch for reading and writing.)
I'm new to Matlab, so any help would be greatly appreciated.

So do you have a problem implementing the arduino sketch or the matlab code? How are you going to output the analog signal? Please show us what you have tried so far.

I would like to know if running two such programs at the same time is possible. Also, I am going to write the output on an SD card, hence the Arduino sketch will just have analogRead() and file.print() functions. I'm not sure how to go about with the Matlab code, (again only if running two programs is possible).

No, it's not possible. Only 1 program at a time. Use a second Arduino. An please mind, that the Arduino Uno does not have a real DAC. If you use analogWrite() it will output a PWM wave, not an actual analog voltage.

No, you can't. The Arduino Uno has no analog outputs to start with and,
as you guessed, it cannot run two programs at the same time.
Maybe you should search for a solution of the initial problem instead.
You should be aware that you cannot get consistent timings with
analogRead(). You will have to read the datasheet of the ATmega328p,
especially the section dedicated to the ADC. Then you will configure the
ADC yourself, at the register level. It has a feature called
“auto-trigger” which is intended to provide perfectly consistent
timings. This is what you are looking for.


text:
How to send keystroke with shift modifier?
This is a bit of a newbie question, but here it goes anyway. So basically I want to send a keystroke using the DigiKeyboard library, but with shift held down. I looked through the code and saw this comment in scancode-ascii-table.h:
//Format: most signifficant bit indicates if scan code should be sent with shift modifier
remaining 7 bits are to be used as scan code number.

I dont really understand where to specify this, whether it's when you call the sendKeyStroke function, or somewhere in the code. Help appreciated.

what does most significant bit mean to you?

I never used this library, but in the header file there are this constants for modifiers:
#define MOD_CONTROL_LEFT    (1<<0)
#define MOD_SHIFT_LEFT      (1<<1)
#define MOD_ALT_LEFT        (1<<2)
#define MOD_GUI_LEFT        (1<<3)
#define MOD_CONTROL_RIGHT   (1<<4)
#define MOD_SHIFT_RIGHT     (1<<5)
#define MOD_ALT_RIGHT       (1<<6)
#define MOD_GUI_RIGHT       (1<<7)

and a function
void sendKeyStroke(byte keyStroke, byte modifiers)

so I would use this to send a key with Shift like this
sendKeyStroke(KEY_F2, MOD_SHIFT_LEFT);

Oooooh thank you! That works perfectly!


text:
Help me get my robotic car to work?
So I recently followed a tutorial on youtube and I've assembled the car and connected all the wires.
What I've done:
Car
Now in the video, when the guy connects all the wires, the wheels constantly turn while in mine they're completely still. Is this a problem? Is it an indicator of some connection issue or something else?
For context, here is the schematic:

Add your code, and use the minimal code that should be able to spin the wheels (preferably test yourself). Also recheck all connections (the picture in the link is hard to 'analyze' ).

when the guy connects all the wires, the wheels constantly turn ... that sounds like his car is not working correctly ... the wheels should not turn until commanded to turn

The ENA/ENB (enable A/B) pins have to be at HIGH level (either hardwired or set by an mcu). There exist lots of different driver boards (mostly based on the same ICs) which sometimes don't provide this enable pin, but they are "enabled" by default. You didn't tell us which board you use, but you'll know.

I don't know your motor-driver board but here are several things to check out, based on your schematic:

The motor driver board has two enable pins. Neither of them is connected. It would make sense that these pins turn the two motors on and off.
The pin marked 12v is connected to +5v.
The linked photo of your car shows two 9v "Transistor" batteries. This kind of battery in particular is not capable of supplying much current and they most likely unable to turn the motors.

Check These:
As you have used two power source you must common ground them.
**You must check L298N motor drivers enable pins.As you have only 4 wire to motor driver from arduino.So you must give EnA and EnB pin 5v/HIGH or  You can give it (0-255) pwm value from arduino to control the speed of your motor **
If wiring is ok then you must go throw you Sketch.


text:
Using a scrolling text in OLED Adafruit_SSD1305
I have been in internet for the past week looking for a way of programming a scrolling text (either left or right) using Adafruit_SSD1305 but I only find scrolling commands for Adafruit_SSD1306. Has anyone tried this before? I really need help on this

Please share links of what you found for the SSD1306. Maybe it can be reused for the SSD1305

The SSD1305 hardware apparently does include scrolling support (SDD1305 datasheet - see section 10) but apparently the Adafruit driver didn't implement it. But The SSD1306 looks so similar to the SSD1305, that if the SSD1306 software driver won't work with it "out of the box" (worth a try!), you could probably compare the two software drivers and back-implement that feature into the the 1305 driver yourself.


text:
Control DC Motor with Arduino Uno WiFi Rev2 Html Slider Code
I would like to control my dc motor using the Arduino Uno WiFi Rev2 using an html range slider. Now I can control the motors speed and direction using push buttons just fine. My code is posted below of what I've done so far.
client.println("");
client.println("<input type=\"range\" class=\"class-name\" orient=\"vertical\" id=\"range\" min=\"0\" max=\"255\" step=\"0\" onchange=\"motor1(this.value)\" value=\"0\">");

This code below is the current button code. I need the below code to be used by the slider code above:
if (currentLine.endsWith("GET /MONFWD")) {
digitalWrite(MOTOR_A_ONE, HIGH);  // Establishes forward direction of Channel A
digitalWrite(MOTOR_A_TWO, HIGH);  // ENGAGE BRAKE
delay(1000);                      // DELAY BEFORE RELEASING BRAKE
digitalWrite(MOTOR_A_TWO, LOW);   // Disengage the Brake for Channel A
analogWrite(MOTOR_A_ENGAGE, 255); // Spins the motor forward on Channel A at full speed

And what is your question? You didn't ask one. Please describe, what exactly your problem is in writing the needed code.

Here's an example of slider that changes a Servo speed,
In html page code you have to add this:

  <input type="range" min="0" max="1023" value="512" class="slider" id="myRange">

Value:

In arduino you have to define handler like this:
void handle_pwm() {
 String  pwm_val = server.arg("PWMval"); // reading from slider on html pagae

 Serial.print("slider val: ");
 Serial.println(pwm_val);
int pwm_value = map(pwm_val.toInt(), 0, 1023, 0, 180);
Servo.write(pwm_value);

server.send(200,"text/plane","0"); // handling the webpage update

}

And define servo and handler in Setup() section:
void setup(void){
....
Servo.attach(MotorPin,1000,2000);
server.on("/setPWM", handle_pwm);
....
 }

I'm not using the servo.h library...I'm using a motor shield which already works with the push buttons....if I ignore the servo.write and servo .attach arguments the  code should work fine correct?

Also the above code is not compatible with the Arduino Uno WiFi Rev 2. It does not use server.on or server.arg

no difference, you can follow the above example for both motor shield and Uno WIFI board,
just replace servo.write() command with motor.setSpeed() for changing DC motor's speed in motor shield.just need to map slider value (0-1023) to your motor speed range,that is usually (0-255).
And by using libraries like WiFiNINA , you can have server.xyz arguments for Uno Wifi board so.

I am using the WiFiNINA library and there are no equivalents for server.arg and server.on except for client.read and client.println. Also no matter where I put the function handle_pwm it throws errors. The slider works fine as I did change the values there. Its getting the function to line up with the slider that its not working. I currently have 3 push buttons that work. Motor FWD, MotorREV and MotorBrake those work fine. I just need a slider to control the motor speed smoothly

the above example is originally written for Nodemcu board,It enjoys much easier libraries to parse http requests ,like ESP8266 WebServer lib including server.arg command and etc...
for Arduino Uno WiFi Rev 2,it is not seemingly as various as nodemcu,so,you should deal with the http requests with commands like client.read() , currentLine.endsWith() and equivalents like this.


text:
Multiple buttons to control relays
Dears,
I have a problem that I could not solve for a while, I tried the code below but it did not work.
There will be 4 buttons controlling 4 relays but in a way that button one will turn relays 1&3 on, if button 2 is pressed only relay 2 turns on, if button 3 is pressed relays 1,2 and 3 will turn on, if button 4 is pressed it is supposed to toggle relays 1&4. one more thing: I need to be able to pass from any button to any of the others and the corresponding relays will be activated while the others will go off.
    #include <Bounce2.h>

    const int     BUTTON_COUNT = 4;
    const int16_t DEBOUNCE_DELAY = 50;
    const uint8_t buttonPins[BUTTON_COUNT] = {28, 29, 30, 31};
    const uint8_t ledPins[BUTTON_COUNT] = {34, 35, 36, 37};

    Bounce buttons[BUTTON_COUNT];
    uint8_t ledStates[BUTTON_COUNT];

    void setup() {
    for (int i = 0; i < BUTTON_COUNT; i++) {
    buttons[i].attach(buttonPins[i], INPUT);
    buttons[i].interval(DEBOUNCE_DELAY);
    pinMode(ledPins[i], OUTPUT);
    ledStates[i] = HIGH;
    digitalWrite(ledPins[i], ledStates[i]);
     }
    }

    void loop() {

// Update the debouncers.
for (int i = 0; i < BUTTON_COUNT; i++)
    buttons[i].update();

// When the first "laban" button is pressed:
if (buttons[0].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[2] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off relays.
    digitalWrite(ledPins[1], HIGH);
    digitalWrite(ledPins[3], HIGH);

}

// When the first "Soda" button is pressed:
if (buttons[1].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[2], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        ledStates[1] = HIGH;
        ledStates[3] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[1].fell()) {

    // turn off the first LED.
   digitalWrite(ledPins[2], HIGH);

}

// When the first "labanUP" button is pressed:
if (buttons[2].rose()) {

    // Light up the first LED.
    digitalWrite(ledPins[1], LOW);
    digitalWrite(ledPins[2], LOW);
    digitalWrite(ledPins[3], LOW);

    // and turn off all the others.
    for (int i = 0; i < BUTTON_COUNT; i++) {
        ledStates[0] = HIGH;
        digitalWrite(ledPins[i], ledStates[i]);
    }
}

// When the first button is released:
if (buttons[0].fell()) {

    // turn off the first LED.
     digitalWrite(ledPins[1], HIGH);
     digitalWrite(ledPins[2], HIGH);
     digitalWrite(ledPins[3], HIGH);
}

// When circulation button is pressed:
 if (buttons[3].rose()) {

    // Toggle its state.
    ledStates[3] = !ledStates[3];
    digitalWrite(ledPins[3], ledStates[3]);
    digitalWrite(ledPins[0], ledStates[0]);
     }
    }

Below code is an simple example of what you described, each button will turn on the relays defined for them and turn off other relays. except for button 4 which will toggle relay 1 and 4.
int relay1 = 2;
int relay2 = 3;
int relay3 = 4;
int relay4 = 5;
int sw1 = 6;
int sw2 = 7;
int sw3 = 8;
int sw4 = 9;
int sw1Status, sw2Status, sw3Status, sw4Status;
int order = 1; // default is to set all relays off.

void setup() {
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
  pinMode(relay3, OUTPUT);
  pinMode(relay4, OUTPUT);
  // input pull-up, so default state of buttons is HIGH.
  pinMode(sw1, INPUT_PULLUP);
  pinMode(sw2, INPUT_PULLUP);
  pinMode(sw3, INPUT_PULLUP);
  pinMode(sw4, INPUT_PULLUP);
}

void loop() {
  // read the buttons status
  sw1Status = digitalRead(sw1);
  sw2Status = digitalRead(sw2);
  sw3Status = digitalRead(sw3);
  sw4Status = digitalRead(sw4);

  if (sw1Status == LOW) { // if button 1 pressed
    order = 2; // go to case 2
  }
  if (sw2Status == LOW) {
    order = 3;
  }
  if (sw3Status == LOW) {
    order = 4;
  }
  if (sw4Status == LOW) { // button 4 toggle
    if (order != 5) { // if order is not equal 5 turn on relay 1 & 4
      order = 5;
    }
    else { // else go to case 1, which will turns off all relays
      order = 1;
    }
  }

  switch (order) {
    case 1: // if order equals 1
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 2: // if order equals 2
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 3: // if order equals 3
      digitalWrite(relay1, LOW);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, LOW);
      break;

    case 4: // if order equals 4
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, HIGH);
      digitalWrite(relay3, HIGH);
      digitalWrite(relay4, LOW);
      break;

    case 5: // if order equals 5
      digitalWrite(relay1, HIGH);
      digitalWrite(relay2, LOW);
      digitalWrite(relay3, LOW);
      digitalWrite(relay4, HIGH);
      break;

    default: // if none of above cases is valid go to case 1
      order = 1;
      break;
  }
}

Having a tidy code format and using simple coding style (if possible) will help to debug/edit/improve the code more easily.
Don't forget to de-bounce the buttons.

Thank you very much, but unfortunately, it did not work the way we were expecting. I thought it maybe my connections so I used the simulator with dc motors instead of the relays and it was the same :(  "
https://www.tinkercad.com/things/k1VCQrax95J-copy-of-arduino-simulator-or/editel?tenant=circuits?sharecode=o-fW6ONb4zlq8c6y1JUVCaG0y66HdNzOcTwLNEqftGE=  "

@medo You shouldn't connect the push buttons to the positive line, we already used the INPUT_PULLUP. remove the resistor and just connect the push button directly to the negative line.

Highly appreciated @newbie.  What do you think changes need to be made if I replace the push buttons with "TTP 223" touch sensors? any idea of changes on the code? since the sensor has 3 lines; ground, vcc and signal

@medo well sensors also have high/low output too, in case of using a sensor instead of push button you have to detect sensor status and apply it in the code: sw1Status, sw2Status .... also you should replace INPUT_PULLUP with INPUT.


text:
Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins?
In many examples I see the following:
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

// set up a new serial object
SoftwareSerial mySerial (rxPin, txPin);

what is the benefit of mapping pins 2 and 3 like this? Why not just use the built in RX (pin 0) and TX (pin 1) pins? I'm using a standard Arduino Uno.

it allows to have two serial ports ... one can then be used for debugging

@jsotola  Please do not answer questions in comments - use the answer box for that. Comments here are for seeking more details about the question.

SoftwareSerial lets you add an additional serial port using "bit banging" to read/write to the port. This lets you connect up another serial device (eg. GPS, RFID reader, MIDI device, LCD) to this extra port, and still use the hardware serial interface (pins 0 and 1) via the USB port to send messages and/or debugging to the connected PC.

Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?

Pins 0 and 1 are connected to the Atmega16U2 USB interface chip. If it gets what looks like serial data it will forward it to the PC.

Is there any special wiring needed to send messages to the connected PC? Or is it enough that they just not be in use?
I'm currently using the hardware ports to communicate with an ESP8266 WiFi module, and I'm still able to see the output of Serial.print() in my serial monitor.

@AdrianM, but the esp8266 gets your debug prints too. if you have AT firmware in esp8266, the firmware attempts to process them. it disturbs the previous and/or the following AT command

See my amended answer. I agree with Juraj though, stuff you send through ports 0 and 1 will also go to whatever you have connected to those pins and the USB interface.

Nick Gammon indicated Pins 0 (RX) and 1 (TX) are already connected to the USB-Serial 16U2 chip.  Correct.  Although the transmit pin, pin 1, can drive multiple devices / serial ports, the receive pin, pin 0, is being driven by the 16U2 chip.
See: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
Trying to use this would result in tying two outputs together (never good unless the outputs are configured for open collector/open drain).  I've seen many shields that try to use pins 2 and 3 for a serial port.  (Not a good idea for a serial peripheral...)

Re “would result in tying two outputs together”: there is a 1 kΩ resistor between the 16U2’s TX and the 328P’s RX that makes this safe.


text:
Sending sensor data from Android app to arduino via USB Serial
I've searched this and have only found solutions for receiving data FROM Arduino TO android, I need the opposite. I basically need to figure out how to press a button from my android phone that will activate the hardware attached to my arduino mega 2560 AND make it where my arduino can read sensor values from the android device. I'm not an expert with android or arduino, most of the code I already have pertaining to the USB Serial connection is from GitHub.

you need to figure out how to translate a button press on an Android screen into serial data ... that is not an Arduino question ... try asking at an Android site

Ill try that, thanks.

use Blynk and the button on Android screen will work from everywhere


text:
Losing top brightness when using tip120 and PWM with 70w LED panel
I have been experimenting with pwm dimming using TIP120 on various high powered LED's, and have noticed a marked drop in the top level brightness compared to original connection without the tip 120 in line.
For instance a 70w panel connected with heavier gauge cable (not using jumper cables) no longer reaches full brightness with pwm set too full.
im using tasmota on a nodemc8266.
Is there something inherent the hardware set up causing the loss that I am missing or is there a software limitation with PWM?
curious
thanks

don't know if it is the cause, but PWM in arduino esp8266 core is software PWM: pin is toggled in timer interrupt

Remove the PWM and just set the pin to HIGH. Then see if there is still a difference. My guess is that there is. I think the TIP120 will have a relatively high voltage drop across it. Making the leds less bright. If that's the case I'd switch to a MOSFET instead of a bipolar (darlington) transistor

One of the main disadvantage of a Darlington transistor pair is the minimum voltage drop between the base and emitter when fully saturated. Unlike a single transistor which has a saturated voltage drop of between 0.3v and 0.7v when fully-ON, a Darlington device has twice the base-emitter voltage drop (1.2 V instead of 0.6 V) as the base-emitter voltage drop is the sum of the base-emitter diode drops of the two individual transistors which can be between 0.6v to 1.5v depending on the current through the transistor.

thank you, all of these comments make such sense and i will experiment with each so I methodically understand the process, and then finally follow up with the specific mosfets as described  by @crossroads.

Replace the TIP120 with a Low Rds N-channel MOSFET. Look at AOD508 or AOD514 for example, very low Rds, so it will develop very little voltage drop as the current increases.


text:
Arduino Uno First Program
Please help with this error.
Arduino: 1.8.10 (Windows 10), Board: "Arduino Uno"
Sketch uses 882 bytes (2%) of program storage space. Maximum is 32256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
avrdude: ser_open(): can't open device "\.\COM4": Access is denied.
Windows 10 Pro
Arduino UNO ATmeg 328P-PU
Have never been able to Upload a sketch.
Pin 13 and Orange LED blink at 1 second

Welcome to the Stack Exchange and on the Arduino World.
Just a note: Since yesterday there is a new version of Arduino IDE (the last version is now 1.8.11).
When you buy an Arduino, a default sketch is already present. This will blink your LED (pin13) with a 1 second interval. This just mean that your Arduino is working and has a bootloader.
To program it, you need to know which COM port is created for your Arduino module:

Press WIN-'R' (execute application)
Write devmgmt.msc

Check the COM port to see wich COM port was used for your Arduino.
This is the only cause, the message could appear if you use a standard USB-cable connected to your standard Arduino UNO board.

did you search for an existing answer?

Checked again and Arduino Uno is connected to Comport 4. And disabled Windows Defender Firewall. No success.

It seems that the port was already opened (as the question is now marked as duplicate).


text:
First Start Arduino Uno
When I started connecting my Arduino Uno for first project: LED to pin 13, resistor, breadboard, USB connected to Windows Laptop, the orange on-board LED flashes every second and the LED on the breadboard did the same.
What program is driving this?
I had NOT uploaded any program.
Please explain.

It is a preloaded sketch and will be overwritten when you upload your first sketch into the Arduino.
Typically it's the Arduino Blink sketch which can be found here:
https://www.arduino.cc/en/Tutorial/Blink
Which has the following (functional) content:
// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Thanks all, Should have checked. I had Cura open!!!!! Lessons learned.

You're welcome, if it helped you, consider upvoting (the up arrow next to the answer), and if it is the correct answer for you, also accept it (pressing the check sign).


text:
Does the Arduino deteriorate after shorting the voltage regulator?
I mistakenly connected a 7.4V battery backwards to an Arduino Nano via the Vin pin. The Arduino still works (I can upload code) connecting it to the PC using the USB cable. Here's my question: will the Arduino deteriorate using this method or can I continue using it (I'm soon going to buy a new voltage regulator)?

Of course, if you can upload the code, you can continue to use it ;)
Even if the Arduino is cheap, it is really reliable. There are always some short circuit protections.
The Voltage Regulator (I think it is a simple LM1117) has a overcurrent protection too (see: http://www.ti.com/lit/ds/symlink/lm1117.pdf)
So, don't worry. You can continue, continue and continue to use it...
Edit: just a note: never drain more than 50mA on an output. This will destroy the pin on your Arduino.


text:
Save joystick movement and run a servo motor
I am planning to use a joystick to input joystick stroke directions, save the directions as number in a variable. The idea is to start a servo motor if the directions match the directions in the sketch.
for example, let us say, I perform the following movement on the joystick:
1. two left movement along x axis ( <-, <-)
2. two right movement along x axis ( ->, ->)
3. One Up movement along y axis
and 4. one down movement along y axis.
These movements are as a result of a user solving a clue. (two left strokes could mean an alphabet 'A' or a number 1, not decided yet, and so on..)
I would like to save the 4 or 5 joystick directions in a variable and if it matches the directions declared in the sketch (True condition), then DC servo motor would start and pull a screen up, which will expose 'SOLVED' written behind the screen.
Hope the scenario is clear. Since, I am new to this, I would like to get some help with the sketch and the connections (Arduino Joystick inputs and DC server output are available on web, it will be helpful if someone can give an overall guidance as well.

how do you do two left movements?

Start simple, and try to detect a single joystick movement first. Print this to the serial port and watch the output on the Serial Monitor. Only if this works, think about the next steps.

The format of this site is not good for project guidance. It's a simple Q&A site, so you need to ask a specific question, that can be asked specifically, without  a contineous back and forth between you and the one, that might answer your question. With which part do you have problems and what are these problems specifically? You might want to try and post at the Project guidance section of the Arduino Forum (you can google it). It is meant for such guidance

Consider using (explicitly asking for help with) a simpler / older joystick with only off / on switches. Such as old computer games might use. Using a joystick made from two potentiometers (like when controlling an RC airplane) would be more difficult. Also, using a 4 way joy stick and leaving out diagonal directions would make the code simpler.  Finally, do you really need to servo motor?  Know the position of the motor at all times? Turning an ordinary motor on and off would be much simpler.  Let me know if you want me to edit your question.


text:
Turn on by long press of a button?
In my project on Arduino, I want to implement turning on the whole circuit by long press of a button.
But at the same time, I want the Arduino to be turned off in standby or sleep mode, but I don't know how to wake it up then.
Can you please advise me how this can be realized?

Your project has one button. You want a (*long) press of the button to wake the Arduino. After some time you want the Arduino to sleep (maybe to save battery power). You want the Arduino to wake again when there is a (*long) press of the button and all that in a continuous cycle. Is that correct or do you also want the Arduino to wake on other triggers as well ?  (*Technically, the Arduino would wake on a short button press but immediately resume sleeping if the button press was too short)

@6v6gt Yes, it's just as you described.
Ideally, I'd like it like this:

3 seconds press (on)
Short press during operation (sleep mode)
Long press during operation (3 sec.) shutdown

Which Arduino are you using ? Not all Arduinos, especially not development boards, bring significant power savings in sleep mode. You'd have to tolerate the Arduino entering "wake" mode as soon as the power supply is connected.  There will only be wake and sleep states using software alone. A full shutdown is also possible but would involve additional hardware to unlatch the Arduino from the power supply. Do you require a full shutdown?

Yes, a complete shutdown is required. I am using an Arduino Mega2560

3 seconds press (on) - Short press during operation (sleep mode) - Long press during operation (3 sec.) shutdown ... please add that to the question ... it does not belong in a comment

you could use an ultra low power microcontroller to detect the keypress and control power to the arduino ... something like https://www.st.com/resource/en/datasheet/stm8l001j3.pdf

You can use a circuit like this to get close to what you want to achieve.

Found on: https://forum.arduino.cc/t/switch-microcontroller-on-and-off-with-a-button-and-mofset/1047044
It is a latching circuit with the special property that you can use the same button to power up the Arduino and later when the Arduino is running, test the button in code.
It works like this. If the Arduino is powered off, pressing the button powers up the Arduino. Your program will immediately (or after a specific chosen interval) switch on D6. This sustains the latch.
Now in your code, you can detect the button press and do what you like with it. Maybe power the device off by setting D6 to LOW if the button has been pressed for X ms.
If you want the device simply to enter sleep mode on a button press, then you can do that also. However, it gets a bit more complicated because the button then has to be used to wake the device. That means setting a pin change interrupt on pin A0 and then testing A0 on wake up to determine the length of the button press. If it is too short, then you can force the Arduino to resume sleep.


text:
Serial.println() cuts off characters
I want to print a string together with number. My code is
Serial.println("Test " + index++);

(In setup() I initialized variable index to 0.) In Java it would output
Test 0
Test 1
Test 2
Test 3
...

But I get this output instead:
Test
est
st
t

Can anybody explain it to me please?

Serial.println() prints the value of one expression. The expression you passed it was `("Test " + index++).
In C/C++ a character literal such as "Test " evaluates to the memory address its first character. Adding 1 to that address gives the address of the next (or 2nd) character. Adding 2 to it gives the address of the 3rd character, and so on.
To get what you were expecting, the value of the literal, AND the value of the index, you would write:
Serial.print("Test ");
Serial.println(index++);

If you had created a String variable with the value "Test ", then the String expression, ("Test " + index++) would have been evaluated differently: The "+" operator would have concatenated the String "Text ", with the String equivalent of the current value of "index"; but that isn't the way a character literal is treated. There is a C++ String library among the Arduino libraries but it's use is not recommended because Strings get reallocated and copied when they get concatenated, resulting in excessive memory use, and the Arduino has very little memory.

JRobert explains very well why it does not work.
Instead of the Serial.print you also can use the sprintf function in case you need a more complicated string to build, or in case you want to mix two different types in one line:
char str[100];
int index = 0;
sprintf(str, "Test %d", index++);
Serial.println(str);

Make sure the buffer (100) is big enough to store the full string including the end symbol ('\0').
For safety you also can use:
snprintf(str, 100, "Test %d", index++);

This will make sure max. 100 characters are filled in (and the remainder is clipped).


text:
MCore(Arduino) - Python bluetooth communication
Pc and Mcore with bluetooth module are paired. The port is COM9 outgoing in PC. However, when I send message Arduino does not get anything. I just disconnect arduino from pc and write simple code in Mcore that turn on LED when input message is 1. However still nothing. These are the codes in python and arduino side:
import time
import serial

port="COM9"          #This will be different for various devices,COM port.
bluetooth=serial.Serial(port, 9600)         #Start communications with the bluetooth unit
bluetooth.flushInput()      #This gives the bluetooth a little kick
bluetooth.write(b'1')       #These need to be bytes not unicode
bluetooth.close()          #Otherwise the connection will remain open until a timeout

Arduino code:
char a;

void setup()
{
  Serial.begin(9600);
  pinMode(13, OUTPUT);
}

void loop()
{
if(Serial.available()){a = Serial.read();}

if (a == '1'){
  digitalWrite(13, HIGH);
  }

  else{
  digitalWrite(13, LOW);}

  delay(100);
}

I have tried to install Pybluez for WIN10, however, there was error. Do you think that this is the reason?
Thanks in advance

first I would remove the else part to debug

I also increased delay much like 3 seconds, still no response. From the led of bluetooth module it is felt that it receives something, but either format is problem or maybe it is not working properly.

I have tried many combinations including your suggestion.

I can't add the comment that's why add an answer. Check this link and you will get your result. https://github.com/huberf/Computer-to-Arduino-Bluetooth

Thank you all for answers, but the reason was very simple: The baud rate of Mbot bluetooth was 115200 and hence it could not get proper data.

Probably because you never called bluetooth.open().
What would be much easier to do is use pySerialTransfer and SerialTransfer.h to guarantee reliable and robust serial communication between Python and your Arduino.
pySerialTransfer is pip-installable and cross-platform compatible. SerialTransfer.h runs on the Arduino platform and can be installed through the Arduino IDE's Libraries Manager.
Both of these libraries have highly efficient and robust packetizing/parsing algorithms with easy to use APIs and come with examples.

kindly add a serial print before the if statement(if (a == '1')) to see what value of a is recieved so we can debug it


text:
Distinguishing between multiple Infra Red Transmitters
I am working on an Arduino project where I use an infra red camera along with 4 transmitters placed each on a corner of a square platform to park a robot perfectly on this platform.
However, it is important for the camera to distinguish between the 4 transmitters.
(it should know the right transmitters from the left and the upper transmitters from the lower).
Can anyone please help me find a solution to this problem?

Why not using a less symmetric shape for the IR transmitters instead of a square. For example an arrow. If you can distinguish between front and back you also can distinguish left and right based on that (assuming, that your robot does not flip between up/down.

Hint: Web-search how the Nintendo controller works.

How do you control where the camera is pointing?  I think I would do something like have the 4 transmitters pulsing at different frequencies, and then have 4 receivers that each look for their matching frequency and ignore others.  Don't you need 6 pairs, for left/right, forward/backward, and up/down?

It's a symmetry problem, you can solve it breaking the simmetry.
Options:

use three transmitter instead of four, the plane and its center is
still determined.
move one transmitter in the middle of the side of the square.
use different duty cycle for one (or more) transmitter.
use linear polarizing filters on the transmitters and a rotating filter on the camera lense.
...

I guess that also SVD could be helpful to find the pattern's center, when the camera is not centered and perpendicular.


text:
What is the call to cli(); routine in interrupt service routine for SPI?
I see this in examples of ISR code but what is it?

cli() disables interrupts so that the ISR itself is not interrupted ... sei() enables the interrupts again

ok. Thanks for all answers. This problem can be closed.
I found the problem with the ISR routine and not knowing what the cli() was for just slowed me down a little.

Interrupts are normally turned off automatically when an ISR is called.
There are two instructions that allow software to turn off (cli) and on (sei) interrupts to create a sequence of non-interruptable instructions, i.e. an atomic operation or critical section.
In some MCU there are several levels of interrupt priority and an ISR with lower priority may be interrupted by an ISR with higher priority. An atomic operation may also be required in an ISR with lower priority.
There are also cases where an ISR may allow interrupts (with the same or lower priority) to occur after the critical section of the ISR.
Normally an ISR should not contain cli()-sei() especially for the AVR. The hardware will automatically turn off interrupts during the execution of the ISR.
Cheers!

Thank you both for the clarification. It's interesting that the ISR that I was looking at uses the cli() at its start but forgot the esi() when closing. But it's got other problems also. Regarding the Arduino as a SPI slave, I know I have good data coming in at a very low clock rate by checking with a Logic Analyzer but the Arduino(UNO or Mega) shows garbage (all '?'). It never sees the '\n' and I can only stop it by counting characters to set the received_data flag before ending the ISR. Weird. Can't figure out why.

Post the sketch or the ISR in a new question if you are happy with the answer to your original question. We try to keep a clean question-answer session to allow others to find and follow. Extending with additional questions does not help reuse.


text:
Write and read problem while interfacing 93LC46B EEPROM through SPI
I try to save and read data from 93LC46B EEPROM using SPI with Arduino UNO.
I'm following this article https://www.arduino.cc/en/Tutorial/SPIEEPROM .
So far I have correctly connected EEPROM pinout (as shown in 93LC46B EEPROM datasheet) with arduino MISO, MOSI, SS, CLK, I copied the code from link and here is the problem, I cant save data to EEPROM, it should be filled with buffer but it is not, whats more everytime I try to read data there are different values on same addresses. How can i solve this problem ? Thanks in advance

Post your circuit and the relevant code and what you see going wrong and what you expect.

The quick answer is that 93LC46B is not compatible with AT25HP512. You can not use that tutorial. There are many differences.
Have a look at this blog instead: http://owlsan.blogspot.com/2012/10/accessing-93c4693c46n-serial-eeprom.html


text:
Missing bytes sended through serial from C# app
I am trying to store values sended by C# app in EEPROM via Arduino UNO. Here is a C# code that reads bytes from file (I'm 100% sure that there are, and always will be 256 bytes) and sends the buffer via SerialPort
        SerialPort port = new SerialPort("COM3", 9600);
        const string fileName = @"filepath";
        port.Open();
        byte[] buffer = File.ReadAllBytes(fileName);
        port.Write("W");
        port.Write(buffer, 0, buffer.Length);

Here is Arduino Code
int flag;
int datasize = 256;
byte byteBuffer[256];

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

  //read_write();
}

void loop() {
  readEEPROM();
  writeEEPROM();
  delay(500);
}

void readEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag == 'R') {
      for (int i = 0; i < datasize; i++) {
        byteBuffer[i] = ME.read(i);
      }
      flag = 'S';
      Serial.write(byteBuffer, datasize);
    }
  }
}
void writeEEPROM() {
  if (Serial.available()) {
    flag = Serial.read();
    if (flag = 'W') {
      int bytesRead = 0;
      digitalWrite(LED_BUILTIN, HIGH);
      delay(500);
      while (bytesRead < 256) {
        if (Serial.available() > 0) {
          byteBuffer[bytesRead] = Serial.read();
          bytesRead++;
        }
      }
  digitalWrite(LED_BUILTIN, LOW);

  for (int i = 0; i < datasize; i++) {
    digitalWrite(LED_BUILTIN, HIGH);
    delay(50);
    ME.writeEnable();
    ME.write(i, byteBuffer[i]);
    ME.writeDisable();
    digitalWrite(LED_BUILTIN, LOW);
    delay(50);
  }
  flag = 'S';
   }
  }
 }

As you can see in writeEEPROM function arduino turns on BUILTIN_LED before it starts reading serial, sadly the LED is never turning off, which makes me think like there are never 256 bytes in SerialPort, whats more, when i turn the c# program on again, the arduino successfully leaves the while loop, but the data is deformed, I mean the values are different.

why don't you know if there are 256 bytes received by the serial port?

Don't forget that the Arduino reboots every time you open the serial port from the computer - and the bootloader runs for a second or two gobbling up any serial data you send its way...

@jsotola Well, to leave the while loop arduino needs to enter into if(Serial.available()) 255 times, right now it is not leaving while loop, that's why i assume that there are couple of bytes missing or something like that :/

@Majenko How can I solve this then ? :)

Either put a delay after opening the serial port to give the bootloader a chance to finish, or write a proper protocol that includes being able to tell if the Arduino is ready to receive data.  Maybe send a "?" and if the Arduino replies "Y" then it's running and you can send data.

But if the arduino comes into Flag = 'W' in my example isn't it already able to read the data? I mean it have to read the serial to start the function :) Anyway I tried delaying the C# program after opening the port, it didn't help

It can't help but get into "w" - you're assigning with = not comparing with ==.

@Shizzle, the reason i asked you why you do not know if 256 bytes have been received was to make you think "how do i verify that 256 bytes have been sent without error?" .... you can debug your code by removing the EEPROM code and replacing it with code that sends the data back to sender ... that way you can narrow down the area of failure

There's two basic things wrong here.
First is your way of opening the serial port and immediately sending data.  The Arduino is reset when you open the serial port and the bootloader runs. This takes a second or so, and during that time any data that you send is lost.
Secondly you're not checking for a flag of "W" but instead you're assigning "W" to the flag, which always succeeds.
The line
if (flag = 'W') {

should read
if (flag == 'W') {

To get around the first problem you can either just put a delay (however you do that in C#) after opening the port and before sending the "W", or you could implement a "Are you there?" handshake to look for the Arduino.
One example would be to add an extra flag of (say) "?" to which the Arduino simply responds "Y".
The PC then sends "?" and, if it doesn't receive "Y" within a certain timeout it loops sending "?" again.
Once it receives "Y" then it knows the Arduino is there and ready to receive data, so you can send the "W" command and the data.


text:
Sending multiple byte data from Arduino as Slave on SPI
I have been working around the teardown of an induction cooktop and thought of having a tweak in the system. So far, I have deduced following circuitry out of the cooktop-
There are two devices communicating with each other in 3-wire SPI mode. The master, which controls power management and Induction circuitry, continuously sends commands and data to the slave. The slave, which is TM1628, receives the master commands and data, then accordingly displays the data on the seven segment or responds with the switch pressed, if any.
The above picture explains it better. Now, I thought of replacing TM1628 with an Arduino. So far so good. I gathered all the data that was being sent by the master and the reply sent by the slave.
But, when I started to code, I got stuck in one place. So the data as sent by the master and its response looks like this -
(Master to Slave)**Command1 - Command2 - Data1 - Data2 - ... - Data 14 - Command1 - Command2 - **(Slave to master)**Data1 - Data2 - ... - Data5 - **(And now the repetition)
When the master is sending the data, I have no issues as the data will continuously be read by Arduino and I can take the action accordingly.
But when the Arduino (Working as a slave) needs to send continuously 5 streams of data, depending only on the clock input timing from the master, how could I know that one stream has been written and now the next data has to be written to the SPDR register.

DodZi , Please write me an email - vjacheslavra @ yandex . ru .
I also now want to do an induction stove control through arduino instead TM1628 .
Please show your sketch arduino.

With SPI there is no such thing as "sending" and "receiving".  It is a full duplex operation every time. Whenever the master runs the clock the slave both receives bits from the master and simultaneously sends bits to the master.
These operations are inseparable.
Whatever mechanism you are using to recognise "A byte has arrived from the master" is the same mechanism that you use for filling the SPDR register. The bytes where you "send" data to the master are actually bytes where the master is sending you data, but you don't care about what that data is. Just like when the master is sending you "commands" you are sending the master data (which you haven't specified) and the master "doesn't care" what that data is.
It's up to you to keep track of how many bytes the master has clocked in and out, and to say "For bytes 19-23 the master is expecting valid data, so I need to make sure that I put data into the SPDR for those bytes".