body:
I was working with Arduino and Xbee with LED, circuit LED  + Servomotor
and doing testing for 5 hours (not continuously).

Then once I omitted the Servomotor circuit and I connected flex sensor, which required connecting 10k Resistor and connect it the laptop as usual, smoke came out of the board (from USB side).  I disconnected it immediately, but now the board doesn't light up and the 5V gives 1.5V.

Is there any chance to fix the board?

I discovered that the B2 diode cracked in the middle, the picture is showing a  good Arduino Nano.

I found a very similar in [this post about dead NANO][2]

[![][1]][1]

  [1]: https://i.stack.imgur.com/GnbJJ.jpg
  [2]: http://forum.arduino.cc/index.php?topic=27931.0

title: smoke came out of Arduino Nano

Answers: 2

body:
The Nano has mainly surface-mounted devices on it. You need to be quite skilled to remove faulty ones and replace them, without special equipment.

By the time you have identified which one needs replacing, removed it (no easy task if it is the processor) and replaced it, it would be easier and probably cheaper to just buy a new board.

You may well have fried the main processor (Atmega328P) which I see with a quick search is selling for around $7 to $8 in one-off quantities, whereas you can buy the entire Nano for around $13 for a genuine one, or around $9 for a clone. It just won't be worth the trouble.

body:
If my understanding is correct, the flex sensor was connected between 5V and GND.
This acted like "short circuit" and should not have burned the AVR, but only the power supply side. If you have a multimeter and some soldering skills it should be possible to fix the board.

Supposing you have an genuine arduino UNO, here is a [schematic][1] but it may not be the right version

 1. Remove the MCU
 2. Check voltage between GND and XUSB is 5V (if not either your USB port is burned or you have a short on the board or a component)
 3. Check voltage between GND and USBVCC is 5V (if not, replace the fuse)
 4. Check voltage between GND and +5V is 5V (if it's still 1.5V as you mentioned, try replacing transistor T1 but I do not understand why it would burn. If it's 5V replace the MCU)

**EDIT for Arduino Nano**

I did not understand you had a nano board ([schematic][2])

The component "B2" you mention is the diode D1 (MBR0520). It burned because of the short circuit you created and nothing else should be defect. It acted like a fuse. Simply replace it and it should be fine.

If you are VERY CAREFULL not to overload the nano with external circuitery and never bring external 5V you could just remove it and make a little solder bridge (waiting for replacement part)

  [1]: https://www.arduino.cc/en/uploads/Main/arduino-uno-schematic.pdf
  [2]: https://www.arduino.cc/en/uploads/Main/ArduinoNano30Schematic.pdf


body:
I am using an Arduino Uno board with IDE 1.6.7.

I have tried to implement a tweaked version of the basic example (`SoftwareSerial` example) from the Software Serial library. The code is attached.

It should blink the light and print the message on the serial monitor. But I am not getting anything.

In fact, I also tried the example as it is. It did not work either.

    #include <SoftwareSerial.h>

    SoftwareSerial mySerial(8, 9); // RX, TX

    void setup() {
        pinMode(13,OUTPUT);
        // 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
        }
        Serial.println("Goodnight moon!");
        // set the data rate for the SoftwareSerial port
        mySerial.begin(9600);
        delay(1000);
    }

    void loop() { // run over and over
        mySerial.println("hell");
        if (mySerial.available() > 0) {
            digitalWrite(13,HIGH);
            Serial.write("working..");
            delay(3000);
            digitalWrite(13,LOW);
            delay(2000);
        }
    }

title: Problem with Software Serial: no response

Answers: 3

body:
>     if(mySerial.available()>0)

`mySerial.available()` returns the number of bytes available in your serial receive buffer. Unless you are sending commands via serial in pins 8 and 9, this will remain 0 and you will never enter the if statement.

Also, you have two declarations for serial here:

1. `Serial.begin()` initialized the built-in UART USB module. Here you will be able to send/receive commands with a program such as Putty.

2. `SoftwareSerial mySerial(8, 9); // RX,`
`mySerial.begin()` initializes serial communications with pins 8 and 9 on the Arduino board. This would be if you wanted to send/receive commands with digital I/O instead of, or in addition to, the UART USB module.

body:
`SoftwareSerial` cannot transmit and receive at the same time.  So even if you connected pin 8 to 9 with a wire, your sketch will not receive what was transmitted.  That's a guess without your wiring diagram.

