message:
How to fade an LED in response to a sensor?

As the sensor "sees" an object nearby, it makes the LED go to full brightness and it remains like that for as long as the sensor keeps on sensing the object. Then, as soon as the sensor stops sensing it, the LED goes OFF instantly... and so on, endlessly. This part of the code works perfectly as it is right now.

MY PROBLEM:

I need all of this ON and OFF switching to happen with smooth PWM fades instead of with abrupt "instant ON" and "instant OFF" changes. I need to have a 1.5 seconds PWM fade-in of the LED from 0% to 100% as soon as the sensor gets activated; and then a 3.5 seconds fade-out as soon as the sensor stops sensing something nearby. As long as the sensor is activated, the LED needs to remain at full brightness. So, simply put: I need the LED to dim smoothly between the sensor's state-changes, instead of changing instantly in an abrupt manner.

body:
Do analogRead(sensor) and check what range of values you are getting. Arduino has 10 bit adc which means you can get 0-1023 in readings. However the sensor might not go complete LOW (0) or complete HIGH (1023). So just measure what's the range you are getting. Assume the range is 125 - 980.

PWM on arduino - This one is 8 bit, which means you can write 0-255. 0 means LED is OFF and 255 means LED is fully ON. Now you need to map 125-980 to 0-255 (as far as I can understand from your comments about synchronizing it with the sensor).

Here is what your code will look like:

    /* Map an analog value (125-980) to 8 bits (0 to 255) */

        void loop()
        {
          int val = analogRead(0); //sensor attached to A0
          val = map(val, 125, 980, 0, 255);
          analogWrite(9, val); //LED attached to D9
        }


sender: user

sender: assistant

body:
This is the typical problem which calls for a [finite state machine][].
You create a “state” variable to keep track of the LED state, which can
be `OFF`, `FADING_IN`, `ON` or `FADING_OUT`. You also need another
variable to remember _when_ you started the fade-in or the fade-out. I
would start the program some declarations like the following:

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

    const uint8_t  LED_PIN       = 3;
    const uint32_t FADE_IN_TIME  = 1500;
    const uint32_t FADE_OUT_TIME = 3500;

    static enum { OFF, FADING_IN, ON, FADING_OUT } led_state;
    static uint32_t fade_start;

Now that you know the LED state, you use it to condition the LED
handling on the current state. For example, the brightness at any given
time can be computed as:

    /* Compute the LED brightness after the given fade time */
    static uint8_t led_brightness(uint32_t fade_time)
    {
        int mapped;
        switch (led_state) {
            case FADING_IN:
                mapped = map(fade_time, 0, FADE_IN_TIME, 0, 255);
                return constrain(mapped, 0, 255);
            case FADING_OUT:
                mapped = map(fade_time, 0, FADE_OUT_TIME, 255, 0);
                return constrain(mapped, 0, 255);
            case ON:
                return 255;
            default:
                return 0;
        }
    }

where `fade_time` would be `millis() - fade_start`. Note the use of the
standard `map()` function to generate a linear ramp, and `constrain()`
to avoid overflowing the range 0 – 255.

Now, switching the LED on or off is just a matter of setting the correct
state... _and_ updating `fade_start` as necessary:

    /* Set the LED pin to HIGH or LOW, through fading. */
    void ledWrite(uint8_t value)
    {
        uint32_t now = millis();
        if (value == HIGH) {
            if (led_state == OFF) {
                fade_start = now;
            }
            else if (led_state == FADING_OUT) {
                fade_start = now - map(now - fade_start,
                        0, FADE_OUT_TIME,
                        FADE_IN_TIME, 0);
            }
            if (led_state != ON)
                led_state = FADING_IN;
        }
        else {
            if (led_state == ON) {
                fade_start = now;
            }
            else if (led_state == FADING_IN) {
                fade_start = now - map(now - fade_start,
                        0, FADE_IN_TIME,
                        FADE_OUT_TIME, 0);
            }
            if (led_state != OFF)
                led_state = FADING_OUT;
        }
    }

A few things worth noting:

* trying to switch the LED on has no effect if it's already on or fading
  in, and trying to switch it off has no effect if it's either off or
  fading out
* if you switch it on while it's fading out, it will move to the state
  `FADING_IN`, and the `fade_start` time will be set to a value that
  ensures continuity of the brightness; same thing when switching from
  `FADING_IN` to `FADING_OUT`.

There is one more thing to do. Your program should periodically update
the LED state, not only to update its brightness, but also to enforce
the transitions `FADING_IN` → `ON` and `FADING_OUT` → `OFF` when needed:

    /* This should be called periodically to update the LED. */
    void update_led()
    {
        uint32_t fade_time = millis() - fade_start;
        if (led_state == FADING_IN && fade_time >= FADE_IN_TIME)
            led_state = ON;
        else if (led_state == FADING_OUT && fade_time >= FADE_OUT_TIME)
            led_state = OFF;
        analogWrite(LED_PIN, led_brightness(fade_time));
    }

With all this in place, you can write the main program just as you did
with no fading, only with the extra call to `update_led()` on every loop
iteration:

    void setup()
    {
        // Initialize the sensor.
        sensor.begin();
    }

    void loop()
    {
        // Set the LED as per the sensor reading.
        if (sensor.detects_object())
            ledWrite(HIGH);
        else
            ledWrite(LOW);

        // Update the LED brightness on every loop iteration.
        update_led();
    }

Oh, and beware not to do anything blocking in `loop()` (e.g., no calls
to `delay()`). Otherwise the LED brightness would be “jumpy”.

[finite state machine]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/


message:
Object Sensor on conveyor belt (want to record the data in EEPROM for testing)

void setup ()
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(LED_Blue_pin, OUTPUT);
    pinMode(LED_White_pin, OUTPUT);

    Serial.begin(9600);
    digitalWrite(LED_Blue_pin, LOW);
    digitalWrite(LED_White_pin, LOW);

    void loop()
    {
        long duration, cm;

        pinMode(trigPin, OUTPUT);
        digitalWrite(trigPin, LOW);
        delayMicroseconds(2);
        digitalWrite(trigPin, HIGH);
        delayMicroseconds(5);
        digitalWrite(trigPin, LOW);

        pinMode(echoPin, INPUT);
        duration = pulseIn(echoPin, HIGH);

        cm = microsecondsToCentimeters(duration);
        long distance = 70 - cm ;

        if (distance < 20) {
            Serial.println("NO ITEM");
            digitalWrite(LED_White_pin, HIGH);
        } else {
            digitalWrite(LED_White_pin, LOW);
        }

        if (distance > 20 && distance < 70) {
            digitalWrite(LED_Blue_pin, HIGH);
            Serial.print("Item : ");
            Serial.print(item++);
            Serial.println(" stk");
        } else {
            digitalWrite(LED_Blue_pin, LOW);
        }

        delay(1500);
    }

    long microsecondsToCentimeters(long microseconds)
    {
        return microseconds / 29 / 2;
    }

The code above is for the Ultrasonic Sensor HC-SR04. The sensor detects items that passes through and counts them along the way. The Blue Led indicates that the sensor detected an item while the White Led detects none. How can I store the data from HC-SR04 to EEPROM? The reason is, I just want to test it out before I sent the data from EEPROM to a database server. I'm still a novice at this.

body:
You can use the [EEPROM.write()][1] function. There is a useful [tutorial][2] on the Arduino site.

The sample code from that tutorial is shown below:

    /*
     * EEPROM Write
     *
     * Stores values read from analog input 0 into the EEPROM.
     * These values will stay in the EEPROM when the board is
     * turned off and may be retrieved later by another sketch.
     */

    #include <EEPROM.h>

    /** the current address in the EEPROM (i.e. which byte we're going to write to next) **/
    int addr = 0;

    void setup() {
      /** Empty setup. **/
    }

    void loop() {
      /***
        Need to divide by 4 because analog inputs range from
        0 to 1023 and each byte of the EEPROM can only hold a
        value from 0 to 255.
      ***/

      int val = analogRead(0) / 4;

      /***
        Write the value to the appropriate byte of the EEPROM.
        these values will remain there when the board is
        turned off.
      ***/

      EEPROM.write(addr, val);

      /***
        Advance to the next address, when at the end restart at the beginning.

        Larger AVR processors have larger EEPROM sizes, E.g:
        - Arduno Duemilanove: 512b EEPROM storage.
        - Arduino Uno:        1kb EEPROM storage.
        - Arduino Mega:       4kb EEPROM storage.

        Rather than hard-coding the length, you should use the pre-provided length function.
        This will make your code portable to all AVR processors.
      ***/
      addr = addr + 1;
      if (addr == EEPROM.length()) {
        addr = 0;
      }

      /***
        As the EEPROM sizes are powers of two, wrapping (preventing overflow) of an
        EEPROM address is also doable by a bitwise and of the length - 1.

        ++addr &= EEPROM.length() - 1;
      ***/

      delay(100);
    }

  [1]: https://www.arduino.cc/en/Reference/EEPROMWrite
  [2]: https://www.arduino.cc/en/Tutorial/EEPROMWrite


message:
What options do I have to get 5v on my current project?

I'm very new to arduino and have started work on my first project, a simple little web server. I'm using a NodeMCU with an sd card module and screen. The issue is that in order to power my sd card module, I need to input 5V which the MCU doesn't provide.

In order to work around this I'm simply using an arduino nano as a power supply to pass into the vin input on the mcu.

What options do I have to exclude the need for the nano? Is there a simple module I can buy that acts as a power supply for 5v?

Any help would be great, thanks!

body:
SD cards require 3.3V. Usually, to connect them to an Arduino running at 5V you need to get a level converter. However in your case it sounds like you are making work for yourself:

    3.3V <--> 5V <--> 3.3V

> in order to power my sd card module, I need to input 5V

**Which** SD card module? Maybe you don't need a "module".


body:
The others write that the card needs 3.3V. Your module need 5V. This means that between the input of the module and the sd card is something. it can be a voltage regulator or something like a voltage dropper (resistor in series with diodes). You can search for it on your module. If you are sure you found it you can solder a bridge around it. After this you can give 3.3V to this module.

I think this must work.


body:
To supplement; if you don’t have a level converter on hand, have a look at this diagram:
http://homediyelectronics.com/projects/arduino/seriallevelconverter/

Just test it on a breadboard, and if Vcc, Rx and Tx are within 10% of 3.3V, solder it to a bit of perfboard. Haven’t needed to build one myself, since these come in tiny SMD packages which cost almost nothing:
https://rover.ebay.com/rover/0/0/0?mpre=https://www.ebay.com/ulk/itm/202151474158

... Are you sure your SD module isn’t 5V tolerant? All mine step down 5V to ~3.3V.


message:
Can't stop my variable value at zero?

In my recent project, I want to set my time according to the requirement. And somehow I'm able to manage that. But when I'm decreasing my time value then one weird problem happens. When decreasing my time value, when I reach ZERO (0) and when I again decrease value then it shows the maximum range of that data type even if I put the condition for stop value at ZERO(0).

