text:
Arduino UNO - Fluctuation of inputs and outputs

I have some pots (100K) on my Arduino board. When I raise the value of one those resistance other pots are being changed (Not too much but it's significant). I have no idea what's going on. I tried to use a capacitor at the beginning of the circuit but didn't work.
These fluctuations change the value of my sensors too. When I raise the value of something other quantities change.
I'm powering up my Arduino using a USB cable.
Any ideas?

Please show a wiring diagram

This is usually because there is only one ADC in the chip. That ADC is multiplexed between inputs. You should do multiple reads of each input. Discard the first few readings, and then take an average of a few readings.

@Majenko Don't you think it takes too much time to do? Besides I need other pins too. Of course, there may be no other choices!

This is expected if the resistances of the pots is above 10 kΩ. Is this the case in your circuit?

@EdgarBonet Yeap. It's 100K!!

You seem to be experiencing cross-talk between the analog channels. This
happens because all the channels are funneled by an analog multiplexer
into the same sample-and-hold capacitor. If the source resistance is too
high, then the capacitor does not have enough time to charge to
the voltage of every channel.
Here is what the datasheet of the ATmega328P says about the
issue:

The ADC is optimized for analog signals with an output impedance of
  approximately 10 kΩ or less. [...] The user is recommended to
  only use low impedance sources with slowly varying signals, since this
  minimizes the required charge transfer to the S/H capacitor.

The problem can be mitigated by reducing the source impedance using a
capacitor at every pot wiper, or by giving more time to the
sample-and-hold circuit: make many dummy readings before the one reading
you want to keep. The proper solution would of course be to replace the
pots with 10 kΩ pots.


text:
Understanding WiFi.printDiag(Serial)
I am having difficulty with setting up websockets using the Arduino IDE with an ESP8266 ESP8266 Websockets problem and I have added WiFi.printDiag(Serial) to the main loop of my code. The Output I get (with my comments added) is
14:34:03.325 -> DIAGNOSTIC INFO   Debug Comment I added
14:34:03.325 ->
14:34:03.325 -> Mode: AP          Presume this means ESP is in AP mode
14:34:03.325 -> PHY mode:N        XXX
14:34:03.325 -> Channel: 1        Presume this means AP is on channel 1
14:34:03.325 -> AP id: 0          XXX
14:34:03.325 -> Status: 255       XXX
14:34:03.325 -> Auto connect: 1   XXX
14:34:03.325 -> SSID (0):         XXX
14:34:03.325 -> Passphrase (0):   XXX
14:34:03.325 -> BSSID set: 0      XXX

The AP is setup and I can see it in WiFI Analyser on my phone.
Is there a reference somewhere that explains the lines with XXX in them, or can
someone suggest meanings? Thanks

Mode: AP

In access point mode. Can also be STA or STA+AP for Station or dual role modes.

PHY mode:N

Physical interface mode. At the moment it's in 802.11n mode. Depends on the AP you are connecting to if any.

Channel: 1

Which WiFi channel you are communicating on
All the following are meaningless in AP mode. They only pertain to STA mode:

AP id: 0

Internal ID of the access point you are connecting to, if any.

Status: 255

Connection status

Auto connect: 1

Automatically connect to an access point.

SSID (0):

Name of the access point currently connected to.

Passphrase (0):

Password used to connect to the current access point

BSSID set: 0

BSSID (kind of like the MAC address) of the access point connected to.
As you can see, much of it is meaningless for access point mode, since it mostly is to do with connecting the ESP8266 to an existing network.  In AP mode there's not a lot of debugging information you can get - "is it running?" is really all there is.

source: Stack Exchange

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

sort: votes


text:
Burning bootloader and uploading sketch on ATMEGA328
I have a ATMEGA328-PU (not a atmega328P-PU) and managed to install the boot loader on it using an Uno as ISP, but now i can not upload any sketch, this are the steps I've done so far:
connected this pins:
reset to pin10
11 to 11
12 to 12
13 to 13
and 5V to 5V and ground to ground.
uploaded ArduinoISP from examples and then changed the programmer to Arduino as ISP.
Then i changed this line in avrdude.conf:
part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x0F;

    ocdrev              = 1;
;

to:
part parent "m328"
    id          = "m328p";
    desc        = "ATmega328P";
    signature       = 0x1e 0x95 0x14;

    ocdrev              = 1;
;

selected burn bootloader and uploaded the boot loader with success.
and then i removed pin 10 to 13 and connected reset to reset, RX to RX and TX to TX and removed the chip from Arduino UNO.
added this lines to boards.txt:
##############################################################

uno328.name=Arduino328

uno328.vid.0=0x2341
uno328.pid.0=0x0043
uno328.vid.1=0x2341
uno328.pid.1=0x0001
uno328.vid.2=0x2A03
uno328.pid.2=0x0043
uno328.vid.3=0x2341
uno328.pid.3=0x0243

uno328.upload.tool=avrdude
uno328.upload.protocol=arduino
uno328.upload.maximum_size=32256
uno328.upload.maximum_data_size=2048
uno328.upload.speed=115200

uno328.bootloader.tool=avrdude
uno328.bootloader.low_fuses=0xFF
uno328.bootloader.high_fuses=0xDE
uno328.bootloader.extended_fuses=0xFD
uno328.bootloader.unlock_bits=0x3F
uno328.bootloader.lock_bits=0x0F
uno328.bootloader.file=optiboot/optiboot_atmega328.hex

uno328.build.mcu=atmega328
uno328.build.f_cpu=16000000L
uno328.build.board=AVR_UNO
uno328.build.core=arduino
uno328.build.variant=standard

Selected that from board menu changed the programmer to AVRISP mkll and tried to upload the blink sketch but it stuck on "uploading" and after a while says "an error occurred during upload".
I triple checked the wiring!

Is your chip set up with a crystal/caps, or a resonator?  The chip needs an external clock source since that's your fuses are set up for.  "changed the programmer to AVRISP mkll" This will do nothing unless you have a Programmer connected to the ICSP pins.   What is connected to what here: "connected reset to reset, RX to RX and TX to TX and removed the chip from Arduino UNO."?

@CrossRoads yes it have a crystal and two capacitors, i wanna use the Arduino as programmer... WIRES connected those pines together.

newbie, use the https://github.com/MCUdude/MiniCore to burn the bootloader and serial upload. btw: you can put the 328 in the socket on Uno

"managed to install the boot loader on it" How did you do that? Do you have another board you are using as a Programmer? Or do you have a Programmer?

@CrossRoads, it started here https://arduino.stackexchange.com/questions/66694/atmega328p-u-vs-atmega328-pu this question make more sense if you put the informations together. but you should read this question again

Not really. There is no indication of how the bootloader was installed.

@Juraj thanks i'll try that and let you know what happened.

@Juraj i placed the 328 on arduino and installed that library from github then followed the instruction but i'm still getting this error: "An error occurred while uploading the sketch"!

@Juraj the led on pin 13 is blinking tho... i have no clue...

sorry, you should burn a 328 bootloader from that package first

the instruction didn't say anything about that, how do i do that? @Juraj

same way like before, only with MiniCore. choose the right settings in Tools menu

Comments are not for extended discussion; this conversation has been moved to chat.

Use the https://github.com/MCUdude/MiniCore for ATmega328. It has Boards Manager installation. Choose the right options in Tools menu for your ATmega328.
First burn the bootloader using programmer or "Arduino as ISP". Then you can do serial upload as usual.
You can put the ATmega328 on Uno if you want.

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


text:
Can we call GPRS HTTP request asynchronously in Arduino?
Usually GPRS modules (SIM800,900, A6, etc) that used with arduino are called in synchronous way in HTTP (GET/POST) request. It takes more than 10 seconds in most times and this makes the system very slow. Is there a way to use them (libraries or the module) asynchronously (or is there any alternatives) and perform these request in background while main business is being done?

Sure there is. All you're doing is reading and writing serial data. All you have to do is learn how to do that without blocking.
Most code I see bandied around is of the form:
Send AT command
Delay for numerous seconds
Read and discard anything that might be there
Send another AT command
Delay for more seconds
Read and discard anything that might be there
... etc ...

That is completely the wrong way to do things.
Instead you should be using non-blocking reading to look for an actual OK response from the AT commands that you have sent and use that to progress through the different stages of a Finite State Machine.
Some reading resources from my blog:

Reading Serial on the Arduino
The Finite State Machine
The Evils of Arduino Strings
Splitting Up Text in C


text:
Debouncing a button with interrupt
I tried to follow the answer here:
https://arduino.stackexchange.com/a/18545/51302
Unfortunately I can only get the interrupt to go once (on serial monitor is the time of that first interrupt), then nothing.
I know this has already been answered but I don't understand the mistake and would appreciate help.
What I'm trying to do:
get a button to set an interrupt to trigger foo and thus write the steps on the monitor.
I've left remarks to try and explain what I try to do, so it would be easier to understand what I left out or used incorrectly.
Thanks.

#define IRF520 A2
#define BUTTON 3
static unsigned long last_press = 0;
static bool button_state = HIGH;             //pull up resistor
volatile bool interrupt_flag = 0;            //when the interrupt fires, button press or noise
bool is_pressed = false;                     //after checking that the button was really pressed
bool was_pressed = false;                    //last state of the button
unsigned long button_pause_duration = 20;        //pause required to accept press in ms
unsigned long interrupt_time=0;

void button_interrupt() {
  interrupt_flag = true;                      //can be a false alarm
  Serial.print("interrupt time: ");         //this is the onlt step that works
  Serial.print(millis());
  Serial.print("\n");
}

void setup() {
  Serial.begin(9600);
  pinMode(IRF520, OUTPUT); //A2 controls IRF520
  pinMode(BUTTON, INPUT_PULLUP);  //pin D2 and D3 are sutible for interrupts
  attachInterrupt(digitalPinToInterrupt(BUTTON), button_interrupt, FALLING);
}

void debounce_button() {
  if (digitalRead(BUTTON) != button_state) {
    button_state = digitalRead(BUTTON);         //if button changed state remember the new state
    interrupt_time=millis();
  }
  if (button_state == LOW) {
    last_press = millis();
    Serial.print("last_press was updated to: ");
    Serial.print(last_press);
    Serial.print("\n");
  } else {
    last_press = 0;
    interrupt_flag = false;
  }
  if ( last_press && (millis() - last_press) > button_pause_duration) {
    last_press = 0;     //set to 0 for the next check
    is_pressed = true;   //button was really pressed
    Serial.print("last_press was set to 0 and is_pressed to true - BUTTON WAS PRESSED at: ");
    Serial.print(millis());
    Serial.print("\n");
  }
}

unsigned int foo(bool is_pressed) {
  if (is_pressed) {
    Serial.print("foo is active, MOSFET does its thing");
    Serial.print("\n");
    }
  }
}