[NeoSWSerial](https://github.com/SlashDevin/NeoSWSerial) can simultaneously transmit and receive.  It is a drop-in replacement for `SoftwareSerial`.

However, [AltSoftSerial](http://www.pjrc.com/teensy/td_libs_AltSoftSerial.html) is even better, and it only works on pins 8 & 9.  Use that instead!

[This answer](https://arduino.stackexchange.com/questions/26240#26277) compares all 4 serial types, including `HardwareSerial`.

body:
I built two scetch for testing. One for Arduino Nano no1 and another for Arduino Nano no2. They are tested and working, not only written to this page.

No2 is sending "hello" and No1 is listening and sending it to PC via Serial.
The speed (1200bps) is slow, but so it is easier to see what is happening.

Connect Pin10 of no1 to Pin11 of no2 and gnd to gnd.
Connect the Nanos to the USB-ports of the PC and set a monitor program (1200, 8N1) to listen no1.

This seems to be a good way to test Serial.print, Serial.println and Serial.write commands. You will be surprised.

/******No1:*****/

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  Serial.begin(1200);
  Serial.println("Testing");
  mySerial.begin(1200);
}
void loop() { // run over and over
 if (mySerial.available()) //If this is missing, you get fast repeating carpage
{
    Serial.write(mySerial.read());
    Serial.print(".");
 }
}
```

/******No2:*****/

```
#include <SoftwareSerial.h>
 SoftwareSerial mySerial(10, 11); // RX, TX
 void setup(){
  mySerial.begin(1200);
}
void loop(){
    mySerial.print("Hello");
}
```


body:
My Arduino IDE works right out of the box without me having to install any USB to UART drivers. I know the Atmega16U2 on the UNO is acting as UART bridge, but this means that OSX recognizes it on a hardware level, which doesn't make sense since no drivers were installed - unless there is some sort of standard here that the Atmega16U2 implements?

The reason why I ask this is that I have a project where I want to connect an ATMega328p to a client mac which may not have access to 3rd party drivers, so having serial work natively with screen would be ideal. If the Arduino IDE can implement serial monitor without any additional drivers then it means I can too.

Does anyone know how this is implemented?

Thanks!

title: How does Arduino IDE for OSX work without drivers?

Answers: 1

body:
Windows 8.1 is the last version of any common desktop system that requires CDC/ACM (that is what the Arduino's USB port is) drivers.

OS X is based on BSD which, like Linux, has had CDC/ACM drivers built in since (pretty much) the dawn of time. It is only really Windows that has had the concept of drivers for anything that isn't vendor specific and/or complex (such as video cards, or devices that don't adhere to published standards).

Even Windows 10 now has the drivers for CDC/ACM built in (it's only taken Microsoft 20 years or so to catch up with the rest of the OS world).


body:
I tried to make a program that can control a 4 channel relay (with LEDs as indicators) with a serial monitor. First time I tried to program it using a `char` command to make it turn on only, it worked. Then I tried to make it off only, it also worked, but when I tried to combine them, to control it to On or Off in the same program, it didn't work.

this is my code

    #define CH1 2
     #define CH2 3
     #define CH3 4
     #define CH4 5
      void setup(){
     Serial.begin(9600);

    pinMode(CH1, OUTPUT);
    pinMode(CH2, OUTPUT);
    pinMode(CH3, OUTPUT);
    pinMode(CH4, OUTPUT);
    digitalWrite(CH1,HIGH);
    digitalWrite(CH2,HIGH);
    digitalWrite(CH3,HIGH);
    digitalWrite(CH4,HIGH);
     }

     void loop (){
      if (Serial.available()) {

    char ser = Serial.read();

     switch(ser){
     case 'on1':

     onPin1();

     break;

     case 'on2':

     onPin2();

     break;

     case'on3':

     onPin3();

     break;

     case 'on4':

     onPin4();

     break;

     case 'off1':

     offPin1();

     break;

     case 'off2':

     offPin2();

     break;

      case'off3':

     offPin3();

     break;

      case 'off4':

     offPin4();

     break;

       }

     }
     }

     void onPin1(){
        digitalWrite(CH1, LOW);
     }
      void onPin2(){
       digitalWrite(CH2, LOW);
     }
       void onPin3(){
       digitalWrite(CH3, LOW);
     }
      void onPin4(){
       digitalWrite(CH4, LOW);
     }

      void offPin1(){
       digitalWrite(CH1, HIGH);
     }
       void offPin2(){
       digitalWrite(CH2, HIGH);
     }
       void offPin3(){
       digitalWrite(CH3, HIGH);
     }
       void offPin4(){
       digitalWrite(CH4, HIGH);
     }

with that code, I got "duplicate value", maybe because the pin is double-called. But when I tried to make it in separate swicth case condition, no error but couldn't respond to the command `char`

title: Controlling Relay Using Serial Monitor

Answers: 1

body:
This is `C++`, so the single quotes are used for character literals. If you want string literal, you have to use double quotes. However, string literals can't be used in `switch`.

And you can't definitely use it like that if you are reading only one character.

However you can use single characters for this:

    #define CH1 2
    #define CH2 3
    #define CH3 4
    #define CH4 5

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

      pinMode(CH1, OUTPUT);
      pinMode(CH2, OUTPUT);
      pinMode(CH3, OUTPUT);
      pinMode(CH4, OUTPUT);
      digitalWrite(CH1,HIGH);
      digitalWrite(CH2,HIGH);
      digitalWrite(CH3,HIGH);
      digitalWrite(CH4,HIGH);
    }

    void loop (){
      if (Serial.available()) {
        char ser = Serial.read();
        switch(ser){
          case '1':  onPin(CH1); break;
          case '2':  onPin(CH2); break;
          case '3':  onPin(CH3); break;
          case '4':  onPin(CH4); break;
          case '5': offPin(CH1); break;
          case '6': offPin(CH2); break;
          case '7': offPin(CH3); break;
          case '8': offPin(CH4); break;
        }
      }
    }

    void onPin(int8_t pin) {
      digitalWrite(pin, LOW);
    }

    void offPin(int8_t pin) {
      digitalWrite(pin, HIGH);
    }

Or you can toggle the relay states.

Test strings as commands are little bit harder to use as you have to read whole command (or use state machine). Following example is little bit unnecessary hard but it's working...

    constexpr uint8_t     channels = 4;
    constexpr uint8_t ch[channels] = { 2, 3, 4, 5};

    template <uint8_t pin, uint8_t val> void setChan() {
      digitalWrite(pin,val);

      Serial.print("setChan: "); Serial.print(pin);  Serial.print(' ');  Serial.println(val);
    }

    using action_t = void(*)(void);

    action_t  on_actions[channels] = {
      &setChan<ch[0],LOW>,
      &setChan<ch[1],LOW>,
      &setChan<ch[2],LOW>,
      &setChan<ch[3],LOW>
    };

    action_t off_actions[channels] = {
      &setChan<ch[0],HIGH>,
      &setChan<ch[1],HIGH>,
      &setChan<ch[2],HIGH>,
      &setChan<ch[3],HIGH>
    };

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

      for (auto pin : ch) {
        pinMode(pin, OUTPUT);
      }
    }

    String command = "";
    action_t action = nullptr;

    void loop() {
      if (action != nullptr) {
        action();
        action = nullptr;
      }
    }

    void serialEvent() {
      if (Serial.available() > 0) {
        char inChar = (char)Serial.read();
        if ((inChar == '\r' || inChar == '\n')) {
          if (command.length() > 0) {
            Serial.print(command);
            if (command.startsWith("on")) {
              uint8_t channel = command.substring(2).toInt()-1;
              if (channel < channels) {
                action = on_actions[channel];
              }
              Serial.print(" On="); Serial.print(channel+1);
            } else if (command.startsWith("off")) {
              uint8_t channel = command.substring(3).toInt()-1;
              if (channel < channels) {
                action = off_actions[channel];
              }
              Serial.print(" Off="); Serial.print(channel+1);
            }
            Serial.println();
            command = "";
          }
        } else {
          command += inChar;
        }
      }
    }


body:
There is an annoying problem with Linino One / Arduino Yun Mini as the syslog (logread) is full of messages from uSDaemon, complaining about missing files.

**ls: /sys/bus/scsi/drivers/sd/*/block/sd?: No such file or directory

handle umount errors

check umount**

(and so on, three lines every two seconds, so every other meaningful information is pushed out of the syslog pretty soon)

If I disable the uSDaemon with

**/etc/init.d/usd disable
**
the syslog is OK, but is there any functionality actually lost if uSDaemon is not running, beside being unable to read from a non-existing uSD card reader?

title: uSDaemon in Linino / Arduino Yun Mini hogging the syslog

Answers: 0


body:
Arduino Uno R3

Windows 10

Bascom AVR

The ON is alright.

The LED flickers now and then.

The RX and TX flickers when I press the program button on Bascom but then disappears almost immediately.

Hello. I have been having this trouble since yesterday. It always appears whenever I click the program button on Bascom. I feel so stupid having to Restart my PC and checking the Device Manager again and again. I am still new to this.
The COM Port is correct and everything else matches. I do not know how to solve this. Please help, I have already watched tutorials but they all assume you have great background in programming which I don't.

So I hope you can use easy terms.
Thank you.

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

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

title: BASCOM-AVR stk500_2_ReceiveMessage(): timeout: -1

Answers: 2

body:
Have you tried a different USB cable?

I was having trouble flashing and the cable turned out to be the issue.

body:
I know next to nothing about Bascom, but Arduino Uno R3 does not use an STK500v2 bootloader.  It uses one that avrdude refers to as "arduino", basically a modified STK500(v1) protocol.  The arduinoisp.ino sketch also implements stk500v1.  So if you're using UNO "as a programmer", that is with arduinoisp.ino, it would also not be STK500v2.  STK500v2 has been used in some of the larger arduino "Mega" boards.

So if you have a choice of programmer, it would be "arduino" or perhaps "stk500(v1)" at 115200 baud.  If you are choosing an arduino board, it sounds like you have an Arduino Mega type board selected rather than the UNO.  If you are using arduinoisp.ino sketch, it would be stk500v1 at 19200 baud.


body:
I am trying to set up a Huzzah ESP8266 and can not get it to work. I have scoured the internet for help and to no avail. I have the board loaded with a baud rate of 115200 and am transmitting at  80 MHz. When I try and upload the sketch it successfully uploads and after a second or two it sends me this error.

> Sketch uses 222,209 bytes (21%) of program storage space. Maximum is
> 1,044,464 bytes. Global variables use 31,576 bytes (38%) of dynamic
> memory, leaving 50,344 bytes for local variables. Maximum is 81,920
> bytes.
>
> warning: espcomm_sync failed
>
> error: espcomm_open failed
>
> error: espcomm_upload_mem failed
>
> error: espcomm_upload_mem failed

Here is my code:

     void setup() {
    pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    }

    // the loop function runs over and over again forever
     void loop() {
    digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the    voltage level
                                    // but actually the LED is on; this is     because
                                    // it is acive low on the ESP-01)
    delay(1000);                      // Wait for a second
    digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
    delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
    }

Does anyone know what I'm doing wrong or can anyone help me out.

title: Setting up Huzzah ESP8266

Answers: 2

body: When using a serial cable (4 wires, only works on windows), you need to press the 2 buttons in the sequence described here (https://learn.adafruit.com/adafruit-huzzah-esp8266-breakout/using-arduino-ide): gpio0 down, reset down, reset up, gpio0 up. The red led should be dim now. This means the huzzah is ready to bootload.

body:
If you´re working with a development board, they (usually) come with tow buttons: *Reset* and *Flash*. If this is the case **before** start to upload your code you **must** press the *Flash* button, this error is common when the *Flash* button it's not pressed.

If you're working with an ESP8266-01 (this is the "naked" esp8266) you **must** read this tutorials: [GreatScott vid on youtube][1], and for the connections: a good [Hackster.io tutorial][2].

Hope you can make it run!!!

  [1]: https://www.youtube.com/watch?v=9QZkCQSHnko
  [2]: https://www.hackster.io/rayburne/esp8266-01-using-arduino-ide-67a124


body:
I have managed to get my 1602 I2C LCD working on a NodeMCU devkit. I can display text parsed from the web but I am not sure how to set it to autroscroll if message is greater than 16 characters. I tried the `lcd.ScrollDisplayLeft()` but it doesn't work. I figured I would have to do it manually and it is a matter of getting string length and then looping the characters.

This is what I have so far:

 #include <ESP8266WiFi.h>
 #include <Wire.h>  // This library is already built in to the Arduino IDE
 #include <LiquidCrystal_I2C.h> //This library you can add via Include Library > Manage Library >

 LiquidCrystal_I2C lcd(0x3F, 16, 2);

 const char* ssid = "ssid";
 const char* password = "pass";
 const char* host = "api.thingspeak.com";

 int find_text(String needle, String haystack, int from) {
   int foundpos = -1;
   if (haystack.length() < needle.length())
  return foundpos;
   for (int i = from; (i < haystack.length() - needle.length()); i++) {
  if (haystack.substring(i, needle.length() + i) == needle) {
    foundpos = i;
    return foundpos;
  }
   }
   return foundpos;
 }

 void setup() {
   Serial.begin(115200);
   delay(100);
   lcd.init();   // initializing the LCD
   lcd.backlight(); // Enable or Turn On the backlight
   delay(200);

   // We start by connecting to a WiFi network
   Serial.println();
   Serial.println();
   Serial.println(ssid);

   WiFi.begin(ssid, password);
   lcd.setCursor(0, 0);
   Serial.print("Connecting to ");
   lcd.print("Connecting");
   lcd.setCursor(1, 1);
   while (WiFi.status() != WL_CONNECTED) {
  delay(500);
  Serial.print(".");
  lcd.print(".");
   }

   Serial.println("");
   Serial.println("WiFi connected");
   Serial.println("IP address: ");
   Serial.println(WiFi.localIP());
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Connected!!");
   delay(1000);
 }
 int value = 0;

 void loop() {

   Serial.print("connecting to ");
   Serial.println(host);

   // Use WiFiClient class to create TCP connections
   WiFiClient client;
   const int httpPort = 80;
   if (!client.connect(host, httpPort)) {
  Serial.println("connection failed");

   }

   // We now create a URI for the request
   String url = "/apps/thinghttp/send_request?api_key=345345345345345";
   Serial.print("Requesting URL: ");
   Serial.println(url);
   // This will send the request to the server
   client.print(String("GET ") + url + " HTTP/1.1\r\n" +
       "Host: " + host + "\r\n" +
       "Connection: close\r\n\r\n");
   lcd.clear();
   lcd.setCursor(0, 0);
   lcd.print("Fetching Data..");
   delay(10000);

   // Read all the lines of the reply from server and print them to Serial
   while (client.available()) {
  String line = client.readStringUntil('\r');

  int start_loc = find_text("<b>", line, 0);
  int end_loc = find_text("</b>", line, 0);
  if (start_loc > 0 && end_loc > 0)
  {
    lcd.clear();
    Serial.println("data:  ");
    lcd.print("data: ");
    lcd.setCursor(1, 1);
    for (int i = start_loc + 3; i < end_loc; i++)
    {
   Serial.print(line[i]);
   lcd.print(line[i]);
   }

   Serial.println();
   Serial.println("closing connection");
   delay(2000);

 }
   }
 }

title: Arduino Text Scrolling on 16x02 I2c on NodeMcu (ESP8266-12)

Answers: 1

body:
[Inspecting the library code][1], it is apparent that the method called only sets up a command bit field and it is actually the display that performs the operation.

So, you might check if your LCD is capable of performing the scrolling operation.

[This web page][2] contains a tutorial on how to use the scrolling feature.  In this code example from that page:

    void loop() {
      // scroll 13 positions (string length) to the left
      // to move it offscreen left:
      for (int positionCounter = 0; positionCounter < 13; positionCounter++) {
        // scroll one position left:
        lcd.scrollDisplayLeft();
        // wait a bit:
        delay(150);
      }

...you can see that it is not automatic.  That you need to call the method each time you want to scroll (in this case) one position to the left.

  [1]: https://github.com/fdebrabander/Arduino-LiquidCrystal-I2C-library/blob/master/LiquidCrystal_I2C.cpphttp://
  [2]: https://www.arduino.cc/en/Tutorial/LiquidCrystalScroll


body: I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

title: How do I use two PulseIn() functions simultaneously in Arduino?

Answers: 1

body:
You can't. `pulseIn()` is a blocking function that waits for a pulse to arrive before returning.

Instead you will either have to use interrupts or (where available) *Input Capture* peripherals.

**However**, using multiple ultrasonic sensors at the same may not make sense. Unless you take great care with your physical design you will get interference between the two.  Echoes from one bouncing around will trigger the other.  For this reason it is normal to not trigger both at once, but to use them sequentially, in which case `pulseIn()` is still perfectly fine to use.


body:
I recently bought a 5050 RGB 12V 3A LED strip and I set it all up with my Arduino and run this code (from adafruit website), everything is good:
Example Code
Once you have the strip wired up, it is easy to control the color of the strip by using PWM output, for Arduino you can use

    #define REDPIN 5
    #define GREENPIN 6
    #define BLUEPIN 3

    #define FADESPEED 5     // make this higher to slow down

    void setup() {
      pinMode(REDPIN, OUTPUT);
      pinMode(GREENPIN, OUTPUT);
      pinMode(BLUEPIN, OUTPUT);
    }

    void loop() {
      int r, g, b;

      // fade from blue to violet
      for (r = 0; r < 256; r++) {
        analogWrite(REDPIN, r);
        delay(FADESPEED);
      }
      // fade from violet to red
      for (b = 255; b > 0; b--) {
        analogWrite(BLUEPIN, b);
        delay(FADESPEED);
      }
      // fade from red to yellow
      for (g = 0; g < 256; g++) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }
      // fade from yellow to green
      for (r = 255; r > 0; r--) {
        analogWrite(REDPIN, r);
        delay(FADESPEED);
      }
      // fade from green to teal
      for (b = 0; b < 256; b++) {
        analogWrite(BLUEPIN, b);
        delay(FADESPEED);
      }
      // fade from teal to blue
      for (g = 255; g > 0; g--) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }
    }

I tried to find a way to achieve the same effect but only with two colors...red to yellow..red fade to yellow and fade to red and so on..

EDIT:
Thanks to @majenko I achieved this...Fade from Red to Yellow and back on:

  for (int r = 0; r < 256; r++) {
   analogWrite(REDPIN, r);
   analogWrite(GREENPINPIN, 255 - r);
   analogWrite(BLUEPIN, 0);
   delay(FADESPEED);
  }

  // Fade red down and blue up
    for (g = 0; g < 256; g++) {
   analogWrite(REDPIN, 255);
   analogWrite(BLUEPIN, 0);
   analogWrite(GREENPINPIN, G);
   delay(FADESPEED);
    }

title: How to correctly code a LED STRIP?

Answers: 1

body:
The main difference between what you want and what that code does is that you want to fade both colours at once, but that code is aimed at only fading one colour at a time.

You want to fade R up whilst fading B down, and then fade R down whilst fading B up. The simplest way is with just two loops:

    // Fade red up and blue down
    for (int i = 0; i < 256; i++) {
      analogWrite(REDPIN, i);
      analogWrite(BLUEPIN, 255 - i);
      delay(FADESPEED);
    }

    // Fade red down and blue up
    for (int i = 0; i < 256; i++) {
      analogWrite(REDPIN, 255 - i);
      analogWrite(BLUEPIN, i);
      delay(FADESPEED);
    }

One fade value (`i`) per loop, and a little bit of maths to turn 0-255 into 255-0 for the value you are fading down.

----

For Red->Yellow->Red you just need to keep red on and fade green on and off.  You already have code to fade green on and off in your original program:

      // fade from red to yellow
      for (g = 0; g < 256; g++) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }

      // fade from teal to blue
      for (g = 255; g > 0; g--) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }

Couple that with setting the red and blue to on and off respectively, and you have:

    #define REDPIN 5
    #define GREENPIN 6
    #define BLUEPIN 3

    #define FADESPEED 5     // make this higher to slow down

    void setup() {
      pinMode(REDPIN, OUTPUT);
      pinMode(GREENPIN, OUTPUT);
      pinMode(BLUEPIN, OUTPUT);

      analogWrite(REDPIN, 255);
      analogWrite(BLUEPIN, 0);
    }

    void loop() {
      int g;

      // fade from red to yellow
      for (g = 0; g < 256; g++) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }

      // fade from yellow to red
      for (g = 255; g > 0; g--) {
        analogWrite(GREENPIN, g);
        delay(FADESPEED);
      }
    }


body:
I was looking at the [blink without delay sketch][1] and I was trying to modify it so the LED would start blinking after 1000 ms. I changed the `previousMillis` variable to 1000, but the program didn't change. In fact, it doesn't seem to change for any value of `previousMillis`. I thought that this would change the if statement:

`if (currentMillis - previousMillis >= interval)`

because 2000ms would have to pass for `currentMillis - previousMillis` to be equal to 1000ms (`interval`). What am I missing?

  [1]: https://www.arduino.cc/en/Tutorial/BlinkWithoutDelay

title: Start LED blink at certain millis() value

Answers: 0


body:
How can I use MPU-6050 with an arduino to measure the distance the robot traveled from it's starting point or just it's current position on the map?

The Robot should be moving in a map same as a 2D array and I need to detect it's position while it is moving and send the data to a station.

title: MPU6050 Measure distance traveled or position

Answers: 1

body:
You won't - not with any degree of accuracy anyway.

You could attempt "dead reckoning" whereby you estimate the current speed by the acceleration and deceleration over time, and from that get a rough idea about the distance travelled in any one direction, but the accuracy will be so poor and the drift so huge that it would be next to pointless.

Instead you really want to monitor the wheels. Count how many revolutions (or half revolutions, quarter revolutions, whatever accuracy you need) and combine that with the circumference of the wheels to calculate how far you have travelled.


body:
My question is how do I replace the Aarduino Uuno board in this circuit:
[![enter image description here][1]][1]

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

...With an Arduino Yun shield? I can setup the hardware - ICSP configuration is easy enough - but how do I go about using the IDE to do this? Cheers

title: Use Arduino Yun Shield as ISP for bootloaded ATMega328-PU

Answers: 1

body:
It's highly unlikely you will be able to do it from the IDE. Instead you will have to do it from the Yun's command line (SSH) using `avrdude` and the `linuxgpio` driver, or the handy `run-avrdude` script.

    $ sudo run-avrdude bootloader.hex

where `bootloader.hex` is the bootloader file found somewhere in the IDE that you need to copy over to the Yun with `scp`.

You may find you need to tweak the fuse settings in the script to get the bootloader to work. I am not familiar with AVR fuses, but IIRC there is one that tells it to run the bootloader instead of the sketch. Just copy the values out of the boards.txt in the IDE and place them into a copy of `/usr/bin/run-avrdude` in your home directory.


body:
I am using an Arduino Uno as ISP (Using the standard ArduinoISP sketch) to program an ATTiny13A through the Arduino IDE. (I also have a USBtinyISP 2.0 and a USBASP 2.0, but can't reliably get either to program this chip with *any* sketch.)

I want to use all six I/O pins on the ATTiny to each control 1 LED. Pins 0 through 4 work fine, but since pin 5 is the RESET pin, it doesn't want to work as an output normally.

I have read from many sources that I can disable the reset pin by changing the fuse bits, and that once I do so I will not be able to program the chip any more. Every source I've seen has given this warning, but has then proceeded to NOT say *how* to accomplish the 1-time-write.

Assume I've got my sketch exactly 100% as I want it, don't have a high-voltage programmer, and am fine with only being able to program the ATTiny once. How can I program the chip and set the appropriate fuse bits with what I have access to?

title: How do I use ATTiny pin 5 (RESET) as a digital output?

Answers: 1

body: RSTDISBL is bit 0 of the high fuse byte. Use avrdude to read the current value of the high fuse byte (`-U hfuse:r:-:h`), clear bit 0, and then write the value back out (`-U hfuse:w:0xXX:m`).


body: I want to connect multiple Ultrasonic sensors to my Arduino board. For that, I need multiple pulseIn() functions to work at the same time. How can I do that?

title: How do I use two PulseIn() functions simultaneously in Arduino?

Answers: 2

body:
You can't use pulseIn() if you want to use both ultrasonic sensors at the same time.

So either:

 - don't use pulseIn, and instead do that part yourself using
   eg. digitalRead,
 - use the ultrasonic sensors sequentially, one then the other, or
 - use pin-change interrupts to sense the signal pulse return.

The easiest approach is to use the ultrasonic sensors sequentially. In that case use the form `pulseIn(PIN, value, timeout);`, where `timeout`, in microseconds sets the maximum time to wait for a pulse.

This is practical if you know the realistic range is within a couple of metres. The speed of sound is 343.2 metres per second, or 0.3432 metres per millisecond. So if `timeout` is set to 3000 microseconds (3 milliseconds), then it will wait for an echo up to (roughly) 0.5 metres away.

Edit:  The distance to the object, measured by timing the delay, is *half* the total distance travelled because the sound travels to the object, then bounces back to the sensor.
Ie. distance to object = total distance travelled by sound / 2

An alternative is to do what pulseIn does, but for more than one pin.
This is simpler than the real pulseIn code, but illustrates the idea:

    int inPin1 = ...;
    int inPin2 = ...;

    void setup() {
      // ... other stuff, then set up the pins
      pinMode(inPin1, INPUT);
      pinMode(inPin2, INPUT);
    }

    void loop() {
      // start ultrasound 1
      // start ultrasound 2
      // wait for ultrasound 1 to send pulse
      // wait for ultrasound 1 to send pulse
      long startTime = micros();
      while (digitalRead(inPin1)==LOW && digitalRead(inPin1)==LOW) {
        ; // do nothing
      }

      long stop1st = micros();
      int firstBack = -1;
      while (digitalRead(inPin2)==LOW) { // wait for the other if it was 1 first
        firstBack = inPin1; // remember pin 1 returned first
      }
      while (digitalRead(inPin1)==LOW) { // wait for the other if it was 2 first
        firstBack = inPin2; // remember pin 2 returned first
      }
      long stop2nd = micros();

      // now have the two return times, and the pin which returned first
    }

You could read the source of `pulseIn()` and write better code than this.

The third option, to use external or pin-change interrupts, depends on which Arduino you are using. A normal ATmega328 has a couple of pins, 2 and 3, which have their own '*external*' interrupt service routines (ie. each pin has a 'function' which is called when the *hardware* detects a signal change on a pin). To see how to attach them, see [attachInterrupt][1].

Other pins can also be used with a ['pin change' interrupt][2], but each interrupt has to figure out which of a port (up to 8 pins) has triggered it, so it isn't as quick and simple.

The idea here is to start the ultrasonic sensors exactly as before, save the time they are started, exactly as before, but let a short interrupt routine capture the time that the returning echo pulse triggers the pin.

There is a little bit of care in making sure the times are captured and the main loop signalled.

You might choose to dedicate a timer to measuring the ultrasounds round trip, if you want higher resolution and lower jitter than the normal 4 microsecond timer. A microsecond is about 0.34mm, so 4 microsecond is about 1.3mm error.

  [1]: https://www.arduino.cc/en/Reference/AttachInterrupt
  [2]: http://playground.arduino.cc/Main/PinChangeInt

body:
here is how i fixed the problem for my self -5 years later im doing this on my own, running the pulsein code twice within the same loop function WILL NOT WORK, i got around it by adding a second separate part, idk the name if its a function or library...but here is my example code simply creating a distance measuring from 2 different sensors. i hope this help

    const int trigPin =6;
    const int echoPin =5;
    const int trigPin2 = 11;
    const int echoPin2 = 10;

    long duration2;
    long distance2;
    long duration;
    int distance;
    void setup() {
    pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
    pinMode(echoPin, INPUT); // Sets the echoPin as an Input
    pinMode(trigPin2, OUTPUT);
    pinMode(echoPin2, INPUT);
    Serial.begin(9600); // Starts the serial communication
    }
    void loop() {
    digitalWrite(trigPin, LOW);// Clears the trigPin
    delayMicroseconds(2);
    // Sets the trigPin on HIGH state for 10 micro seconds
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance= duration*0.034/2;
    Serial.println(distance2);
    test();
    }

    void test()
    {
    digitalWrite(trigPin2, LOW);// Clears the trigPin
    delayMicroseconds(2);
    digitalWrite(trigPin2, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin2, LOW);
    // Reads the echoPin, returns the sound wave travel time in microseconds
    duration2 = pulseIn(echoPin2, HIGH);
    distance2= duration2*0.034/2;
    }

my code only prints the second sensor distance not both as you can see...not perfect this was a quick sketch i did


body:
I am using Ethernet Shield enc28j60 for retrieve data from web server, but Ethernet Shield enc28j60 hangs after some time and it only works after restarting power supply (router usb port).

My sketch : https://github.com/shyamjos/Arduino_ServerMon

title: Arduino uno - Ethernet Shield enc28j60 hangs after some time

Answers: 2

body:
Are you sure your ethernet connection works? Try to debug with `Serial.println(F("message"))` to find out where it hangs.

I used the same Ethernet Shield and EtherCard library, and I had to change

    if (ether.begin(sizeof Ethernet::buffer, mymac) == 0) {
on line 152 to

    if (ether.begin(sizeof Ethernet::buffer, mymac, 10) == 0) {
because the ENC28j60 uses a different default CS pin (10 instead of 8).

body: I have fixed it myself by increasing `Ethernet::buffer`size, I have also heard that sometimes it is caused due to power issues so providing external 3.3V for enc28j60 may help.


body:
Having my Arduino Nano 328P disconnected from any circuitry and setting all pins to `pinMode(OUTPUT)` and writing `LOW` to (almost) all the pins, when I connect my multimeter to every output pin and the Arduino ground, I measure 0.7 volts on pin 2 and 0.0 volts on 3 to 19. Here I mean the pin numbers on the edge of the Nano, not the processor pins.

For my project it worked out fine because I needed those 0.0 and not the 0.7, but I'm afraid it suddenly might not be pin 2 that's 0.7 in the future and my circuit would fail.

> Why is there this one pin giving 0.7 instead of 0.0 and how can I make sure or argue that it will only be pin 2 that gives 0.7?

EDIT as per request, the full test code is below.

    void setup() {
      for (int i=1;i<20;i++){
      pinMode(i, OUTPUT);
      }
    }

    void loop() {
      for (int i=1;i<20;i++){
        digitalWrite(i, HIGH);
      }
        delay(3000);
        for (int i=1;i<20;i++){
        digitalWrite(i, LOW);
        }
        delay(3000);
    }

title: Measuring .7 volts on pin 2 and 0.0 on the rest when setting all pins low

Answers: 1

body:
For future reference, thanks to Majenko: these values fall within the expected voltage output range of 0-0.9V, and you cannot be certain it will stay this way. See the [datasheet][1] page 313.

  [1]: http://www.atmel.com/images/Atmel-8271-8-bit-AVR-Microcontroller-ATmega48A-48PA-88A-88PA-168A-168PA-328-328P_datasheet_Complete.pdf


body: I want to make a soccer goal counter using Arduino and some sensors. I built using an ultrasonic sensor, but it does not detect if the ball is moving too fast. Are there any other sensors I can use to detect soccer ball?

title: What sensor would work for soccer ball detection efficiently using Arduino?

Answers: 2

body: You should be able to detect an object as large as a soccer ball with an array of modulated IR transmitters and receivers.  However you might want to avoid using IR receivers like the ones found in entertainment equipment.  These have an AGC stage which will, when blocked, turn up the gain until the receiver finds a weak indirect signal.  Instead, try searching using "Long-Range Presence and Proximity Sensors".

body:
This is potentially well beyond the capabilities of a simple MCU like an Arduino UNO. So I think it is very important to clearly define the problem you're trying to solve.

Currently, at top national and international level, video cameras are used to detect a ball crossing the goal line. AFAICT, a lot of the complexity comes from having the goal keeper and several players on the line too. It is important that a player kicking across the goal line is not mistaken for the ball crossing the line. Also, it is important that players bodies can't block the view; a simplistic approach might not be able to see the ball if its kicked between a players legs.

This amounts to (probably) millions of sensors (one per pixel) being monitored at 100+ Hz.

So, I'll assume you *are not* trying to solve such a complex problem. Instead I'll assume you only want to detect a ball crossing the back edge of the goal line, without considering interference by players.

First, let's gather some numbers to describe the core problem.

A [soccer ball/football is at least 68cm in circumference][2], so it is
68/pi = *21.6cm in diameter*, or 0.216m, which is 0.108cm radius.

Then there is the goal. FIFA rules say "[The distance between the posts is 7.32 m (8 yds) and the distance from the lower edge of the crossbar to the ground is 2.44 m (8 ft)][2]"

So a question is, must the system detect the ball crossing the goal line at any place?

A goal is about 34 times wider than the diameter of the ball, and
just over 11 times taller. So, if the sensors were some form of 'light beam' being broken, the 'simplest' system would need more than 11 sensors looking horizontally from one goal post to the other.

How fast might the ball travel through the posts? This says Cristiano Ronaldo was measured [kicking a ball at 130km/hr][3]. That's 36.1m/s.

So the ball is going to take 0.216/36.1 = 0.006 seconds, 6 milliseconds to pass the back edge of the goal line, ie. front edge to back edge will pass a point in 6 milliseconds. This means the sensors must all be scanned, at worst, every 6 milliseconds.

For a sound based system there are more issues.

How much of the ball is 'seen', ie. if only a small fraction of the ball is 'in view' might the returned sound be too small to register with an off-the-shelf ultrasound sensor? For example, if the angle of the reflected sound is too big, ie. from the front or back of the ball, will enough reflected sound return to the sensor to be detected?

Does the ball reflect sound well? It is a membrane at quite a low excess pressure, very different from a solid wall, so I would guess it isn't a perfect sound reflector. I haven't found anything quantifying this, but it seems reasonable to assume off-the-shelf ultrasound sensors might miss the ball under some circumstances.

So it would seem reasonable to assume that two or more sensor readings of the ball would give a significantly more reliable reading than a single sensor reading.

This equates to sampling at least every 3milliseconds. That is a maximum distance of 0.34m * 3/2millisecons (round trip) = 0.5m (approximately).

This might seem to be too much of a restriction. However, the ultrasound sensor only sends a pulse of a few cycles, so it isn't able to detect the ball for the whole of that 3 milliseconds. I haven't found a spec for the off the shelf sensors, but a plausible assumption might be each pulse lasts for about 10 cycles of 40kHz, so the pulse lasts for 0.25 milliseconds. That is the time the ball might travel, about, 1cm. So the angle of reflection would not change much. Hence trying to detect the ball more frequently will increase the quality of at least one signal.

This may explain why the ball is not always detected using ultrasound sensors in your existing approach.

Using any type of sensors to detect the ball, there is a bit of a trade-off. The ball is round, and so if the sensors are almost at the balls diameter apart, then the sensors are going to need to be scanned more quickly to detect a small part of the ball (think of this as a much smaller ball). On the other hand, if the sensors are much closer so at least one gets a longer 'view' of the ball, then one is going to see something closer to the diameter of the ball, hence see it for longer, and so they could be scanned more slowly.

This adds up to a similar outcome. Increase the number of sensors so one sees the ball for a reasonable length of time, or scan the sensors much faster to have a reasonable chance of a measurement.

A 'classic' way to detect something crossing a plane (a door way or in this case the goal mouth) is with a set of laser beams (think Mission Impossible, Entrapment, etc.).

So, consider eye-safe visible-light laser pointers? They **must** be eye safe, which AFAIK largely implies visible light lasers as eye-safe partly depends on the eyes 'blink response'.

At the width of a goal, the laser will have spread to several cm, but should still be straightforward to detect. With some care, it might be feasible to use mirrors to reflect a beam back towards the goal post carrying the laser, halving the number of lasers, and keeping all of the wiring on one side. I don't know how many reflections might work, but it is worth experimenting as every reflection reduces the number of lasers and sensors.

One advantage of an optical approach vs sound is the goal mouth could easily be monitored at a much higher rate than the ball could possibly pass.

To discriminate between sunlight, stadium or street lights, or other sources of light, the lasers would be modulated. 5kHz is a common figure, this is well away from mains frequency. The signal should be 'low' when the laser is off, and 'high' when the laser is on. If that isn't the case, then their is signal interference, and it isn't going to work.

With a little bit of electronics at the sensors, the signals may be purely digital, so there would be no reliance on the Arduino's slow ADC; the sensors could be scanned with digital GPIO pins, with, say, all 11 sensors being scanned at 10kHz.

You may be able to achieve a similar effect using narrow angle, high-power LEDs, lenses and tubes. A reasonable lens system should be able to focus LEDs over 7.32m of the goal mouth. However, I think eye-safe laser pointers would work with simpler optics, and the mechanics and optical systems are often harder to make robust than the electronics.

**Summary**:
A 'raster' of eye-safe, visible-light lasers, at approximately 10cm apart, maybe with mirrors to significantly reduce the number of lasers and sensors, directed horizontally across the goal mouth, could detect a ball passing.

However, it would be confused by players across the goal line.

  [1]: http://www.soccerballworld.com/Laws.htm
  [2]: http://www.fifa.com/mm/document/footballdevelopment/refereeing/81/42/36/log2013en_neutral.pdf
  [3]: http://www.nytimes.com/2011/09/14/sports/soccer/14iht-soccer14.html?_r=0


body:
Can anyone help me to build a code which will activate a LED after 2 minutes when the power supply is cut off and blink that LED after a time interval of 30 seconds.
I want to import the code on Arduino-Uno.

I will power the Arduino with cell and assign two pins as sensor if they are connected to each other than every this is fine if they are cut the Arduino will blink the LED after 2 minutes and will keep blinking at 30 seconds interval

title: Code for activating a led after 2 minutes and will blink after 30 seconds interval

Answers: 4

body:
Use a [commonly available USB power pack][1] re-charging from mains and powering the Arduino.  Use a light source directly powered by main and optically couple that to an Arduino.  There are plenty of [examples][2] on the web where an Arduino is used to detect light.  Once triggered, write some additional code to [blink the led][3].  Since you are not doing anything other than timing, you can use the [delay Arduino library][4] to time events.

  [1]: http://lmgtfy.com/?q=usb power pack
  [2]: http://arduinobasics.blogspot.com/2011/06/arduino-uno-photocell-sensing-light.html
  [3]: https://www.arduino.cc/en/tutorial/blink
  [4]: https://www.arduino.cc/en/Reference/Delay

body:
The Blink example will tell you how to blink an LED, you just need to change the times in the delay statements.

You want to detect the failure of a power supply.  You Arduino has a backup battery (cell) to power it when the power fails.  Correct?

There are voltage sensor kits available that can monitor mains voltage, just search for "Arduino Voltage sensor".  However there is a risk to you working with main voltages.  So using optical isolation (as ST2000 says) is probably safer for you.  There may be some optical isolator IC that can manage mains and 5V, they are usually white in colour.

body:
I have a code edited by me

    int pinButton = 8; //the pin where we connect the button
    int LED = 2; //the pin we connect the LED

    void setup() {
     pinMode(pinButton, INPUT); //set the button pin as INPUT
     pinMode(LED, OUTPUT); //set the LED pin as OUTPUT
    }

    void loop() {
     start:delay(120000);
     check:int stateButton = digitalRead(pinButton); //read the state of the button
     if(stateButton == 0) { //if not pressed

       digitalWrite(LED, HIGH);
       delay(250);
       digitalWrite(LED, LOW);
       delay(30000);
       goto check;
     }
     else { //if  pressed
      digitalWrite(LED, LOW);
      goto start;
     }
    }

body:
DISCLAIMER: This is just a suggestion. No hate for this anwser please.

You could use a capacitor. A super capacitor (high capacity) with a proper joule theft circuit for your project could power the arduino for propably another 5min even if main power is cut off, plus you do not need any extra power source once the main source is cut off. It can be useful if you need to change the battery or move it to an other location but you do not want the module to be turned off.

    const int led = 13;    //led pin
    const int sensor = A0; //connect this your power supply, use a voltage divider if necessary
                           //this will act like a volt meter

    void setup()
    {
      pinMode(led, OUTPUT);
      pinMode(sensor, INPUT);
    }

    void loop()
    {
      int V = analogRead(sensor);
      V = map(V,0,1023,0,5); // the 5 is replaced with the ammount of voltage that you supply the arduino

      if(V < 1) // when the power is below a point or simply disconnected, the capacitor
                //will kick in by itself because the Arduino will draw its power
        {
        delay(120000)
        while(V < 1)
        {
          V = analogRead(sensor);
          V = map(V,0,1023,0,5);

          digitalWrite(led, HIGH);
          delay(500);
          digitalWrite(led, LOW);
          delay(29500);
        }
      }
    }


body:
I want to make a USB gamepad, and I've heard that an Arduino would be great for this kind of project. But before I start to work on it, I want to make sure I understand some things. Here are my basic diagrams of what the project will look like during prototyping and *after* prototyping:

![Prototype](https://i.stack.imgur.com/pwNuJ.gif)

----------------------------------------------------------------

!["Final" Circuit](https://i.stack.imgur.com/ers8z.gif)

Do the diagrams look right? Am I understanding the process correctly? For me to properly build a final circuit, I would have to emulate all the necessary (the most important one being the USB) circuitry that an Arduino has around it's microprocessor.

And my final question is, how would I load my program on to the microprocessor (with and without the "Arduino-like" USB circuitry)?

title: What to do after prototyping?

Answers: 1

body:
Yes, your thinking is pretty much correct.

You can place an ATMega32U4 chip and the associated required circuitry within your own circuit design. The required circuitry is actually quite simple - a crystal for the CPU clock, a few capacitors (load capacitors for the crystal, and decoupling), two 22Ω termination resistors for the USB bus, and a 10KΩ pullup on the reset pin. That's about it (besides power of course).

As far as programming goes, you can either install a bootloader (butterfly - like the Leonardo etc) that works through the USB, or you can directly program the chip using ICSP. It's best to provide an ICSP header anyway (it's the SPI pins plus RESET basically), and if you have done that (which you'd need really to be able to get a bootloader on there) then you may as will skip the bootloader entirely and just program direct through the ICSP header. Of course, you'll need some kind of programmer (an Arduino can do the job at a pinch, but it's worth spending the $10 to get a cheap AVR programmer from eBay).


body:
I have a kit of 37 sensors as described here:

* http://www.instructables.com/id/Arduino-37-in-1-Sensors-Kit-Explained/?ALLSTEPS
* https://tkkrlab.nl/wiki/Arduino_37_sensors

I want to create a simple circuit:

* if the light is detected - flash LED
* if there is no light - do nothing

Among 37 sensors I don't seem to find anything related to light / brightness / lumens...

**Can you please advise me which sensor to get?**

---

Shall I get a photocell  (Light Dependent Resistor) as described here: https://learn.adafruit.com/adafruit-arduino-lesson-9-sensing-light/parts ?

title: Which sensor to detect light?

Answers: 4

body:
Number 23 in the list says _photoresistor_, corresponding to module KY-018 in your kit, which is what you called _photocell_ (a photocell is another type of sensor to my knowledge).
As the name states, a photoresistor is a device changing it's resistance depending on the amount of light it detects/receive.

A photoresistor usually looks like:
[![enter image description here][1]][1]

In order to get a meaningful reading from an LDR you need to convert the resistance into a voltage which the Arduino's ADC can read. The simplest method is to use a [voltage divider][2]: the junction between the LDR (photoresistor) and R1 is the node to connect your analog pin to get your readings, which will be a voltage that is a proportion of the supply voltage (5V) defined by the ratio of the two resistances.

The KY-018 module mentioned above already provides all the necessary and provides you 3 pins: `5V`, `ANALOG` and `GND`.

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

<!-- End schematic -->

  [1]: https://i.stack.imgur.com/N6rE7.jpg
  [2]: http://learn.sparkfun.com/tutorials/voltage-dividers

body:
You are after the "KY-018 Photo resistor module". It is number #23 "Photoresistor" on the instructables.com webpage.

[![KY-018 Photo resistor module][1]][1]

The module contains a Light Dependant Resistor (LDR).

More information on the module can be found at https://tkkrlab.nl/wiki/Arduino_KY-018_Photo_resistor_module.

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

body:
Use a photoresistor aka photocell. They are variable resistors that change there values depending on the intensity of the light source.

It is sensor KY-018 : KY-018 Photo resistor module.

Here is a helpful code:

    const int sensor = A0; //declare photocell pin
    const int led = 13;

    void setup()
    {
      pinMode(sensor, INPUT);
      pinMode(led, OUTPUT);
    }

    void loop()
    {
      int val = analogRead(sensor);
      if(val > 512)
      {
        digitalWrite(led, HIGH);
        delay(500);
        digitalWrite(led, LOW);
        delay(500);
      }
    }

body:
No,  I would suggest you not bother with photocell, phototransisters nor light-dependent resistors.

Better answer is the 1750 light-detection and measurement module.

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

It connects by I2C and reads out a numeric value corresponding to the amount of light (Lux) it senses.

Very easy to set up.

I use one to measure the light of the sky so I can compare it to the output of my solar cells.

Here is a cool light meter project (complete with hookup instructions and code) that uses one to sense light and displays the results on a 7-segment display:

[BUILDING A SIMPLE DIGITAL LIGHT METER USING ARDUINO AND BH1750FVI SENSOR][2][![enter image description here][3]][3]

  [1]: https://i.stack.imgur.com/nwb5x.jpg
  [2]: http://embedded-lab.com/blog/building-a-simple-digital-light-meter-using-arduino-and-bh1750fvi-sensor/
  [3]: https://i.stack.imgur.com/NvK7X.jpg


body: I am using Arduino UNO/ MEGA to read the incremental encoder pulses (Baumer encoder EIL580). Currently, I am using it in single-ended mode (reading A,B and Z outputs) as I am not sure how to read the differential signal in Arduino (A, Ainv, B, Binv, Z, Zinv) as it would improve the reliability of the data. Is there any addon shield or circuitry to interface this signal with Arduino?

title: How to read differential TTL signal from encoder using Arduino?

Answers: 1

body:
It looks to me like something similar to RS485 (I have a page about that [here](http://www.gammon.com.au/forum/?id=11428)).

You could use a chip like the LTC1480 to take the A+ and A- inputs and convert them to TTL levels.

I haven't tried it with your encoder but in principle it should work. (You would need two chips if you want to handle A+/A- and B+/B-. Or three if you want to handle R+/R- as well). Still, it's about a $6 chip.


body:
I'm working with Arduino boards with AVR C coding to perform simple SPI communication from master for simple blink application on slave side.

They don't work, the TX function on the master side doesn't seem to work, after serial monitor debugging is discovered the function never get over the while loop! Why is that?

Here are the codes I worked on last night:

Master:

    /* nano board is the Master and transmit
      data to slave to blink LEDs */

    void SPI_Init(void);
    void SPI_TX(uint8_t data);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);//start Serial
      Serial.println("Setting Up");
      void SPI_Init();
      delay(100);
      Serial.println("SPI intialization is complete");
    }

    void loop() {
      uint8_t d = 0x20;
      SPI_TX(d);
      Serial.println("just sent the 1st byte");
      _delay_ms(400);
      d = 01;
      SPI_TX(d);
      Serial.println("just sent the 2nd byte");
      _delay_ms(400);
    }

    void SPI_Init(void)
    {
      DDRB = (1 << DDB3) | (1 << DDB1); // DDB2 MOSI, DDB1 SCK
      SPCR = (1 << SPE) | (1 << MSTR) | (1 << SPR0);
    }

    void SPI_TX(uint8_t data)
    {
      SPDR = data;
      while (!(SPSR & (1 << SPIF)));
    }

    -------------------------------------------------------------- -

Slave:

    -------------------------------------------------------------- -

    /* pro micro as slave and receives data then push them on
      PORTD and PORTB to blink LEDs */

    void SPI_Init_S(void);
    void SPI_RX(void);

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);//start Serial
      Serial.println("Setting Up");
      SPI_Init_S();
      delay(100);
      Serial.println("SPI intialization is complete");
      DDRD = (1 << DDD5); // TX LED as output
      DDRB = (1 << DDB0); // RX LED as output
    }

    void loop() {
      // put your main code here, to run repeatedly:
      SPI_RX();
      PORTD = SPDR;   // blink the TX LED on pro micro board
      _delay_ms(500);
      SPI_RX();
      PORTB = SPDR;   // blink the RX LED on pro micro board
      _delay_ms(500);
    }

    void SPI_Init_S(void)
    {
      SPCR = (1 << SPE) | (1 << SPR0);
    }

    void SPI_RX(void)
    {
      return SPDR;
    }

title: Arduino nano & pro micro SPI simple communication

Answers: 2

body:
You should use `SS` (Select Slave) pin for synchronization on both devices. If you have master with default settings for `SS` pin (= `INPUT`), any interferences will switch your master into the slave mode and `SPI_TX` will wait forever for clock pulses from outside.

Without using `SS` on both sides it can be also shifted (unsynchronized).

Edit: And yes, also not calling `SPI_Init` causes pretty similar deadlock.

body:
>      void setup() {
>     // put your setup code here, to run once:
>      Serial.begin(9600);//start Serial
>      Serial.println("Setting Up");
>      void SPI_Init(void);   // <---------------- this is wrong!
>      delay(100);
>      Serial.println("SPI intialization is complete");
>      }

That isn't how you call a function.

It should read:

    SPI_Init ();


body:
I'm looking at controlling Arduino by reading audio commands sent from a raspberry pi (through javascript). I've found the [SoftModem](https://github.com/arms22/SoftModem) code and wonder how it works. It claims that "It uses the phone's audio jack and Bell 202 modem-like FSK encoding", but I wonder how it's done. Doesn't it need to sample the ADC and apply some filtering like FFT? I can't seem to find where all this is done.

Any thought appreciated.

title: An audio jack modem

Answers: 1

body:
Judging by the blog from the post you linked, he is calculating the frequency received by using the analog comparator built into the processor. That lets you detect a signal rising, falling or both, compared to a reference voltage.

With some interrupts and some timing, you could work out what frequency signal you were receiving, and thus deduce if you got a 0 or 1 bit incoming.

I have a [page about the analog comparator](http://www.gammon.com.au/forum/?id=11916) if that helps.


body: I am new to Arduino. Can I combine Arduino UNO and MEGA in 1 project? Arduino UNO is for audio output and MEGA for LCD display. If I am wrong, is there any ideas how do combine both LCD display and audio output in one microcontroller?

title: combination of arduino uno and mega?

Answers: 2

body:
I think you can manage to find a display that uses only a few pins, like [Adafruit 2.2 TFT][1] which has a 3-pins SPI communication.
Then you have a lot of pins left to connect for example an audio [shield][2].

I think this could be done on a single Arduino, you'll just have to find an Arduino board compatible with both audio and video systems you choose.

I only wonder if the audio playing would be suffering from screen refresh if both communications are in SPI.

  [1]: https://learn.adafruit.com/2-2-tft-display/overview
  [2]: https://learn.adafruit.com/adafruit-shield-compatibility/wave-shield?view=all

body:
When you want to transport 8 people to a festival you can either use two cars and have 4 in each car, or you can get a minibus and have everyone together in one vehicle. It's often simpler to get a minibus, though hiring one may be outside your budget, so two cars is quite often the norm. The tricky part is to set up some form of communication between the drivers so they can both get to the same place at the same time and find each other.

It is exactly the same with microcontrollers (which the Arduino basically is). You can use one big powerful microcontroller to do everything, or you can split your task between a number of smaller microcontrollers. The tricky part is setting up some form of communication between them so that they can all coordinate what they are doing. Bigger microcontrollers can be more expensive though, and if you already have a couple of Arduinos at your disposal then connecting them together and sharing out different parts of your project to them is a good way of going.

Communicating between the Arduinos can be done in a number of ways, depending on how many Arduinos you are connecting, what kind of data there is going between them, etc. One common method which is well documented is to use I2C (Wire.h) to communicate. This is often chosen because it uses just two wires. For higher speed communication SPI is a good choice, but it requires more pins (4 for bi-directional communication). Of course, you can also connect them together using the UARTs, but on the smaller chips (such as the ATMega328P you get on the Arduino Uno) you only get one UART and that is used for programming, so using that for other things gets tricky.


body:
I noticed that I have VB0+, VB0-, VB1+ and VB1- pins on my LCD. In the datasheet it says they are for the "LCD Bias Voltage". I have never heard about that. So what is it? Where do I have to connect it?

Here is the datasheet of the LCD: http://www.buydisplay.com/download/manual/ERC12864-655_Series_Datasheet.pdf

title: What is LCD bias voltage and where do I have to connect it?

Answers: 1

body:
You need to look at the interfacing document kindly provided on the same page as that datasheet:

* http://www.buydisplay.com/download/interfacing/ERC12864-655_Interfacing.pdf

It shows plainly that you need to connect 2.2µF capacitors between the + and - of each pair of pins.


body:
What I want to achieve is that between 10 and 60 cm of my HCSR04 sensor the color fades from red to blue on my RGB LED in steps of 1 cm between 10 and 60 cm.

I have tried creating some own functions which calculate how much the analogWrite has to change every cm. Yet have had no succes..

I want to implement this function in the following code:

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

I hope my question is understandable...

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

title: Fading RGB LED between 10 and 60 cm

Answers: 1

body:
    analogWrite(Kleur1,distance);
    analogWrite(Kleur2,1024-distance);

Theoretically, this is all you need.

You'll color the LED "kleur1" with the analog value of the distance, so it will become brighter when the distance is higher.
And you'll color the LED "kleur2" with the "inverted" analog value of the distance, so it will become less brighter when the distance is higher.

But this kind of depends on what the value is on your maximal distance etc.


body:
I made a part of code to change the temperature limit for alarm system. On warm days user have to change the temperature limit with buttons and OLED display.

**The question is:** How can the variable `templimit` keep its last setup value after many restarts(for many reasons)?

This is the code:

    const int  buttonPin = 8;    // up
    const int  buttonPin1 = 3;    // down
    const int  buttonPin2 = 2;    // enter

    int buttonPushCounter;   // counter for the number of button presses
    int buttonState;;  // up
    int buttonState1;;  // down
    int buttonState2;;  // enter
    int templimit; // temperature limit for alarm

    void setup() {
      Serial.begin(9600);
      Serial.print("Update temperature limit if not wait 10 sec time out");
      updatevalue();
      Serial.print("Done");

    }

    void loop() {
    // do nothing
    }

    int updatevalue(void) {
      int timenow;
      int timepassed;
      timenow = millis();
      // this loop is just for 10 sec time out
      while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) {
        buttonState2 = digitalRead(buttonPin2); // enter
        buttonState = digitalRead(buttonPin); //up
        buttonState1 = digitalRead(buttonPin1); // down
        timepassed = (millis() - timenow);
        if (timepassed >= 10000)
        return 0;
      }
      while (buttonState2 != HIGH) { // do this until enter is pressed

        buttonState2 = digitalRead(buttonPin2); // enter
        buttonState = digitalRead(buttonPin); //up
        buttonState1 = digitalRead(buttonPin1); // down

        if (buttonState == HIGH) { // up
          buttonPushCounter++;
          Serial.print("number of button pushes:  ");
          Serial.println(buttonPushCounter);
        }
        if (buttonState1 == HIGH) { // down
          buttonPushCounter-- ;
          Serial.print("number of button pushes:  ");
          Serial.println(buttonPushCounter);
        }
        delay(700);
      }
      templimit = buttonPushCounter; // update templimit value

    }

[![This is the schematic][1]][1]

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

title: Update variable using buttons

Answers: 2

body:
An Arduino Uno has 512 bytes of non-volitile memory called EEPROM or Electrically Erasable Programmable Read Only Memory. Other Arduino platforms might have more. Accessing it is complex.  Fortunately there is an [Arduino EEPROM library][1] already written for you.  Your value is stored in a type int so I would use the read() and update() methods in the EEPROM library.  The read is self explanatory.  But the update, unlike the write, only runs if what is in the EEPROM location is different from what you want to write.  In this way we save the EEPROM a little bit of ware and tare.  As EEPROMs usually have a finite number of write cycles until they start failing.  Which usually is in the tens of thousands.

  [1]: https://www.arduino.cc/en/Reference/EEPROM

body:
The microcontroller on the Arduino MEGA boards have 1024 bytes of EEPROM: memory whose values are kept when the board is turned off (like a tiny hard drive).
These values will stay in the EEPROM when the board is turned off and may be retrieved later by another sketch.

I wrote two read/write functions if the value you want to write on EEPROM is **negative** because temperature has negative values too. Arduino EERROM write word with values between 0-255, also, has a [lifetime][1] 100,000 write cycle/ cell.

You can use EEPROM.update(address, value) instead of EEPROM.write(address, value) so the value is written only if differs from the one already saved at the same address.

**Save to EEPROM:**

    void save_to_eeprom(unsigned int address, float config) { // (address, value)

      for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
        EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
      }

**Read from EEPROM:**

    float read_from_eeprom(unsigned int address) { //(address)
      float config;
      for (byte i = 0; i < sizeof(config); i++) { // size of config is 4
        reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
      }
      return config;
    }

**This is how `templimit` will keep its last value after restart, the full code is:**

    #include <EEPROM.h>

      float read_from_eeprom(unsigned int address) {// read
        float config;
        for (byte i = 0; i < sizeof(config); i++) {
          reinterpret_cast<byte*>(&config)[i] = EEPROM.read(address + i);
        }
        return config;
      }

    // this constant won't change:
    const int  buttonPin = 8;    // up
    const int  buttonPin1 = 3;    // down
    const int  buttonPin2 = 2;    // enter

    // Variables will change:
    int buttonPushCounter;   // counter for the number of button presses
    int buttonState;;  // up
    int buttonState1;;  // down
    int buttonState2;;  // enter
    int templimit = read_from_eeprom(20); // temperature limit for alarm

    void setup() {
      Serial.begin(9600);
      Serial.println("Update temperature limit if not wait 10 sec for time out");
      updatevalue();
      Serial.println("Done");
      Serial.println(templimit); // temperature limit for alarm

    }

    void loop() {
      // do nothing
    }

    int updatevalue(void) {
      int timenow;
      int timepassed;
      int counter = 10;

      timenow = millis();
      while (buttonState == LOW and buttonState1 == LOW and buttonState2 == LOW) { // this loop is just for 10 sec time out
        buttonState2 = digitalRead(buttonPin2); // enter
        buttonState = digitalRead(buttonPin); //up
        buttonState1 = digitalRead(buttonPin1); // down
        timepassed = (millis() - timenow);
        delay(1000);
        Serial.println(counter--);
        if (timepassed >= 10000)
          return 0;
      }
      while (buttonState2 != HIGH) { // do this until enter is pressed

        buttonState2 = digitalRead(buttonPin2); // enter
        buttonState = digitalRead(buttonPin); //up
        buttonState1 = digitalRead(buttonPin1); // down

        if (buttonState == HIGH) { // up
          buttonPushCounter++;
          Serial.print("number of button pushes:  ");
          Serial.println(buttonPushCounter);
        }
        if (buttonState1 == HIGH) { // down
          buttonPushCounter-- ;
          Serial.print("number of button pushes:  ");
          Serial.println(buttonPushCounter);
        }
        delay(700);
      }

      save_to_eeprom(20, buttonPushCounter); // save to address 20 tha value it can be negative

    }

    void save_to_eeprom(unsigned int address, float config) {// write value it can be negative

      for (byte i = 0; i < sizeof(config); i++) {
        EEPROM.write(address + i, reinterpret_cast<byte*>(&config)[i]);
      }
    }

  [1]: https://arduino.stackexchange.com/questions/226/what-is-the-real-lifetime-of-eeprom


body:
I have a theoretical question about using digital pins of arduino. The specification of Arduino Uno (or any other I guess) says, that maximum current from digital pin is 40mA. If I would need more than 40mA and less than 80mA, can I use two pins to supply enough power to the sensor or would it burn the pins in the end?

Thanks

title: Using two pins to sum maximum available current

Answers: 1

body:
40mA is the *absolute maximum* current allowed. The recommended steady-state current is 25mA, so you'd need three or four IO pins to remain safe.

Theoretically, yes, that should be possible. However in practice doing such things is problematic.  You have to ensure that there is no point at which the sensor is being powered by less than the required number of IO pins, which means turning them all from off to on at the same time (doing them one at a time means you start with the full load through just one pin then start sharing it around). That means ensuring that all your pins are on the same port and using direct port manipulation to control all the pins at once.

It is far better, more reliable, and simpler to program, to just slip a simple p-channel MOSFET in there with a pullup on the gate to control the 5V power to the sensor. Pull the gate low and the sensor gets all the power it needs.


body:
I'm very new to electrical engineering and I'm trying to read microphone input with Arduino Nano. I've made a separate microphone module ([based on this example][1]) and plugged it into Arduino like this:

[![Connection][2]][2]
Unfortunately it was the last time my Arduino was working. It's no longer displayed as a connection, and acts "randomly", so I think my microphone toasts controller for some reason. Here are some more pictures and a scheme of my mic module, could someone explain what am I doing wrong?

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

<!-- End schematic -->

**R1** - CR1/4W 10 (brown,black,black,gold)

**R2** - CR1/4W 2KO (red,black,red,gold)

*I have no education in electrical engineering, so I'm not sure about the correctness of this schema of units, just pasted what's written on the pack*

[![Back][3]][3]
[![Front][4]][4]

  [1]: https://engmousaalkaabi.blogspot.lt/2015/10/sound-level-detector-using-arduino-and.html
  [2]: https://i.stack.imgur.com/OE5pNm.jpg
  [3]: https://i.stack.imgur.com/oYQeP.jpg
  [4]: https://i.stack.imgur.com/7fNxD.jpg

title: Self made microphone burns Arduino

Answers: 1

body:
Your schematic shows R1 as 10k ohms.
Your color codes and description lists it as 10 ohms. 10K would be Brown, Black, Orange.

http://www.allaboutcircuits.com/textbook/reference/chpt-2/resistor-color-codes/

So R1 is the wrong value by a factor of 1000, you may want to fix that ;-)

As for damage to the main board, depending on the microphone used that may have put an excessive strain on the 5V supply pin. Does the power LED still come on at the same brightness as before? If not then the power supply regulator is probably toast. If it does then I'm not sure what the problem is, you shouldn't have broken anything else.


body: I want to power my Arduino with a mobile charger, the out put is 5V 2A, will it kill my Arduino? And what's the max input current as power source?

title: Will 5V 2A current input to the power port kill my Arduino?

Answers: 1

body:
"*I want to power my arduino with mobile charger the out put is 5v 2apms will it kill my arduino?*"

No! It won't. Even tough the reason has been already explained [in this other post][1], I want to add something.

First of all, your question is really common among the ones who, like you (and me), have little/none electrical/electronic knowledge: if you ask such a question, it means you lack the "basic". This is perfectly **ok**, as we're here to learn "Arduino"... and this (typically) means we're here as the first step towards the electronic world. This is the very reason why I'm writing this answer. So... back to your question....

You're missing a key point, here: **the maximum current that your power supply can provide.... is a maximum! And this does NOT means that such a maximum will be given always, and regardless of the devices connected to it!**

In other words:

 - if you have a device that requires a very little amount of current to properly operate (*as an example, [this DHT22 sensor][2], requires as little as 2.5mA, or 0.0025 A*) and connect it to your 2A power supply, what will happen is that along the wire from your power-supply to the DHT22 will flow only 0.0025 A of current;

 - if you have 100 (one hundred) DHT22 connected in some exoterical network/schematic, each one requiring 2.5mA of current, in order to power the all of them, concurrently, you need 2.5mA * 100 = 0,25A (or 250mA), that means that again, your power-supply, will be more than enough (to power the all of them, concurrently);

 - if you have 1000 (one thousand) DHT22, than you'll need 2,5A (or 2500 mA) and... if you need to power the all of them, concurrently, and if you need to stick with your power-supply (capable of "only" 2A)... you'll have problems, as your power supply will not be able to provide the amount of current required by your equipments (*Which kind of problems you'll encounter is a matter for a different question!*)

To be more specific:

 - a common/base Arduino MEGA, without any external component connected, requires around 170mA of current;
 - an common/base ethernet shield, requires 180mA of current;

So, if you plug your 2A power-supply to the USB socket of a MEGA which has an Ethernet shield mounted on its top, than your power-supply will have no problem at all in powering such two devices (as they jointly requires 350mA of current).

 - you'll be able to power up to 6 of those MEGA+EthShield, as 6 x 350 = 1900mA, which is lower than 2A. Anyway, it's common practice to **not** require the maximum! It's good-style to not exceed 75/80% of the maximum, as sometimes, based on the quality of your power-supply, some "strange" things start happening when reaching the top!

In the above discussion we talked about "current", without taking into account the "voltage". Anyway, "voltage" is another key-point as "voltage" and "current" [are strongly related][3].

In your OP you mentioned "*mobile charger ... 5V*" so I bet that you've an USB power-supply, rated at 2A/5V.

People starting playing with Arduino, should use such 5V power-supply to power Arduino trough the USB socket: it has been designed _exactly_ to be connected to a 5V power source, being it an ad-hoc power-supply (with an USB termination) or an USB cable connected to a computer. As for this last case (a computer), please note that:

  - as for the USB2 specification, every USB2 "host" should be able to provide at least up to 500mA of current at 5V;

  - as for the USB3 specification, every USB3 "host" should be able to provide at least up to 900mA of current at 5V;

So, supposing you have an USB2 port on your PC and that you connect an USB "simple hub" (an hub without an explicit power-socket) to such port, you can connect only one MEGA+EthShield as this will require 350mA (of the 500mA available). If you have an USB3 port, you can connect 2 of them (and you can also try with three... but with unexpected results).

As for voltage, please note that you can power a tipical Arduino (eg: UNO or MEGA) also via a [barrel-jack][4], providing a voltage inline with what specified by [official documentation][5]:

> [...]
> The board can operate on an external supply of 6 to 20 volts. If
> supplied with less than 7V, however, [...] the board may become unstable. If using more than 12V,
> the voltage regulator may overheat and damage the board. The
> recommended range is 7 to 12 volts.
> [...]

The above statement introduce the "voltage regulator". This is another key-component that you should be familiar quite soon. At a very high-level, think to the "voltage regulator" as a magic box that:

 1. from one side (the external world) receive a not-so-stable-and-clean current, flowing in the range 7V-12V;

 2. apply some "magic" to such a current and bring it down _to_a_very_precise_ 5V flow;

 3. provide the resulting 5V potential to the "internal world" of Arduino.

In other words, the voltage-regulator is responsable for providing the exact/constant 5V required by Arduino components, by relying on some "unstable" external current.

 You might wonder how is possible to "lower" a 12V "input" to a 5V "output". I really don't know (and, actually, I don't care!). Anyway, a **fundamental** concept to be kept in mind is that **such a reduction will produce "heat"**! And the more you lower... the more heat it will produce! And the more current you'll "transform", the more "heat" it will produce! ...and if such heat will not be dissipated properly, chances are high that... something will stop working quite soon!

Having said all the above, please note that I'm well aware that lots of other concepts should have been discussed/introduced and that I have done some big oversimplification in the above description. Anyway, I really think that.... should someone had told me those concepts when I did my first steps in Arduino, my experience would have been shorter (...and easier). Nevertheless... don't blame me if you'll discover that those above will result mostly useless once you'll get slightly expert :-)

  [1]: https://arduino.stackexchange.com/a/18812/13193
  [2]: https://www.adafruit.com/products/385
  [3]: https://en.wikipedia.org/wiki/Ohm's_law
  [4]: https://en.wikipedia.org/wiki/DC_connector#Cylindrical_connectors
  [5]: https://www.arduino.cc/en/Main/ArduinoBoardMega2560


body:
Im having problems with Attiny85 programming. I am making something similar like [this project][1]. But i added function that every day on some time it turns on output - something like alarm clock. The real struggle is to make it active for longer time as one minute.. If current time is equals alarm time `wake_HOUR==hour()& wake_MINUTE==minute()` then it will run only for a minute so I added changeable field for the time how long output should be active - for example 5 minutes despite 1 minute. I tried to make timer with `millis()` and after those 5 minutes [reset timer][2] but this is where i stuck, because compiling for attiny it shows error, but if i use same code sample just for arduino then its working.. Code below:

    #include <avr/sleep.h>
    #include <TinyWireM.h>
    #include <EEPROM.h>
    #include "ssd1306.h"
    #include "WDT_Time.h"

    #define TIMEOUT 6000            //display timeout
    #define UNUSEDPINA 1            //RESET
    #define ALARM 4                 //ALARM
    #define BUTTONPIN  3            //GND
    unsigned int wake_HOUR = 0;     //Hours when it should wake up
    unsigned int wake_MINUTE = 0;   //Minutes when it should wake up
    unsigned int wake_SECOND = 0;   //Seconds when it should wake up - Not using
    unsigned long ALARM_TIME;       //How long alarm should be active- changable in display
    unsigned long new_millis = 0;   //Timer
    unsigned long interval;         //How long alarm should be active
    extern volatile unsigned long timer0_millis;
    unsigned int ACTIVE_ALARM = 0;  //alarm activated?

    #define SET_UP_BUTTON_THRESHOLD 100   //100k
    #define UP_DOWN_BUTTON_THRESHOLD 600  //7k
    #define PRESSED_BUTTON_THRESHOLD 1000 //NO resistance

    // enum
    typedef enum {
    normal, sleeping
    }  run_status_t;

    typedef enum {
    time_mode, debug_mode, alarm_mode
    }  display_mode_t;

    // button field constant
    #define NO_FIELD 0
    #define YEAR_FIELD 1
    #define MONTH_FIELD 2
    #define DAY_FIELD 3
    #define HOUR_FIELD 4
    #define MINUTE_FIELD 5
    #define SECOND_FIELD 6
    #define ALARM_HOUR_FIELD 7      //Alarm Hour
    #define ALARM_MINUTE_FIELD 8    //Alarm Minute
    #define ALARM_FIELD 9           //How long should alarm be active - minutes
    #define SET_ALARM_FIELD 10      //Activate alarm
    #define FIELD_COUNT 10
    //#define ALARM_SECOND_FIELD 9

    // variables
    SSD1306 oled;
    static uint32_t display_timeout = 0;
    static run_status_t run_status = normal;
    static display_mode_t display_mode = time_mode;
    static display_mode_t last_display_mode = time_mode;
    static bool time_changed = false;
    static bool alarm_changed = false;
    static uint8_t selected_field = NO_FIELD;

    uint8_t wake_SET = 0;
    //const char wake_BACK[15] = "GO BACK";

    void setup() {
      // setup input pins, also pullup unused pin for power saving purpose
      pinMode(UNUSEDPINA, INPUT_PULLUP);
      pinMode(BUTTONPIN, INPUT_PULLUP);
      pinMode(ALARM, OUTPUT);
      digitalWrite(ALARM, LOW);
      interval = ALARM_TIME*60000;

      // init time
      init_time();

      // init I2C and OLED
      TinyWireM.begin();
      oled.begin();
      oled.fill(0x00); // clear in black

      // init display timeout
      set_display_timeout();
    }

    void loop() {
      // detect and handle button input
      check_button();
      unsigned long currenTime = millis();
      //unsigned long new_value;
      //setMillis(new_value);

      if (run_status == sleeping) {
        // return to sleep mode after WDT interrupt
        system_sleep();
      } else { // not sleeping
        if (millis() > display_timeout) { // check display timeout
          enter_sleep();
        } else { // normal flow
          readRawVcc();
          readRawTemp();
          draw_oled();
        } // normal flow
      } // not sleeping
      if (ACTIVE_ALARM==1)
      {
        if (wake_HOUR==hour()& wake_MINUTE==minute())
        {
        digitalWrite(ALARM, HIGH);
        new_millis = millis();
        }
        else if (currenTime -new_millis <= interval)
        {
        new_millis = millis();
        digitalWrite(ALARM, HIGH);
        }
        else if (currenTime -new_millis >= interval)
        {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
        }}
      else if (ACTIVE_ALARM==0)
      {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
      }
    }
    //void setMillis(unsigned long new_millis){
    //  uint8_t oldSREG = SREG;
    //  cli();
    //  timer0_millis = new_millis;
    //  SREG = oldSREG;
    //}

    void enter_sleep() {
      oled.fill(0x00); // clear screen to avoid show old time when wake up
      oled.off();
      delay(2); // wait oled stable

      run_status = sleeping;
    }

    void wake_up() {
      run_status = normal;

      delay(2); // wait oled stable
      oled.on();

      // update display timeout
      set_display_timeout();
    }

    void set_display_timeout() {
      display_timeout = millis() + TIMEOUT;
    }

    /*
     * UI related
     */

    void draw_oled() {
      if (display_mode != last_display_mode) {
        oled.fill(0x00);
        last_display_mode = display_mode;
      }
      oled.set_font_size(1);
      if (display_mode == time_mode) {
        // 1st row: print info
        oled.set_pos(5, 0);
        oled.print("TIME");
        oled.set_pos(80, 0);
        oled.print("AcALARM=");
        oled.print(digitalRead(ACTIVE_ALARM));
        oled.set_pos(80, 1);
        oled.print("A_TIME=");
        oled.print(digitalRead(ALARM_TIME));
        oled.set_pos(80, 2);
        oled.print("ALARM=");
        oled.print(digitalRead(ALARM));

        // 2nd row: print date
        print_digit(7, 1, year(), (selected_field == YEAR_FIELD));
        oled.write('-');
        print_digit(7 + (5 * FONT_WIDTH), 1, month(), (selected_field == MONTH_FIELD));
        oled.write('-');
        print_digit(7 + (8 * FONT_WIDTH), 1, day(), (selected_field == DAY_FIELD));

        // 3rd-4th rows: print time
        oled.set_pos(30, 4);
        oled.print("SET ALARM");
        oled.set_pos(3, 5);
        oled.print("HH:MM-->ALARM MIN");
        oled.set_pos(95, 5);
        oled.print("ON/OFF");
        oled.set_font_size(2);
        print_digit(0, 2, hour(), (selected_field == HOUR_FIELD));
        oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 2, 2, 2, 0b00011000);
        print_digit(2 * FONT_2X_WIDTH + 5, 2, minute(), (selected_field == MINUTE_FIELD));
        oled.draw_pattern(4 * FONT_2X_WIDTH + 6, 2, 2, 2, 0b00011000);
        print_digit(4 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 2, second(), (selected_field == SECOND_FIELD));
        print_digit(0, 6, wake_HOUR, (selected_field == ALARM_HOUR_FIELD));
        oled.draw_pattern(2 * FONT_2X_WIDTH + 1, 6, 2, 2, 0b00011000);
        print_digit(2 * FONT_2X_WIDTH + 5, 6, wake_MINUTE, (selected_field == ALARM_MINUTE_FIELD));
        print_digit(6 * FONT_2X_WIDTH + 2 * FONT_WIDTH, 6, ALARM_TIME, (selected_field == ALARM_FIELD));
        print_digit(80, 6, ACTIVE_ALARM, (selected_field == SET_ALARM_FIELD));
      }
      else if (display_mode == debug_mode) { // debug_mode
        print_debug_value(2, 'I', get_wdt_interrupt_count());
        print_debug_value(3, 'M', get_wdt_microsecond_per_interrupt());
        print_debug_value(4, 'V', getVcc());
        print_debug_value(5, 'T', getRawTemp());
      }
    }

    void print_digit(uint8_t col, uint8_t page, int value, bool invert_color) {
      oled.set_pos(col, page);
      if (invert_color) oled.set_invert_color(true);
      if (value < 10) oled.write('0');
      oled.print(value);
      if (invert_color) oled.set_invert_color(false);
    }

    void print_debug_value(uint8_t page, char initial, uint32_t value) {
      oled.set_pos(0, page);
      oled.write(initial);
      oled.set_pos(14, page);
      oled.print(value);
    }

    // PIN CHANGE interrupt event function
    ISR(PCINT0_vect) {
      set_display_timeout(); // extent display timeout while user input
    }

    void check_button() {
      int buttonValue = analogRead(BUTTONPIN);

      if (buttonValue < PRESSED_BUTTON_THRESHOLD) { // button down
        set_display_timeout(); // extent display timeout while user input

        if (run_status == sleeping) {
          // wake_up if button pressed while sleeping
          wake_up();
        } else { // not sleeping
          if (buttonValue > UP_DOWN_BUTTON_THRESHOLD) { // down button
            handle_adjust_button_pressed(-1);
          } else if (buttonValue > SET_UP_BUTTON_THRESHOLD) { // up button
            handle_adjust_button_pressed(1);
          } else { // set button
            handle_set_button_pressed();
          }
        } // not sleeping
      } // button down
    }

    void handle_set_button_pressed() {
      display_mode = time_mode; // always switch to time display mode while set button pressed

      selected_field++;
      if (selected_field > FIELD_COUNT) { // finish time adjustment
        selected_field = NO_FIELD;
        if (time_changed) {
          wdt_auto_tune();
          time_changed = false;
        } //time changed
      } // finish time adjustment
    }

    void handle_adjust_button_pressed(long value) {
      if (selected_field == NO_FIELD) {
        // toggle display_mode if no field selected
        display_mode = (display_mode == time_mode) ? debug_mode : time_mode;}
      else {
        long adjust_value;
        if (selected_field == YEAR_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY * (leapYear(CalendarYrToTm(year())) ? 366 : 365);
        }
        else if (selected_field == MONTH_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY * getMonthDays(CalendarYrToTm(year()), month());
        }
        else if (selected_field == DAY_FIELD) {
          // TODO: handle leap year and reverse value
          adjust_value = value * SECS_PER_DAY;
        }
        else if (selected_field == HOUR_FIELD) {
          adjust_value = value * SECS_PER_HOUR;
        }
        else if (selected_field == MINUTE_FIELD) {
          adjust_value = value * SECS_PER_MIN;
        }
        else if (selected_field == SECOND_FIELD) {
          adjust_value = value;
        }
        else if (selected_field == ALARM_HOUR_FIELD)
        {
          if (wake_HOUR >= 23)
          {
          wake_HOUR=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           wake_HOUR--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           wake_HOUR++;
           }
            }
        else if (selected_field == ALARM_MINUTE_FIELD) {
          if (wake_MINUTE >= 59)
          {
          wake_MINUTE=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           wake_MINUTE--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           wake_MINUTE++;
           }
            }
          else if (selected_field == ALARM_FIELD) {
          if (ALARM_TIME >= 59) //MAX 1h
          {
          ALARM_TIME=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           ALARM_TIME--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           ALARM_TIME++;
           }
            }
          else if (selected_field == SET_ALARM_FIELD) {
          if (ACTIVE_ALARM >= 1)
          {
          ACTIVE_ALARM=0;
          }
          else if (analogRead(BUTTONPIN) > UP_DOWN_BUTTON_THRESHOLD)
          { // down button
           ACTIVE_ALARM--;
          }
          else if (analogRead(BUTTONPIN) > SET_UP_BUTTON_THRESHOLD)
          { // up button
           ACTIVE_ALARM++;
           }
            }

        adjustTime(adjust_value);
        time_changed = true;
      }
    }

I would like to reset timer then when wake_hours&minutes and changeable alarm activation time `interval = ALARM_TIME*60000` have passed.

          if (ACTIVE_ALARM==1)
      {
        if (wake_HOUR==hour()& wake_MINUTE==minute())
        {
        digitalWrite(ALARM, HIGH);
        new_millis = millis();
        }
        else if (currenTime -new_millis <= interval)
        {
        new_millis = millis();
        digitalWrite(ALARM, HIGH);
        }
        else if (currenTime -new_millis >= interval)
        {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
        }}
      else if (ACTIVE_ALARM==0)
      {
        new_millis = 0;
        digitalWrite(ALARM, LOW);
      }

Any ideas what kind a timer/delay i could use to make my code work?

  [1]: http://www.instructables.com/id/ATtiny-Watch-Core/step3/Power-Down-WDT-and-Time/
  [2]: https://arduino.stackexchange.com/questions/22994/resetting-millis-and-micros

title: Proper Attiny85 timer/delay

Answers: 2

body:
As noted in the comment of IgnacioVazquez-Abrams, in the instances at hand you should be using the `&&` (logical AND) relational operator, rather than the `&` (bitwise AND) arithmetic operator.

That aside, you should separate things out so that instead of an ungainly `if - else` series you have some independent cases.  For example:

    if (wake_HOUR==hour() && wake_MINUTE==minute()) {
       digitalWrite(ALARM, HIGH);
       alarmMillis = millis();
    }
    if (millis()-alarmMillis > interval) {
       digitalWrite(ALARM, LOW);
    }

This will do the job, as follows:

• During the match-minute, `ALARM` will be driven high over and over, and `new_millis` will update to the current `millis()` value over and over.  Which is OK.

• After the match-minute but before the end of the timed interval, `ALARM` will remain high and `new_millis` will remain fixed with the time of the end of the match-minute.  OK, that's as desired.

• After the end of the timed interval, ie, when `millis()-new_millis > interval`, `ALARM` will be driven low over and over.  Which is OK.

Note, I don't see a declaration of `currenTime` or anywhere it is updated.  Hence, it does not represent current time and should not be used as such.

Note, `interval` should be declared as something like a `const unsigned long int`, with a value that is a minute shorter than the total length of interval that you want.  (`new_millis` represents the *end* of the first minute of the interval.)

Note, `new_millis` should *not* be zeroed at the end of the interval.  If the original code were magically made to mostly work, because of  `new_millis` being zeroed it still would have a bug.  During the first few minutes after each `millis()` overflow, a false alarm would sound.  `millis()` overflows are about 49.71 days apart.

body:
So i fixed my problem. I didnt use timer what i wanted in the beginning but as the code it self's running clock i used current clock as to activate output and then based on clock to turn off output.
Not always the hardest way is better.
Basically this is what i needed to change:

    if (ACTIVE_ALARM==1)
    {
    if (start_wake_HOUR==hour()&& start_wake_MINUTE==minute())
    {
    digitalWrite(ALARM, HIGH);
    }
    if (end_wake_HOUR==hour()&& end_wake_MINUTE==minute())
    {
    digitalWrite(ALARM, LOW);
    }
    }
    else if (ACTIVE_ALARM==0)
    {
    digitalWrite(ALARM, LOW);
    }


body:
I have just installed Arduino on Mac OS. The Arduino folder is created under Documents. But whenever I save the sketch it gets stored in some ghost location and gives an error, the same name already exits. Upon finding the location of file. It gets stored under this directory(Hidden).

    /private/var/folders/_v/nbrwcsh51wd2k07kfhy9vhjm0000gn/T/untitled1010592992.tmp/sketch_sep28a

How can I move this location to my documents folder. In Arduino preferences, I have also changed the location of sketch, still it does save in above location.

title: The Arduino Sketch does not save in Arduino folder location

Answers: 1

body:
 - Download the latest IDE from Arduino.cc
 - Drag your Arduino application icon to the trash.
 - Open up terminal and type `rm -r ~/Library/Arduino15`
 - Delete the Arduino folder in your Documents folder for good measure
 - Drag the newly downloaded Arduino application to your application folder and see how it goes from a clean install.

Failing that PlatformIO IMO is a much better IDE for developing on these platforms : http://platformio.org/