My code is below:

    const int kPinSw1 = 2;
    const int kPinSw2 = 3;

    int plusBtnIncState = 0;
    int lastPlusBtnIncState = 0;

    int minusBtnDecState = 0;
    int lastMinusBtnDecState = 0;

    unsigned long currentMillis;
    unsigned long previousMillis;
    unsigned long interval = 0UL;

    void setup() {
      Serial.begin(9600);
      pinMode(kPinSw1, INPUT_PULLUP);
      pinMode(kPinSw2, INPUT_PULLUP);
    }

    void loop() {
      //---------------INC_TIMER---------------//
      plusBtnIncState = digitalRead(kPinSw1);
      if(plusBtnIncState != lastPlusBtnIncState) {
        if(plusBtnIncState == HIGH) {
          interval = interval + 1000;
        }
        delay(50);
      }
      lastPlusBtnIncState = plusBtnIncState;

      //---------------DEC_TIMER---------------//
      minusBtnDecState = digitalRead(kPinSw2);
      if(minusBtnDecState != lastMinusBtnDecState) {
        if(minusBtnDecState == HIGH) {
          interval = interval - 1000;
          if(interval <= 0) {
            interval = 0;
          }
        }
        delay(50);
      }
      lastMinusBtnDecState = minusBtnDecState;

      //---------------------------------------//
      Serial.print("Int:");
      Serial.print(interval);
      Serial.print("\n");
    }

And output:

    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:2000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:1000
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:0
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296
    Int:4294966296

As you can see in output when I reach ZERO and then again decrease the value then the value is like 4294966296 instead of ZERO. I put the logic for that if we reached ZERO or less ZERO then it must stay at ZERO. I don't understand why this happens. Please suggest me something.

body:
The `interval` variable is `unsigned long`.

In this example, we are using `int` that are 4 bits long (just to keep thing short) just to subtract 1 from 0:

        0b0000
       -0b0001
        ------
        0b1111

That is normal arithmetic, but in binary.

The result `0b1111` can read as a signed int, in which case we read the value '-1', or you can read as unsigned, and you read it as '15'.

The same thing is working in your case, only that your `int` are 32 bits long.

The `unsigned` keyword is not a promise that "0-1" will produce "0". It only indicates that whatever bit configuration is inside that variable, it will be treat as a positive value.


body:
The variable "interval" is an unsigned long.  This means it can not go negative.  It also means that it is made up of a 32 bits.

Instead of going negative, an unsigned variable will cycle to its most maximum value by following a modulo 2 math behavior.  So a 32 bit value will become 2^32 or 4294967296 if, for example, decremented 1 past 0.

In the above program the 32 bit value was decremented by 1000 past 0 resulting in 4294967296 - 1000 or 4294966296.

Testing if an unsigned number is negative is futile.  So this code:

      if(interval <= 0)
      {
        interval = 0;
      }

...does nothing.  Instead, test if "interval" is larger than 1000 before subtracting 1000.


body:
As already mentioned in previous answers, the issue is that an unsigned
number wraps modulo MAX+1. The obvious fix would be to make `interval` a
signed number.

Another option would be to avoid subtracting from `interval` anything
larger that `interval` itself. You could do this by replacing

    interval = interval - 1000;
    if(interval <= 0) {
      interval = 0;
    }

by

    if (interval >= 1000)
      interval -= 1000;
    else
      interval = 0;

Note that the `else` clause could be dropped if you can guarantee that
`interval` is always a multiple of 1000.


message:
Digispark ATtiny85 keyboard

I have a small project that I have in mind and I'm pretty new with Arduino.

I want to make a small device that if a key was pressed it would do something.

Now I know I could use a button with the device but I want to specifically use a Cherry MX Blue Switch.

So I wanted to know if the test code I wrote up would get me in the right stating place and I want to know where I would wire the key switch onto the board.

From how I have the code written I'm guessing I connect the positive pin from the switch to P0 on the board and the other pin to ground on the board, is this correct?

    #include "DigiKeyboard.h"

    void setup() {
        pinMode(0, INPUT);
    }

    void loop() {
        // put your main code here, to run repeatedly:
        if(digitalRead(0)==HIGH){
            DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
            DigiKeyboard.print("test");
        }
    }

body:
I would suggest to connect one pin of the with to 5v and the other to ground. The Arduino will be able to detect 5v as logic HIGH.

The code looks correct except for better programming technique I would suggest to indent you code, this make debugging easier for longer programs:

    #include "DigiKeyboard.h"

    void setup() {

       pinMode(0, INPUT);

    }

    void loop() {
      // put your main code here, to run repeatedly:

      if(digitalRead(0)==HIGH){

        DigiKeyboard.sendKeyStroke(MOD_GUI_LEFT,KEY_R);
        DigiKeyboard.print("test");

      }
    }


body:
Do you want the absolute lowest power consumption? If yes then instead of using a microcontroller, use a dual D type latch. The circuit below will take the first break of the optical beam, turn on the output for that latch, and will block the other latch from turning on.

When the clock input goes high (beam broken) the high on the D input is transferred to Q and -Q will go low. That low will force the output of the other latch to stay low.

To reset the light the push button switch is used to clear the Q output. It is then ready again.

I didn't show the power supply (bypass cap). The chip is a CD74HC74. 14 pins containing two latches.The only current drawn is the LED current and the current of the opto-transistors.

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

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


message:
Uploading code to Mega 2560 is stuck

I'm trying to upload code from a Mac (online Arduino editor) onto an Arduino Mega2560, to connect a motor to pin 52 and Ground to get it to move. But at the top it says busy (like it does when it uploads) and doesn't do anything else. Refreshing the page doesn't work. The code is verified, and here's the code:

    void setup() {
    }

    void loop() {
      digitalWrite(52,HIGH);
    }

The Arduino application (with same code copied in) comes up with this error:

    Arduino: 1.8.4 (Mac OS X), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)" Sketch uses 1190 bytes (0%) of program storage space. Maximum is 253952 bytes.
    Global variables use 9 bytes (0%) of dynamic memory, leaving 8183 bytes for local variables. Maximum is 8192 bytes.
    avrdude: ser_open(): can't open device "COM1": No such file or directory
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    ioctl("TIOCMGET"): Inappropriate ioctl for device
    avrdude: ser_send(): write error: Bad file descriptor
    avrdude: stk500_send(): failed to send command to serial port
    avrdude: stk500v2_ReceiveMessage(): timeout
    avrdude: stk500v2_getsync(): timeout communicating with programmer
    the selected serial port avrdude: stk500v2_getsync(): timeout communicating with programmer does not exist or your board is not connected

I hope someone can work out why it doesn't upload!