void loop() {
 if(interrupt_flag){
    Serial.print("the button is now being pressed: ");
    Serial.print(millis());
    Serial.print("\n");
 }
 debounce_button();
 foo(is_pressed);
}

do not use serial.print() inside the interrupt handler ... set the interrupt flag and save the value of millis() ... do the  serial.print() inside loop()

Edited the question, tried it but it doesn't solve the problem.

the && in the if statement looks wrong ... what are you trying to do?

I check that the timing is good and that last_press is not 0. because it is 0 for the cases I ignore and if it is not 0, along with the other condition, ist a real event.

In general, it's a bad idea to use interrupts for bouncing buttons. And interrupts are not able to do debug printouts.

So, I grabbed a Mega and several pushbutton switches (one of which turned out to be a push-on, push-off, much to my bemusement), and ginned up a small Arduino program to illustrate an interrupt-driven button debounce technique.  Please feel free to point out any and all errors ;-)
Here is a small program to debounce any momentary contact switch.  The Mega interrupt line (pin 2, interrupt 0) triggers on any low-to-high or high-to-low transition.  the interrupt service routine (ISR) simply sets a flag to TRUE and exits.  If multiple interrupts occur before the loop() function can service the flag, the second and subsequent ISR calls do nothing (well, they set the flag, but since it was already set...).  The loop() code looks for a set flag, and if it finds one, generates a 50uSec pulse on a selected pin, delays 100mSec, resets the flag, and exits.  As long as the switch's contact bounce activity ceases before the 100mSec delay expires, one and only one pulse per transition will be generated.  YMMV.
/*
Small program to demonstrate switch debounce technique using an interrupt
The ISR is called for low-to-high and high-to-low transitions, and may get
called multiple times per button press.  However, the code in loop() ensures
that each transition produces one and only one pulse per transition, assuming
the typical 10-20 mSec max bounce duration.

Note that if the line 'delayMicroseconds(50); //used to show multiple bounces'
is used instead of the line 'delay(100);//ignore bounces for 100mSec', then
multiple contact bounces will each generate their own 50uSec pulse.  This is
useful for O'scope diagnosis if you happen to have one.
*/

#include <elapsedMillis.h>
#include <PrintEx.h> //allows printf-style printout syntax

StreamEx mySerial = Serial; //added for printf-style printing

//pin assignments
const int LED_PIN = 13;
const int BUTTON_PIN = 2;
const int BUTTON_STATE_PIN = 3;

//variables
bool buttonState = 0;
bool blinkState = 0;

// ================================================================
// ===               INTERRUPT DETECTION ROUTINE                ===
// ================================================================

volatile bool Interrupt = false;     // indicates whether MPU interrupt pin has gone high
void BtnInterrupt()
{
    Interrupt = true;
}

// ================================================================
// ===                      INITIAL SETUP                       ===
// ================================================================

void setup() {
    // configure pins
    pinMode(LED_PIN, OUTPUT);
    pinMode(BUTTON_PIN, INPUT_PULLUP);
    pinMode(BUTTON_STATE_PIN, OUTPUT); //scope monitor pin
    digitalWrite(BUTTON_STATE_PIN, LOW);

    buttonState = digitalRead(BUTTON_PIN);
    mySerial.printf("Initial button state is %s\n", buttonState == LOW ? "LOW" : "HIGH");
    attachInterrupt(digitalPinToInterrupt(BUTTON_PIN), BtnInterrupt, CHANGE);
}

// ================================================================
// ===                    MAIN PROGRAM LOOP                     ===
// ================================================================

void loop()
{
    if (Interrupt)
    {
        digitalWrite(BUTTON_STATE_PIN, HIGH);
        delayMicroseconds(50);
        digitalWrite(BUTTON_STATE_PIN, LOW);
        //delayMicroseconds(50); //used to show multiple bounces
        delay(100);//ignore bounces for 100mSec
        Interrupt = false;
    }
}

Here are two O'scope screen grabs. One shows the pulse train generated by a single button transition with a 50uSec delay, and the other shows the same switch with the 100mSec delay.  In both photos, the horizontal time scale is 500uSec/cm

Amazing answer. This deserves more likes!

this works really fine, thanks!

I think the problem is that you only trigger the interrupt when the button is pressed (interrupt FALLING)
Therefore, there is no opportunity to call debounce when the button is released.
Therefore, there is no way to change the button state variable back to HIGH (I.e. when the button is released).
To verify the hypothesis or gain some other insights, I suggest trying to put a debug statement in your loop similar to the following
  If (millis () >= debugTime) {
       DebugTime = millis() + 1000:   // output every second...
       Serial.print("value of button state is: ");
        Serial.println(button_state);
      // and a few other variables.
  }

I will leave it to you to properly declare debugTime (unsigned long) and choose a few other key variables (maybe interrupt flag) to print in the debug message block.
And i think you already have done so,  but also delete the print statements in your ISR.

The problem is that you need to check whether the last interrupt was far enough in the past that the output can be considered stable.
The most obvious solution to me is to have the ISR record the time it was called, and the main loop can simply check if that time is sufficiently before the current time.  The comparison is very cheap, and doesn't require a delay.
The "same record interrupt time and then compare" can cover multiple buttons on MCUs like the ATTINY85 which uses a single shared ISR.  The disambiguation etc. resides outside the ISR.


text:
How do I have this audio and LED activate ONLY when a button is held using an Arduino?
I have this code that I am using to play a sound effect where I used a program called wav2c to convert a .wav file to number values that I put into a header file that I use in the code to generate the sound. I currently have it programmed to play the audio upon uploading it to the Arduino with an LED being activated along with it and staying lit for just the duration of the sound effect. I am trying to program it so that the sound and LED only activate when I am pressing a button. I have the pin the button is plugged into already programmed in but I'm not sure how to have it control the audio and LED as stated above. I don't have much experience with programming or Arduino so any help is much appreciated! I am using an Arduino Mega 2560.
The code

#include <stdint.h>
#include <avr/interrupt.h>
#include <avr/io.h>
#include <avr/pgmspace.h>

#define SAMPLE_RATE 20000
#include "Test.h"

int ledPin = 2;
int speakerPin = 9; // Can be either 3 or 11, two PWM outputs connected to Timer 2
const byte pinSwitch1 = 3;
volatile uint16_t sample;
byte lastSample;

void stopPlayback()
{
    digitalWrite(ledPin, LOW);
    // Disable playback per-sample interrupt.
    TIMSK1 &= ~_BV(OCIE1A);

    // Disable the per-sample timer completely.
    TCCR1B &= ~_BV(CS10);

    // Disable the PWM timer.
    TCCR2B &= ~_BV(CS10);

    digitalWrite(speakerPin, LOW);
}

// This is called at 8000 Hz to load the next sample.
ISR(TIMER1_COMPA_vect) {
    if (sample >= sounddata_length) {
        if (sample == sounddata_length + lastSample) {
            stopPlayback();
        }
        else {
            if(speakerPin==11){
                // Ramp down to zero to reduce the click at the end of playback.
                OCR2A = sounddata_length + lastSample - sample;
            } else {
                OCR2B = sounddata_length + lastSample - sample;
            }
        }
    }
    else {
        if(speakerPin==11){
            OCR2A = pgm_read_byte(&sounddata_data[sample]);
        } else {
            OCR2B = pgm_read_byte(&sounddata_data[sample]);
        }
    }

    ++sample;
}

