message:
The current direction for digital output pins

I am new to Arduino. The digital pins can be configured as output (https://www.arduino.cc/en/Tutorial/DigitalPins) for triggering some sensors. I am now setting a digital (output pin), say no. 7,which is connected to the `in1` pin of a SRD relay (https://blog.siliconstraits.vn/relay-what-is-it-and-how-to-use-it/):
[![enter image description here][1]][1]

I am not very clear about the direction of current flowing in the wire connecting the arduino digital pin to `in1`. To my understanding, when `digitalWrite(pin, HIGH)`, no current flow into the arduino pin, the relay is not triggered, while `digitalWrite(pin, LOW)`, the current flow into the arduino, and the relay is triggered. Please correct me if I am wrong. Thanks.

  [1]: https://i.stack.imgur.com/MnK3v.png

body: When you set a pin to HIGH then that pin will provide 5V.  When you set a pin to LOW then that pin will be set to 0 volts.  Which direction the current flows depends on what is at the other end of the wire.  Current always flows from higher voltage to lower voltage.  If you set a pin to HIGH and the thing it is connected to is at ground then current will flow out of the pin towards ground.  If you set a pin to HIGH but the thing it is connected to is already at 5V then no current flows.  If you set a pin to LOW and the thing it is connected to has some positive voltage then current will flow to the pin.  If you set the pin to HIGH (5V) but the thing it is connected to has more voltage than that (say 10V) then current will flow towards the lower voltage and into the pin, probably damaging the Arduino in the process.


sender: user

message:
Is this the right way to blink a character on LCD?

The code is this:

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

    LiquidCrystal_I2C lcd(0x27, 16, 2);

    unsigned long blinkTime = 0;
    int ValueA = 22;
    String placeHolder = "  ";

    void setup() {
      lcd.begin();
    }

    void loop() {
      lcd.setCursor(7, 0);
      if (millis() - blinkTime > 2000) {
        lcd.print(ValueA);
        blinkTime = millis();
      }
      if (millis() - blinkTime > 1000) {
        lcd.print(placeHolder);
      }
    }

The I2C LCD library have a `lcd.blink()` function but it seems that only blinks a "cursor".

The problem with above code is the `placeHolder`, what if `ValueA` gets bigger than 2 digits?

Is there a better way to blink a value on LCD?

sender: assistant

body:
To blink a number (alternate between the number and empty space(s)), you could try the `BlinkLCD` class in this sketch. It only works with numbers from 0 to 4294967295 or text (`char` array, 16 characters max). It does not work with floating point numbers.

    // 4540 bytes.
    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>

    LiquidCrystal_I2C lcd(0x27, 16, 2);

    class BlinkLCD{

      private:

        byte m_blinkState, m_startPosition, m_dataLength;
        unsigned long m_dataToBlink, m_previousMillis, m_blinkRate;
        char m_text[16 + 1];

      public:

        BlinkLCD(): m_blinkState(0), m_startPosition(0), m_dataLength(0),
                    m_dataToBlink(0), m_previousMillis(0), m_blinkRate(500),
                    m_text(){}

        void Update(){

          unsigned long m_currentMillis = millis();

          if(m_currentMillis - m_previousMillis >= m_blinkRate){

            byte m_row = 0;
            m_blinkState = !m_blinkState;
            m_previousMillis = m_currentMillis;

            if(m_startPosition > 15){
              m_startPosition -= 16;
              m_row = 1;
            }

            lcd.setCursor(m_startPosition, m_row);

            if(m_blinkState){
              if((unsigned)strlen(m_text) > 0){
                lcd.print(m_text);
              }
              else{
                lcd.print(m_dataToBlink);
              }
            }
            else{
              for(byte i = 0; i < m_dataLength; i++){
                lcd.print(" ");
              }
            }
          }
        }

        void SetBlinkRate(unsigned long blinkRate){
          m_blinkRate = blinkRate;
        }

        void SetNumber(unsigned long dataToBlink){
          m_dataToBlink = dataToBlink;
        }

        void SetLength(byte dataLength){
          m_dataLength = dataLength;
        }

        // LCD top row, columns 0 - 15
        // LCD Bottom row, 16 - 31
        void SetStartPosition(byte startPosition){
          m_startPosition = startPosition;
        }

        void SetText(char text[]){
          strcpy(m_text, text);
        }

    };

    BlinkLCD TopRowLCD;
    BlinkLCD BottomRowLCD;
    BlinkLCD BottomRowLCDtext;

    void setup(){
      lcd.init();
      lcd.backlight();
      lcd.clear();
      lcd.print("Temperature 35 C");
      lcd.setCursor(0, 1);
      lcd.print("Num = 4294967295");
    }

    void loop(){

      // Simulate sensor data.
      static byte counter = 35;
      static unsigned long previousMillis = 0;
      unsigned long currentMillis = millis();

      // Update the temperature reading every 2 seconds.
      if(currentMillis - previousMillis >= 2000){
        previousMillis = currentMillis;
        counter++;
        if(counter > 45){counter = 35;}
        lcd.setCursor(12, 0);
        lcd.print(counter);
      }

      // Blink the temperature reading if it's over 40 C.
      if(counter > 40){
        TopRowLCD.SetNumber(counter);
        TopRowLCD.SetStartPosition(12);
        TopRowLCD.SetLength(2);
        TopRowLCD.SetBlinkRate(250);
        TopRowLCD.Update();
      }

      // Blink a number on the second row of the LCD
      // with a default blink rate of 500ms ON, 500ms OFF.
      BottomRowLCD.SetNumber(4294967295);
      BottomRowLCD.SetStartPosition(22);
      BottomRowLCD.SetLength(10);
      BottomRowLCD.Update();

      // Blink some text with at the default blink rate.
      BottomRowLCDtext.SetText("Num");
      BottomRowLCDtext.SetStartPosition(16);
      BottomRowLCDtext.SetLength(3);
      BottomRowLCDtext.Update();

    }


message:
What is the default setting for a digital output pin

With `digitalWrite(pin_number,value)`, we can set an output pin as `HIGH` or `LOW`. But if only coding `pinMode (pin_number, OUTPUT)`, what is the default state for the pin `pin_number`, `LOW` or `HIGH`? It is noted that: `Pins configured as OUTPUT with pinMode() are said to be in a low-impedance state`. Does that mean the pin will be in the state `LOW`?

body:
On the AVR-based Arduinos at least, pins start in the `INPUT`, i.e. high
impedance state. If you then `pinMode(pin, OUTPUT);`, the pin turns to
`OUTPUT` `LOW`. Note, however, that if you first set the pin to
`INPUT_PULLUP`, and **then** to `OUTPUT`, the pin ends up in the
`OPUTPUT` `HIGH` state.

Sometimes you want to control the state the pin will have right when
it's turned to `OUTPUT`. You may for example simulate an open collector
output by switching between `INPUT` (or `INPUT_PULLUP`) and `OUTPUT`
`LOW`, while avoiding the `OUTPUT` `HIGH` state. In this case, a safe
idiom is to set the output level _before_ switching the pin to `OUTPUT`,
e.g.

```c++
// Set pin to OUTPUT LOW without going throught the OUTPUT HIGH state.
digitalWrite(pin, LOW); // do this first
pinMode(pin, OUTPUT);
```

A side effect of performing a `digitalWrite()` on a pin that is not set
to `OUTPUT` is that the pin gets switched to either `INPUT` (if writing
`LOW`) or `INPUT_PULLUP` (if writing `HIGH`). This is an idiosyncrasy of
the AVR IO ports you should probably not rely on if you want your code
to be readable or portable.

Reference: [the source code of `pinMode()`][pinMode] in the Arduino
core, and the datasheet of the relevant MCU. See for example the section
[Ports as General Digital I/O][datasheet] in the ATmega328P’s datasheet.

[pinMode]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/wiring_digital.c#L29
[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf#G3.1185755


body:
I've had a similar issue with an ATTINY85 powered DIGISPARK board.

I was getting a glitch when setting a pin to `OUTPUT` and the driving it `HIGH` immediately. Looked something like this:

`CH1:`

`pinMode(ch1, OUTPUT);          // it is at this line that ch1 becomes LOW`

`digitalWrite(ch1, LOW);        // technically redundant since ch1 pin already driven LOW`

`CH2:`

`pinMode(ch2, OUTPUT);          // at this point ch2 goes LOW`

`digitalWrite(ch2, HIGH);       // and only goes HIGH once this instruction executes`

[![Glitch on CH2 when setting PIN to OUTPUT and then turning it HIGH][1]][1]

  [1]: https://i.stack.imgur.com/N6MY8.png

The solution that mitigated the above glitch in my case (ATTiny85 / Digispark Board) was, as Edgar Bonet pointed out above, going through the INPUT_PULLUP phase:

`pinMode(ch2, INPUT_PULLUP);`

`pinMode(ch2, OUTPUT);`

`digitalWrite(ch2, HIGH);`


message:
Control relay with both Arduino and DAQ at the same time

I want to control a relay with both Arduino and DAQ. Arduino is used as an embedded  device for the control, while the DAQ is hooked up with a computer and performs the control with a user interface. Here is below a schematic of the circuit wiring for the control:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/gULcG.png

The two signal pins of the relay are connected with the digital pins of Arduino and DAQ. For some reasons, when Arduino comes into play, the control via DAQ cannot be achieved. If only Arduino or DAQ is connected to the relay, there is no problems with the control.

My plan here is, mstly, to let Arduino to instruct some tasks. In some special cases, I want to have the control with DAQ. Anyone can debug my circuit above? Thanks!

body:
I guess, that you drive the digital pin of the Arduino directly with `digitalWrite()` for HIGH and LOW and that the DAQ does the same (I didn't researched this).

In that case your circuit is dangerous for the devices. As long, as they both output the same, everything is ok. But take the case, that the Arduino is driving it's pin HIGH, while the DAQ driving it LOW. That would be a short through the pin driving circuit's of both devices and most likely the flowing current will exceed the maximum current rating of the pin. This can fry the involved pins hardware or even the complete devices. You get some kind of race condition here: The device, that can handle drain/source more current will be the winner.

In general you have to implement rules, how the devices should work together. Do you need the actions from the DAQ to be executed no matter what the Arduino does? Or should the Arduino be the master here? Or something inbetween? It is not clear, what do you need here.

I will give you 2 suggestions about possible ways:

1. You could control the relay only with the Arduino. The DAQ can be connected to a digital input of the Arduino (so that it can sense the DAQ's output state) and in the Arduino code you can implement all the logic you need to drive the relay to your liking.

2. You could define an idle state of your relay input and set it with a pullup or pulldown resistor. It will ensure, that the relay input is at the defined idle state, as long as no device is driving the line to the opposite state. For this you need the devices outputs to be high impedance (on the Arduino this means the pin is configured as input; for the DAQ you need to know yourself or research it).

    Let's say the idle state would be HIGH. We would connect the relay pin with 5V through a high resistor (this is the pullup resistor) (maybe 10k, the value is not critical). Both devices can be connected directly. If one device needs to change the state to LOW, it can drive it's output pin actively low, forcing the relay pin to also go to LOW. If it doesn't need the state to be LOW anymore, it should put it's pin into high impedance mode. The pullup resistor will pull the state to HIGH again. You can also add relatively low resistors between the devices to protect against damages from accidentally driving active HIGH while the other is LOW (These can be calculated from the maximum current rating for the pins; 20mA for the Arduino). This kind of logic is often called open drain logic.

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/W1Qzo.png)

<!-- End schematic -->

If the DAQ cannot put it's pins to high impedance, you can setup that circuit yourself with a single MOSFET:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/b9uLs.png)

<!-- End schematic -->

If you use this circuit on both devices, you don't need the small resistors anymore.

---

The second possibility already implements a specific logic. You need to decide if this logic is good for you. You can invert it's logic (idle state LOW). Personally I would go with the first option, because it is easier and more flexible.


message:
DigiSpark AT Tiny85 compile problem?

Friend asked me to find problem with compilation for his DigiSpark AT Tiny85 board.
We are trying to compile sketch from here:
https://forum.arduino.cc/index.php?topic=314773.0

But with no luck - there is something mixed in headers or configuration and I do not know what exactly.

This ISR does not compile:

**ISR(TIMER1_OVF_vect)** {       //timer1 overflow

First there were some errors like TCCR1 = 0; not defined in this sketch, then after playing with #define __ AVR_ATtiny85__, #undef _AVR_IOXXX_H_ and replacing avr/io.h with iotn85.h errors like multiple definition of __vector_x(?) came. Commenting out this line:

*//attachInterrupt(0,zeroCrossingInterrupt, FALLING)*

helped, but now even this one works, but ISR not.

I know there is a lot of caches and you do not see what is going on behind curtains, but I am quite lost yet...

Maybe there is also problem I have multiple installs in different dirs, but do not know how to clean old ones (1.6.5-r2) and at the end both work same way now, my latest fresh installed is 1.8.9.

Does anyone have any experiences with or some working demo sketch using both compare match and overflow ISRs ?

**Edit**

*Setup info*

*This board selected (...\AppData\Roaming\Arduino15\packages\digistump\hardware\avr\1.6.7\boards.txt):*

    digispark-tiny.name=Digispark (Default - 16.5mhz)
    digispark-tiny.upload.using=micronucleusprog
    digispark-tiny.upload.protocol=usb
    digispark-tiny.upload.tool=micronucleus
    digispark-tiny.upload.maximum_size=6012
    digispark-tiny.build.mcu=attiny85
    digispark-tiny.build.f_cpu=16500000L
    digispark-tiny.build.board=AVR_DIGISPARK
    digispark-tiny.build.core=tiny
    digispark-tiny.build.variant=digispark
    digispark-tiny.upload.wait_for_upload_port = false
    digispark-tiny.upload.use_1200bps_touch = false
    digispark-tiny.upload.disable_flushing = false

And these are available:

    (...\AppData\Roaming\Arduino15\package_digistump_index.json)
    ...
    "boards": [
      {
        "name": "Digispark (Default - 16.5mhz)"
      },
      {
        "name": "Digispark Pro (Default 16 Mhz)"
      },
      {
        "name": "Digispark Pro (16 Mhz) (32 byte buffer)"
      },
      {
        "name": "Digispark Pro (16 Mhz) (64 byte buffer)"
      },
      {
        "name": "Digispark (16mhz - No USB)"
      },
      {
        "name": "Digispark (8mhz - No USB)"
      },
      {
        "name": "Digispark (1mhz - No USB)"
      }
    ],
    ...

**Edit 2**

Fresh install attempt on W10

Few more links - 2nd manual here:

https://www.electronicshub.org/getting-started-with-attiny85/

http://digistump.com/package_digistump_index.json

have to be translated to

https://raw.githubusercontent.com/digistump/arduino-boards-index/master/package_digistump_index.json

https://downloads.arduino.cc/arduino-1.8.9-windows.zip

W10

When installing shows error downloading (timeout?):

http://downloads.arduino.cc/tools/avr-gcc-4.8.1-arduino5-i686-mingw32.zip

Downloaded by hand to (there was empty file of this name):

...\AppData\Local\Arduino15\staging\packages\

avr-gcc-4.8.1-arduino5-i686-mingw32.zip

...\AppData\Local\Temp\arduino_build_139604\core\core.a(wiring.c.o): In function `__vector_4':

...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny/wiring.c:93: multiple definition of `__vector_4'

...\AppData\Local\Temp\arduino_build_139604\sketch\sketch_jun28a.ino.cpp.o:...\arduino-1.8.9\SketchBook\sketch_jun28a/sketch_jun28a.ino:60: first defined here

collect2.exe: error: ld returned 1 exit status

exit status 1
Error compiling for board Digispark (Default - 16.5mhz).

...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\core_build_options.h (not found that file in arduino dir):

    /*=============================================================================
      Build options for the ATtiny85 processor
    =============================================================================*/

    #if defined( __AVR_ATtiny25__ ) || defined( __AVR_ATtiny45__ ) || defined( __AVR_ATtiny85__ )
    #define __AVR_ATtinyX5__
    #endif

    #if defined( __AVR_ATtinyX5__ )

    /*
      For various reasons, Timer 1 is a better choice for the millis timer on the
      '85 processor.
    */
    #define TIMER_TO_USE_FOR_MILLIS                   1

body:
The problem is the following:

The digispark core already implements the `TIMER1_OVF_vect` ISR (Timer1 Overflow Interrupt). Since you have a `1` for the `#define TIMER_TO_USE_FOR_MILLIS`, Timer1 will be used for counting the `millis()` value in the background. For this the Timer 1 Overflow interrupt is needed.

The code, that you copied from that site, does not anticipate, that you might use a core, that already implements the interrupts. It is written for a generic ATtiny85, not specifically for the Digispark version.

**What you can do to solve the problem:**

- You can use Timer0 for your code, keeping the Digispark core untouched. You can change all registers from Timer1 to Timer0 (by replacing the `1` with a `0`). Additionally you need to replace `TCCR1` with `TCCR0B`, because for Timer0 that's the register, that set's the prescaler (and turns the timer off if zero is written to it). Also you need to consider, that Timer0 has other prescaler settings. So the line `TCCR1 = B00001011;` in `zeroCrossingInterrupt()`  must be changed to `TCCR0B = B00000101;`. That will set the prescaler to 1024 as mentioned in the comment. The resulting code compiles fine for me with the digispark core (though I have not tested it's functionality).

- You can set the Digispark core to use Timer0 for `millis()`, by changing the definition of `TIMER_TO_USE_FOR_MILLIS` in the Attiny85 section of the file `arduino_folder/packages/digistump/hardware/avr/1.6.7/cores/tiny/core_build_options.h` to the value `0` instead of `1`. If you do this, the original sketch compiles fine. Though the comment before that build options states, that Timer1 is better for `millis()` "for various reasons", which is not very specific. You can try, if it works good for you.

- You can use another Attiny core. Though you might have to change it too, to accomodate for the unusual clock frequency fo 16.5MHz (most cores I have seen have 16, 8 and 1MHz). That might be as easy as changing the value of the defined clock speed in the cores files, but I'm not sure about that.


body:
Another simple option - rewrite or remove the ISR in wiring.c:
...\AppData\Local\Arduino15\packages\digistump\hardware\avr\1.6.7\cores\tiny\wiring.c

For example after changing like this was able to compile without problems.

Simplest solution would be to put that code to my ISR too or call one from another.

    #ifdef nothing
    // bluebie changed isr to noblock so it wouldn't mess up USB libraries
    ISR(MILLISTIMER_OVF_vect, ISR_NOBLOCK)
    {
      // copy these to local variables so they can be stored in registers
      // (volatile variables must be read from memory on every access)
      unsigned long m = millis_timer_millis;
      unsigned char f = millis_timer_fract;

    /* rmv: The code below generates considerably less code (emtpy Sketch is 326 versus 304)...

      m += MILLIS_INC;
      f += FRACT_INC;
      if (f >= FRACT_MAX) {
        f -= FRACT_MAX;
        m += 1;
      }
    ...rmv */

      f += FRACT_INC;

      if (f >= FRACT_MAX)
      {
        f -= FRACT_MAX;
        m = m + MILLIS_INC + 1;
      }
      else
      {
        m += MILLIS_INC;
      }

      millis_timer_fract = f;
      millis_timer_millis = m;
      millis_timer_overflow_count++;
    }
    #endif

If you rename wiring.c and restart editor, you get **main.cpp:5: undefined reference to `init'** error, there is that "crappy" heart of arduino:

    #include <WProgram.h>

    int main(void)
    {
     init();

     setup();

     for (;;)
      loop();

     return 0;
    }

WProgram.h starts with:

    #ifndef WProgram_h
    #define WProgram_h

    #include <stdlib.h>
    #include <string.h>
    #include <math.h>

    #include <avr/interrupt.h>

    #include "core_build_options.h"
    #include "core_pins.h"
    #include "wiring.h"
    ...
And init of that ATtiny85 (inside **wiring.c**) evn looks like this:

    void init(void)
    {
      // clock calibration stuff
      // recalibrate clock if it was calibrated by bootloader (like micronucleus)
      #if F_CPU != 16500000L
        if (OSCCAL != read_factory_calibration()) {
          // adjust the calibration down from 16.5mhz to 16.0mhz
          if (OSCCAL >= 128) {
            // maybe 8 is better? oh well - only about 0.3% out anyway
            OSCCAL -= 7;
          } else {
            OSCCAL -= 5;
          }
        }
      #endif

      // TODO: detect if fuses set to PLL, regular internal oscillator or external and change behaviour in this next section...
      #if F_CPU < 16000000L
        cli();
        CLKPR = 0b10000000;
        #if F_CPU == 8000000L
          CLKPR = 1; // div 2
        #elif F_CPU == 4000000L
          CLKPR = 2 // div 4
        #elif F_CPU == 2000000L
          CLKPR = 3; // div 8
        #elif F_CPU == 1000000L
          CLKPR = 4; // div 16
        #elif F_CPU == 500000L
          CLKPR = 5; // div 32 = 500khz
        #elif F_CPU == 250000L
          CLKPR = 6; // div 64 = 250khz
        #elif F_CPU == 125000L
          CLKPR = 7; // div 128 = 125khz cpu clock
        #else
          #warning "Cannot prescale chip to specified F_CPU speed"
        #endif
      #endif

      // this needs to be called before setup() or some functions won't work there
      sei();

      // In case the bootloader left our millis timer in a bad way
      #if defined( HAVE_BOOTLOADER ) && HAVE_BOOTLOADER
        MillisTimer_SetToPowerup();
      #endif

      // Use the Millis Timer for fast PWM
      MillisTimer_SetWaveformGenerationMode( MillisTimer_(Fast_PWM_FF) );

      // Millis timer is always processor clock divided by MillisTimer_Prescale_Value (64)
      MillisTimer_ClockSelect( MillisTimer_Prescale_Index );

      // Enable the overlow interrupt (this is the basic system tic-toc for millis)
      MillisTimer_EnableOverflowInterrupt();

      // Initialize the timer used for Tone
      #if defined( INITIALIZE_SECONDARY_TIMERS ) && INITIALIZE_SECONDARY_TIMERS
        initToneTimerInternal();
      #endif

      // Initialize the ADC
      #if defined( INITIALIZE_ANALOG_TO_DIGITAL_CONVERTER ) && INITIALIZE_ANALOG_TO_DIGITAL_CONVERTER
        ADC_PrescalerSelect( ADC_ARDUINO_PRESCALER );
        ADC_Enable();
      #endif
    }


body: I had similar problem. I removed functions loop() and setup() and I used classic C construction with main() function and it started to work. (I think loop() and setup() enables using of other functions like delay() - and it uses timer - only my hypothesis).


message:
analogRead Function AC Voltage Reading Capabilities

Usually when you sense AC voltage, you get a sinusoidal waveform. However, for AC voltage sources, Arduino analogRead ( ) only presents positive voltage values. So what's basically happening? Is it skipping half the cycle where the voltage is negative. If so, how can I account for that when I try to use the voltage values to calculate for total electrical energy generated by the source (piezoelectric film) and avg. power?

[![voltage/time graph provided by Arduino analogRead( ) function when sensing AC voltage values from piezoelectric film][1]][1]

  [1]: https://i.stack.imgur.com/iRKtB.png

body:
I guess that you are showing the voltages there directly calculated from `analogRead()` and that you connected the AC voltage directly to the analog input (and it's ground with the Arduino's ground).

The reference for every communication/voltage measurement/digital input is ground. Naturally the Arduino can only measure voltages inside of it's own supplied voltage range, meaning 0 to 5V for the Uno. If you apply a negative voltage (relative to ground), you will measure a voltage of 0V. You can even damage the microcontroller, if the negative voltage is too high.

If you have negative and positive voltages, you should offset the signal at the analog input pin, so that the resulting signal stays in the range from 0 to 5V. You can do this with a simple voltage divider. Use two resistors with the same value (for example 5kOhm), so that you will get a new zero point at 2.5V. The AC signal will then variate around that value.

---

For what is happening inside the microcontroller:

The ADC is responsible for measuring the voltage. For this the voltage on the analog input pin will first be sampled (loaded onto an internal condensator) and then step by step compared to the voltages, that the ADC generates by dividing the supply voltage range into 1024 distinct values (10 bit). Again the reference, to which the voltage is measured/compared, is ground. It cannot generate negative voltages, thus cannot compare them.


message:
Serial Enable Maxim RS485 Pin

If I want to use a MAXIM 485 for a RS485 communication, is there any option to include the Control `DE` and `RE'` pin in a natural manner in the code, instead changing the control pin everytime I made a `Serial.print()`?

Should I overload the HardwareSerial object in order to add those pin operations everytime?

body:
No, there isn't - you have to do it manually. And don't forget to flush.

You *could* inherit HardwareSerial if you really wanted - or just write a couple of functions to do the sending and controlling of the DE pin.


message:
Program Arduino Mega Adk on linux

for a project my supervisor gave me a Arduino Mega ADK board (https://store.arduino.cc/arduino-mega-adk-rev3) and the usb-cable.

I only programmed a Atmega32 8 bit controller on linux ubuntu. I have no possibility to use windows (i heard it's easy to program the arduino using atmel studio). I can only use ubuntu 16.04. Is there a convient way to program the Arduino like a microcontroller?

I'm not aloud to use the highlevel Arduino libraries. I have to do a cascaded control for a dc-motor and sensor-fusion.

Thanks in advance.

If it's offtopic, could you transfer me to a suitable board?

body:
You can use [Eclipse](https://www.eclipse.org/downloads/packages/release/helios/m7/eclipse-ide-linux-developers), along with [AVR-GCC](https://gcc.gnu.org/wiki/avr-gcc) and [AVRDude](https://www.nongnu.org/avrdude/) and an [AVR plug-in for Eclipse](http://avr-eclipse.sourceforge.net/wiki/index.php/Plugin_Download). Debugging may be a little painful since you don't have all the tools that Atmel Studio gives you. I'd question your employer if you aren't allowed to use the best (free) tools even if they do run on Windows.

Really all you need is the avr-gcc and avrdude to write software for it, you can use any text editor (although it isn't really convienent).  Seems like they are pigeon-holing you into a difficult job. Good luck.


message:
How to read a specific amount of data via serial?

I'm trying to send data via serial from my Arduino nano to my ESP. Its an integer from 1 to 4 digits
so something like 0, 13, 1234, 123, ...

Every thing works fine but when the data comes too fast it stopps the output and  then it print all the data on the screen.

I use this method to recieve data.
```
void loop() { // run over and over
        if (Serial.available()) {
                incomingByte = Serial.readString();
                Serial.println(incomingByte);
        }
}
```

body: From what you have posted, assuming this is the ESP code in the question, it is clear that for every character the Arduino sends the ESP the ESP will send 3 back. So at some speed this will likly stop working


message:
Nth-Light LED Strip power connections

Based on [this question on the Adafruit forum][1] for Nth-Light Narrow LED Flexible Strip Light ([https://www.adafruit.com/product/3683][2]) and the image below is it safe to connect from the 12v source + a wire to the Vin (orange wire) or it is better to connect to another DC barrel?

[![enter image description here][3]][3]

  [1]: https://forums.adafruit.com/viewtopic.php?f=47&t=140255&p=693992&hilit=nth#p693992
  [2]: https://www.adafruit.com/product/3683
  [3]: https://i.stack.imgur.com/KYipB.png

body:
If your 12V power supply has enough current to drive your LED strip at its maximum power, plus the Arduino's power supply, plus about 10-20% of "wiggle room" you should be fine. As the LED strip draws spikes of current the voltage from your power supply might bounce around a little, but the Arduino's voltage regulator would be fine with as little as 7.5V input.

Note that your Arduino's voltage regulator will get hot if you use much current from the Ardunio's 5V rails, since it has to regulate 12V down to 5V and the linear regulator on the Arduino converts the extra voltage to heat.


message:
Powering a Sim800L Module

I am trying to use a DC [power supply][1]. I am thinking whether I can use this power supply to provide power for [Sim800L][2] module. After some research, I gathered that the Sim800L module requires a max current of 2A during GPRS transmission at 3.8-4.2 V (4.0 recommended). With the power supply I can easily configure the voltage at 4.0V. My question is: for this setup, do I need a [DC-DC][3] Buck Converter as in this one for regulation/step-down (not sure which)?

  [1]: https://mcs.com.bd/product/dazheng-ps-305d-dc-power-supply-3-digit-0v-30v-0a-5a/
  [2]: https://nettigo.eu/products/sim800l-gsm-grps-module
  [3]: https://www.addicore.com/lm2596-module-p/ad281.htm

body:
The lab power supply you linked is serious overkill for your needs. It shouldn't need a separate voltage regulator or buck converter, since I assume that it provdes a voltage and current regulated supply.

A regulated, fixed voltage 4V power supply that can provide 2A is what you want. That will probably cost < 1/10 of the amount of the lab supply you linked. The challenge is to find a 4V supply. (Most regulated power supplies are either 3.3V or 5V, since those are common voltages for solid state electronics.)

That said, the linear voltage regulators are usually adjustable with a decent voltage range using a resistor.

You could always build your own voltage regulator using a linear voltage regulator rated for 2A, plus a resistor and a couple of capacitors. You could either feed it from an unregulated 6V power supply or use a transformer, bridge rectifier, and capacitor to provide an unregulated DC input to a voltage regulator.

## Edit:

With a little googling I found a few 4V 2A power supplies online. This one, for example:

https://www.alibaba.com/product-detail/US-AC110-220V-To-DC-4V_62155516966.html?spm=a2700.7724857.normalList.14.a5e64009aUU1ln&s=p

(That link is to a wholesale manufacturer that sells them in volume, but you may be able to find the same supply for single unit sale. A 2A switching 4V supply would meet your needs as well)


message:
DS3231 RTC module and battery problem

I've a CR2032 battery connected to DS3231 module as backup battery, when module is connected to 5V the battery voltage is at 4.3V and without power 3.7V.

That means the module is trying to charge the nonchargeable battery, i couldn't find a chargeable (LIR23032) battery to buy and after some research someone in forums suggested to remove the diode from the module...

1. If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?

2. is there any other way than modifying the module it self?

body:
> If i keep using the CR2032 battery for long run 24/7, how long will battery last? is there a chance of explosion?

Yes. Recharging a non-rechargeable battery is dangerous. It should be avoided at all costs.

> is there any other way than modifying the module it self?

You have to prevent the power getting to the battery. That power is fed through a diode (hence 4.3V, which is 5V minus 0.7v for a silicon diode forward voltage).  Without knowing what the module is, I can't tell you if there is any other way that modifying it - however I would guess that no there isn't. You need to stop that power getting to the battery, and that can only be done at some point between where the power comes in to the module and the battery itself - and the simplest method is to remove the diode.

The purpose of that diode is to prevent power from the battery from trying to power the rest of your circuit when you remove the main power. Removing the diode will have no adverse affect.  You just won't be able to charge a rechargeable battery in future.


message:
Rotary encoder using interrupt

This is my first time working with a rotary encoder and interrupts.  I am using a Pro Micro which has interrupt pins at pin0 and pin1.  The code below works as expected.

My question: do I need to use an interrupt pin for PinB as well, or can I use any digital pin?

It does not seem to work when I choose PinB = 9, for example.

    #include <Wire.h>
    #include <LiquidCrystal_I2C.h>
    LiquidCrystal_I2C lcd(0x27, 16, 2); // set the LCD address to 0x27 for a 16 chars and 2 line display

    // Used for generating interrupts using CLK signal
    const int PinA = 0;

    // Used for reading DT signal
    const int PinB = 1;

    // Used for the push button switch
    const int PinSW = 8;

    // Keep track of last rotary value
    int lastCount = 50;

    // Updated by the ISR (Interrupt Service Routine)
    volatile int virtualPosition = 50;

    // ------------------------------------------------------------------
    // INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT     INTERRUPT
    // ------------------------------------------------------------------

    void isr ()  {
      static unsigned long lastInterruptTime = 0;
      unsigned long interruptTime = millis();

      // If interrupts come faster than 5ms, assume it's a bounce and ignore
      if (interruptTime - lastInterruptTime > 5) {
        if (digitalRead(PinB) == LOW)
        {
          virtualPosition-- ; // Could be -5 or -10
        }
        else {
          virtualPosition++ ; // Could be +5 or +10
        }

        // Restrict value from 0 to +100
        //virtualPosition = min(100, max(0, virtualPosition));

      }
      // Keep track of when we were here last (no more than every 5ms)
      lastInterruptTime = interruptTime;
    }

    // ------------------------------------------------------------------
    // SETUP    SETUP    SETUP    SETUP    SETUP    SETUP    SETUP
    // ------------------------------------------------------------------
    void setup() {
      // Just whilst we debug, view output on serial monitor
      //  Serial.begin(9600);

      lcd.init();                      // initialize the lcd

      lcd.backlight();

      // Rotary pulses are INPUTs
      pinMode(PinA, INPUT);
      pinMode(PinB, INPUT);

      // Switch is floating so use the in-built PULLUP so we don't need a resistor
      pinMode(PinSW, INPUT_PULLUP);

      // Attach the routine to service the interrupts
      attachInterrupt(digitalPinToInterrupt(PinA), isr, LOW);

    }

    // ------------------------------------------------------------------
    // MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP     MAIN LOOP
    // ------------------------------------------------------------------
    void loop() {

      // Is someone pressing the rotary switch?
      if ((!digitalRead(PinSW))) {
        virtualPosition = 50;
        while (!digitalRead(PinSW))
          delay(10);
        //    Serial.println("Reset");
      }

      // If the current rotary switch position has changed then update everything
      if (virtualPosition != lastCount) {

        lcd.clear();
        lcd.print(virtualPosition);

        // Keep track of this new value
        lastCount = virtualPosition ;
      }

      //delay(100);
    }

body: Found my error... on the ProMicro, the pins are not arranged 0, 1, 2, 3, 4, 5 etc instead they arranged 1, 0, 2, 3, 4, 5 etc... On the board I misread TXO and RXI as TX0 and RX1 and just didn't notice it on my pinout sheet.... so I had D0 and D1 swapped. All works well now. Learning more everyday! I appreciate your time...


message:
Which kind of diodes I should use in buttons/keys matrix input? (Making gaming keyboard)

When making matrix input of NxM columns/rows with push buttons, there should be a diode next to each button to prevent "ghosting" and able read many keys pressed together correctly. There is a lot of pictures everywhere.

My problem is, **which diodes** to use and also **why** this type (or why it does not matter).

----------

More details:

I would use 5 V Arduino (ATmega32U4), datasheet states for input low voltage max 0.3Vcc, which is 1.5 V and minimal high input voltage 0.7Vcc = 3.5 V and pullups at least 1.5 kΩ (Vcc-0.4 V / 3 mA)

I would like to use 74HC138 3-to-8 decoder for addressing, which makes one of 8 outputs Low (max 0.1 V), while other 7 High (min 4.5 V) and drive the Arduino inputs Low, if button is pressed.

To be on safe side, I would like also add resistors on each pin to make sure, that bad programming (make some input pin OUTPUT and HIGH and pressing key connect it to LOW output on other side) could not damage the circuits, so it looks like 5 V/20 mA = 250 Ω (and I will hope it would not hit more pins, so I would not consider total port/chip limitations).

In typical case it would be **5 V** - 1.5 kΩ pullup - **input** - 250 Ω - wires and button - **diode** - 250 Ω - **0.1 V** for selected line.

If the diode would be theoretical and ideal, then there is (in the worse case) promised to be max 1.2 V on Input, which is slightly less then "maximal low" voltage (1.5 V) and like 5V/2 kΩ = 2.5 mA current.

But the diode is not ideal and have some forward voltage, which make the case even worse.

So I probably cannot use simply `INPUT_PULLUP` (as it may work by luck, but is not guaranted by specs) but I need to use `INPUT` and set some higher pullup there to "burn" more volts on it to compensate for the diode.

The Input Current for each pin is 10 µA (in or out) and I heard some recommendation, that on resistor divider should be the total current 10x more, then the input current, so it would mean 100 µA = 0.1 mA

The pullup then could go as high as ((5 V - 0.1 V - Vf)/0.1 mA ) - 500 Ω If the forward voltage would be 1 V (wild guess) it would go to something like 38.5 kΩ pullup and 1.15 V on input. The maximal Vf forward voltage would be like 1.35 V (at 0.1 mA), pullup 35 kΩ and 1.5 V on input.

----------

My problem is, that many online Arduino schemes works just because Arduino usually work good even in way out-of-spec situations, and suggested values cames from what the author just randomly had at hands and it worked by pure luck and maybe another hidden factors, as parasite capacity of breadboard or so. So I want to uderstand, **why** I should choose some parts and how to came to such conclusions by myself.

I want to make reliable projects, not just projects, which works most of the time and fail only occasionally.

----------

 - It is the right path, how to compute it or did I some mistake?
 - I want use scanning frequency at least 800 Hz (8 lines and results
   100x per second) or more (like 10 kHz to be done fast and to have more time to spend with other
   tasks, like sending USB packets, computing macros, managing light
   effects etc)
 - which common and cheap SMD diodes I should buy?
   - reverse voltage over 5 V, current over 100 mA, switch frequency over 10 kHz, forward voltage under 1.3 V at 0.1 mA (rather much less to have safe gap from limits)
   - really common cheap model, so everybody would know it and so I could use it everywhere in similar settings without thinking ( or even computing like in previous section)
   - preferably what you (and everyone else and his dog too) use for such cases
   - I would like to order from AliExpress, so rather higher margin for guaranteed values
   - preferably to fit on 0.1 inch spaced universal PCB (0805 SMD LEDs are really easy to solder there (so rather not smaller than that), but it may be twice the size too or something like that)
   - I would buy like some hundreds of such diodes to have them ready on hands and I will probably make more similar projects over time for me and my friends

Thanks for all comments and suggestions

body:
When I've used a keypad matrix I've wired it up like this:

[![Keypad matrix with diodes][1]][1]

I used 1N4148 SMD diodes which I bought cheaply. I cut the traces on my cheap board that I had purchased from Jaycar and soldered them in like this:

[![1N4148 SMD diodes][2]][2]

The dot is the cathode (there is a line etched on my diodes at the cathode end).

The 10k resistors effectively turn the columns into pull-ups, therefore there is no danger of bad code damaging the Arduino or anything else.

Example code to scan the matrix:

<!-- language: lang-c++ -->

    // Keypad_Decoder
    //
    // Author: Nick Gammon
    // Date: 17th February 2018

    // Outputs to Serial in the format: 0b1nnnnnnn for a key down and 0b0nnnnnnn for a key-up
    //            nnnnnnn will be the current row/column combination
    //            Also every HEARTBEAT_TIME outputs 0xFF if all keys are up (heartbeat)

    #include <limits.h>     /* for CHAR_BIT */

    const byte ROWS = 4;
    const byte COLS = 4;
    const bool ENABLE_PULLUPS = true;  // make false if you are using external pull-ups
    const unsigned long DEBOUNCE_TIME = 10;     // milliseconds
    const unsigned long HEARTBEAT_TIME = 2000;  // milliseconds
    const bool DEBUGGING = false;               // make true for human-readable output

    // define here where each row and column is connected to
    const byte rowPins [ROWS] = {6, 7, 8, 9}; //connect to the row pinouts of the keypad
    const byte colPins [COLS] = {2, 3, 4, 5}; //connect to the column pinouts of the keypad

    // See: http://c-faq.com/misc/bitsets.html

    #define BITMASK(b) (1 << ((b) % CHAR_BIT))
    #define BITSLOT(b) ((b) / CHAR_BIT)
    #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
    #define BITCLEAR(a, b) ((a)[BITSLOT(b)] &= ~BITMASK(b))
    #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))

    // number of items in an array
    #define ARRAY_SIZE(x) (sizeof(x) / sizeof((x)[0]))

    // total number of keys
    const byte TOTAL_KEYS = ROWS * COLS;

    // remember previous setting of each key
    char lastKeySetting [(TOTAL_KEYS + CHAR_BIT - 1) / CHAR_BIT];  // one bit each, 0 = up, 1 = down
    unsigned long lastKeyTime [TOTAL_KEYS];       // when that key last changed
    unsigned long lastHeartbeat;                  // when we last sent the heartbeat

    void setup ()
    {
      Serial.begin (115200);
      while (!Serial) { }  // wait for Serial to become ready (Leonardo etc.)

      // set each column to input-pullup (optional)
      if (ENABLE_PULLUPS)
        for (byte i = 0; i < COLS; i++)
          pinMode (colPins [i], INPUT_PULLUP);

    }  // end of setup

    void loop ()
      {
      byte keyNumber = 0;
      unsigned long now = millis ();  // for debouncing

      // check each row
      for (byte row = 0; row < ROWS; row++)
        {
        // set that row to OUTPUT and LOW
        pinMode (rowPins [row], OUTPUT);
        digitalWrite (rowPins [row], LOW);

        // check each column to see if the switch has driven that column LOW
        for (byte col = 0; col < COLS; col++)
          {
          // debounce - ignore if not enough time has elapsed since last change
          if (now - lastKeyTime [keyNumber] >= DEBOUNCE_TIME)
            {
            bool keyState = digitalRead (colPins [col]) == LOW; // true means pressed
            if (keyState != (BITTEST (lastKeySetting, keyNumber) != 0)) // changed?
              {
              lastKeyTime [keyNumber] = now;  // remember time it changed
              // remember new state
              if (keyState)
                BITSET (lastKeySetting, keyNumber);
              else
                BITCLEAR (lastKeySetting, keyNumber);
              if (DEBUGGING)
                {
                Serial.print (F("Key "));
                Serial.print (keyNumber);
                if (keyState)
                  Serial.println (F(" down."));
                else
                  Serial.println (F(" up."));
                }  // if debugging
              else
                Serial.write ((keyState ? 0x80 : 0x00) | keyNumber);
              }  // if key state has changed
            }  // debounce time up
          keyNumber++;
          } // end of for each column

        // put row back to high-impedance (input)
        pinMode (rowPins [row], INPUT);
        }  // end of for each row

      // Send a heartbeat code (0xFF) every few seconds in case
      // the receiver loses an occasional keyup.
      // Only send if all keys are not pressed (presumably the normal state).
      if (now - lastHeartbeat >= HEARTBEAT_TIME)
        {
        lastHeartbeat = now;
        bool allUp = true;
        for (byte i = 0; i < ARRAY_SIZE (lastKeySetting); i++)
          if (lastKeySetting [i])
            allUp = false;
        if (allUp)
          {
          if (DEBUGGING)
            Serial.println (F("No keys pressed."));
          else
            Serial.write (0xFF);
          } // end of all keys up
        } // end if time for heartbeat
      } // end of loop

---

Speedwise, I measured around 300 µs for doing a scan with no keys pressed. If that time seems a bit long, you could always do a time check, and scan every 5 ms or so.

I have a post about all this on [my forum](https://www.gammon.com.au/forum/?id=14175). In that post I also mention a library that handles N-key rollover, so you can detect multiple keys being pressed at the same time. For example, you could use A/B/C/D on the keypad as "shift" keys, so that A+1 meant something different than just 1.

---

Matrix from the front:

[![Keypad matrix][3]][3]

---

> My problem is, which diodes to use and also why this type (or why it does not matter).

I don't think the exact diode is critical in this case. If this was a very high speed application, then a diode with fast switching might be required. If it was high voltage then a higher-spec diode might be required. In some cases the reverse voltage might apply. In this particular case, since we are dealing on/off at logic levels, I don't think much of this matters, although the switching speed might to a certain extent, however I am guessing from empirical observations that the speed of the 1N4148 is fast enough.

Also see: [Wikipedia - 1N4148](https://en.wikipedia.org/wiki/1N4148_signal_diode):

> The 1N4148 is useful in switching applications up to about 100 MHz with a reverse-recovery time of no more than 4 ns.

  [1]: https://i.stack.imgur.com/MsPOe.png
  [2]: https://i.stack.imgur.com/YaUy6.jpg
  [3]: https://i.stack.imgur.com/rZgNj.jpg


body:
Solution: 1N4148 diode

generally if you want connect diode to Arduino pin, use this one as it would be OK under nearly any normal use

 - 75 V reverse voltage (much more than 5V allowed there)
 - 1 V forward voltage at 10 mA (less at lower current)
 - 10 mA recommended current (destroys at 1 A 1 sec pulse) (and you do
   not want more then 10 mA anyway)
 - usable up to 100 MHz (so using digitalRead/digitalWrite and
   some logic you are way slower anyway)
 - super extra common for long time (even 10 years ago was considered
   "classical") and still actual (so when you get old, it would still be
   here)
 - dirty cheap (buy few hundreds just now and you do not need care
   anymore)


message:
Handling arduino output current

I need to power an actuator that requires 12 volts and consumes between 5 and 10 amperes depending on the weight it is charging. Therefore I bought a power supply of 12 volts and 10 amperes.

My intention is to send in the arduino output the 12 volts and the current provided by the power supply.

The options that I have thought are the following:

a) Connect the power supply to the arduino input pins and send the voltage and current from the power supply to the actuator through the arduino output (I know I could do it directly to the actuator, but I am interested in doing it through of arduino since it will involve programming code to put conditionals)

My doubt with this option is if I do not damage the arduino by connecting that power source with that amperage. If there is no problem, my question is if I could handle the current of the power supply at the output or the current could only be handled by what arduino gives that would not be much.

b) The other option that I think is simply to send a flag to the output and then this flag activates the power supply in some way and then I could use the 12 volts and the 10 amperes to connect them to the actuator.

I would like you to guide me on the alternatives I have thought about and tell me what would be the right thing to do, or if you know some other way in which you should do it.

Thank you very much in advance
Cheers

body:
As others have said, an Arduino pin can't handle 12V, and can't handle anywhere near 10A of current directly. A digital pin on an Arduino is limited to 20mA, or 1/500 as much current as you need, at 5V, which is less than half the voltage you need.

If you try to connect 12V to a pin on an Arduino pin you will almost certainly destroy that pin, and may destroy the entire Arduino. If you try to source or sink even 1/100 of the current you are talking about through an Arduino pin, even at 5V, you will also probably destroy that pin and possibly the entire Arduino.

This sounds like a good application for a power MOSFET transistor. With that much current you'll need to put a heatsink on the transistor.

Here's one that would work:

https://www.sparkfun.com/products/10213

You'd use a logic pin from the Arduino to control the gate on the transistor, and the transistor would switch 12V at high current with very little resistance.

If the actuator is inductive, you'll need to protect the transistor with a suitably large "flyback diode" to protect it from the reverse current (or "back EMF") you get from an inductor when you remove power from it:

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


body:
Duncan's  answer is how I would do it as well. Indeed that is how I did do it as well.

Having said that the challenge I had to work out was how to mix the voltages. For me, this was the hardest part of the project as I had little idea about current and voltage.

I also wanted to use just one power supply.

 So what's the problem? The LED strip requires 12V@1Amp. Which is, I think the upper limit for what can be supplied to arduinio's power jack. Also the arduino can only supply a small current at 5v to switch the relatively massive 12V 1A led circuit.

The MOSFET was the answer (after multiple failed attempts). MOSFETs are apparantly safe for connection to Arduino as there is apparantly no electrical connection between the base (where the arduino connnects) to the other two pins (where the power flows). The articles I read say that the base is insulated from the rest of the circuit by a piece of glass!

Anyway, Here is my  [Motion activated stair lighting](https://www.instructables.com/id/Motion-Activated-Automatic-LED-Stair-Lighting-With/) project. I am not an electronics expert, but FWIW, this has been running flawlessly 24x7 for almost 12 months now.


message:
Will Funduino Joystick Shield work on a Mega?

I am trying to get a Funduino Joystick Shield working with an Arduino Mega and I need to use the WiFi capability. The specs I have found for the Funduino (see [https://protosupplies.com/product/funduino-joystick-shield-v1-a/][1]) use the standard UNO pins for the RF24: 9..13, The Mega uses pins in the high 40s for this interface. Is there a way to make this work?

  [1]: https://protosupplies.com/product/funduino-joystick-shield-v1-a/

body:
The shield will work on Mega, except of the SPI connection for the nRF24L01 connector. The shield expects SPI on pins 11, 12, 13 and Mega has them on 50, 51, 52. Other shields use the SPI pins on the ICSP header to have compatibility with different boards. This shield doesn't connect to the ICSP header.

You can wire the nRF24L01 to SPI pins on 50, 51, 52.


message:
ATMEGA328P-U vs ATMEGA328-PU

On my Arduino UNO the chip part number is ATMEGA328**P-U**, i recently bought a ATMEGA328-**PU** to make a standalone Arduino. realized the part number differences after receiving the package...

I noticed that some arduino UNOs have the chip with part number of ATMEGA328**P-PU**! I'm totally confused!

Those chip are the same? can i use the one that i bought for an standalone Arduino?

If no what are the differences?

body:
The main difference is the bit before the `-`. That is, the 328 vs the 328P.  The "P" there denotes "Picopower" which allows the chip to run at very low power consumptions.

Basically the P version is a more modern version of the non-P chip.  There are probably other internal differences too but you will have to check the datasheets thoroughly for those.

Everything after the `-` is to do with the packaging and environmental grading of the chip.  For example PU is a -40C to +85C grade DIP chip. ANR is a -40C to +105C grade TQFP chip, etc.

If you see 328P-U then that's probably a fake chip. There's no such thing as single U suffix.


body:
There are three die types:

328

328P

328PB

all have different signature bytes which may or may not impact loading code into them. Generally tho the programming software needs to know which part type is being used, at a minimum for installing bootloader code.  Serial downloading may end up ignoring the signature bytes of a bootloaded part.

They can be had in different packaging, this is what Digikey is showing as available options:

-PU - 28 pin DIP

-AU - 32 pin TQFP

-AN - 32 pin TQFP

-MM - 28 pin leadless package, smaller than 32 pin leadless

-MN - 32 pin leadless package

-MU - 32 pin leadless package

-15AZ - 32 pin TQFP, rated for a higher temperature range

-15MZ - 32 pin leadless package rated for a higher temperature range

Any letters to the right of those seen when ordering indicate the method they are supplied - loose parts, parts in a reel, parts in a tube, etc.

Anything else is either an older part that did not follow the convention, or is a counterfeit part.

Tables 38.7 and 38.8 lists these options for the 328 and 328P for example, with H indicating a type of lead finish, and R indicating Tape & Reel availability:

http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf

ATmega328-AU

ATmega328-AUR

ATmega328-MMH

ATmega328-MMHR

ATmega328-MU

ATmega328-MUR

ATmega328-PU

And 328P options:

ATmega328-AU

ATmega328-AUR

ATmega328-MMH

ATmega328-MMHR

ATmega328-MU

ATmega328-MUR

ATmega328-PU

With these rated to 105C

ATmega328P-AN

ATmega328P-ANR

ATmega328P-MN

ATmega328P-MNR

ATmega328P-PN

I think you need to pull up the Automotive data sheet to see the Z numbered parts.

And the PB is a different data sheet as well.


body:
User `line_code` from [forum.arduino.cc][1] recently received an `ATMEGA328P-U` (or actually `ATMEGA328P U`) from Mouser (a company which you would not suspect to send out fakes or source from the gray market). He asked Mouser (who contacted the manufacturer Microchip) and got the following response:

> As part of Part marking change due to the migration from Atmel to
> Microchip, the package identifier has been removed from the device
> marking as this can be observed visually for different packages. This
> will be updated in the upcoming revisions of the device datasheet.  As
> per this new marking the ATMEGA328P U are valid devices without any
> process change. [...]

(Source: https://forum.arduino.cc/index.php?topic=561928.msg3890391#msg3890391)

So the P stands for pico power (the low power modern version) and if the package is a 28-pin DIP like in the photo I took then this specific `ATMEGA328P U` is an `ATMEGA328P-PU`.

[![ATMEGA328P U in a 28-pin DIP is an ATMEGA328P-PU][2]][2]

Note that the Microchip response does say that the packaging is omitted from the marking. Hence we can expect `ATMEGA328P U`s to pop up in other packages. What the `U` stands for is unclear.

  [1]: https://forum.arduino.cc
  [2]: https://i.stack.imgur.com/Sodz4.jpg


message:
Why map Arduino pins 2 and 3 to Rx and Tx instead of using the build in Rx and Tx pins?

In many examples I see the following:
```
#include <SoftwareSerial.h>

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

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

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

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

---

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

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


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


message:
What are the better options to the basic Arduino Serial Plotter?

Arduino Serial Plotter does not allow analysis or saving of data. What are the best serial data graphing software (preferably free, but i don't mind if it's paid as long as it's better than the bare-bones Arduino Serial Plotter)?

1. It should work well with Arduino

2. It should allow plotting several variables on the same graph

3. Allow exporting data to CSV so i can show it in Excel.

body:
Custom devices require custom solutions.

I suggest using Python (don't be scared).

[This tutorial][1] shows us how to read data from serial and save it to .csv file. You don't have to use a file. For example you can modify it to use an in memory list, and save just values from last 30 seconds. You can also read several values, and not just one.

    import serial
    import time
    import csv

    ser = serial.Serial('/dev/ttyACM0')
    ser.flushInput()

    while True:
        try:
            ser_bytes = ser.readline()
            decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8"))
            print(decoded_bytes)
            with open("test_data.csv","a") as f:
                writer = csv.writer(f,delimiter=",")
                writer.writerow([time.time(),decoded_bytes])
        except:
            print("Keyboard Interrupt")
            break

[This tutorial][2] (and [this one][3]) shows you how very quickly to show a sophisticated plot of the data you collected. You can even make a plot that shows several graphs and updates in real time.

    import matplotlib.pyplot as plt
    plt.plot([1,2,3,4])
    plt.ylabel('some numbers')
    plt.show()

Don't be scared it's not black magic. It just takes few days to understand how things work.

  [1]: https://arduino.stackexchange.com/questions/66711/what-are-the-better-options-to-the-basic-arduino-serial-plotter
  [2]: https://matplotlib.org/users/pyplot_tutorial.html
  [3]: https://realpython.com/python-matplotlib-guide/


message:
Variable declaration inside main loop

In the past I declared variables inside the main loop which worked just fine.
In a new project I did the same:

    void loop(void)
    {
        uint8_t counter;
        ....
        if (buttonPress)
            counter = 0;
        ...
        if (someCondition == true)
        {
            Serial.println(counter);
            counter++
        }
    }
But then the output of the variable *counter* shows that for some reason the counter variable is reset to 0 instead of counting up. This happens even after the button is released.

The scope of the variable *counter* is the main loop and I just assumed that it will keep its value and count up.

What might be the reason for this variable to reset to 0?
Is it that other functions are called within the main loop?
Is it that an interrupt handler is called every now and then?

The solution I've found is to declare the variable as static:

    static uint8_t counter;

Then it increments as expected.

Even though I've found a solution I'd really like to understand what the problem with my first approach was.

body:
The problem is that you declare a new variable. So even though the name is the same, the local variable is destroyed at the end of the loop and recreated at the beginning.

Actually, there is no good solution:

- Global variables are best to be avoided. They can be seen as 'singleton's', e.g. variables that are needed at many places in the code and have only one occurrence.
- As you found out, static solves the problem. I would use this option, although personally I'm not a fan of static variables.
- Another way is to put the loop in a while, so you get:

    void loop(void)
    {
        uint8_t counter = 0; // Always initialize variables
        while (true)
        {
            // Your code
        }
    }

 This will work too, as your counter is only initialized once, however the loop is already (internally) a while loop, so you have two.

- A much better way but more extra work, is to create a C++ class, where counter can be a class variable, which is local for that class (which could still be a singleton). Of course this is only true when the counter variable is belonging logically to that class, if it is not, just keep it a global variable (updated after Edgar Bonet's remark).


body:
Michael's answer was good, as usual. Let me give you some more background though:

In C/C++ (And in most modern languages) variables have a "scope", or an area where they are defined.

Global scope:

Variables declared at the top level of your program have global scope, and exist for the life of your program. These variables are usually created on the .data or .bss sections.

Local scope

Variables declared inside a function have local scope. Unless they are `static`, they get created when the function is entered, and get discarded when the function exits. These variables are created on the stack as part of the function's stack frame.

Object scope

In C++ and other object-oriented languages, instances of objects have their own scope, "instance variables". Every instance of an object has its own set of instance variables. (Think of cars, and a car radio. You and I might own the exact same model of car, but if I set my car's radio station and you set your car's radio to a different station, each instance of the car has a different setting for the radio station.)

Static variables:

Static variables are variables that are declared "statically." That means that they are only created once and persist, even if they are declared inside a scope like a function or a class instance. These have the lifespan of a global variable but can be declared inside a function or in an object.

----

Loop is a function, so variables declared inside of `loop()` are local variables. They get created anew every time the function is called, and discarded every time the function exits.


body:
Your code has a couple of bugs.  First you don't initialize counter before using it.  Second the variable 'counter' has limited scope, it has no definition when loop() exits.  If you want this variable to stay around declare it as static.

Both bugs corrected
e.g.:

    void loop(void)
    {
        static uint8_t counter = 0;
        ....
        if (buttonPress)
            counter = 0;
        ...
        if (someCondition == true)
        {
            Serial.println(counter);
            counter++
        }
    }

Note:  Initializing counter to 0 only happens once, on subsequent calls to loop() counter will retain it's previous value.


message:
Arduino Timer0 Piggyback

As described here
https://learn.adafruit.com/multi-tasking-the-arduino-part-2/timers

I use timer 0 to get my own timer with a milliseconds resolution.

It is setup like this:

    void setup (void)
    {
        ...
        cli();
        OCR0A  = 0xAB;
        TIMSK0 |= (1 << OCIE0A);
        sei();
        ...
    }
The value 0xAB is chosen randomly and should not affect the behaviour.

The interrupt handler looks like this:

    ISR(TIMER0_COMPA_vect)
    {
        if (myTimer != 0)
            myTimer--;
        return;
    }

This works just OK but having a closer look at the actual timing values using millis() I've found that the timer values given by this ISR are about 2-3% too long.

According to adafruit.com this method should exactly follow the built-in millis() timer of the Arduino.
In my program there are no other interrupts active. There are some Serial.print() outputs, maybe they affect the timing?
The solution I've found looks like this:

    ISR(TIMER0_COMPA_vect)
    {
        static unsigned long timeLast;

        unsigned long timeNow = millis();
        uint8_t timeDiff = (uint8_t)(timeNow - timeLast);
        timeLast = timeNow;

        if (myTimer != 0)
            myTimer -= timeDiff;

        return;
    }

Instead of simply decrementing the timer, the timer value is decreased by the actual amount of time since the last call of the ISR.

With this my timer follows exactly the millis().
But why doesn't the first approach give an exact timing? Apparently there are some cases where the time between calls of the ISR is not 1ms but 2ms.

body:
The Arduino core configures Timer 0 for a period of 1,024 µs. Your
ISR will then be called at very regular intervals, and is a good place
to have timing-related code. You just have to keep in mind that the unit
of time is not one millisecond, but 1.024 ms.

If this “weird” unit bothers you, then you could do what [the Arduino
timing ISR][isr] does: keep track of how late, relative to a 1 ms
period, you are getting. When you notice you are 1 ms late, count
one extra millisecond.

[isr]: https://github.com/arduino/ArduinoCore-avr/blob/1.6.23/cores/arduino/wiring.c#L42-L63


message:
Make a set LED dimming schedule?

I'm trying to made the LED's go from minimum brightness to maximum brightness and back to minimum in 2.55 seconds.

I really don't know where to begin. I have the following basic code for making it blink simultaneously, but how do I make it cycle through during the time I want:

    int led = 10;           //the PWM (tilde) pin the LED is attached to

    int led2 = 9;

    int led3 = 11;

    int brightness = 0;    //how bright the LED is

    int delaytime = 25;

    int fadeAmount = 5;    //how many points to fade the LED by

    //the setup routine runs once you press the reset:

    void setup() {

      // declare pins to be an output:

      pinMode (led, OUTPUT);

      pinMode (led2, OUTPUT);

      pinMode (led3, OUTPUT);

    }

    //the loop routine runs over and over again forever:

    void loop() {

      // set the brightness of pin 10:

      analogWrite (led, brightness);

      analogWrite (led2, brightness);

      analogWrite (led3, brightness);

      //change the brightness for next time through the loop:

      brightness = brightness + fadeAmount;

      //reverse the direction of the fading at the ends of the fade:

      if (brightness <= 0 || brightness >= 255) {

        fadeAmount = -fadeAmount;

      }

    //wait for set milliseconds to see the dimming effect

    delay (delaytime);

    }

**bonus: the next part includes making each LED go on its own schedule so the more thoroughly you can explain this first the better I can attempt the next part.

THANK YOU!

body:
The way to go is the non-blocking coding style, that can be found in the `BlinkWithoutDelay` example, that comes with the Arduino IDE. There you use `millis()` to measure time. You save a timestamp for every LED and in every execution of the `void loop()` you check, if enough time has passed since the last timestamp. You have to do this for every LED.

Since this coding style has been explained numerous times through the internet and on this site, I will not go more into detail. You can google the rest, understand, how that style works and then transfer that to your case.


body:
Have a look at these instructables...

One does the gradual fading of an led (on and off) via PWM: [LED lighting in a staircase](https://www.instructables.com/id/Motion-Activated-Automatic-LED-Stair-Lighting-With/).

The second deals with the "there own schedule" bit - which I assume means cycle on and off independently of one another.:  [cooperative multitasking](https://www.instructables.com/id/Cooperative-Multitasking-on-Arduino-With-Pretty-Bl/).

Disclaimer.. they are my instructables posts, but they do address the question. There are also several libraries available for running "timed tasks" if you prefer an alternative solution.

Here is an practical example that should deal with both aspects of your question (hopefully it will stem the tide of negative feedback)...

It should work on an UNO or any other Arduino with PWM on pins 3, 5 and 6. Of course you are free to adjust the pins to suit your needs (including adding more or taking some out).

```C

int pwmPin[] = {3, 5, 6 };        // Pins that are being used for PWM.
int pwmValue [] = { 0, 0, 0};     // Initial value of PWM duty cycle in the range 0 to 255.
int pwmIncrement[] = {1, 1, 1};   // The value by which the PWM will be incremented at each step.
                                  // NB, this can not be zero but you can start with negative numbers if you wish.
unsigned int pwmDelay[] = { 20, 30, 70 }; // The delay between steps for each PWM.

// To get a good effect select good initial values for the delay, value and increment.
// larger delays mean less frequent changes to the PWM duty cycle.
// larger increments means each adjustment to the PWM duty cycle is larger.
// Set the value at the starting point e.g. 0, for off, 127 for 50% brightness or 255 for 100%.

#define PINS sizeof(pwmValue)
unsigned long pwmNextStepTime[PINS]; // The point in time when the PWM will next be adjusted.

void setup() {
  for (int i = 0; i < PINS; i++) {   // Initialise each pin as:
    pinMode(pwmPin[i], OUTPUT);      // an output.
    pwmNextStepTime[i] = millis() + pwmDelay[i];   // The time when next the duty cycle shoud be adusted.
    analogWrite(pwmPin[i], pwmValue[i]);           // Set the duty cycle of the PWM.
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  for (int i = 0; i < PINS; i++) {    // On each loop, check the PWM pin to see if we need to do anything.
    unsigned long now = millis();     // What is the current "time"?
    if (now > pwmNextStepTime[i]) {   // Has the time passed the adjustment time for PWM pin i?
      pwmNextStepTime[i] = now + pwmDelay[i];  // Yes, calculate the next adjustment time.
      pwmValue [i] += pwmIncrement[i];         // Adjust the duty cycle as per the pin's increment.
      if (pwmValue [i] >= 255) {               // Have we gone too far up?
        pwmValue[i] = 255;                     // Yes, set the maximum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count down)
      } else if (pwmValue[i] <= 0) {           // Have we gone too far down?
        pwmValue[i] = 0;                       // Yes, set the minimum value.
        pwmIncrement[i] = -pwmIncrement[i];    // Reverse the increment (so now we count up)
      }
      analogWrite(pwmPin[i], pwmValue[i]);     // Finally, set the duty cycle for the LED.
    }
  }
}

```


message:
Why won't this code play a converted wav2c header file through an Arduino to my speaker?

I used this converter wav2c to convert a .wav file to a C that I can put in a header file. I was able to put converted audio into the h file but the program where I reference it does not seem to be working correctly. The code compiles and uploads to the Arduino but no sound plays. I used the code here to implement the converted audio. I'm using an 8-ohm 0.25w speaker. I'm no programmer nor an expert at electronics so it's likely something dumb that I did wrong. Any help is much appreciated!

Note: The speaker does work with a simple tone sketch.

The code in the header file (minus the hundreds of lines of values for the audio)
<!-- language-all: lang-cpp -->

    #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=10000;
    //const int sounddata_sampleRate=8000;

    const unsigned char sounddata_data[] PROGMEM = {
      15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,254,16,1,197,255,65,0,9,0,227,0,127,254,87,0,175,1,61,254,132,1,135,255,21,1,72,0,104,1,172,0,122,0,213,1,65,255,188,1,100,1,215,0,210,255,59,2,17,0,193,0,200,2,207,255,203,0,65,1,17,1,169,255,121,2,112,0,193,255,65,255,252,255,232,0,101,255,88,2,4,0,26,255,

    //Several hundred lines more of these numbers for the audio

    105,108,101,45,49,46,48,46,50,52,41,0,105,100,51,32,42,0,0,0,73,68,51,3,
      0,0,0,0,0,31,84,88,88,88,0,0,0,21,0,0,0,83,111,102,116,119,97,114,101,0,76,97,118,102,53,50,46,57,51,46,48,0,};

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

Here is the code that I used from the Arduino Playground page to play the audio from the header file.

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

    #define SAMPLE_RATE 8000
    #include "Test.h"

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

    void stopPlayback()
    {
        // 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(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);
        startPlayback();
    }

    void loop()
    {
        while (true);
    }

body:
This program uses the Timer 2 PWM facility to generate audio output on
pins OC2A or OC2B. On the Arduino Uno, these pins are labeled “11” and
“3” respectively, and the program carries this mapping as an implicit
assumption. You are trying to run the program on an Arduino Mega, which
has a different pinout. For instance, on the Mega:

* OC2A = digital 10
* OC2B = digital 9

You can easily port the program to the Mega by replacing every reference
to pins 11 and 3 by 10 and 9 respectively. E.g., every occurrence of

```c++
if(speakerPin==11){
```

becomes

```c++
if(speakerPin==10){
```

Make sure to fix the comments so that they remain consistent with the
code.

And you should, of course, choose an appropriate pin for your speaker.

Side note: you are stressing the output pin if you connect it directly
to an 8 Ω speaker. It's fine for a test as long as you don't care
too much about the life span of your Arduino.


message:
Arduino IDE doesn't pick up serial ports

I am fairly new to Arduinos and I recently bought a nodeMCU Amica esp2866 for this [tutorial][1]. I have my board connected to my MacBook Air (10.14.5 with Mojave) and only the "/dev/cu.Bluetooth-Incoming-Port" is the only one that shows up.

[![Screenshot][2]][2]

I am using a basic USB cord to connect the board to my MacBook and I know the cable isn't broken because I have used it in the recent past. If anyone knows how to fix this problem or has run into this problem in the past, please let me know. Let me know if you'd like anymore information. Thank you!

  [1]: https://www.instructables.com/id/IoT-Motion-Detector-With-NodeMCU-and-BLYNK/
  [2]: https://i.stack.imgur.com/kpQxh.jpg

body:
The MAC / Arduino install instructions appear to be [here][1].

If your Arduino (possibly a NodeMCU 1.0 version board) is using the CP210x chip set there appears to be a download page [here][2].

If your Arduino (possibly a NodeMCU 0.9 version board) is using the ch340g, ch34g or ch34x chip set there appears to be an effort to create a Mac OS X driver [here][3].

The install instructions from that github page are as follows:

> Installation
>
>     Unplug any CH34* devices.
>     Unload the old drivers if running:
>         sudo kextunload /Library/Extensions/usbserial.kext
>         sudo kextunload /System/Library/Extensions/usb.kext
>     Remove the old driver by issuing one of the following commands (depending on your installation):
>         sudo rm -rf /System/Library/Extensions/usb.kext
>         sudo rm -rf /Library/Extensions/usbserial.kext
>     Double-click on the CH34x_Install_V1.5.pkg file and install (no need to reboot)
>     Instead of rebooting, you can force quit Installer after it completes.
>     Load the new driver:
>         sudo kextload /Library/Extensions/usbserial.kext
>     Plug in your device. It should now be listed under the /dev directory. Examples:
>         /dev/cu.wchusbserial1410
>         /dev/tty.wchusbserial14210 (driver version 1.5)

  [1]: https://www.arduino.cc/en/Guide/MacOSX
  [2]: https://www.silabs.com/products/development-tools/software/usb-to-uart-bridge-vcp-drivers
  [3]: https://github.com/adrianmihalko/ch340g-ch34g-ch34x-mac-os-x-driver


message:
Error: exit status 1 stray '#' in program

I got this error:

    exit status 1 stray '#' in program

How can I remove this error..?

    int keys = {1,2,3,A,4,5,6,B,7,8,9,C,*,0,#,D};

body:
There are several -more or less severe- issues in your one line of code

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

( Find the differences :) )

Depending on your usage, you eventually even need a 2-dimensional array

    const char keys[4][4] =  ...


message:
What is the difference between Nano 328p-au and 328p-mu?

Does it have to do with the updated bootloader or is it just a different board design? I want to make sure I order the correct one and I could not find a proper answer so far. Thanks.

body:
The AU and MU on the chip just refer to the shape of the chip. AU is TQFP and MU is VQFN.

You can see the full list of suffixes [here](https://www.microchip.com/wwwproducts/en/ATmega328p) (select the red "Buy Now" tab for a table).


message:
What is the right way to query an I2C device from an interrupt service routine?

The [ADXL345](https://www.analog.com/media/en/technical-documentation/data-sheets/ADXL345.pdf), for example, requires that interrupts are responded to by querying the `INT_SOURCE` (interrupt source) register. In example code for the [SparkFun ADXL345 Arduino Library](https://github.com/sparkfun/SparkFun_ADXL345_Arduino_Library), there is code that looks like:

```lang-arduino
void ADXL_ISR() {
  // getInterruptSource clears all triggered actions after returning value
  // Do not call again until you need to recheck for triggered actions
  byte interrupts = adxl.getInterruptSource();

  // Free Fall Detection
  if(adxl.triggered(interrupts, ADXL345_FREE_FALL)){
```

However, under the covers `adxl.getInterruptSource()` is sending an I2C message and receiving a response. This seems to be a bad idea in an interrupt service routine (ISR).

A possible option seems to be to turn on interrupts prior to calling `adxl.getInterruptSource()`, however there is much advice about not doing this (such as, [Nick Gammon's informative post](http://www.gammon.com.au/interrupts)). I've managed to get it to work with something of the form:

```lang-arduino
void setup() {
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
  ...
}
void isr() {
  detachInterrupt(digitalPinToInterrupt(INT_PIN));
  interrupts();
  byte interrupts = adxl.getInterruptSource();
  ...
  attachInterrupt(digitalPinToInterrupt(INT_PIN), isr, LOW);
}
```
This seems to work but I'm worried I'm missing something. Any suggestions?

EDIT: Thanks for the answers that suggest polling, however I am using a MKR1400 and wish to minimise power consumption by putting the processor into a sleep state - only waking up to process the relatively rare "activity" or "free fall" events. As pointed out by @Majenko, a combination of sleeping and polling might be used. So this really just leaves the question of *why* is the above a bad idea.

body:
Just because a pin is called "interrupt" doesn't mean that you have to read it using an interrupt input.  The INTx pins of the ADXL345 are simple "level" outputs.  All the time there is an "interrupt" pending (a signal from the ADXL345 that something has happened) the corresponding INT pin is held LOW.  It remains LOW until the interrupt has been handled by your code.

It's not something that is very brief - it's something that persists as long as you need it to.

You can just read the INTx pins with normal `digitalRead()` from within your `loop()` function (polling). Unless you *really* need to respond *right now* to an event on the ADXL345 there is no need to use an interrupt input.


body:
"What is the right way to query an I2C device from an interrupt service routine?"

The right way is to **NOT** query an I2C device from in ISR. Interrupt service routines should be **very** fast to execute. (people advise going as far as avoiding `digitalWrite()` and `digitalRead()` function calls and using port registers directly, since those functions are a little slow. Anything done on a serial line is, by definition, not fast. It takes multiple milliseconds to read or write a few characters from a serial port, which is an eternity.)

When the Arduino services an interrupt it stops doing everything else, including handling other interrupts. Your timers will stall, other sensor data will be missed, any other serial communications that are in progress when the interrupt triggers will get errors, etc.

JUST DON'T DO IT.


body:
Majenko's answer is useful — you can simply forego the use of interrupts for this and poll the pin directly in your main loop. Especially on AVR where the external pins are exposed as registers which can be read as fast as main memory this is a reasonable approach. But what if you really want the code to be "interrupt-fast" without writing code that might deadlock an ISR handler? Given the case of a fall or impact sensor, latency might be a genuine issue. Well, there are some things you can do.

First, structure your code so that you never go too long without polling the pin. That means that every bit of code needs to either return to the main loop within an acceptably short period of time, or else needs to take on the job of periodically polling the pin itself. Large compute tasks should have polls sprinkled into them, or be broken into subtasks that can be run by a state machine in the main loop. Long delays should be rewritten in the form

    start = micros();
    while (micros() - start < howLong) {
      // poll the ADXL interrupt
    }

or, again, avoided entirely by queuing up work for the main loop to run later, instead of calling `delay`.

Second, consider using direct port access for the polling. A check like `if (PORTB & (1<<3))` compiles down to a bare couple of instructions, and costs 2 cycles if the interrupt isn't actually asserted (which will be the usual case). Doing `if (digitalRead(port))` does a call to a function which takes around 25 times as long. It's still only a few microseconds, but if you've taken the advice of the previous step to poll as frequently as possible to minimize latency, then you don't want all of those microseconds to add up and impact the performance of other code.

Lastly, a technique that doesn't make a lot of sense for *this* scenario, but could be applicable if you were running on a system other than an AVR-based Arduino, or if you wanted to react to some interrupt *other* than a level-triggered pin interrupt: you have an ISR that doesn't do any real work, but instead sets a global `volatile` variable to true and then immediately returns. Then in your main code, instead of polling the port directly, you check the value of that variable. If it's true, you set it to false and then run your "interrupt handler" code. The handler runs shortly after the interrupt triggers, but it's run in an interrupts-on context where it's safe to do slower operations or operations that require timer interrupts to work. This is equivalent to the old Linux concept of "bottom halves".


message:
Arduino UNO - Fluctuation of inputs and outputs

[![enter image description here][1]][1]

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?

  [1]: https://i.stack.imgur.com/yGlSW.png

body:
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][datasheet] 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.

[datasheet]: http://ww1.microchip.com/downloads/en/DeviceDoc/ATmega48A-PA-88A-PA-168A-PA-328-P-DS-DS40002061A.pdf#G3.1738797


message:
Understanding WiFi.printDiag(Serial)

I am having difficulty with setting up websockets using the Arduino IDE with an ESP8266 https://arduino.stackexchange.com/questions/66704/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

body:
> 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.


message:
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!*

body:
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.


message:
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?

body:
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](https://majenko.co.uk/blog/reading-serial-arduino)
* [The Finite State Machine](https://majenko.co.uk/blog/finite-state-machine)
* [The Evils of Arduino Strings](https://majenko.co.uk/blog/evils-arduino-strings)
* [Splitting Up Text in C](https://majenko.co.uk/blog/splitting-text-c)