body:
I would suggest to download the Arduino app (https://www.arduino.cc/en/Main/Software).

Download both the latest version and an a legacy build (https://www.arduino.cc/en/Main/OldSoftwareReleases#00xx). Within the DMG for the legacy you'll need to install the FTDI drivers to allow Arduino app to see the Arduino in ports.


message:
Why is my DS18B20-PAR not picked up?

I have had a DS18B20-PAR for some time and have often used it without a problem until now. Yesterday it just suddenly stopped working. I was trying to use it along with two i2C sensors at the time. I don't really know of anything which could have fried it, though.

**Edit**: It is turning out much more complicated than I thought. I can't ever get it to work on pin 10. The sensor sometimes works on other pins (3, 9 and 11), but it often does not. I can still use pin 10 to blink and fade an LED, and receive input from a button, but it never picks up my DS18B20-PAR. What is happening here?

# My setup:

I have just one DS18B20-PAR connected to my Arduino Uno look-alike as shown in the following image:

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

Please note that on the DS18B20-PAR the third pin is internally not connected.

# The code:

My Arduino is running this code (a OneWire example sketch which has always worked before):

    #include <OneWire.h>

    // OneWire DS18S20, DS18B20, DS1822 Temperature Example
    //
    // http://www.pjrc.com/teensy/td_libs_OneWire.html
    //
    // The DallasTemperature library can do all this work for you!
    // http://milesburton.com/Dallas_Temperature_Control_Library

    OneWire  ds(10);  // on pin 10 (a 4.7K resistor is necessary)

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

    void loop(void) {
      byte i;
      byte present = 0;
      byte type_s;
      byte data[12];
      byte addr[8];
      float celsius, fahrenheit;

      if ( !ds.search(addr)) {
        Serial.println("No more addresses.");
        Serial.println();
        ds.reset_search();
        delay(250);
        return;
      }

      Serial.print("ROM =");
      for( i = 0; i < 8; i++) {
        Serial.write(' ');
        Serial.print(addr[i], HEX);
      }

      if (OneWire::crc8(addr, 7) != addr[7]) {
          Serial.println("CRC is not valid!");
          return;
      }
      Serial.println();

      // the first ROM byte indicates which chip
      switch (addr[0]) {
        case 0x10:
          Serial.println("  Chip = DS18S20");  // or old DS1820
          type_s = 1;
          break;
        case 0x28:
          Serial.println("  Chip = DS18B20");
          type_s = 0;
          break;
        case 0x22:
          Serial.println("  Chip = DS1822");
          type_s = 0;
          break;
        default:
          Serial.println("Device is not a DS18x20 family device.");
          return;
      }

      ds.reset();
      ds.select(addr);
      ds.write(0x44, 1);        // start conversion, with parasite power on at the end

      delay(1000);     // maybe 750ms is enough, maybe not
      // we might do a ds.depower() here, but the reset will take care of it.

      present = ds.reset();
      ds.select(addr);
      ds.write(0xBE);         // Read Scratchpad

      Serial.print("  Data = ");
      Serial.print(present, HEX);
      Serial.print(" ");
      for ( i = 0; i < 9; i++) {           // we need 9 bytes
        data[i] = ds.read();
        Serial.print(data[i], HEX);
        Serial.print(" ");
      }
      Serial.print(" CRC=");
      Serial.print(OneWire::crc8(data, 8), HEX);
      Serial.println();

      // Convert the data to actual temperature
      // because the result is a 16 bit signed integer, it should
      // be stored to an "int16_t" type, which is always 16 bits
      // even when compiled on a 32 bit processor.
      int16_t raw = (data[1] << 8) | data[0];
      if (type_s) {
        raw = raw << 3; // 9 bit resolution default
        if (data[7] == 0x10) {
          // "count remain" gives full 12 bit resolution
          raw = (raw & 0xFFF0) + 12 - data[6];
        }
      } else {
        byte cfg = (data[4] & 0x60);
        // at lower res, the low bits are undefined, so let's zero them
        if (cfg == 0x00) raw = raw & ~7;  // 9 bit resolution, 93.75 ms
        else if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms
        else if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms
        //// default is 12 bit resolution, 750 ms conversion time
      }
      celsius = (float)raw / 16.0;
      fahrenheit = celsius * 1.8 + 32.0;
      Serial.print("  Temperature = ");
      Serial.print(celsius);
      Serial.print(" Celsius, ");
      Serial.print(fahrenheit);
      Serial.println(" Fahrenheit");
    }
On the serial monitor is just prints "No more addresses." every 250 milliseconds.

  [1]: https://i.stack.imgur.com/M98lQ.jpg

body:
If the setup worked fine and then stopped, you must examine what changed. If your code is unchanged then it could be your sensor or your Arduino.

You can try putting the sensor on a different input pin and update the code accordingly.

You can try the sensor on a different Arduino or a new sensor if the same type on your Arduino.

These are the first steps to troubleshooting.


message:
Using a pushbutton to power Arduino on and off

I need help adding a pushbutton to provide power to an Arduino to save power, as I am using a battery and the same button to power it off. This is the circuit I wish to implement.

[![this is the circuit I wish to implement][1]][1]

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

Thanks.

body: You can attach an interrupt and just turn the arduino in sleep mode. If one of your mudules drain power while beeng inactive and drains less than 20mah while working than connect the VCC to one of the digital pins and when the arduino wakes up just turn the pin to HIGH.


body: You can use the button as a switcher for the Arduino power. Just wire up the button between the battery + out and the Arduino's Vin port.


body:
This is a hardware/software "bootstrapping" problem: you need a power switch to be controlled by an Arduino, but the power switch also feeds power to, or turns ON the Arduino, which means the Arduino can't control the power switch until the Arduino is ON, and the Arduino can't be ON until the power switch is ON. Each relies on the other, so you must "bootstrap" it to turn it on and get the cycle started.

The process will look like this: you mechanically press a button with your finger, which controls either the Gate of a MOSFET transistor or the Base of a BJT transistor (or it could even power ON a normally-off relay), momentarily turning it ON. This split-second of ON time is just enough to turn on the Arduino, which now commands a signal to the Gate or Base to keep the transistor ON. Now, the Arduino maintains its own power, continually sending the necessary signal to the transistor to keep the transistor ON, which in turn powers the Arduino to keep the Arduino ON. Now, you can press another button to turn the Arduino OFF. This other button press will be read simply as a button press and the Arduino will then command the digital output pin to stop sending the signal which keeps the transistor ON, thereby turning the transistor OFF, which then turns the Arduino OFF. Now, the whole system is 100% OFF. The Arduino isn't even in sleep mode, it's just 100% not powered anymore. You use your finger press on the ON button again to bootstrap the whole system and start the process over again.

As for all of the details, this is an interesting problem I've been wanting to implement for years. I suspect it could be done with a single button, but haven't gone through the design to prove it yet. Meanwhile, for simplicity's sake, just use two separate buttons: one for ON and one for OFF, as I describe above.


message:
Weird Voltage Noise

I'm new to this forum, so hello to everyone out there.

So I have an Uno with A0 connected to the positive end of a chain of LEDs (they light up when a motion sensor goes off, clunky, but it works), and the negative end is hooked up to the GND of the analog side of the Uno. It runs the following code:

    void setup()
    {
      Serial.begin(115200);
      pinMode(A0, INPUT);
      pinMode(A1, INPUT);
    }

    void loop()
    {

      Serial.println(printVals(A0));
    }

    float printVals(uint8_t pin)
    {
      int sensorValue = analogRead(pin);
      float voltage = sensorValue * (5.00 / 1023.00);
      return voltage;
    }

And when I open the Serial Plotter, I get a weird square wave for the voltage (when there is 0V on the LEDs, I used a volt meter).
Out of curiosity, I added a jumper cable from A2 to +5V (the red wire in the diagram) and added plotting for A2, and this solved the problem - except now, the read on A0 is about 0.53.

Now, I'm more of a software guy, so I figure just subtract 0.53 and move on (varies only +- 0.03V), but I want to know: What in the world did that jumper cable do?![enter image description here](https://i.stack.imgur.com/Bc9XT.png)![enter image description here](https://i.stack.imgur.com/7u1nq.png)![enter image description here](https://i.stack.imgur.com/voQYE.png)

body:
Why are you connecting a chain of leds to a pin setted as an input and then connected to GND? I think that is like connect the pin to nothing.
in the documentation of arduino they have a note about the funcion analogRead() and a fluctuation of data.
https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/
i think if you need to read an input put a button (or maybe i didnt understand you scheme)


body:
@Ferba, my chain of LEDs is actually part of a circuit board for a driveway monitor receiver. When it detects motion, the LEDs light up and the voltage measured by analogRead increases by about a volt.

Also, as it turns out, the jumper to +5v was functioning as a pull-up wire... not a good idea. It burned out the chip in the driveway monitor by backfeeding an output.
In the end, I added an "_PULLUP" after the INPUT in setup and that solved the problem.


message:
Alternative to UART/I2C LCD displays?

I'm building a MIDI synthesizer on Arduino Uno, and am considering user interface options.

I see on Adafruit and Sparkfun there are 16x2 LCD panels available that interface via I2C serial or by UART, but I think neither of those will work in my application:

 * The UART is clocked at 31250 baud to receive MIDI, and that's not a supported baud rate for these LCD devices;

 * I'm producing audio by driving an external DAC (MCP4725) over full-speed I2C; any transmission to another device would audibly jitter the DAC output;

 * SoftwareSerial would get around the UART clocking problem, but I believe it would stall the main loop while driving the output.

One option might be to roll my own software serial routine, carefully clocking it on the main loop, which (I believe) reliably runs at either 14.8KHz or 22.2KHz depending on the DAC protocol in use. I could set a SparkFun SerLCD into a slow data rate (2400 baud) and count passes through the main loop to time the data output.

Another option would be to use a secondary MCU -- I have a surplus Trinket M0 on hand -- and define a custom synchronous serial protocol between the two MCUs, and have the secondary relay commands to the LCD but that's getting into Rube Goldberg territory.

Any obvious options I'm overlooking?

body:
One obvious option would be to get a display with SPI interface, since you have it available. Another option is to get a DAC running on SPI, and use the I2C for the display.

If you insist on using one of these 16x2 LCDs, there are SPI adapters for them as well. [Example](http://bitwizard.nl/shop/LCD-I2C-SPI-Interface-with-16x2-LCD)


message:
How to post JSON data from Arduino?

I want to post data that I'm getting from the sensor every 5 seconds to my application in JSON format. Initially, I'm getting data as int and converting into String.

For example:

if data=15, it is converting into string.

    String st=String(data);

Now I want to post `st` every 5 seconds.

        int S2 = http.sendRequest("PUT", "{\"itemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\",\"item\":{\"Properties\":{\"AssetSensorDistance\":\"+st+\"}},\"operationType\":\"Update\",\"originalItem\":{\"Work_Order\":{\"ItemId\":\"64006A962B71A1E7B3A0428637DA997C.327681\"},\"Properties\":{\"AssetSensorDistance\":\"+st1+\"}}}");
        Serial.print("Sensor Status: ");
        Serial.println(S2);

st1 is the previous value, it is printing httpcode -2(invalid Syntax).

Can anyone help me with this issue?

Thanks in advance.

body:
The string

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

    "{\"AssetSensorDistance\":\"+st+\"}"

contains a literal "+st+". If you want to do string concatenation, you
should terminate the string with a double quote character, then add st,
then use another double quote to start the second part of the string:

    "{\"AssetSensorDistance\":\""+st+"\"}"


message:
LED Programme where it delays the amount written in the Serial Monitor

I have written a simple code to delay the blinking of LED 13, the delay time is set by us.I have incurred a problem when I enter a 2 digit value in the serial monitor.There is some problem with the ASCII. Is there a way to solve this problem without using `Serial.parseInt()`.

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

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Programming is starting");
      pinMode(13,OUTPUT);
    }

    void loop()
    {
      if(Serial.available())
      {
        int val=Serial.read();
        int val1=val-'0';
        Serial.println(val1);
        digitalWrite(13,HIGH);
        delay(val1*1000);
        digitalWrite(13,LOW);
      }
    }

body:
Here you have.

No error checking. Anything not digit produce zero as output.

    void setup()
    {
     Serial.begin(9600);
     Serial.println("Programming is starting");
     pinMode(13,OUTPUT);
    }

    void loop()
    {
     static int value = 0;

     while(Serial.available() > 0) {
      int c = Serial.read();

      if(isDigit(c)) {
       value = value * 10 + (c - '0');
      } else {
       Serial.println(value);
       digitalWrite(13,HIGH);
            delay(value*1000);
       digitalWrite(13,LOW);
                value = 0;
      }
     }

It convert chars to values as they are being readed, one by one. There are no size limit for the input string, other that final value must fit in an `int`

You write a value in the Serial Monitor and end it with return, space bar or whatever non digit key you want.


message:
How to prevent optocoupler to activate when resetting the arduino?

From various example on how to use optocouplers ( eg 4N25)  I gathered that they
work in inverted way meaning that for the optocoupler to output a signal,
the input LED must be OFF.

This is very easy to process by code as I just need to use digitalWrite LOW
instead of digitalWrite HIGH to activate the output of the optocoupler.

My problem is that when I reboot the arduino, the optocupler LED goes OFF and thus activate the ouput of the optocoupler for a few seconds until the code is loaded on the arduino.

How can I prevent this behavior ? Should I connect the optocoupler in a non inverted way ? ( And if so how ? ). Should I use an inverter ?

body:
The Fairchild datasheet for 4N25 shows this diagram:

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

describing the (or 'an') operation of the device. If this is how yours is operating, and if the input side is connected between an output pin and ground, then yes, on reset, the LED will go out and the switched output will go high. If you connect the device's input between the pin and +5v, the LED will light on reset, taking the switched output low. Plus, the switched output will now have the same sense as the Arduino output pin: i.e., `digitalWrite(PIN, HIGH)` will turn the switched output on, and vice-versa.

  [1]: https://i.stack.imgur.com/roj27.jpg


message:
rev id and read_rev_id() function

What is a rev id? I have looked everywhere for a proper definition but I haven't found anything. I am trying to understand the code below. I don't understand why this read_rev_id function is necessary and yes, I tried to look in the user manual for the IMU I am using but it is practically none-existent. I am using the myAHRS IMU and the only manual I could find, on GitHub, didn't even show a register by this name.

    void setup()
    {
      //Initialization
      Wire.begin();
      Serial.begin(115200);
      who_am_i();
      read_rev_id();
      delay(1000); //Wait for 1second.
    }

body:
You haven't provided enough information for anyone to easily help you. Assuming that you took your code from GitHub myAHRS_plus_i2c.ino you can look further down the file to find the definition of **read_rev_id()**. It simply reads the revision number from the AHRS chip and displays it on the console. Since this is all that it does you could leave out the call to read_rev_id(). But if you are going to use it then be aware that it contains an obvious bug. The second **read()** should be to I2C_SLAVE_REG_REV_ID_MINOR.

    //READ REVISION ID
    int read_rev_id()
    {
        uint8_t id_1 = 0;
        uint8_t id_2 = 0;
        read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_1, 1);
        read(I2C_SLAVE_REG_REV_ID_MAJOR, &id_2, 1);
        Serial.print("READ REVISION ID= "); Serial.print(id_1); Serial.println(id_2);
    }


message:
Unable to use Keyboard library with Arduino UNO even after changing the firmware

So I'm trying to use my UNO as an HID device. I followed [this][1] tutorial, flashed the firmware and got the UNO to be detected as an HID device.

[1]:http://www.instructables.com/id/Make-arduino-uno-work-like-leonardo/
However, I am still getting the error
>'Keyboard' not found. Does your sketch include the line '#include <Keyboard.h>'?

Here's the code -

    /*
    Copyright (c) 2014 NicoHood
     See the readme for credit to other people.

     Keyboard example
     Press a button to write some text to your pc.
     See official documentation for more infos
     */

    // include HID library
    #include <HID.h>

    const int pinLed = 13;
    const int pinButton = 8;

    void setup() {
      pinMode(pinLed, OUTPUT);
      pinMode(pinButton, INPUT_PULLUP);

      // Starts Serial at baud 115200 otherwise HID wont work on Uno/Mega.
      // This is not needed for Leonado/(Pro)Micro but make sure to activate desired USB functions in HID.h
      Serial.begin(115200);

      // Sends a clean report to the host. This is important because
      // the 16u2 of the Uno/Mega is not turned off while programming
      // so you want to start with a clean report to avoid strange bugs after reset.
      Keyboard.begin();
    }

    void loop() {
      if (!digitalRead(pinButton)) {
        digitalWrite(pinLed, HIGH);

        // Same use as the official library, pretty much self explaining
        Keyboard.println("This message was sent with my Arduino.");
        Serial.println("Serial port is still working and not glitching out");

        // simple debounce
        delay(300);
        digitalWrite(pinLed, LOW);
      }
    }

    /*
    Definitions:

     KEY_LEFT_CTRL
     KEY_LEFT_SHIFT
     KEY_LEFT_ALT
     KEY_LEFT_GUI
     KEY_RIGHT_CTRL
     KEY_RIGHT_SHIFT
     KEY_RIGHT_ALT
     KEY_RIGHT_GUI

     KEY_UP_ARROW
     KEY_DOWN_ARROW
     KEY_LEFT_ARROW
     KEY_RIGHT_ARROW
     KEY_BACKSPACE
     KEY_TAB
     KEY_RETURN
     KEY_ESC
     KEY_INSERT
     KEY_DELETE
     KEY_PAGE_UP
     KEY_PAGE_DOWN
     KEY_HOME
     KEY_END
     KEY_CAPS_LOCK
     KEY_F1
     KEY_F2
     KEY_F3
     KEY_F4
     KEY_F5
     KEY_F6
     KEY_F7
     KEY_F8
     KEY_F9
     KEY_F10
     KEY_F11
     KEY_F12

     KEY_PRINT
     KEY_SCROLL_LOCK
     KEY_PAUSE
     */

Can anyone point out what I'm doing wrong here?

body: If I open the rar library file, than I see a file called Keyboard.h. I'm sure you need to include Keyboard.h, than the class Keyboard is known and you can use it in your sketch.


body:
Okay, so the problem was that the added HID library was conflicting with the core Keyboard/Mouse library. I replaced the core library with the new one and it worked without any problems.

Well one problem actually, it would ask for a platform.h. To solve this download the Arduino v1.5.7 BETA zip and find the platform.h file in it and paste it in your current Arduino directory.


message:
Make Arduino send and receive at the same time

I am working on a project where I connect a GPS module and GPRS SIM900 shield. The location will be sent when it recives a certain character.

Now my question is, can the Arduino receive from GPRS and GPS module data at the same time? The GPS is not given coordinates, however it works properly without receiving a message from the GPRS.

I am using softwareserial  for both. Should/can I use hardware serial and softwareserial?

body:
Probably you don't need to use both GPS and GPRS in same time. Just check for a certain character from GPRS in the loop and when it comes check the GPS data.

Why not connect GPS module to hardware serial?


body:
> I am using `SoftwareSerial` for both.

As others have said, you cannot listen to 2 `SoftwareSerial` ports at the same time.

>   Should/can I use `HardwareSerial` and `SoftwareSerial`?
>
>  ... can the Arduino receive from GPRS and GPS module data at the same time?

Yes, but...

[This answer](https://arduino.stackexchange.com/questions/34126#34130) provides full details on choosing "good" combinations of hardware and software serial ports.  To summarize:

*  Use the `HardwareSerial` port (i.e., `Serial`) for one of the devices.  You can still use it for debug prints, as long as the device has some kind of command "format".  For example, if commands start with "AT", just make sure that none of your debug prints start with "AT".  It is the absolute best choice.  You would have to disconnect RX pin 0 from the device in order to upload new sketches over USB.

*  Use `AltSoftSerial` for the other device.  It is the most efficient software serial port, and it can be used at the same time as `Serial`.  It only works on two specific pins.

*  `NeoSWSerial` is the next best choice, at limited baud rates.  It can be used with the above choices, but transmitting on `NeoSWSerial` prevents them from receiving.

*  `SoftwareSerial` is the worst choice.  Receiving **or** transmitting on `SoftwareSerial` prevents all of the above from receiving anything.  It disables interrupts for long periods of time.


body: you can connect gps to hardware serial port rx and gsm to software serial.  in similar way,  I solve the problem


message:
Send and receive text between Arduino Mega 2560 and C# via ENC28J60

I'm working on an Arduino project that sends and receives text to/from a C# application via ENC28J60 in a LAN network. Whenever C# sends a request to Arduino (In text), Arduino responds to it by sending also a text. What is the best way to do this? I'm newbie in network programming (Or whatever it's called). Thanls in advance :)

body:
You can use TCP or UDP protocols.

https://www.arduino.cc/en/Tutorial/UDPSendReceiveString

https://www.arduino.cc/en/Tutorial/DhcpChatServer

You can use free UDP, TCP port listener sofwares for Windows, Linux etc.. for testing your setup.

For C# development:

https://stackoverflow.com/questions/20038943/simple-udp-example-to-send-and-receive-data-from-same-socket

and

https://stackoverflow.com/questions/10182751/server-client-send-receive-simple-text


message:
SSID was not declared in this scope

so I am new to arduino and coding in general, I am trying to use the arduino to remotely survey plants, I am using this guide: https://create.arduino.cc/projecthub/arduino/plant-communicator-7ea06f. The entire code is:

    #include <WiFi101.h>
    #include<WiFiSSLClient.h>
    const char* ssid = SKY1C9D0;    //  your network SSID (name)
    const char* password = SYDTSTQR;  // your network password
    String httpsRequest = https://hooks.zapier.com/hooks/catch/2821422/84ehn1/;
    // your Zapier URL
       const char* host = "hooks.zapier.com";
    WiFiSSLClient client;
    void setup() {
      Serial.begin(9600);
      while (!Serial);
      delay(2000);
      Serial.print("Connecting Wifi: ");
      Serial.println(ssid);
      while (WiFi.begin(ssid, password) != WL_CONNECTED) {
        Serial.print(".");
        delay(500);
      }
      Serial.println("");
      Serial.println("WiFi connected");
    }
    void loop() {
      float temperature = 22;
      int moisture = 150;
      int light = 40;
      String warning = "This is a warning message";
      warning.replace(" ", " ");
      send_email(temperature, moistue, light, warning );
      delay(20000)
    }
    void send_email(float temperature, int moisture, int light, String warning)     {
      // convert values to String
      String _temperature = String(temperature);
      String _moisture = String(moisture);
      String _light = String(light);
      String _warning = warning;
      if (client.connect(host, 443)) {
        client.println("POST " + httpsRequest + "temperature=" + _temperature +                 "&moisture=" + _moisture + "&light=" + _light + "&warning=" + _warning + "     HTTP/1.1");
        client.println("Host: " + String(host));
        client.println("Connection: close");
        client.println();
        delay(1000);
        while (client.available()) { // Print on the console the answer of the server
          char c = client.read();
          Serial.write(c);
        }
        client.stop();  // Disconnect from the server
      }
      else {
        Serial.println("Failed to connect to client");
     }
    }

The error is specifically highlighted here:
    `const char* ssid = SECRET_SSID;    //  your network SSID (name)`. The error is that the ssid has not been declared.
I am unsure of what to do to fix this and any other possible errors that have gone unnoticed. I would highly appreciate any help or guidance.
Thank you

body:
You need quotes around literal string values.

    const char* ssid = "SKY1C9D0" ; // your network SSID (name)
    const char* password = "SYDTSTQR" ;


body:
A problem in the include file on the line previous could cause the following line to be misinterpreted. To test that try moving the ssid after the password and see if the error changes. Obviously make sure all strings are properly quoted.

    #include <WiFi101.h>
    #include <WiFiSSLClient.h>

    const char* password = "SYDTSTQR";  // your network password
    const char* ssid = "SKY1C9D0";    //  your network SSID (name)
    String httpsRequest = "https://hooks.zapier.com/hooks/catch/2821422/84ehn1/";


message:
Arduino UNO - analogRead() returning mixed results

I have created a small circuit with a 220 Ohm resistor and a LED connected to PIN9 for power.

I want to measure the Voltage of the current flowing through the circuit. In order to do that I connected a bridge from between the resistor and the LED to the A3 PIN and used this code:

    int ledPin=9;
    int inPin=A3;
    long int in=0;
    float V_in=0;
    int val;

    void setup() {
      analogReference(DEFAULT);
      pinMode(ledPin, OUTPUT);
      pinMode(inPin, INPUT);
      Serial.begin(9600);
      }

      void loop() {
        if (Serial.available() > 0) {
          val = Serial.parseInt();

          if (val>=0 && val<=155) {
            analogWrite(ledPin, val);
            //Serial.println(val);

            for (int i=0; i<10; i++) {
              val+=5;
              analogWrite(ledPin, val);
              //Serial.println(val);

              delay(1000);
              in = analogRead(inPin);
              V_in=float(5.0)*(float(in)/float(1023));
              Serial.println(V_in);
              delay(1000);
              }

            }
            else {
              Serial.println("Dio è morto.");
              }
          }
        }

**The problem is that when I run it, with an Input of 55, I get what seams to be a random arrangement of 0s and 2.56s. While I expect a increasing sequence of numbers between 0 and 2.5.**

**What am I doing wrong?**

I measured the Voltage on the A3 Pin using a voltimeter, and it increases every step by 0.2, exactly as expected.

This is an output example:

[![example][1]][1]

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

body:
The `analogWrite` function, despite its name, outputs PWM (pulse width modulation) which is either fully on or fully off, with varying duty cycles. If you run that through a RC network (eg. 4.7k in series and 10 µF to ground), it will smooth out the pulses and you will actually get a varying voltage.

So in your case you are measuring on or off depending on the timing. However since you are measuring between the resistor and the LED, you won't get 5V because of the voltage drop over the resistor. An LED, depending on the colour, might have a voltage drop of around 2.2V, and thus you might expect 2.8V at that junction. This is approximately what you got.

---

> I want to measure the Voltage of the current ...

This doesn't make any sense electrically. You are either measuring the voltage (in volts) or the current (in amps). You don't measure the "voltage of the current". I suppose you mean "the voltage at that point".

---

### Reference

Arduino functions reference:

[Reference > Language > Functions > Analog io > Analogwrite ](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)


message:
Arduino extended database library data type. Is char str[] in Arduino the equivalent of VARCHAR in SQL?

I am new to Arduino and I am currently working with an Arduino Uno and SD card module - SD/MMC for database storage using the Arduino database library from <https://github.com/jwhiddon/EDB>.

My question is, is the `char str[]` type the equivalent of `VARCHAR`?

Here is my arbitrary record definition for my table:

    struct LogEvent {
      int logId;
      int unumber;
      char username[10];
      char fname[15];
      char lname[15];
      char role[6];
      char boxid[10];
      char userStatus[2];
    } logEvent;

body: If you're referring to the SQL type `VARCHAR`, then, vaguely. `char username[10];` for instance will define a char array of 10 bytes. A `char` being the equivalent of a byte. That's about it for the type. This is C++, so you're pretty close to the iron, and a char array is about as basic as it gets. No collation, no encoding (remember that a character is not always a single byte!), no indexing. Just a bunch of bytes put together.


body:
If you mean, are these equivalent:

    foo VARCHAR(100);

and:

    char foo [100];

No, they are not equivalent, really. In the case of SQL you can put 100 characters into foo. In the case of C++ you would (generally speaking) put up to 99 characters into foo, with the final character being 0x00 which indicates the length of the string.

You could conceivably put 100 characters into `foo` but then you would have to store the size of `foo` in another variable.


message:
ENC28J60 is not getting ping

I bought a new ENC28J60 module and I tried to communicate with the PC through Arduino Uno board.

When I tried to ping the address that I gave in the program it's not getting the ping. Give me some solution.

I used the web server example that is in the example section of Arduino. I even turned off my firewall setting.

The code that I used is:

    /*
      Web Server

     A simple web server that shows the value of the analog input pins.
     using an Arduino Wiznet Ethernet shield.

     Circuit:
     * Ethernet shield attached to pins 10, 11, 12, 13
     * Analog inputs attached to pins A0 through A5 (optional)

     created 18 Dec 2009
     by David A. Mellis
     modified 9 Apr 2012
     by Tom Igoe
     modified 02 Sept 2015
     by Arturo Guadalupi

     */

    #include <SPI.h>
    #include <Ethernet.h>

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 1, 20);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    void setup() {
      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());
    }

    void loop() {
      // listen for incoming clients
      EthernetClient client = server.available();
      if (client) {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        while (client.connected()) {
          if (client.available()) {
            char c = client.read();
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank) {
              // send a standard http response header
              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close");  // the connection will be closed after completion of the response
              client.println("Refresh: 5");  // refresh the page automatically every 5 sec
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("");
              // output the value of each analog input pin
              for (int analogChannel = 0; analogChannel < 6; analogChannel++) {
                int sensorReading = analogRead(analogChannel);
                client.print("analog input ");
                client.print(analogChannel);
                client.print(" is ");
                client.print(sensorReading);
                client.println("
");
              }
              client.println("");
              break;
            }
            if (c == '\n') {
              // you're starting a new line
              currentLineIsBlank = true;
            } else if (c != '\r') {
              // you've gotten a character on the current line
              currentLineIsBlank = false;
            }
          }
        }
        // give the web browser time to receive the data
        delay(1);
        // close the connection:
        client.stop();
        Serial.println("client disconnected");
      }
    }

body:
You have an ENC28J60 based module. Your code is for the Wiznet-based module. The two are not interchangeable.

See this: http://nathanhein.com/2013/02/getting-arduino-online-with-an-enc28j60/

Good luck.


message:
Code that worked in Uno/Nano is not working in Mega - help me port the code to Mega

I used the code from this [project...](https://digibird1.wordpress.com/arduino-as-a-5m-sample-osciloscope/comment-page-1/#comment-354) to build an oscilloscope-like project. It worked fine with Uno and Nano.

Later I tried to do the same with a Mega, but I don't know what's wrong. It's not working! Maybe due to some pin or port number mismatch (I think so...). Because it has some low level code like:

    ------------------------------------------------------
    // set up 8 MHz timer on pin 9
    pinMode (9, OUTPUT);
    // set up Timer 1
    TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
    TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
    OCR1A =  0;       // output every cycle
    ---------------------------------------------------------

And like:

    Data.Values[i]=PINC;

I have very little knowledge about these registers.

Please help me port this code to Mega and make it work...

body:
There is some concept you would have to learn before you can go from Arduino Uno to Mega.
Because your [project][1] is designed to operate on Arduino Uno R3, the registers operations like below are specific to the microcontroller in Arduino Uno - in this case ATmega328P-PU - datasheet [here][2]
`TCCR1A = _BV (COM1A0);  // toggle OC1A on Compare Match
 TCCR1B = _BV(WGM12) | _BV(CS10);   // CTC, no prescaling
 OCR1A =  0;`
You can find description of registers in mentioned datasheet in chapter 19. TC0 - 8-bit Timer/Counter0 with PWM
Now, you grab another datasheet - one which describes ATmega2560 (yes, this is microcontroller which is sitting in Arduino Mega), find corresponding pin (like OC1 in Uno - check the drawing below):
[![Arduino Uno R3][3]][3]
and find proper pin and corresponding register from ATmega2560 [datasheet][4].
Take a look at the schematic picture first, select one of OCx pins and configure what is needed.
Pins from Aruino Mega with OCR functionality:
[![Arduino Mega][5]][5]
and
[![Ard Mega][6]][6]
You need to learn what registers are, and what they can do. Can be a little demanding task, but believe me - this will give you supernatural powers in microcontrollers world ;)

  [1]: https://digibird1.wordpress.com/arduino-as-a-5m-sample-osciloscope/comment-page-1/#comment-354
  [2]: http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42735-8-bit-AVR-Microcontroller-ATmega328-328P_Datasheet.pdf
  [3]: https://i.stack.imgur.com/aOH4g.png
  [4]: http://www.atmel.com/Images/Atmel-2549-8-bit-AVR-Microcontroller-ATmega640-1280-1281-2560-2561_datasheet.pdf
  [5]: https://i.stack.imgur.com/Y84uE.png
  [6]: https://i.stack.imgur.com/KsafT.png


message:
Finding ESP8266 in a network

I am connecting an ESP8266 to my home network (WiFi). After successful connection, an IP is assigned to it. I am sending commands to the ESP8266 from an Android app.

What can I do to find the ESP8266 on any network where my Android app is also connected? I ask this because whenever I change the network, a new IP is assigned to the ESP8266 and I have to manually change the IP in the Android app.

I just need to find the ESP8266 on the network, get its IP address and send commands to it.

Thanks in advance.

body:
Some solutions that have worked for me:

1. **Reserved IP** - use the router's DHCP reservation to give the same ESP the same IP each time.

2. **Static IP** - Set the ESP to use the same IP each time, bypassing the DHCP feature altogether. This also boots the ESP slightly faster. `WiFi.config(ip, gateway, subnet);`

3. **Dump the IP** address to Serial on boot, so that you can at least see what's assigned: `Serial.println(WiFi.localIP());`

4. Give the **STA a unique name** that you can find in the router's DCHP clients page: `WiFi.hostname("look_here");`

5. use **mDNS** to assign a domain-like local URL to the device: `MDNS.begin("esp8266");// default to "http://esp8266.local/"`


body:
The best way to do this if you are doing it for product is using SSDP protocol.
It's Simple service discovery protocol which allows you to search for device in a network. It's implemented in many smart devices now a days with dlna or upnp.

Implement a SSDP server on esp8266 and
Implement a SSDP client on Android device.

You can find many devices with this approach, using simple filter to result with your specific information you want from SSDP packet can allow you to only get desired devices from network.

All the documentation about SSDP is given on Arduino esp8266 GitHub page.

You can broadcast your IP in your SSDP packet and then use it in your app, But still your most imp problem of dynamic IP remains unsolved as your IP will always be changing and using IP for accessing a hardware like home automation is not proper way.

You can either use.
1) Static IP for this if you want offline access or
2) Use cloud based solutions, such as mqtt to access device anywhere without the worries of NAT, IP or anything.