void startPlayback()
{
    pinMode(speakerPin, OUTPUT);

    // Set up Timer 2 to do pulse width modulation on the speaker
    // pin.

    // Use internal clock (datasheet p.160)
    ASSR &= ~(_BV(EXCLK) | _BV(AS2));

    // Set fast PWM mode  (p.157)
    TCCR2A |= _BV(WGM21) | _BV(WGM20);
    TCCR2B &= ~_BV(WGM22);

    if(speakerPin==11){
        // Do non-inverting PWM on pin OC2A (p.155)
        // On the Arduino this is pin 11.
        TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
        TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2A = pgm_read_byte(&sounddata_data[0]);
    } else {
        // Do non-inverting PWM on pin OC2B (p.155)
        // On the Arduino this is pin 3.
        TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
        TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
        // No prescaler (p.158)
        TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set initial pulse width to the first sample.
        OCR2B = pgm_read_byte(&sounddata_data[0]);
    }

    // Set up Timer 1 to send a sample every interrupt.

    cli();

    // Set CTC mode (Clear Timer on Compare Match) (p.133)
    // Have to set OCR1A *after*, otherwise it gets reset to 0!
    TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
    TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

    // No prescaler (p.134)
    TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

    // Set the compare register (OCR1A).
    // OCR1A is a 16-bit register, so we have to do this with
    // interrupts disabled to be safe.
    OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

    // Enable interrupt when TCNT1 == OCR1A (p.136)
    TIMSK1 |= _BV(OCIE1A);

    lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
    sample = 0;
    sei();

}

void setup()
{
    pinMode( pinSwitch1, INPUT );
    pinMode(ledPin, OUTPUT);
    digitalWrite(ledPin, HIGH);
    startPlayback();
}

void loop()
{
    while (true);
}

The header file referenced in the code with the numeric values to create the audio.
#ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
#define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

const int sounddata_length=32000;
//const int sounddata_sampleRate=20000;

const unsigned char sounddata_data[] PROGMEM = {
  15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

//There are many lines of more numbers in between that I cut out to save space

};

#endif // _HEADERFILE_H    // Put this line at the end of your file.

remove startPlayback() from setup() ... place it in loop() so that it is called only when the switch is moved from released to pressed .... when the switch is moved from pressed to released then call stopPlayback()

I moved the 'startPlayback()' to setup() and added                                   //buttonState = digitalRead(pinSwitch1);
//while (buttonState == LOW) {
//stopPlayback();  }  And the same for stopPlayback, but it doesn't seem to be working, any suggestions?

read my first comment carefully ... the changes you made are not same as what i suggested

ok, I will reread. The audio does not play when I changed the location of 'startPlayback()' and the button doesn't affect anything.

also looks like you added comments, not code

don't forget that loop() repeats many times per second .... any code that runs when the button is in the released state (or in pressed state) will run at each iteration of loop() .... you want your code to run only once when there is a change in switch state

your best course of action is to test intermediate code ... in loop(), call startPlayback(), pause for 5 seconds, call stopPlayback(), pause for 5 seconds .... that will tell you if you can start and stop playback from within loop()

note: there is no reason to have while (true); inside loop() if it is empty ... loop() is while(true); already


text:
Unable to control servo with decoupling capacitor and external power supply, but motor shield works
I'm a hobbyist trying to up my arduino and electronics knowledge.
I can successfully control a hobby servo using an motor driver shield (https://learn.adafruit.com/adafruit-motor-shield/overview) but am running into issues when I try to control it without the shield using standard servo control circuits.
When the servo is connected to the basic, unworking circuit, it generally doesn't move and clicks occasionally, as though underpowered. It works flawlessly with the shield, when powered just through the standard 5V USB connection.
Schematic of circuit that doesn't work:

Schematic of circuit working with shield (shield is approximation from fritzing):

I've tried :

a 470uF or 1000uF decoupling capacitor between ground and +5V. Also tried with no capacitor.
powering the servo and/or arduino from an external power supply.  Grounds are connected correctly.
Different 5V power supplies. (batteries intended for phone charging, 5V from computer, 5V from wall).
Different Arduino Unos.
Different servos.

Code running on Arduino:
#include <Servo.h>

Servo servo;

void setup() {
  servo.attach(10);
}

void loop() {
  servo.write(135);
  delay(500);
  servo.write(45);
  delay(500);
}

I'd like to understand what I'm doing wrong, how to troubleshoot, and/or what the shield is doing that the basic circuit is not.
I'm using Arduino Unos, a hobbytech YM-2765 servo (rated for 4.8-6V), or a 3001HB servo.

The wiring diagram you link to shows the servo on pin 9. Yet your code has the servo on pin 10. Do you actually have the servo on pin 9, or on pin 10? Please show your actual wiring, not a picture of what you think you followed.

Servo is on pin 10, sorry for confusion. Have updated with schematic of wiring. I note that these are still technically a picture of what I think I followed. Let me know if actual images or a circuit schematic would help.

Your schematic shows you feeding 5V to Vin.  Vin feeds the regulator and needs at least 7 volts.  If you have regulated 5V then feed that into the 5V pin.

Switched to 5V pin - same issue. Updated schematic to reflect this.


text:
Current consumption of a buzzer
I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?
https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf
I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.

In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.
Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.
To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.
In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.
In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.
Thus
Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                 ^
                                           Arduino GPIO pin

Point of clarification: You shouldn’t use a boost converter on a GPIO pin, only on a 5V supply rail. Boosting voltage takes a lot of current. >2.4x more.

@Duncan Yes I meant that (after a transistor), I will make it more clear.

Yeah, I assumed that's what you meant, but remember that lots of newbies read these boards.

@DuncanC True indeed, thanks for the notification.

If this is a piezo buzzer they typically work over a wide range of voltages and use very little current. I've seen them with specs for an input voltage ranging from 3 to 18v.
You could likely drive a piezo buzzer directly from a GPIO line without problems.


text:
Timer 1 COMPA ISR - default behaviour?
I'm creating a LCD frequency generator.
When TIMER1 reaches a set value, it's set to toggle Pin 9 (via OC1A).
Accidentally, I left the TIMER1 "interrupt on compare match A" enabled, but never defined the TIMER1_COMPA_vect interrupt vector.
This made the Uno reset itself - but not running through the bootloader, just the program part - whenever TIMER1_COMPA_vect would've been called.
Once I defined the ISR, even without it having any content, it would run as expected.
Is there a default content for ISRs, which resets the device / starts just after the bootloader? Shouldn't the compiler detect a completely missing ISR?

The compiler cannot detect a missing ISR since it is very difficult, in
the general case, to tell whether any particular interrupt-enable bit
has been set by the program.
The avr-libc library does indeed provide a “catch-all” ISR and, as
stated by the manual,

the default action is to reset the device by jumping to the reset
  vector.

If you don't like this behavior, you can override this catch-all with
your own, as explained in the manual (search for “Catch-all
interrupt vector”).

Very interesting, that solves my confusion - thank you.


text:
Blynk.Begin(auth, ssid, pass) causing watchdog reset
I am trying to follow this tutorial and I keep hitting a problem repeatedly. I checked in my code that every time it hits the line Blynk.begin(auth, ssid, pass);, the serial monitor shows me that there was a cause:4, boot mode:(3,6) wdt reset. I looked it up a little bit and learned that this is a "hardware watchdog reset" but I am not sure why this problem is happening. Please let me know if you guys would like anymore info. Thank you!
here is my code:
#include <ESP8266WiFi.h>

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <BlynkSimpleEsp8266.h>
char auth[] = "xxx";

/* WiFi credentials */
char ssid[] = "xxx";
char pass[] = "xxx";

/* HC-SR501 Motion Detector */
#define ledPin 7
#define pirPin 2 // Input for HC-S501
int pirValue; // Place to store read PIR Value

void setup()
{
  Serial.begin(115200);
  Serial.println("here 1");
  delay(10);
  Serial.println("here stop?");
  Blynk.begin(auth, ssid, pass);
  pinMode(ledPin, OUTPUT);
  pinMode(pirPin, INPUT);
  Serial.println("here 2");
  digitalWrite(ledPin, LOW);
}

void loop()
{
  getPirValue();
  Blynk.run();
  delay(10);
  Serial.println("here 3");
}

/***************************************************
 * Get PIR data
 **************************************************/
void getPirValue(void)
{
  pirValue = digitalRead(pirPin);
  if (pirValue)
  Serial.println("here 4");
  {
    Serial.println("==> Motion detected");
    Blynk.notify("===> Motion detected");
    Serial.println("here 5");
    delay(10);
  }
  digitalWrite(ledPin, pirValue);
  Serial.println("here 6");
}

Serial Monitor:
[6485] Connected to WiFi
[6486] IP: xx.x.x.xx
[6486]
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on ESP8266

[6492] Connecting to blynk-cloud.com:80
[6584] Ready (ping: 38ms).

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
here 1  (Serial.println in line 19 of code)
here stop? (Serial.println in line 21 of code)

Specs:

Board: Generic ESP8266 Module
Upload Speed: 115200
CPU Frequency: 80MHz
Flash Frequency: 40MHz
Flash Mode: DOUT (compatible)
Flash Size: 512K (no SPIFFS)
Crystal Frequency: 26MHz
Reset Method: ck
Debug Port: Disabled
Debug Level: None
IwIP Variant: v2 Lower Memory
VTables: Flash
Exceptions: Disabled
Builtin LED: 2
Erase Flash: Only Sketch
Espressif FW: nonos-sdk 2.2.1 (legacy)
SSL Support: All SSL ciphers (most compatible)

sorry, now I see the true error. you can't use io 7. it is wired to flash memory. what esp8266 board/module do you have?

Moving from io 7 to io 6 solved the error for a little bit but when the motion sensor detected motion, it restarted again with the same original error. Could my PIR sensor be causing the problem?

https://arduino-esp8266.readthedocs.io/en/latest/reference.html

Changing the io from 6 to 4 solved the problem. Thank you Juraj!


text:
Would it be feasible to build an arduino that takes 12v on/off signals from a vehicle diagnostic port (1984 pre-OBD)?
The vehicle is an AMC eagle, they come with a diagnostic port
I have made a diagnostic tool that lights led lights when signals turn on and off, but it has to be wired in and is bulky. I am wondering if it would be possible to have an arduino plugged in and running off the 12v battery supply (with step-down to 5v) and have it catch the signals and send them over Bluetooth to a computer. Does this sound like it is within the scope of an arduino or am I asking too much? Or is there a better and easier way to do this?

Two things. 1. With the engine running, you may have 14.5VDC, not 12VDC. 2. Be careful with the tach signal. If it's connected to the negative side of the ignition coil, you could see a voltage spike of up to 250 volts.

You can step down 12V to 5V with resistor dividers, or drive transistor base with 12V and let the collector pulldown an input with pullup resistor to signal an active signal (like an optocoupler, but without the slow optical part).
Arduino reading the inputs and sending via bluetooth to something else is pretty straightforward, perhaps send only when a change from 0 to 1, and 1 to 0, on any input is sensed. Check Adafruit.com for bluetooth modules that are easy to use.

I have a bunch of 2n222 smd parts but I doubt they could handle 12v, would I need to have one transistor per gpio used? The diagnostic port has 16 inputs that I would like to use.

Also, a lot of these signals are either always on, off, or change rarely. For example coolant temperature switch just goes from off (0v) to on (12v) when the coolant temperature reaches 135deg F. So speed is not that critical for most operations. Would an optocoupler work fast enough for these types of signals? My only concern is putting a bunch of resistors in a small package in a hot engine bay and having them constantly divide 12v would make the whole thing pretty hot. I could be wrong thou, I have a pretty basic understanding of electrics.

The current flow thru the transistors is very low, not much heat will be generated.  P=IIR, so say you had a 10K and a 5Kin series to drop 12V down to 4V, then the current thru the pair would be I=V/R = 12/15000= 0.8mA, and P = 0.096W * 16 = 1.5W for 16 circuits. You could increase the resistor values and lower the generated power.   Alternatively, you could use a pair of cd74HC4050 as level translaters, powered from 5V, to bring 12V down to 5V. 48 cents each at Digikey.com. That would use even less current for lower power dissipation as the output is just 1uA to drive the Arduino inputs.

I like the cd74HC4050 idea, in looking at the spec sheet, are there 6 inputs per chip? So for instance I would plug 5v regulated into pin 1, arduino gpio X into pin 2 and input 1 into pin 3? I'm specifically looking at the cd74HC4050E if there are differences between the chips. If there are 6 "inputs" per chip I would need 3 correct?

Yes, 3 chips would provide 18 channels. I don't have the datasheet in front of me, but the pinout is straight forward. Don't forget to use a 0.1uF cap from 5V to Gnd, located near the chip.

Yes, it is possible. The 12v signals would have to be conditioned for the Arduino to receive them (0 - 12v or maybe 0 - 12-14.5v?). Then the Bluetooth side would be the same as any other Bluetooth data transmission.
So your question comes down to: Is this a fun project that's worth the effort you put into it for the learning experience? Or is this meant to answer a need, and the most practical means to that end is the best means?
Ex: I wanted to know how long / what kind of driving would it take to get my car's oil to full temp (~100C), starting from dead-cold in the winter? I had a thermo-logger I'd built for another experiment, so I taped a sensor to my oil filter (yeah, not the greatest, but quick and dirty) and lead a cable outside the hood, through the driver's window, to the experimental PC board on my dash-board. It wasn't a miserable failure but nothing to be proud of, either.
The solution I settled on was a USD$12.00 OBD port sender and an iPhone app. The results were much better, and while I didn't have the built-it-myself experience, I got the data and the answers I needed.

It is to answer a need, it would be a replacement for my homemade diagnostic tool that I built (picture added). These vehicles are finicky as older cars can be, and I would like to be able to provide a simple tool for me and others who want it to use, not unlike the small Bluetooth obd2 readers that have pop'd up. Arduino sounds like the best option but I wanted to ask before I went down the rabbit hole only to find out that there is already something that does pretty close to what I'm after.


text:
How can remove the WiFi/Bluetooth libraries when compiling the firmware using the Arduino IDE?
I have an ESP32-D0WDQ6, which is part of the ESPIRIT freematics development kit. The processor is a 2-core Tensilica LX6 and the module has 520 kB SRAM + 4 MB external on-module flash. It also has the SIM5360E 3G/GSM module. So with that connection, I don't need neither the Bluetooth nor the WiFi stack. However, it seem that when compiling using the Arduino IDE, all these libraries are still included in the compile, even if not used. This is bad as it seem to take up a lot of extra FW space that I need for my growing app, while running my device at high currents, and heating it up.
How can I ensure that WiFi/Bluetooth libraries are not compiled in with the Sketch when using Arduino IDE?
At this point I have tried to disable them, but that required to #include Wifi.h (or similar) which no longer fit on my sketch. (This doesn't make any sense, that I need to include Wifi.h just to be able to disable it.)

UPDATE:
It's most definitely linking all those...

#--------------------------------------
# Linking everything together...
#--------------------------------------

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-gcc"
-nostdlib "-LC:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/sdk/lib"

    "-LC:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/sdk/ld"
    -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.libgcc.ld -T esp32.rom.spiram_incompatible_fns.ld
    -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static
    -Wl,--undefined=uxTopUsedPriority -u __cxa_guard_dummy -u __cxx_fatal_exception
    -Wl,--start-group "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\BTHealthThermometer.cpp.o"

    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\ECUBluetoothTask.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\FreematicsNetwork.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\FreematicsPlus.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\KolbanTask.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\eCUesp32.ino.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\eCUlogging.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\esp32fota.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLE2902.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLE2904.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAddress.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAdvertisedDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAdvertising.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEBeacon.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLECharacteristic.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLECharacteristicMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDescriptor.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDescriptorMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEEddystoneTLM.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEEddystoneURL.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEExceptions.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEHIDDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteCharacteristic.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteDescriptor.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteService.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEScan.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLESecurity.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEServer.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEService.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEServiceMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEUUID.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEUtils.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEValue.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\FreeRTOS.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\GeneralUtils.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\ETH.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFi.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiAP.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiGeneric.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiMulti.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiSTA.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiScan.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiServer.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiUdp.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SPI\\SPI.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\SD.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\sd_diskio.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\sd_diskio_crc.c.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\FS\\FS.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\FS\\vfs_api.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\HTTPClient\\HTTPClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFiClientSecure\\WiFiClientSecure.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFiClientSecure\\ssl_client.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\Update\\Updater.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\core\\core.a"

-lgcc
-lopenssl
-lbtdm_app
-lfatfs
-lwps
-lcoexist
-lwear_levelling
-lesp_http_client
-lprotobuf-c
-lhal
-lnewlib
-ldriver
-lbootloader_support
-lpp
-lfreemodbus
-lmesh
-lsmartconfig
-ljsmn
-lwpa
-lethernet
-lphy
-lapp_trace
-lconsole
-lulp
-lwpa_supplicant
-lfreertos
-lbt
-lmicro-ecc
-lesp32-camera
-lcxx
-lxtensa-debug-module
-ltcp_transport
-lmdns
-lvfs
-lesp_ringbuf
-lsoc
-lcore
-lfb_gfx
-lsdmmc
-llibsodium
-lcoap
-ltcpip_adapter
-lprotocomm
-lesp_event
-limage_util
-lc_nano
-lesp-tls
-lasio
-lrtc
-lspi_flash
-lwpa2
-lwifi_provisioning
-lesp32
-lface_recognition
-lapp_update
-lnghttp
-lspiffs
-lface_detection
-lespnow
-lnvs_flash
-lesp_adc_cal
-llog
-ldl_lib
-lsmartconfig_ack
-lexpat
-lm
-lfr
-lmqtt
-lc
-lheap
-lmbedtls
-llwip
-lnet80211
-lesp_http_server
-lpthread
-ljson
-lesp_https_ota
-lfd
-lstdc++
-Wl,--end-group
-Wl,-EL
-o "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.elf"

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/gen_esp32part.exe"
-q "C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/partitions/default.csv"
"C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.partitions.bin"

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/esptool/esptool.exe"
--chip esp32 elf2image --flash_mode dio --flash_freq 80m --flash_size 4MB
-o "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.bin"
"C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.elf"

the arduino libraries are not linked if you don't use them. but the closed source SDK is precompiled in 80 .a files. using esp without Espressif SDK is like using a computer without OS.

That's weird, because during the linker part it seem that it links a whole bunch of libraries that I'm supposedly not using. So then there must be 2nd/3rd dependencies that are using them. I'll post the linker output tomorrow. So are there any open alternatives to the SDK?

Arduino libraries are a thin layer over the SDK.

I'm not quite sure, but I'd think that your best option would be to forfeit the Arduino libs and build directly on the Espressif SDK...

Yeah, I really wish that Arduino devs could provide better control for this. Or at least clearly document what are the dependency chain of all the other libraries. WiFi and BT are both huge, so it would be great to be able to get rid of those, when not needed.

I've also seen this forum post, but there were never any response to that post.


text:
how to apply a timer to an analogWrite command for Arduino
I have 2 sketches that control a fan using Arduino UNO, that I try to combine.
The 1st is a timer, that turns a pin ON and OFF for a determined period of time.   The pin signal drives a MOSFET that in turn switches a small fan ON and OFF.
Since I need to control the speed of the motor, I would rather use the PWM control, however I am not sure how I can apply the timer since analogWrite command refers to a pin and value.
Thanks
timer code:
const byte relayPin = 6; // relay module on pin 6
const byte monitorPin = 13; // builtin LED output
const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
unsigned long currentMillis, previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH); // relay OFF
  pinMode(monitorPin, OUTPUT);
  digitalWrite(monitorPin, LOW); // LED off
}