But second option is more of commercial kind, you need multiple resources to implement it.


message:
LED Blinking Using Push button

Whenever I upload the following program I am getting error message
showing "expected initializer before interval".

Kindly Help me to solve out this probleme.

    const byte button=2;
    const byte LED=10;
    bool blinking =false;//defines when blinking should occur
    unsigned long blink Interval=250;// number of milliseconds for blink
    unsigned long currentMillis;// variables to track millis()
    unsigned long previousMillis;
    void setup()
    {
     pinMode(button,INPUT);
     pinMode(LED,OUTPUT);
    }
    void loop()
    {
     // this code  blinks the LED
     if(blinking) {
      currentMillis =millis();// better to store in variable, for less jitter

      if((unsignedlong)(currentMillis-previousMillis) >=blinkInterval) { // enough time passed yet?
       digitalWrite(LED,!digitalRead(LED)); // shortcut to toggle the LED
       previousMillis =currentMillis;// sets the time we wait "from"
      }
     } else {
      digitalWrite(LED,LOW); // force LED off when not blinking
     }

     int reading=digitalRead(button);
     delay(50); // crude de-bouncing

     if(reading==LOW) // buttons with pull-up are pressed when LOW
     { blinking =true; }// start blinking
     else
     { blinking =false; }// stop blinking
    }