void loop() {
  // put your main code here, to run repeatedly:
  currentMillis = millis();
  if (currentMillis - previousMillis >= interval_1)
  {
    digitalWrite(relayPin, LOW); // relay ON
    digitalWrite(monitorPin, LOW); // LED on
  }
  if (currentMillis - previousMillis >= (interval_1 + interval_2))
  {
    digitalWrite(relayPin, HIGH); // relay OFF
    digitalWrite(monitorPin, HIGH); // LED off
    previousMillis = currentMillis; // reset
  }

PWM code:
int PWMControl= 6;
int PWM_Input = A0;

int PWM_Value = 0 ;

void setup() {
  pinMode(PWMControl, OUTPUT);
  pinMode(PWM_Input, INPUT);
}

void loop()
{
  PWM_Value = analogRead(PWM_Input);
  PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
  analogWrite(PWMControl, PWM_Value);
}

Thanks for the hand with editing the code

I don't really understand, what your problem is. have you tried to just pu the analogwrite into the timer code?

chris1 - I did and it did not work; just replacing digitalWrite with analogWrite doesn't do the trick: the fan runs continually whereas the LED follows the timing

Then please provide your combined code and describe how it does not work. What are you expecting to see? And what do you actually see?

@chrisl, I described that in my post just preceding yours

Then show us your combined code, since that is the problematic code

If I understand correctly, this is what you want to do:

Fan + led off for 15s
Fan on (speed determined by A0) + led on for 15s
Repeat

clearly defining your goal in english can help with coding, so I hope I guessed right.
here's my suggestion for your code
 const byte controlPin = 6; // MOSFET on pin 6
 const byte monitorPin = 13; // builtin LED output
 const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
 unsigned long currentMillis, previousMillis = 0;
 int PWM_Input = A0;
 int PWM_Value = 0 ;

 // setting pin direction and default state
 void setup() {
   pinMode(controlPin, OUTPUT);
   digitalWrite(controlPin, HIGH); // MOSFET OFF
   pinMode(monitorPin, OUTPUT);
   digitalWrite(monitorPin, LOW); // LED off
 }

 // run fan for a while, then stop fan for a while
 void loop() {

   currentMillis = millis();

   //fan on, led on, both signals active low
   if (currentMillis - previousMillis >= interval_1){
       PWM_Value = analogRead(PWM_Input);
       PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
       analogWrite(PWMControl, PWM_Value);
       digitalWrite(monitorPin, LOW);
   }

   //fan off, led off, reset timing
   if (currentMillis - previousMillis >= (interval_1 + interval_2)){
      digitalWrite(controlPin, HIGH); // MOSFET OFF
      digitalWrite(monitorPin, HIGH); // LED off
      previousMillis = currentMillis; // reset
   }
 }

There are still issues I can with this code:

You did not tell us what type of MOSFET you are using, so I can't tell if it is actually active low
I believe that the LED on most arduino boards (pin 13) is active high, so that's probably wrong
Don't forget comments. I find comments more useful for a block of code than for a single line, but you can do both if you want ;)
I find your code convoluted regarding millis logic, for me it would be more logical to have something along the lines of:
 current = millis()-previous
 if current < interval1
    fan off
 elseif current < inteval1+interval2
    fan on
 else
    previous = millis()

It would be more readable for a human, the result on the arduino would be similar.

you've got it right; I use a BUZ11 N-channel MOSFET to control the fan.   The code as it is now, works fine: the LED is on only when the fan is on.   I tried replacing the digital Write with the analogWrite as suggested but it didn't work so that's why I posted the code here.   It's obvious I'm not an experienced programmer...

@kwhunter have you tried to use the Serial monitor to make sure your initial program does what you think it does? It's extremely useful to debug arduino code. A few thing to monitor: does the fan turn on/off when you think your code turns it on/off. You also should monitor the PWM_Value before and after map, to make sure you are feeding analogWrite with the proper parameter. These would be the first things I look at.

No I did not, application not critical; for the record, I use the fan to move around the air in the Humidor for the temperature and humidity to even out.   Current setting is 1 minute ON and 15 minutes off.

Thinking back at my note#4, the resulting program would actually be different, since while the fan is on, it would immediately react to a change on A0, which is arguably better. your initial program with the on-off structure would have been easily implemented with delay() - also if you plan to run this program for a very long time, you will have an unexpected behavior when millis() overflows.

I made some edits to your program since the fan was ON all the time and when timer 2 kicked in it changed speed since A0 controlled it; now it works as it should, thanks.   Aren't the millis() reset each cycle? if not what can I do to prevent the overflow?

no, millis() returns the number of milliseconds since you powered-up the board, it keeps counting until it reaches its max value, then goes back to zero (after ~50 days according to arduino documentation: https://www.arduino.cc/reference/en/language/functions/time/millis/). you can guard against it with an if statement, or some clever math, there are examples you can easily find, this is NOT an unusual thing. also, if that's been helpful to you, consider up-voting and select the answer. If you think I should change something specific in the code I gave in my answer, I can do that too.

sorry MAB, I cannot vote since I do not have enough privileges.   The code is Ok, I didn't know you can turn on an output with an analogWrite and turn it off with a digitalWrite... Someone wrote another code for me, but it is a more advanced use of commands and therefore not as easy to add the PWM function, in my opinion.   I will google for the millis overflow; if I cannot handle, I will just turn the board off every week...

functionally, digitalWrite(LOW) is equivalent to analogWrite(0), digitalWrite(HIGH) is equivalent to analogWrite(255) if the pin is PWM capable. I can only encourage you to use https://www.arduino.cc/reference/en/ more, it has a lot of useful information.

Don't think of what you have as a "timer".  That's not what it really is.  What you have is a loop function that repeats itself thousands of times per second and an if statement that asks "is it time to do this yet".  So if you want to use analogWrite instead of digitalWrite when it is time to do that thing then use analogWrite instead.  It doesn't change your timing setup one bit.  Just replace the digitalWrite calls with analogWrite calls.  If you want to read your pot at the same time then put that in there as well.  Basically everything inside the block of code controlled by that if statement is going to happen every time that interval passes no matter what it is that you put there.  If you want something to print every interval then you could put a print statement in there.  If you want it to call some custom function every interval then call that function in there.  There's nothing special about that way of timing that only works with digitalWrite.


text:
XBee using Serial rather than SoftwareSerial--how to fix
So I have a couple of XBee S2Cs, and I have configured them properly--they can in fact communicate with each other. I am using them with Arduino Unos and this shield: https://store.arduino.cc/usa/shield-xbee-without-rf. I am attempting to interface with the XBees with SoftwareSerial, but for whatever reason, they are instead using just regular Serial. Anything I put on the SoftwareSerial appears to be ignored entirely, while anything I put on Serial appears in my serial monitor and also is transmitted to the other XBee. I have this code for transmitting:
#include <SoftwareSerial.h>
SoftwareSerial xbee (2, 3);
void setup() {
    Serial.begin(9600);
    xbee.begin(9600);
}

void loop() {
    xbee.println("hello");
    Serial.println("world");
    delay(5000);
}

And this code for receiving:
#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3);

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

void loop() {
    if (xbee.available() > 0) {
        Serial.println("xbee: " + xbee.readString());
    }
    else {
        Serial.println("no xbee data");
    }

    if (Serial.available() > 0) {
        Serial.println("serial: " + Serial.readString());
    }
    else {
        Serial.println("no serial data");
    }
    delay(5000);
}

Every 5 seconds, I get this output through the serial monitor on the transmitting side:
world

and this on the receiving side:
no xbee data
serial: world

I also get the string world when I connect a third XBee to my XCTU console.
So I have a couple of questions:
First off--how is this happening? I'm no Arduino expert, but as far as I can tell from what I've read, if the XBee is capturing my serial output, then I shouldn't also be able to see it in the serial monitor.
Second off--how can I get the SoftwareSerial to work? I could theoretically just use Serial forever, but that would make debugging way more trouble, and would probably create a code-maintenance headache later. If I had to guess, I might need to use different pins for my shield, but I have no idea how to find out what pins are the right ones to use.
Update: Based on what I've seen and read, it looks like the particular combination of the Uno with this shield leaves me with no options but to use the hardware serial. A different shield or Arduino board would grant me options to separate my serial output from my xbee output, but that does not appear to be an option here.

If that shield has the xbee wired to the hardware serial pins (0 and 1) then no amount of creating software serial instances is going to rewire it.  There isn't much information on that shield in the link, is there a way to change what pins it is using?

That could be the case. I have no idea how I would change that--I haven't found much info on the shield either, and I'm not enough of an electrical guy to delve into it without.

The big lesson may be, "Always check for documentation BEFORE plunking down your money."   No matter how cool some device might seem, if it doesn't come with some sort of instructions then it is pretty much useless.

What position are the jumpers in?  Read this: https://www.arduino.cc/en/Main/ArduinoXbeeShield

To debug the sketch with SoftwareSerial, remove the jumpers from JP2 and JP3 and wire (with jumper wires) the middle pin of JP2 and JP3 to SoftwareSerial pins of your choice.
Middle pin of JP2 is TX of the Xbee so wire it to RX of SoftwareSerial. Middle pin of JP3 is RX of XBee.
On that particular board, JP2 is the jumper closer to the middle of the board, while JP3 is closer to the edge.
shield's schematics

You will need an xbee breakout board Xbee breakout board or this one from Sparkfun to do that...
Make sure you check if the board comes with headers as they are not always included. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the 2mm headers required for xbee and regular 0.1" headers required for connection to a breadboard or jumper wires etc.
Actually, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, but it is not connected to pins 0 and 1.
The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.
So on Leonardo, you can do Serial.println("Debug msgs"); and Serial1.println("xbee messages"); (note the digit 1 in Serial1). Of course other platforms such as Mega also can be used in the same way.
I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.
FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.
As soon as i moved to leonardo, it worked like a charm.


text:
Calculate statistic in EEPROM
I've search on how to do statistic calculation in EEPROM, but non related.
The data that I stored in EEPROM is body temperature.
Currently I stored the data using float.
Below is my code for data store in eeprom.
I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.
Does anyone have an idea on how can we do calculation using data from EEPROM?
#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.
Thanks.

Doing that calculation from EEPROM is exactly the same as doing it from any other source.  You have a count so you know where the EEPROM data ends.  You know where the EEPROM data starts.  You know how to read a number out of EEPROM.  What is stopping you from creating a for loop to read the i'th address from EEPROM and add all those numbers together just like you would for an array?
for (int i = EEPROM_START; i < EEPROM_END; i++){
   sum = sum + EEPROM.read(i);
}
average = sum / count;

where EEPROM_START and EEPROM_END are supplied by you by knowing what address you started and ended writing at.

There are quite a few issues with your program. Averaging is just one of
them.
You wrote:

Currently I stored the data using float.

No, you didn't. You stored 8-bit unsigned integers (aka uint8_t).
int contCount = EEPROM.get(5, count) / 10;

Assuming you are using an 8-bit Arduino, this is reading the EEPROM
cells at addresses 5 and 6, combining these two readings into a single
signed 16-bit number, and storing it in count. Given that these EEPROM
cells are also used to store temperature readings, this operation makes
no sense at all. BTW, the line above also stores a copy of the newly
updated count into a fresh local variable that gets immediately
discarded. This also makes no sense.
Later you wrote:
for (int i = 0 ; i < EEPROM.length() ; i++) {
  if(EEPROM.read(i) != 0)  //skip already "empty" addresses
  {
    EEPROM.write(i, 0);    //write 0 to address i
  }
}

There is an EEPROM.update() method meant to do this in a simpler way:
for (int i = 0 ; i < EEPROM.length() ; i++) {
  EEPROM.update(i, 0);  //write 0 to address i unless it is already 0
}

Later:
for (j = 0; j < READSAMPLES; j++)
{
  sample[j] = analogRead(LM35);        //read sensor value
  delay(50);
}

There is no point in storing all the readings in RAM just to compute the
average. You can get rid of the sample array and instead:
float average = 0;
for (int j = 0; j < READSAMPLES; j++)
{
  average += analogRead(LM35);  //read sensor value
  delay(50);
}
average /= READSAMPLES;

Later:
float cel = ( mv / 10 );
EEPROM.write(address, cel);
[...]
address++;

This is probably your biggest issue. You may believe you are storing
floats, yet EEPROM.write() can only write bytes. Thus the value
cel, which is a voltage in centivolts, is implicitly casted to a
uint8_t. This means it is rounded down to the nearest integer below
it, then wrapped modulo 256. This is quite likely not what you want.
If you really want to store floats, you should replace the last two
lines of code above by
EEPROM.put(address, cel);
address += sizeof cel;

but then beware that when reading the EEPROM you should also increment
the address in steps of sizeof(float).


text:
Serial communication between PC and Arduino using C
I'm trying to send some data to my arduino mega 2560 using serial communication.
I'm using the exemple that I found here without success.
Every site I read say that I can send data to the arduino board like writing to any file on ubuntu.
But I alway get Segmentation fault
Here is my code
#include <stdio.h>
#include <string.h>

char arduinoPort[] = "/dev/ttyACM0";

int main() {

  char buffer[] = {'1'};

  FILE *usb_port;

  usb_port = fopen(arduinoPort, "rwb");

  fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

  fclose(usb_port);

  return 0;
}

why are you not using the arduino IDE?

@jsotola, because they write for PC

Your program works flawlessly on my Ubuntu 18.04. I would guess that you
have a problem with your setup (flaky USB port, permission problems...)
rather than the program itself. Still, I would recommend you add some
error checking: right after the fopen() call,
if (!usb_port) {
    perror(arduinoPort);
    return 1;
}

I would expect you see something like
/dev/ttyACM0: No such file or directory

or
/dev/ttyACM0: Permission denied

that could help you pin down the real problem.

Thank you so much. It wasn't working because i opened the serial monitor and because the message i could see it. When serial monitor is opened the serial is busy.


text:
If I try to pause my loop function my output screen starts printing trash
I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.
void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}

I don't see the number 50 anywhere in your code. What happens if you don't try to pause it? Is the output OK then?

ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.
Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.
The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.
I would suggest adding a delay() or yield() to your while block will fix the problem.

There is nothing immediately obviously wrong with your program, but what happens if you do it a bit more "normally"?
By normally, just do nothing after the 10th (or 50th) time through, instead of the infinite loop you are currently executing.
int cntr = 0;
float initial=0,inside=0,outside=0,sum=0,x;

void loop()
{
  if (cntr < 10 /* or 50 */) {
    cntr++;
    x=sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) {
      Serial.print(" TIMEOUT");
    }
    sum=sum+x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
}

My reason for suggesting this is that when I tried an ESP board, there was an enourmous amount of bloatware included in the generated code. There may well be other stuff that needs to happen in the background between calls to the loop method. But you are preventing that from happening with your infinite loop.
However, clearly something is happening in the background because your infinite loop is somehow generating, as you put it,  "garbage".
You did not publish the  details of sensor library or its methods. Could there be any side affects there? What pins does the sensor connect to?


text:
Can the Arduino (Nano) bootloader be updated via itself and the Arduino IDE or is an ISP required?
I ran into the following error with a recent Arduino IDE version (1.8.9) when trying to upload to an "Arduino Nano" clone (ATmega328P):
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x18
...
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x18
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The problem could be resolved by choosing "ATmega328P (Old Bootloader)" as Processor in the Tool menu - as now suggested to me and solved in Arduino Nano uploading gives error: avrdude: stk500_recv(): programmer is not responding.
The change was made in August 2018 with the release of Arduino IDE 1.8.6: https://github.com/arduino/Arduino/releases/tag/1.8.6
Details about the different bootloaders are described in
Arduino Nano ATmega328P bootloader difference.
It seems the fuses have to be changed in order to make full use of the newer, smaller bootloader, so an ISP will have to be used anyway.
But is the bootloader able to update itself (via Tools > Burn bootloader) or is there an intermediate "bootloader update sketch" available?

On ATmega328p and similar ATmega MCUs with bootloader support, the application is not allowed to write to flash. Only code running in bootloader area of the flash memory is allowed to write to flash. Bootloader area is at the end of the flash and the beginning is set with the BOOTSZ fuses.
The write to flash page is done in two steps. First step is deleting the contents of the flash page, second step is write the new data to the flash page. In bootloader area* it is allowed to first prepare the data to temporary buffer page, then delete the flash and write the data in one step. So in theory the bootloader could overwrite itself with a function running in the last flash page. But I don't know about bootloader which would do it.
To write a bootloader an ISP programmer is necessary. Or other Arduino with the "Arduino as ISP" sketch.
*note: the read-while-write area at the end of flash has the size of the largest bootloader area possible and is not determined by BOOTSZ.

I think you CAN write to the bootloader from a Sketch if you can make sure the writing method is within the No-Read-While-Write section of the application flash. This is much easier when not using the Arduino IDE. (Also this is not possible if the bootloader occupies the entire NRWW section, which is not the case for OptiBoot used by Arduino.)

@Kwasmich, the boundary for SPM execution is BOOTSZ fuse


text:
My HC-05 Bluetooth Module is not working
I have been trying to use the HC-05 Module with my Arduino Uno to control a LED, which can be turned on and off by my phone. Everything is fine when i input the values from the serial monitor. The problem only occurs when I use my phone. I am using a bluetooth terminal for HC-05 and it shows it connected. The bluetooth module is conected as its blinking slows down when I use the app.
Here's the code:
#define ledPin 8
int state = 0;

void setup() {
 pinMode(ledPin, OUTPUT);
 digitalWrite(ledPin, LOW);
 Serial.begin(38400); /
}

void loop() {
 if(Serial.available() > 0){ // Checks whether data is comming from the serial port
 state = Serial.read();
 }
 if (state == '0') {
 digitalWrite(ledPin, LOW);
 Serial.println("LED: OFF");
 state = 0;
 }
 else if (state == '1') {
 digitalWrite(ledPin, HIGH);
 Serial.println("LED: ON");;
 state = 0;
 }
}

Here's the serial monitor output;

Appreciate the Help!

Can u plz say what is the name of the app u are using to control hc-05 Bluetooth module to turn on and off

What phone are you using? HC-05 is basic Bluetooth. Not BLE. If you're using iOS it will not work.

Few Points that you might want to Look into.

Where exactly are you connecting Bluetooth Module with Uno. Make sure you are connecting it with Rx and Tx Pin Only.
First make Simple Program to send some data on Serial Say "Hello World" at every 1second and make sure your Bluetooth is connected to Hardware Serial Pins only. If you receive data on phone then you are good to receive as well If not then Try below points.
Make sure your HC-05 Baudrate is correct. If you are not sure then try some others as well like 9600, 115200 etc.
Make sure Rx and Tx pins are connect with correct pins of HC-05. If you know your Baudrate then try swapping Rx Tx and it should response to you.

When switching from serial monitor to phone, did you change how the Arduino board was powered? If you power Arduino board via VIN port, then voltage across VIN and GND needs to be STRICTLY between 7 to 12 volts, otherwise the Arduino board is unstable (even if the board is on).
More tips and supporting information can be found on Step 3 of:
https://www.instructables.com/How-to-Connect-HC-05-to-Windows-1011-Mac-Apple-Com/


text:
measure +3V and -3V through resistor divider and switch on/off by digital pins
I've seen that resistor dividers can be used to read negative voltages, but I'ld like if there is a way to accomplish this with less components and having a way to turn this off.
I was thinking if there would be an extreme option of changing from pinMode INPUT to INPUT_PULLUP or INPUT_PULLDOWN to power the circuit and use the 20k pullups to make part of the divider, together with another resistances on the input. Alternatively, switching from INPUT to OUTPUT would be fine.
What I want to measure is an external +3V/GND/-3V power supply (battery pack) that shares the GND with the arduino SAMD21 (3.3V), measuring both +3V and -3V, and avoiding drain when not measuring (hence the pin mode changes)
Currently I'm using this schema to measure the voltage of +5V supply battery (connected through VIN, thus using the internal regulator), by dividing with 2 1Mohm resistances, ground to digital pin and measurement by internal adc. I don't need so much precision, so this is enough here. So I'm looking for the same or better alternatives, but for the -3V I don't know how to properly calculate the 3 resistor divider.

When measuring a voltage that is higher than the maximum rating, the voltage of interest is tied to ground with a voltage divider. When measuring a negative voltage, you instead have to tie the voltage of interest to the positive supply voltage (study the answers to this question).
In theory you can use the internal pullup to spare one resistor, but I would consider this a bad practice and recommend using an external pullup for the following reasons:

a uC's internal pullups/-downs are not accurate and sometimes not specified
especially when measuring negative voltage, chances are that harmful voltage is applied to the adc (consider the default state of a gpio)
a pullup/-down is an uncritical component concerning its value and precision. Therefore they are very cheap

Two 1M resistors for a voltage divider is high. You could add a capacitor (1nF or 10nF) to GND and the analog input.
Could you try to find what the leakage current or the self-discharge current of the battery itself is? Then take a percentage of that, for example 20%, then calculate what resistor value the voltage divider should be.
It does not have to be 20%, it can be any current that you are willing to give up to be able to measure the voltage.
For example, when the battery has a self-discharge current of 10µA, then 20% is 2µA, which is two resistors of 825kΩ. That happens to be close to the 1M resistors that you already use.

Yes, 1M resistor were high, but I tried with 10k ones and behaviour was bad. Later, I deduced that the reason was that I was switching the digital pin (low) from output to input to avoid consumption, and when left floating, the analog pin was receiving 5V (for a 3.3V MCU...). Probably it works with 1M due to very low current, but I've also to change that.

@avelo there will be no relevant consumption. Why do you switch "to input"? When using the adc the corresponding gpio is an input allready. The adc only sinks a very small current to charge its sample-and-hold circuitry (small capacity).

@SimSon i was using an analog (A1) pin in the middle of the divider, and a digital one (6) at the end to connect to ground digitalWrite(6,LOW); pinMode(6,OUTPUT); when measuring (disconnecting by changing it to INPUT). Just as a way to save the 5/20k power waste. With 2*1Mohm the consumption drop to irrelevant as you said, so no reason to use the digital pin for that (and I'll have the +5V problem if let it floating), I agree!


text:
Logging data to SD card from software serial
I have an Arduino Uno and an Adafruit data logging shield and I have connected a digital pressure sensor that uses serial communication. The sensor requires a character to start transmitting data. I have managed to read the data using this code:
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

int depth;

void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");

}

void loop()
{

 if (mySerial.available()) {

   depth = mySerial.read();

 }

}

This returns the following:

C1000
  C1000
  C1000

where 1000 is the value.
I have written another code that logs data to the shield and tested with other sensors but I cannot log data from this sensor by modifying the above code and cannot find any relevant examples.
If I add something like this it does not return the same value.
logfile.println(depth);

Complete newbie in so any suggestions are welcome.
UPDATE

Comments are not for extended discussion; this conversation has been moved to chat.

use the C as the line start indicator. if received char is 'C' then do a file.println(); example with output to Serial
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

void setup() {
    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");
}

void loop() {
 if (mySerial.available()) {
   char c = mySerial.read();
   if (c == 'C') {
     Serial.println();
   }
   Serial.write(c);
 }
}

But this code does not do anything different than the simple code. My problem is not that I am not reading the data or that I do not see the data printed in the serial monitor. I do receive all the data. The problem comes when I try to log the data. I think the data come in so fast from the serial, but when I add delays everything is messed up.

it prints completely different then the code in Question. did you try it?

Yes I tried it. It prints the same with a gap between its measurement. Also it uses a lot more of the dynamic variable. But it prints the same with a gap between each C1000

is it not what you want? every set on a new line?

No. I want to log the data to an SD card. When I use this code to log I get one number every second. I have added a screen shot in the original post. I want to get all the 4 numbers in one second and then the new 4 numbers in the next second.

you stil have println instead or write or you look at lines recorded before the change

I have completely removed the serial.println () after the if but it does not change anything

in my Answer you have a complete sketch. run it as it is. don't change anything

I have run it as it is. The update I have added in the original post is when I run this sketch. It still prints its byte in a different line. 6171 is one reading and the code returns it in 4 seconds and its number in a different line

do you have 9600 baud set in Serial Monitor?

does the device send data at 9600 baud?

yes to both questions. When I use the sketch I posted initially (at 9600) it returns the data in one line as expected continuously. I get this problem when I add any type of delay. For example when I log every 1 s, I get the problem I mentioned.

you can't add a delay. the device doesn't stop to send data, the serial buffer overflows and some part of he data will be lost

So how can I log this data? There is no way?

you could after the delay first read the buffer clean (read SERIAL_RX_BUFFER_SIZE count of bytes), the wait for C and read until next C


text:
Two libraries collide. Ambiguous functions/variables?
I get several errors once I try to include these two libraries:

error: expected unqualified-id before '{' token
     #define DEBUG_PRINTLN(...) {}

#include <DHT.h>
#include <DGS.h>

void setup() {
}

void loop() {
}

Apparently DEBUG_PRINTLN is causing the problems, because it is defined as a private function in DGS.h and as a constant (#define) in DHT.h.
Including DGS.h before DHT.h does not throw errors. But is this a safe workaround or might I run into errors later? How can I deal with that, without modifying the libraries?
DGS.h:
/*
  DGS_25SEP17.h - Library for reading KWJ Engineering with SPEC Sensors on Digital SDK with firmware date 25SEP17.
  Created by David E. Peaslee, Mar 29, 2018.
*/

#ifndef _DGS_h
#define _DGS_h

#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#elif defined(SPARK)
//#include "application.h"
#else
#include "WProgram.h"
#endif

#include "Stream.h"

class DGS
{
  private:
    Stream *_mySerial;
    long dataArray[11]; //Multipurpose array
    //void unlock(void);
    void DEBUG_PRINTLN(long x);
    void DEBUG_PRINTLN(float x);
    void DEBUG_PRINTLN(String x);
    void DEBUG_PRINT(long x);
    void DEBUG_PRINT(float x);
    void DEBUG_PRINT(String x);

  public:
    DGS(Stream &mySerial); //Class that represents DULP with Stream as class for Serial
    DGS(Stream *mySerial); //Class that represents DULP with Stream as class for Serial

    bool DEBUG;

    int setToff(float offset);  //Sets a temperature offset
    int setBC(String BC);  //Initializes DGS with all information from barcode, only way to set Span
    String getFW(void); //Returns the Firmware Date

    int getLMP(void); //Loads LMP[3] with register values from LMP91000
    int LMP[3];  //LMP Registers, needs to be loaded with getLMP
    int setLMP(int R1, int R2, int R3); //Sets new LMP registers and reintializes LMP

    int zero(void); //Zeros to current reading, Zero only in a clean air environment
    int setXSpan(float); //ReCalibrates device, only should be used after zero, and using a calibrated gas

    int getData(char c); //Gets the data and loads into variables
    long getConc(char x = 'p');  //Reads concentration from current data array 'p' ppb or 'c' counts
    long getTemp(char t = 'C');  //Reads temperature from current data array 'C' for Celsius or 'F' for Fahrenheit
    long getRh(char r = 'r'); //Reads Rh from current data array 'r' for Rh and 'c' for counts

    void getEEPROM(void); //Loads variables into EEPROM E[5] and e[14] arrays, outputs EEPROM if DEBUG is true
    String eepromStr[5]; //Stores the character based EEPROM data
    long eepromInt[13];  //Stores the integer based EEPROM data
    float Sensitivity_Code;  //Stores the sensitivity coefficient in nA/PPM
};

#endif

DHT.h:
/* DHT library

MIT license
written by Adafruit Industries
*/
#ifndef DHT_H
#define DHT_H

#if ARDUINO >= 100
 #include "Arduino.h"
#else
 #include "WProgram.h"
#endif

// Uncomment to enable printing out nice debug messages.
//#define DHT_DEBUG

// Define where debug output will be printed.
#define DEBUG_PRINTER Serial

// Setup debug printing macros.
#ifdef DHT_DEBUG
  #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
  #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
#else
  #define DEBUG_PRINT(...) {}
  #define DEBUG_PRINTLN(...) {}
#endif

// Define types of sensors.
#define DHT11 11
#define DHT12 12
#define DHT22 22
#define DHT21 21
#define AM2301 21

class DHT {
  public:
   DHT(uint8_t pin, uint8_t type, uint8_t count=6);
   void begin(uint8_t usec=55);
   float readTemperature(bool S=false, bool force=false);
   float convertCtoF(float);
   float convertFtoC(float);
   float computeHeatIndex(bool isFahrenheit=true);
   float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true);
   float readHumidity(bool force=false);
   bool read(bool force=false);

 private:
  uint8_t data[5];
  uint8_t _pin, _type;
  #ifdef __AVR
    // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask
    // for the digital pin connected to the DHT.  Other platforms will use digitalRead.
    uint8_t _bit, _port;
  #endif
  uint32_t _lastreadtime, _maxcycles;
  bool _lastresult;
  uint8_t pullTime; // Time (in usec) to pull up data line before reading

  uint32_t expectPulse(bool level);

};

class InterruptLock {
  public:
   InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
    noInterrupts();
#endif
   }
   ~InterruptLock() {
#if !defined(ARDUINO_ARCH_NRF52)
    interrupts();
#endif
   }
};

#endif

The DEBUG_ functions in the DGS class are private and used only in DGS.cpp. They will not collide with the macros from DHT.h
If DHT.h is included before DGS.h, the preprocessor replaces the DEBUG_ function names with the content of the macros from DHT.h and the result doesn't make sense for the compiler.
You could do #undef DEBUG_PRINT and #undef DEBUG_PRINTLN after DHT.h to undefine the macros for the rest of the sketch. DHT.cpp includes DHT.h and will have the macros defined.

Thanks! I assume by 'GBS' you mean 'DGS'?


text:
Reading a simple sensor with Modbus RTU on Arduino Uno
I'm integrating a wind direction- and speed sensor with an Arduino. It communicates over RS485 Modbus RTU, which I don't have any experience with.
The documentation is very short, and it just says:
9600bps, 8 bit, stop bit: 1, check bit: no
Slave address is FFH.
Host Scan Order( slave address 0xFF)
FF 03 00 00 00 02 D1D5
Slave Response
FF 03 04 00 09 00 3A 0401
The bold parts are fixed, the last two bytes are for checksum.  So the data of the response is direction in the two first bytes (00 09), and then speed in the two after that.
So basically I gotta send that exact byte sequence to the sensor, and then decode what I get. I'm not gonna need to do anything more advanced with this, and so I'm trying to figure out what the most easy way to do this is.
There are different modes, like single, mutliple registry, discrete values, coils, I don't know which one I'm supposed to pick, would be grateful if someone could take the time to explain to me how to do it.