body:
It is `blinkInterval`, not `blink Interval`. You have an space in the name in the declaration:

    unsigned long blinkInterval=250; // number of milliseconds for blink
    // ....
 if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {


body:
The fully working sketch

    const byte button=2;
    const byte LED=10;
    bool blinking =false;
    unsigned long blinkInterval=250;
    unsigned long currentMillis;
    unsigned long previousMillis;
    void setup()
    {
        pinMode(button,INPUT);
        pinMode(LED,OUTPUT);
    }
    void loop()
    {

        if(blinking) {
            currentMillis =millis();

            unsigned long blinkInterval=100;
            if((unsigned long)(currentMillis-previousMillis) >= blinkInterval) {
                digitalWrite(LED,!digitalRead(LED)); LED
                previousMillis =currentMillis;
            }
        } else {
            digitalWrite(LED,LOW);
        }

        int reading=digitalRead(button);
        delay(100);

        if(reading==LOW)
        { blinking =true; }
        else
        { blinking =false; }
    }


message:
EEPROM - Arduino

In my recent project, I want to store values permanently. So for that, I want to use the EEPROM. I searched for it and read about it. Now, I have some questions.

Questions:

>1. How many locations are there in the EEPROM? (For Arduino Uno & Mega)
>
>2. I read that an EEPROM has a limit of 100,000 write cycles per
single location. That means if one location is used 100,000 times then
we can use another after that? Or overall the EEPROM has a limit of 100,000 write cycles?
>
>3. So, what about reading the contents of the EEPROM? Does it have the same limit?
>
>4. And what is the starting location (address) of the EEPROM? (For Arduino Uno & Mega)

EDIT:1

> 5. Suppose I store the HIGH value of LED in one location and the LOW value of LED in another one. Then now read the value from that locations. Now how many times I can read this value? So what about write cycle? It just uses for only one time maybe?

Any better option for storing data permanently?

body:
> (1) How many locations are there in EEPROM? (For ARDUINO UNO & MEGA)

Read the datasheet for the chip on the board. It tells you how many bytes or kilobytes the chip has for EEPROM. For instance the ATMega328P on the Uno has 1024 bytes (1k).

> (2) As I read out EEPROM has a limit of 100,000 write cycles per single location. That means If one location is used 100,000 times then we can use another after that? Or Overall EEPROM has a limit of 100,000 write cycle?

Each cell has at least a 100,000 write limit. Or more specifically a 100,000 *erase* limit (since a cell must be erased before writing).

> (3) So, what about reading the content from EEPROM? Has it maybe same limit?

No, no limit - the limit as I mentioned is on erasing: you don't erase when reading.

> (4) And what is starting location(address) of EEPROM? (For ARDUINO UNO & MEGA)

Zero.  It's not really part of any address space, it uses special instructions and registers to get at it.


message:
Arduino HTTP Post request

I have a Arduino Mega with Wiznet 5100 Ethernet shield. Am trying to post some data onto localhost for started later on which will be accepted by a website.
But when I try to post the data I get some error. When I try to send the same data via postman it gets accepted . But when it goes from arduino error occurs.
The arduino Code is as follows:

    client.println("POST /api/trackers/5a28eddaf57a6e2060e85601/solars/5a3bb2adf57a6e1a71ca135b/arduino_data HTTP/1.0");

    client.println("Host: 192.168.6.16");

    client.println("Accept: application/vnd.mirasol.v1");
    Serial.println("After Accept application vnd");

    client.println("User-Agent: Arduino/1.0");
    Serial.println("After User Agent Arduino");

    client.println("Accept: application/json");
    Serial.println("After Accept application json");

    client.println("Content-Length: ");
    Serial.println("After content length");

    client.println(postdata.length());

    client.println("Content-Type: application/json");
    Serial.println("After content type application json");

    client.println("Connection: close");
    Serial.println("After connection close");

    client.println();
    Serial.println("After client println");

    client.println(postdata);
    Serial.println("After post data");
    Serial.println(postdata);

The output in the serial monitor is as follows:

        connecting...
    connected
    After Accept application vnd
    After User Agent Arduino
    After Accept application json
    After content length
    After content type application json
    After connection close
    After client println
    After post data
    {"current":10.50, "voltage":10.50}
    H
    disconnecting.

And the error shown in localhost is as follows:

    2017-12-27 15:21:57 +0530: HTTP parse error, malformed request (): #<Puma::HttpParserError: Invalid HTTP format, parsing fails.>

I have the application in Ruby on Rails with Mongoid as the DB.

FYI: New to coding..

body:
Your problem most likely stems from this bit:

    client.println("Content-Length: ");
    Serial.println("After content length");

    client.println(postdata.length());

You have an extraneous "ln" in there causing the post data length to be on a separate line from the Content-Length:

    Content-Length:
    23

You should change the first `println` to a `print`. Also the order could do with changing to keep things logically grouped:

    client.print("Content-Length: ");
    client.println(postdata.length());

    Serial.println("After content length");

Which would result in:

    Content-Length: 23


message:
Detecting the presence of a specific smartphone

I would like you to give me some clues about a projet I have: I want to make sure that my little brother's smartphone stays in a shelf overnight and during school hours in order to monitor the time he spends with it.

In order to fulfill my needs, I thought of using an Arduino to detect that the smartphone stays in proximity at certain hours.

Since this is my first Arduino project, I'm not quite sure what I could do, and what is possible to do.

Hence I've got a lot of questions:

- Can I easily detect that a specific smartphone is in range?
- Can I use the smartphone's NFC (RFID) to do so?
- What kind of output could I possibly get from an Arduino? I would like to make statistics, so it must be stored somewhere, and I know Arduino doesn't have a lot of memory.
- Is it possible to write on a USB key?
- Which Arduino is best suited for my needs Should I consider buying an Arduino with Ethernet in order to send emails?

Thanks a lot!

body:
> Can I easily detect that a specific smartphone is in proximity ?

It can be done, yes. How "easily" depends on how much money and expertise you have to throw at it.

> Can I use the smartphone's NFC (RFID) to do so ?

It is possible to use that, yes - if you add the right hardware and software to the Arduino.

> How long can an Arduino run on battery using a 9V battery from the market ?

A couple of hours if you're lucky. They are useless batteries.

> What kind of output could I possibly get from an Arduino ? I would like to make statistics, so it must be stored somewhere, and I know Arduino has not a lot of memory.

Whatever you want. Again, it's SMOP / SMOH.

> Is it possible to write on an USB key ?

Sure, if you get the right hardware for that.

> Which Arduino is best suited for my needs ? Should I consider buying an Arduino with Ethernet in order so send email ?

The Arduino that provides the facilities your project requires - and that depends on how you are going to decide on how to do it. Remember: the Arduino is just the "brain" of the operation. You need to decide what "organs" the brain needs to control and in what way.

There's a million and one ways of achieving what you want. You could even do it 100% in the phone in software (there's probably an app for that...) without need of an Arduino...