the 03 is Read Holding Registers

Thanks, Juraj! That helps. Do you know what the 04 is, is it some kind of address?

04 is length of data. 4 bytes

https://en.wikipedia.org/wiki/Modbus


text:
Connect Arduino and ESP8266 NodeMCU
I want to connect multiple sensors and see their measurements via ESP8266 Web Server. But, the problem is that ESP8266 has only one analog pin and I can't connect multiple sensors to it, so i need to connect it to the Arduino. How can i do that?

you could use I2C ADC module with 4 or 8 analog pins

How to connect it?

what? the I2C module? like any other I2C module. usually to D1/D2

How can I connect the sensors to ESP8266 using I2C module? I'm a beginner, I'm sorry.

https://learn.adafruit.com/adafruit-4-channel-adc-breakouts/signal-connections

Thanks. Helped a lot.


text:
Order of Evaluation for #define Macros
EDIT: I think this fits better in the C++ Stack Overflow, so I'm going to re-post this there.
I am working on a menu system with #define macros (inspired by the Marlin firmware on my 3D printer) I am attempting to generalize each menu item with the macro #define MENU_ITEM_EDIT(). The full code is really long, so I am leaving out chunks of code of compactness. However, you can find the full code here: https://pastebin.com/h24itG9y
void draw_row(int row, char* value) { /* Stuff here*/ } // Draws row
char* uiToStr(int x) { /* Stuff here*/ } // Converts unsigned int to a string