message:
Supervised inputs for alarm panel

I'm using an Arduino Mega 2560 to make a fire alarm control panel. The control panel takes 50 (inputs) [supervised inputs][1]. The normal way as mentioned in the link is to use the analog inputs, which I am short of. Is there any other way to monitor supervised inputs other than using analog inputs?

Thanks in advance for your time – if I’ve missed out anything, over- or under-emphasized a specific point let me know in the comments.

  [1]: https://resources.altium.com/pcb-design-blog/how-to-implement-supervised-inputs-in-your-pcb-circuit-design

body:
I can think of a number of ways of doing this:

1. **Multiplexing** -- Employ a (large) number of analog MUX chips to expand the number of analog inputs you have available. That would get messy *very* quickly.
2. **External ADC Chips** -- Add more real analog inputs over SPI or I2C. For 50 inputs that would be quite a lot of extra chips.
3. **Use Op-Amps** -- Each input can be [converted into a pair of digital inputs using two op-amps to compare the voltage of the input against two thresholds](http://tinyurl.com/y8oxpzk8), which would give you an "active" and a "fault" signal. That would be 100 digital inputs needed (and 100 op-amps, which could be done with 25 quad op-amp chips).
4. **Distributed processing** -- Don't try and do it all with one device. Split your system into zones with far less inputs then get the zones to communicate with each other.

Of course, you can combine any of those - you could have analog MUX chips fanning out a number of external ADC chips inputs. You could MUX the inputs to the op-amps. You could have external ADC chips on multiple zone systems. Etc.

Personally, on a system of this size, I would certainly consider distributing the inputs across multiple processors even if they are all in the same physical control unit. However, distributing nodes across the building (it sounds like it's quite a large building for 50 inputs) would reduce the amount of cable needed to implement those inputs, and some industry standard bus snaking its way around the building connecting all the nodes up to a master unit would, if implemented correctly, be robust. CAN is a popular protocol for interconnecting control systems (it's used in modern lifts, and those are life critical... you don't want a lift to fail...) so could be a good choice for this.


message:
Can I measure multiple photoresistors from one pin?

I would like to make a laser sensor to detect light coming from a 650nm diode. My current idea would be to use CdS photoresistors/LDRs. I want to measure a few (4-8?) at once, where light falling onto any one of them generates a signal - I don't care from which sensor it actually came. However, I would like to put as many sensors on as few pins as possible.

I've already somewhat figured out that putting LDRs in parallel isn't ideal, because any changes in voltage will become smaller the more I use. Instead, it would seem like a better idea to build some kind of 'switch' by putting each LDR together with a fixed resistor and a transistor. How exactly would a circuit for this look like, or are there better ways to do it?

body:
If response time is critical (on the order of about a quarter of a second) consider using [photo diodes][1] instead of [Cadmium sulfide cells][2].

Also, consider using an Arduino with more ADC ports.  The number of ADC ports is usually a constraint of the processor used.  Different Arduinos use different processors.  Some may have more ADC ports.

Finally, to utilize a single ADC port for multiple unknown resistances, consider using a resistor network where all the unknown resistances and a known pull down resistance are connected to the ADC port. Then, in turn, using as many Arduino digital pins as there are unknown resistance, apply a digital high to only 1 unknown resistance. Keeping the digital pins to all the other unknown resistance in a high impedance state. That is, change them from OUTPUT to INPUT digital ports. Then take an ADC sample. Apply this same procedure for all the other unknown resistances. Consider adding a delay after changing the state of the digital pins to allow for the ADC input to acclimate to the new voltage.

<!-- 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/ZhGHP.png)

<!-- End schematic -->

  [1]: https://en.wikipedia.org/wiki/Photodiode
  [2]: https://en.wikipedia.org/wiki/Photoresistor


body:
I think you can take them paralel to each other and in series with a simple resistor. The point within the series can be used as input voltage. Everytime the input voltage is higher than the reference voltage you can generate an interrupt from the comparator. This means if one of x resistors decreases its value this will affect the upper half resitance. Simply it will decrease the value too. Because of this the input voltage will increase and will be above of the reference voltage. This will produce interrupt (signal).

The Question is how accurate will it work. The resistors are nor 100% accurate because of that the circuit will not work accurate. What can accept? What is OK and what not?


message:
How to loop a specific tone?

I am building a security system, and found the following code

    #define NOOT_B0  31
    #define NOOT_C1  33
    #define NOOT_D1  37
    #define NOOT_E1  41
    #define NOOT_F1  44
    #define NOOT_G1  49
    #define NOOT_A1  55
    #define NOOT_B1  62
    #define NOOT_C2  65
    #define NOOT_D2  73
    #define NOOT_E2  82
    #define NOOT_F2  87
    #define NOOT_G2  98
    #define NOOT_A2  110
    #define NOOT_B2  123
    #define NOOT_C3  131
    #define NOOT_D3  147
    #define NOOT_E3  165
    #define NOOT_F3  175
    #define NOOT_G3  196
    #define NOOT_A3  220
    #define NOOT_B3  247
    #define NOOT_C4  262
    #define NOOT_D4  294
    #define NOOT_E4  330
    #define NOOT_F4  349
    #define NOOT_G4  392
    #define NOOT_A4  440
    #define NOOT_B4  494
    #define NOOT_C5  523
    #define NOOT_D5  587
    #define NOOT_E5  659
    #define NOOT_F5  698
    #define NOOT_G5  784
    #define NOOT_A5  880
    #define NOOT_B5  988
    #define NOOT_C6  1047
    #define NOOT_D6  1175
    #define NOOT_E6  1319
    #define NOOT_F6  1397
    #define NOOT_G6  1568
    #define NOOT_A6  1760
    #define NOOT_B6  1976
    #define NOOT_C7  2093
    #define NOOT_D7  2349
    #define NOOT_E7  2637
    #define NOOT_F7  2794
    #define NOOT_G7  3136
    #define NOOT_A7  3520
    #define NOOT_B7  3951
    #define NOOT_C8  4186
    #define NOOT_D8  4699

     int melody[] = {
    // NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
    NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
    };
    int NOOTDurations[] = {
     4, 4, 4, 4, 4, 4, 4, 4
     };
     void setup() {
        // iterate over the NOOTs of the melody:
      for (int thisNOOT = 0; thisNOOT < 8; thisNOOT++) {

    // to calculate the NOOT duration, take one second divided by the NOOT type.
    //e.g. quarter NOOT = 1000 / 4, eighth NOOT = 1000/8, etc.
    int NOOTDuration = 1000 / NOOTDurations[thisNOOT];
    tone(8, melody[thisNOOT], NOOTDuration);

    // to distinguish the NOOTs, set a minimum time between them.
    // the NOOT's duration + 30% seems to work well:
    int pauseBetweenNOOTs = NOOTDuration * 1.50;
    delay(pauseBetweenNOOTs);
    // stop the tone playing:
    noTone(8);
      }
     }

    void loop() {
    int melody[] = {
     // NOOT_C4, NOOT_G3, NOOT_G3, NOOT_A3, NOOT_G3, 0, NOOT_B3, NOOT_C4
     NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8, NOOT_D8
      };
     int NOOTDurations[] = {
      4, 4, 4, 4, 4, 4, 4, 4
      };

      }
How can i let the specific tone loop? Right now it's not within the loop and i am struggling to make it work in the loop. Thanks in advance!

body:
    #include "Arduino.h"

    const byte TONE_PIN = 4;
    const int ALARM_BEEP_1 = 4186;
    const int ALARM_BEEP_2 = 4699;

    const int ALARM_TONE_LENGTH = 200;
    const int ALARM_TONE_PAUSE = 800;
    const int ALARM_TONE_REPEAT = 6;

    boolean alarm = false;

    void setup()
    {
      alarm = true;
    }

    void loop()
    {
      if (alarm) {
        alarmSound();
      }
    }

    void alarmSound() {
      static unsigned long next = millis();
      static byte count = 0;
      if (millis() > next) {
        next += ALARM_TONE_LENGTH;
        count++;
        if (count == ALARM_TONE_REPEAT) {
          next += ALARM_TONE_PAUSE;
          count = 0;
        }
        tone(TONE_PIN, (count % 2) ? ALARM_BEEP_1 : ALARM_BEEP_2, ALARM_TONE_LENGTH);
      }
    }


message:
Arduino uno PWM CTC mode - strange behaviour on interrupt

i have this simple code that i use for generating a square wave signal of 125 KHz on pin 9 using Timer1 in the "Clear Timer on Compare Match (CTC) Mode".
I also use Timer1 Compare Match A interrupt for toggling pin 7 of PORTD.

    void setup() {
    pinMode(9, OUTPUT);
    pinMode(7, OUTPUT);

    TCNT1 = 0;
    TCCR1A = 0;
    TCCR1B = 0;

    OCR1A = 7;
    TIMSK1 = _BV(OCIE1A);
    TCCR1A = _BV(COM1A0);
    TCCR1B = _BV(CS11) | _BV(WGM12);
    }

    void loop() {
    }

    ISR(TIMER1_COMPA_vect)
    {
      PORTD = PORTD ^ 128;
    }
It happens that

 - The 125KHz waveform on pin 7 is delayed by 1us with respect to the waveform of pin 9. I think that is related to the time that the microcontroller takes to "entering" the interrupt function and toggling the PORTD pin (1us are 16 clock cycle of the 16MHz master clock).

 - Sometimes the waveform on pin 7 (the one generated inside the interrupt service routine) has some "gaps". For example, this is the waveform acquired with my scope:[![enter image description here][1]][1]Why this strange behaviour happens?

  [1]: https://i.stack.imgur.com/YEc5v.png
Thank you

body:
This isn't the only `ISR` in the Arduino, there is at least the one counting `millis`. Counter 0 overflow ISR is not as short as yours, so every `1024us` it'll cause some jitter (or as in your case, skipping the edge and basically inverting the phase). It'd be also several clock cycles delayed (against HW generated signal). Pushing and poping the registers into the stack are the deterministic delays, but the latency between setting the `ISR` flag and calling the `ISR` routine depends on currently executed instruction (some of them takes 2cycles, and there are also longer ones).

There is not much time to do anything else either. Your `ISR` might take less than `20` cycles, but you only have `64` cycles (`ISR` is called at `250kHz` rate so it generates `125kHz` signal).
So if anything else prevents your `ISR` to be called (another `ISR`, disabled interrupts), you can miss them, as there is only one interrupt flag.

If you want the same waveform on pin 7, just use a wire and let the pin mode as `INPUT`.

BTW: You don't have to use `PORTB = PORTB ^ _BV(PB7);`, the `PINB = _BV(PB7)` toggles PB7 without read-modify-write access.


message:
WEMOS: How to install it?

I have been using an Arduino Uno for a year now, and I bought a WEMOS D1 Mini and a NodeMCU. I want to select WEMOS or NodeMCU from the Arduino Web Editor but it doesn't appear on the list:

[![Arduino Editor Board List][1]][1]

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

I think I need to install a driver but it's only for the Arduino desktop editor (not for the web editor).

body:
I just read that it can't. It's a shame:

[https://forum.arduino.cc/index.php?topic=441328.0][1]

  [1]: https://forum.arduino.cc/index.php?topic=441328.0


message:
Arduino Uno: Driving a small LED strip with 2N3904 NPN

I'd like to know why I cannot dim the small LED strip with my design. I can only turn them on and off. This is a problem for me as I wanted to have a fade effect. Here is my circuit:

[![Circuit using fritzing][1]][1]

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

The voltage from the power jack is 5 volts. My NPN transistor is a 2N3904 (from left to right: emitter, base, collector).
For the Arduino I am only using the fade exemple sketch:

    int led = A2; // the PWM pin the LED is attached to
    int brightness = 0; // how bright the LED is
    int fadeAmount = 5; // how many points to fade the LED by

    // the setup routine runs once when you press reset:
    void setup() {
       pinMode(led, OUTPUT);
     }

    // the loop routine runs over and over again forever:
    void loop() {
      // set the brightness of pin 9:
      analogWrite(led, 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 30 milliseconds to see the dimming effect
      delay(30);
    }

By the way, this is my first post so please tell me if something is wrong with it! Thank you for your help!

Have a nice day.

body:
The `analogWrite` works only on `PWM` pins (in your scheme it's marked by ~). On the other pins it's possible to set only `LOW`/`HIGH` (values under `128` are translated to the `LOW`)

Not to mention weirdly used `NPN` with LEDs as negative feedback. But that's why it doesn't burned out yet. The usual way is connect the Emmiter to the ground and base is driven over current limiting resistor (about 1k).
This is how we usualy use `PNP` transistor (again with 1k resistor and emitter to the `Vcc`, not the collector). But `PNP` won't work with `5V` logic and higher `Vin` than `5V` as there will be current flow from `0V` or `5V` to the `Vin`.


message:
How to store values from a sensor inside an empty array?

I need to store the value of the distance in the dist array, then calculate the maximun value and print the index associated with this value:

The problem is when starting the nested for inside another for, the servomotor stops working

    // Includes the Servo library
    #include <Servo.h>

    // Array y valores para funcion valor maximo

    int max=0;

    int angle=0;

    int distance=0;

    // Defines Tirg and Echo pins of the Ultrasonic Sensor

    const int trigPin = 10;

    const int echoPin = 11;

    // Variables for the duration and the distance

    long duration;

    //int distance[180];

    Servo myServo1; // Creates a servo object for controlling the servo motor

    void setup() {

      pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output

      pinMode(echoPin, INPUT); // Sets the echoPin as an Input

      Serial.begin(9600);

      myServo1.attach(12); // Defines on which pin is the servo motor attached
      }

    void loop() {

    distance = calculateDistance();
      if (distance <= 15 && distance >=2)
      {

      // rotates the servo motor from 1 to 179 degrees and calculate the distance at each angle

      for(int j=90;j>=0;j--){

      myServo1.write(j);

      delay(30);}

      for(int j=0;j<=180;j++){

      myServo1.write(j);

      int i=0;

      int  dist [i] = {calculateDistance()};

          for (i=0;i=180;i++){           <--------------------------------------

           if (dist[i]>max){
          max=dist[i];
          angle=i;
          Serial.print(angle);
          delay(30);}

      }
          }

      // Repeats the previous lines from 179 to 90 degrees

    for(int j=180;j>90;j--){

      myServo1.write(j);

      delay(30);

      }
    }
    }

    // Function for calculating the distance measured by the Ultrasonic sensor
    int calculateDistance(){

      digitalWrite(trigPin, LOW);

      delayMicroseconds(2);

      // Sets the trigPin on HIGH state for 10 micro seconds

      digitalWrite(trigPin, HIGH);

      delayMicroseconds(10);

      digitalWrite(trigPin, LOW);

      duration = pulseIn(echoPin, HIGH); // Reads the echoPin, returns the sound wave travel time in microseconds

      distance= duration*0.034/2;

      return distance;

    }

body:
      int i=0;
      int  dist [i] = {
        calculateDistance()      };

I'm not sure what you are thinking here, but you obviously cannot store data into a zero-length array. You also cannot put a function call to populate an array of variable length.

You need to decide how many elements you need in the array, in advance, and allocate an array of that size.

---

Maybe more like this:

     int  dist [180];

      for (i=0;i<180;i++){
        dist [i] = calculateDistance ();
        if (dist[i]>max){
          max=dist[i];
          angle=i;
          Serial.print(angle);
          delay(30);
        }

      }

---

Also, this is wrong in your code:

    for (i=0;i=180;i++){

You need to test for < 180 here. Your `for` loop will **assign** 180 to i and then check to see if it is non-zero, which will always be true.


message:
Pause running program using a pushbutton

I have a program that flashes three LED in sequence indefinitely. How can O program a pushbutton to pause the program in the middle of the code?

Also, can I modify the code so that pressing the button a second time would speed up the flashing of the LED?

Each time I try to use a pushbutton to pause the program, it only pauses it once the program loops back to the beginning.

Here's my code at the moment (sorry, it's not very clean):

    int ledpins[]   = {4, 5, 6};
    int buttonpin   = 3;
    int buttonstate = 0;

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

      for (int pin = 6; pin > 3; pin--) {
        pinMode(ledpins[pin], OUTPUT);
      }
      pinMode(buttonpin, INPUT);
    }

    void loop() {
      buttonstate = digitalRead(buttonpin);
      if (buttonstate == HIGH) {
        digitalWrite(ledpins, HIGH);
      }
      if (buttonstate == LOW) {
        for (int pin = 4; pin < 7; pin++) {
          digitalWrite(pin, HIGH);
          delay(200);
          digitalWrite(pin, LOW);
        }
        for (int pin = 6; pin > 3; pin--) {
          digitalWrite(pin, HIGH);
          delay(200);
          digitalWrite(pin, LOW);
        }
      }
    }

body: The problem in this code is that the for loops are blocking with delay for 1.2 seconds and only once that ends does the code come back around to check the button.  You should instead use the loop function itself to handle the looping and use the Blink Without Delay method of timing to handle the timing.  In that way the loop function is never blocked from running and can run thousands of times per second, never missing any presses of the buttons.  And also in this way you would be able to pause the program at any point, not just once every 1.2 seconds.


message:
Multiple Slaves(Arduino Mega 2560) response over SPI

I have problem creating Setup which have :

1. A SPI Master (Arduino Mega 2560)

2. SPI slaves (Arduino Mega 2560) ,which responds to the Masters request by sending float data (or Rather a 2D float array ,but lets just go step by step).

So,I initially started with 3 Arduinos in total (going step by step):

 - Arduino_1 :Master
 - Arduino_2 :Slave_1
 - Arduino_3 :Slave_2

I used ICSP pins for connection and Digital pin 53 (as mentioned in Nick Gammon's page :http://www.gammon.com.au/spi or https://arduino.stackexchange.com/questions/16348/how-do-you-use-spi-on-an-arduino   ,they are  good resources to start with SPI) and 10 for SS.

MY Master codes looks like:

    #include <SPI.h>
    #define SS_Slave_2 10

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

     pinMode(SS,OUTPUT);
     pinMode(SS_Slave_2,OUTPUT);
     pinMode(MOSI,OUTPUT);
     pinMode(SCK,OUTPUT);

     digitalWrite(SS, HIGH);  // ensure SS stays high for now
     digitalWrite(SS_Slave_2, HIGH);

     digitalWrite(SCK,LOW);
     digitalWrite(MOSI,LOW);

     // Put SCK, MOSI, SS pins into output mode
     // also put SCK, MOSI into LOW state, and SS into HIGH state.
     // Then put SPI hardware into Master mode and turn SPI on
     SPI.begin ();

     // Slow down the master a bit
     SPI.setClockDivider(SPI_CLOCK_DIV8);
    }

    byte transferAndWait (const byte what)
    {
      byte a = SPI.transfer (what);
      delayMicroseconds (100);
      return a;
    }

    union first_union
    {
     float f;
     byte b[4];
    }data;

    float yaw, pitch, roll, alt, temp;
    float yaw_2, pitch_2, roll_2, alt_2, temp_2;

    void loop (void)
    {
     digitalWrite(SS_Slave_2, HIGH);
     digitalWrite(SS, LOW);

     //YAW
     transferAndWait ('Y');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     yaw = data.f;

     //PITCH
     transferAndWait ('P');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     pitch = data.f;

     //ROLL
     transferAndWait ('R');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     roll = data.f;

     //TEMP
     transferAndWait ('T');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     temp = data.f;

     //ALT
     transferAndWait ('A');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     alt = data.f;

     digitalWrite(SS, HIGH);
     digitalWrite(53, HIGH);
     digitalWrite(SS_Slave_2, HIGH);
     Serial.println("Slave_01: Start");
     Serial.print("yaw:");
     Serial.println(yaw, 4);
     Serial.print("pitch: ");
     Serial.println(pitch,4);
     Serial.print("roll:");
     Serial.println(roll,4);
     Serial.print("alt: ");
     Serial.println(alt,4);
     Serial.print("temp: ");
     Serial.println(temp,4);
     Serial.println("Slave_01: End");

     digitalWrite(SS, HIGH);
     digitalWrite(53, HIGH);
     digitalWrite(SS_Slave_2, LOW);

     //YAW
     transferAndWait ('Y');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     yaw_2 = data.f;

     //PITCH
     transferAndWait ('P');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     pitch_2 = data.f;

     //ROLL
     transferAndWait ('R');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     roll_2 = data.f;

     //TEMP
     transferAndWait ('T');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     temp_2 = data.f;

     //ALT
     transferAndWait ('A');
     data.b[0] = transferAndWait ('1');
     data.b[1] = transferAndWait ('2');
     data.b[2] = transferAndWait ('3');
     data.b[3] = transferAndWait ('Z');
     alt_2 = data.f;

     digitalWrite(SS_Slave_2, HIGH);
     digitalWrite(SS, HIGH);
     digitalWrite(53, HIGH);
     Serial.println("Slave_02: Start");
     Serial.print("yaw_2:");
     Serial.println(yaw_2, 4);
     Serial.print("pitch_2: ");
     Serial.println(pitch_2,4);
     Serial.print("roll_2:");
     Serial.println(roll_2,4);
     Serial.print("alt_2: ");
     Serial.println(alt_2,4);
     Serial.print("temp_2: ");
     Serial.println(temp_2,4);
     Serial.println("Slave_02: End");

     delay(500);
    }

And Slave Code goes like:

    #include <SPI.h>

    volatile byte command;
    //Set the default object
    float ypr[3];
    float alt = 0;
    float temp = 0;

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

      // turn on SPI in slave mode
      SPCR |= _BV(SPE);

      // have to send on master in, *slave out*
      pinMode(MISO, OUTPUT);
      pinMode(MOSI,INPUT);
      pinMode(SCK,INPUT);
      pinMode(SS,INPUT);

      // turn on interrupts
      SPCR |= _BV(SPIE);

    }

    union first_union
    {
        float f;
        byte b[4];
     }data;

    ISR (SPI_STC_vect)
    {
      byte c = SPDR;

      command = c;

      switch (command)
      {
       case 'Z':
       data.f = 0;
       SPDR = 0;
       break;
       case 'Y':
       data.f = ypr[0];
       SPDR = data.b[0];
       break;
       case 'P':
       data.f = ypr[2];
       SPDR = data.b[0];
       break;
       case 'R':
       data.f = ypr[1];
       SPDR = data.b[0];
       break;
       case 'A':
       data.f = alt;
       SPDR = data.b[0];
       break;
       case 'T':
       data.f = temp;
       SPDR = data.b[0];
       break;
       case '1':
       SPDR = data.b[1];
       break;
       case '2':
       SPDR = data.b[2];
       break;
       case '3':
       SPDR = data.b[3];
       break;
      }
    }

    void loop()
    {
      Serial.println("loop() starts");
      ypr[0] = -1.1111;
      ypr[1] = -2.2222;
      ypr[2] = -3.3333;

      alt = -4.4444;
      temp = -5.5555;
      Serial.println("loop() ends");
    }

The above codes (Master and Slave) are basically modified and adopted from Joseph Roberts' Question on https://stackoverflow.com/questions/20409799/sending-floats-from-an-arduino-to-another-arduino-over-spi-using-a-union
 , purely for learning purpose only.
(I modified it a bit and now similar codes works well for 1 SPI Master and 1 SPI slave Arduino setup).

//Note:Same Slave code uploaded to both the slaves.

OUTPUT:

    Slave_01: Start
    yaw:-1.1111
    pitch: -3.3333
    roll:-2.2222
    alt: -4.4444
    temp: -5.5555
    Slave_01: End
    Slave_02: Start
    yaw:0.0000
    pitch: 0.0000
    roll:-2.2222
    alt: 0.0000
    temp: 0.0000
    Slave_02: End
    Slave_01: Start
    yaw:-1.1111
    pitch: -3.3333
    roll:-2.2222
    alt: -4.4444
    temp: -5.5555
    Slave_01: End
    Slave_02: Start
    yaw:0.0000
    pitch: 0.0000
    roll:0.0000
    alt: 0.0000
    temp: 0.0000
    Slave_02: End
    Slave_01: Start
    yaw:-1.1111
    pitch: -3.3333
    roll:-2.2222
    alt: -4.4444
    temp: -5.5555
    Slave_01: End
    Slave_02: Start
    yaw:0.0000
    pitch: 0.0000
    roll:0.0000
    alt: ovf
    temp: 0.0000
    Slave_02: End
    Slave_01: Start
    yaw:-1.1111
    pitch: -3.3333
    roll:-2.2222
    alt: -4.4444
    temp: -5.5555
    Slave_01: End
    Slave_02: Start
    yaw:0.0000
    pitch: 0.0000
    roll:0.0000
    alt: 0.0000
    temp: ovf
    Slave_02: End

As we can see from output ,I got output from one of the slave only (Arduino_2:Slave_1) ,the other gave unreliable/garbage output .That is the problem ,I don't get it where the zeros for 2nd Slave comes from ?And how to correct it.Did I missed something ?

Even the page(http://www.gammon.com.au/spi) by Nick Gammon on SPI ,lacks details on Multiple Slave Arduino SPI connection (Although It is really a good place to start with SPI on Arduino, no offense  ).I know my Question is similar to https://arduino.stackexchange.com/questions/9616/slaving-multiple-arduinos-via-spi ,but still the answer there doesn't helps much. I almost spend entire Night searching for the solution.

I even tried things like changing the SS for the Slaves ,but still only   Arduino_2 gave the correct results and Arduino_3 does not.

And yes ,Arduino_3 is not damaged (It works well in 1master_1slave setup). And all the Arduinos has common GND .

Any constructive criticisms are also welcomed.

Warm Regards

SV

body:
I know this item is quite old, and I'm also trying to implement multiple Arduino SPI slaves, and looking at all documentations, my understanding is that the SS is not automatically managed in the slave Arduinos. From that, unsure about the wiring of your 1 master/2 slaves Arduinos that can alter the results as shown above, it looks to me your slave code does not manage the SS from two aspects :

1 - I don't see when you identify in your ISR reception procedure if the applicable slave is enabled ( aren't both modules processing the message all the time in this configuration, I suspect they both do  )

2 - Also about the SS event management in the slave module, pinMode(MISO, OUTPUT); should only be set when SS is low, otherwise you may have faulty signal with two slaves having MISO as outputs. My understanding is that only one slave at a time should have it as an output ( hence my question about wiring )

Hope it helps,


message:
Alternative of relay

I am carrying out a physics experiment using an Arduino. This experiment requires accurate time measurements of upto a millisecond. However I am using a relay to turn on/off an electromagnet and there is a maximum lag of 10ms due to the relay. I am a complete beginner. Please suggest alternative mechanisms to switch the electromagnet and save those precious milliseconds.
P.S. - the magnet is driven by 12V 2.5A DC.

body:
A relay is just an electromagnet, and the same circuit that can drive a relay can drive an electromagnet. You just need to make sure it can handle the power.

The simplest circuit is to use an N-channel 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/su86b.png)

<!-- End schematic -->

Just make sure that the MOSFET can handle the required power dissipation and switches on fully at below 5V on the gate (a gate threshold voltage of less than 3V is ideal).