#define disp_array(display, value)  display[value]
#define disp_func(display, value)   display(value)
#define disp_char(display, value)   display

#define MENU_ITEM_EDIT(min, max, rate, display, displayType, width, label, value) \
    // A bunch of stuff
    draw_row(rowNum, disp_ ## displayType(display, value)); \
    // More stuff

Using the code macro would look like:
// Values
const char item1[] = "Item 1", item2[] = "Item 2", item3[] = "Item 3";
const char* const itemList[] = {item1, item2, item3};
int currentItem = 0;
uint8_t item1Val = 10;

void menu1()
{
   START_MENU();
       MENU_ITEM_EDIT(0, 3, 1, itemList, array, 6, "Item:", currentItem);
       MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 1 Value:", item1Val);
   END_MENU();
}

Which displays as:
Item:     Item 1
Item 1 Value: 10

For convenience in the declarations of my menus, I am trying to use common menu types, such as an uint8_t that ranges from 0 to 255. Then, in the menu, I would use __u255_t instead of the first 6 arguments.
#define __u255_t 0, 255, 1, uiToStr, func, 3

void menu2()
{
    int item2Val = 10;

    START_MENU();
        MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
    END_MENU();
}

Previously, I had it set up such that every time I wanted a different type of menu, even if I would only use it once, I had to define a type for it and how it should evaluate in the macro. This way, I can use 1 argument instead of 6 for commonly recurring types in rows. However, I still want the ability to use the 6 argument option when I have a row that has a unique set of arguments, such as a different range or list of display strings.
However, in this example, the program won't compile because it places __u255_t into min in the MENU_ITEM_EDIT() macro, rather than expanding __u255_t into its 6 values and placing them into the first 6 arguments of MENU_ITEM_EDIT(). The macro evaluates as:
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT( (0, 255, 1, uiToStr, func, 3), "Item 2 Value", item2val, , , , , );

Note: I put an extra set of parentheses to make it more clear to understand.
But I want:
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 2 Value", item2Val);

I thought about using a struct, however I'm not sure that I can because depending on the row, the value string in draw_row() could be a function or an array. Does anyone have any advice on how to solve this problem?
Also, please let me know if I need to add any more code to make my problem more clear.

I agree - this is a language question, not an Arduino one - but the short answer is that macros are not part of the language (C or C++); they are a preprocessor feature (standard on C and C++ compilers, to be sure) that is evaluated at compile time, so they must be completely evaluable at that time. Therefore, being evaluated before the compiler ever sees your code, they also don't have the overloading capability, including variable-length parameter lists, that C++ provides.

including variable-length parameter lists -- actually they do: __VA_ARGS__ and #define foo(...)

C/C++ precompiler macros are a hot mess. (Especially macros that take parameters, like the ones you're using.) They're not type-safe, and they get resolved at compile-time in ways that are quite confusing. There are other ways of solving this sort of problem

You need to turn your macro itself into a macro. Sounds odd, I know.  But take the following example:
#define foo bar, baz
#define foobar(X, Y, Z) something(X, Y, Z);
#define boofar(...) foobar(__VA_ARGS__)

boofar(foo, 4)

boofar is a macro that takes a variable argument list.  That expands out into a call for your actual macro call, expanding foo in the process.  Then your actual macro gets expanded out with the real arguments already in here. The point here is that foo is expanded before being passed to the macro that needs the multiple arguments that are inside foo.
So the expansion chain is actually:
boofar(foo, 4) ->
foobar(bar, baz, 4) ->
something(bar, baz, 4);

Running it through cpp and you get:
# 1 "t.c"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "t.c"

something(bar, baz, 4);

Gak. Props for explaining how to make it work, but gak just the same.

Yeah, it is confusing, but your explanation makes sense. Thanks!


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